# Robotic AI Bear using ChatGPT

## Overview

https://www.youtube.com/watch?v=A8uWOsRVxYk

The [Peek-A-Boo Teddy Bear by GUND](https://amzn.to/3lIUwh7) is an affordable robotic bear that plays pre-recorded sounds. It has a motorized mouth to simulate talking and motorized arms that can lift a blanket to hide its face.

This guide will show you how to enhance the bear to make it do more than just play 'peek-a-boo' by tying it to OpenAI's ChatGPT API. Now you can speak to the toy and ask it questions, have it tell you stories, and more! Voice recognition is used to generate the prompts and then text-to-speech plays back the response

We do this by replacing the electronics inside with a [Raspberry Pi 4](https://www.adafruit.com/product/4292), an [Adafruit Motor HAT](https://www.adafruit.com/product/2348), and a couple of options for playing audio such as the [MAX98357 I2S Amp](https://www.adafruit.com/product/3006) and a [Mini USB Speaker](https://www.adafruit.com/product/3369). The Raspberry Pi 4 will be running a custom Python script that interacts with multiple APIs including two from OpenAI and one from Azure.&nbsp;

It takes inspiration from some iconic bear characters including a popular toy in the 1980s called [Teddy Ruxpin](https://en.wikipedia.org/wiki/Teddy_Ruxpin) that would tell stories while making prerecorded robotic gestures and movements. This project was also inspired by the toy bear from the movie [A.I.](https://en.wikipedia.org/wiki/A.I._Artificial_Intelligence), which was advanced robotic companion designed to provide love and comfort to a child.

This project combines the best of both worlds to create a robotic bear that not only tells stories, jokes, and poems, but also interacts with you using natural language processing powered by ChatGPT. This technology allows the bear to respond to questions and engage in conversations.

By the end of this guide, you will have learned how to upgrade your own robotic bear with ChatGPT integration, gaining hands-on experience with robotics, programming, and artificial intelligence.

## Parts

This project has a few options depending on how compact versus how easy you would like the project. Here are the parts you will need for either build.

The first thing you will need is a Raspberry Pi 4. This project will likely also work on a Raspberry Pi 3 or Pi 5 if you skip the custom enclosure, but it has not been tested.

You may also be able to use another board, but it likely won't run Raspberry Pi OS, so the software setup will likely be significantly different and covering other boards is beyond the scope of this guide.

### Raspberry Pi 4 Model B

[Raspberry Pi 4 Model B](https://www.adafruit.com/product/4297)
The Raspberry Pi 4 Model B is the newest Raspberry Pi computer made, and the Pi Foundation knows you can always make a good thing _better_! And what could make the Pi 4 better than the 3? How about a&nbsp;_faster_ processor, USB 3.0 ports, and updated Gigabit Ethernet chip with...

Out of Stock
[Buy Now](https://www.adafruit.com/product/4297)
[Related Guides to the Product](https://learn.adafruit.com/products/4297/guides)
![Angled shot of Raspberry Pi 4](https://cdn-shop.adafruit.com/640x480/4297-02.jpg)

You will also need a motor HAT. The reason for the HAT over the bonnet is because more soldering points are available.

### Adafruit DC & Stepper Motor HAT for Raspberry Pi - Mini Kit

[Adafruit DC & Stepper Motor HAT for Raspberry Pi - Mini Kit](https://www.adafruit.com/product/2348)
Let your robotic dreams come true with the new DC+Stepper Motor HAT from Adafruit. This Raspberry Pi add-on is perfect for any motion project as it can drive up to 4 DC or 2 Stepper motors with full PWM speed control.

**Raspberry Pi and motors are not included. Works with any and...**

In Stock
[Buy Now](https://www.adafruit.com/product/2348)
[Related Guides to the Product](https://learn.adafruit.com/products/2348/guides)
![Angled shot of Adafruit DC & Stepper Motor HAT.](https://cdn-shop.adafruit.com/640x480/2348-07.jpg)

You will need this set of nylon screws and standoffs for the project.

### Black Nylon Machine Screw and Stand-off Set – M2.5 Thread

[Black Nylon Machine Screw and Stand-off Set – M2.5 Thread](https://www.adafruit.com/product/3299)
Totaling 380 pieces, this **M2.5 Screw Set** &nbsp;is a must-have for your workstation.&nbsp;You'll have enough screws, nuts, and hex standoffs to fuel your maker tendencies&nbsp;for days on end! M2.5 size screws fit almost all of the Adafruit breakout/dev board mounting holes...

In Stock
[Buy Now](https://www.adafruit.com/product/3299)
[Related Guides to the Product](https://learn.adafruit.com/products/3299/guides)
![Black Nylon Screw and Stand-off Set with M2.5 Threads, kit box](https://cdn-shop.adafruit.com/640x480/3299-00.jpg)

### Part: GUND Peek-A-Boo Teddy Bear
quantity: 1
The bear that you will be modifying
[GUND Peek-A-Boo Teddy Bear](https://amzn.to/3lIUwh7)

### Part: Mini USB Microphone
quantity: 1
You can use this or any USB microphone
[Mini USB Microphone](https://www.adafruit.com/product/3367)

### Part: USB to 2.1mm Male Barrel Jack Cable
quantity: 1
Cheap USB plug to wire option
[USB to 2.1mm Male Barrel Jack Cable](https://www.adafruit.com/product/2697)

### Part: Premium Male/Male Jumper Wires
quantity: 1
6" x 20 wires
[Premium Male/Male Jumper Wires](https://www.adafruit.com/product/1957)

### Part: 3 Amp Battery Bank
quantity: 1
10000mAh 5V 3A Battery Pack Charger
[3 Amp Battery Bank](https://amzn.to/3nryAHX)

## Easier Build Option
### Part: Mini External USB Stereo Speaker
quantity: 1
USB-powered Speaker
[Mini External USB Stereo Speaker](https://www.adafruit.com/product/3369)

### Part: Female DC Power adapter
quantity: 1
For easily connecting USB power
[Female DC Power adapter](https://www.adafruit.com/product/368)

## Compact Build Option
### Part: Adafruit I2S 3W Class D Amplifier Breakout
quantity: 1
MAX98357 Amplifier
[Adafruit I2S 3W Class D Amplifier Breakout](https://www.adafruit.com/product/3006)

### Part: Mini Metal Speaker
quantity: 1
Optional 8 ohm 0.5W speaker upgrade
[Mini Metal Speaker](https://www.adafruit.com/product/1890)

### Part: 100K Through-Hole Resistors
quantity: 1
For reducing the gain on the amp
[100K Through-Hole Resistors](https://www.adafruit.com/product/2787)

### Part: USB Type A to Type C Cable
quantity: 1
Short USB Cable
[USB Type A to Type C Cable](https://www.adafruit.com/product/4473)

## Optional Parts

These parts are optional, but enhance the project.

### Part: Heat Shrink Pack
quantity: 1
Heat shrink tubing to prevent wires from shorting
[Heat Shrink Pack](https://www.adafruit.com/product/344)

### Part: Aluminum Heat Sink for Raspberry Pi
quantity: 1
This fits perfectly under the motor HAT
[Aluminum Heat Sink for Raspberry Pi](https://www.adafruit.com/product/3083)

### Part: 2-pin JST SM Plug + Receptacle Cable Set
quantity: 1
For easily disconnecting the foot button from the pi
[2-pin JST SM Plug + Receptacle Cable Set](https://www.adafruit.com/product/2880)

### Part: Wire Ferrule Kit
quantity: 1
This helps in certain situations, but most of the wiring is too small gauge
[Wire Ferrule Kit](https://www.adafruit.com/product/5131)

### Part: USB A Extension Cable
quantity: 1
If you'd like to position the USB microphone better
[USB A Extension Cable](https://www.adafruit.com/product/4055)

# Robotic AI Bear using ChatGPT

## Circuit Diagram

![](https://cdn-learn.adafruit.com/assets/assets/000/119/878/medium800/hacks_Bear_Circuit_bb_wide.jpg?1680038507)

## Required Wiring

The HAT Motor Power will come from a USB cable that will be plugged into the battery pack.

- **Green** Arms Motor Wire to **HAT M1 left side (1st terminal position)**
- **Orange** Arms Motor Wire to **HAT M1 right side (2nd terminal position)**
- **Yellow** Mouth Motor Wire to **HAT M2 left side (4th terminal position)**
- **White** Mouth Motor Wire to **HAT M2 right side (5th terminal position)**
- Foot Button wire 1 to **HAT GPIO #16**
- Foot Button wire 2 to **HAT Gnd**
- **HAT Motor Power +** to External USB +5V
- **HAT Motor Power -** to External USB Gnd

## Compact Build Additional Wiring

For the speaker wires, the order doesn't matter. Since it only has a single speaker.

- **MAX98357 Vin** to **HAT 3V**
- **MAX98357 Gnd** to **HAT Gnd**
- **MAX98357 LRC** to **HAT GPIO #19**
- **MAX98357 BCLK** to **HAT GPIO #18**
- **MAX98357 DIN** to **HAT GPIO #21**
- 100K Resistor to **MAX98357 Gain**
- Other side of 100K Resistor to **MAX98357 Vin**
- Speaker Wires to **MAX98357 Speaker Output**

# Robotic AI Bear using ChatGPT

## 3D Printing

Warning: 

![](https://cdn-learn.adafruit.com/assets/assets/000/119/941/medium800/hacks_IMG_4848.jpeg?1680125359)

This project will be assembled with just a few 3D printed parts, described below.&nbsp;The parts are available in either the STL (older) or 3MF (newer) format. Most slicers support both. You'll need to print multiples of some parts:

### Main Case

- 1 x **Case Top.stl**
- 1 x **Case Bottom.stl**

### Speaker Retainers

If you're using the 4mm 0.25W speaker from inside the bear:

- 2 x **4mm Thick Speaker Retainer.stl**

If you're using an upgraded Adafruit 2mm 0.5W speaker:

- 2 x **2mm Thick Speaker Retainer.stl**

[Download STL Files](https://github.com/adafruit/Adafruit_Learning_System_Guides/raw/main/ChatGPT_Bear/Enclosure/STL_Files.zip)
[Download 3MF Files](https://github.com/adafruit/Adafruit_Learning_System_Guides/raw/main/ChatGPT_Bear/Enclosure/3MF_Files.zip)
[Download CAD Source](https://github.com/adafruit/Adafruit_Learning_System_Guides/raw/main/ChatGPT_Bear/Enclosure/CAD_Files.zip)
## Slicer Settings

The specific setting values aren't that important with this case. However, here's the settings used to print the case for this guide.

For the larger case parts:

- 20% infill
- Supports on build plate enabled
- 0.2mm Layer Height

For the small speaker retainers:

- 20% infill
- 0.2mm Layer Height
- No Supports

## Parts Details
### Case Bottom

The Raspberry Pi and Motor HAT will be housed here

![hacks_IMG_4836.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/934/medium640/hacks_IMG_4836.jpeg?1680124205)

### Case Top

The speaker and MAX98357 will be attached here

![hacks_IMG_4843.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/935/medium640/hacks_IMG_4843.jpeg?1680124770)

### 4mm Thick Speaker Retainer

These retainers are for the 4mm thick speaker that you can harvest from inside the bear.

![hacks_IMG_4847.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/938/medium640/hacks_IMG_4847.jpeg?1680125226)

### 2mm Thick Speaker Retainer

These are for holding the thinner 2mm 0.5W Adafruit speaker upgrade.

![hacks_IMG_4846.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/939/medium640/hacks_IMG_4846.jpeg?1680125279)

# Robotic AI Bear using ChatGPT

## Modifying the Bear

To be able to make use of the bear, you will need to disassemble it and remove the circuitry so that it can be connected to the Raspberry Pi. Some of the tools you will need include a couple of sizes of phillips-head and Flathead screwdrivers, some isopropyl alcohol, and flush cutters or a soldering iron.

Info: 

## Disassembly

As you disassemble the bear, be sure to carefully set aside the screws and electronics as some of this will be re-used in the final circuit.

Primary: 

Start by removing the bear from the packaging.

![hacks_IMG_4741.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/785/medium640/hacks_IMG_4741.jpeg?1679965932)

Turn the bear over and open the flap covering the battery compartment. You may want to remove the battery cover and batteries so you can use them for something else. They won't be used in this project.

![hacks_IMG_4742.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/787/medium640/hacks_IMG_4742.jpeg?1679966141)

Remove the 4 screws and set them aside. Then remove the cover. You may need to pry it a bit.

![hacks_IMG_4743_marked.jpg](https://cdn-learn.adafruit.com/assets/assets/000/119/789/medium640/hacks_IMG_4743_marked.jpg?1679966679)

The fabric around the electronics housing should now be free to pull away. Go ahead and pull the housing out of the bear.

![hacks_IMG_4746.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/791/medium640/hacks_IMG_4746.jpeg?1679966988)

To expose the housing, first carefully push the cloth around the housing up so that the bottom half inch of the housing is exposed. Then push it up the rest of the way.

![hacks_IMG_4747.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/792/medium640/hacks_IMG_4747.jpeg?1679966964)

The housing is attached further up with a bunch of hot glue. Applying some isopropyl alcohol (or IPA) to the glue with a cotton swab or something similar will cause the glue to become brittle and less adhesive. The higher the concentration of IPA, the better it works. Don't forget to remove the glue on the lower white wires.

![hacks_IMG_4748.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/799/medium640/hacks_IMG_4748.jpeg?1679967948)

There are 4 more screws holding the housing together. Remove those screws and set them aside.

![hacks_IMG_4749_marked.jpg](https://cdn-learn.adafruit.com/assets/assets/000/119/795/medium640/hacks_IMG_4749_marked.jpg?1679967292)

Once the two halves of the housing are taken apart, you will have access to the electronics and wiring.

![hacks_IMG_4752.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/796/medium640/hacks_IMG_4752.jpeg?1679967567)

On the circuit board are connections to the power, mouth motor, arms motor, foot button, and speaker. Remove everything except the power wires because they won't be needed. If you are doing the easier build option or upgrading the speaker, you won't need the built-in speaker either. You can either use flush cutters or remove the glue and desolder each wire.

![hacks_Circuit_Connections.jpg](https://cdn-learn.adafruit.com/assets/assets/000/119/803/medium640/hacks_Circuit_Connections.jpg?1680017312)

## Preparing the Motor Wires

In order to connect the motor wires to the Adafruit Motor HAT, we recommend extending the thin wires with thicker jumper wires and a nice connector on the end.

If you don't mind the wires being short on the short side, you may want to try wire ferrules. These have the advantage of not being as deep and you don't risk melting the polyfill stuffing inside the bear. However, the wire gauge is a bit small and it's tricky to get the ferrules to stay on properly.

You could also combine the two methods and extend the wires with thicker ones and replace the long black connectors with the shorter ferrules.

Danger: 

With the 6" wires, by cutting in half, you can have 2 useable parts. If you would like longer wires, you can just cut off 1 end.

![hacks_IMG_4801.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/810/medium640/hacks_IMG_4801.jpeg?1679961621)

You'll want to cut, strip, and tin 4 wires to match the motor wires. You will also want to cut 4 pieces of heat shrink tubing. Place the heat shrink on the wires now so you don't forget later.

![hacks_IMG_4810.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/811/medium640/hacks_IMG_4810.jpeg?1679961680)

Strip and tin the wires inside the bear. Very carefully solder the wire extensions to the motor wires sticking out. You may want to temporarily remove some of the stuffing to give you more room to work and place some aluminum foil around the area you are working.

![hacks_IMG_4811.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/812/medium640/hacks_IMG_4811.jpeg?1679961757)

Now slide the heat shrink tubing up and heat it. I used a hot air soldering station set at 120° Celsius, which seemed to be just hot enough to shrink it. You could also use electrical tape to insulate if you aren't comfortable with heat shrink.

![hacks_IMG_4813.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/813/medium640/hacks_IMG_4813.jpeg?1679961853)

## Preparing the Foot Button

If you would like to make it so the foot button can be disconnected, you can attach the JST SM Plug cable to it and the receptacle to the Pi.

If you are not using this connector, just strip and tin the pair of white wires coming out of the bear with a small knot in the end without shortening the wires.

The foot button wires and JST cables are quite long, so it's helpful to trim them down a bit.

![hacks_IMG_4788.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/889/medium640/hacks_IMG_4788.jpeg?1680042345)

![hacks_IMG_4785.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/890/medium640/hacks_IMG_4785.jpeg?1680042409)

Place some heat shrink tubing on the foot button wires. Since the wires are already separated, it make things a lot easier.

![hacks_IMG_4786.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/892/medium640/hacks_IMG_4786.jpeg?1680042458)

Strip, tin, and solder the harness to the foot button wires. The specific wire doesn't matter since pushing the button connects them together.

![hacks_IMG_4789.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/894/medium640/hacks_IMG_4789.jpeg?1680042607)

Slide the heat shrink tubing over the soldered wires and heat it up. Since the wiring isn't as short as the motor wires, this is much easier.

![hacks_IMG_4790.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/893/medium640/hacks_IMG_4790.jpeg?1680042528)

That's it. You'll connect the receptacle on the Wiring page.

![hacks_IMG_4791.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/897/medium640/hacks_IMG_4791.jpeg?1680042723)

## Preparing the Speaker

If you are reusing the speaker and you would like to use the terminal connector on the MAX98357, you will want to replace the wires on the speaker with ones similar to the motor. Otherwise, you can just strip and tin the existing wires.

Prepare two more wires and desolder the ones that come with the speaker.

![hacks_IMG_4806.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/815/medium640/hacks_IMG_4806.jpeg?1679962205)

Solder the new wires onto the speaker.

![hacks_IMG_4807.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/816/medium640/hacks_IMG_4807.jpeg?1679962304)

That's it! The bear is all prepared for adding the new electronics.

# Robotic AI Bear using ChatGPT

## DC and Stepper Motor HAT Assembly

# Solder on Headers and Terminal Block

Before we can motorin' there's a little soldering to be done. This step will attach the 2x20 socket header so that we can plug this HAT into a Raspberry Pi, and the terminal blocks so you can attach external power and motors.

Start by plugging the 2x20 header into a Raspberry Pi, this will keep the header stable while you solder. Make sure the Pi is powered down!

![raspberry_pi_headeron.jpg](https://cdn-learn.adafruit.com/assets/assets/000/022/677/medium640/raspberry_pi_headeron.jpg?1422308108)

Place the HAT on top so that the short pins of the 2x20 header line up with the pads on the HAT

![raspberry_pi_place.jpg](https://cdn-learn.adafruit.com/assets/assets/000/022/678/medium640/raspberry_pi_place.jpg?1422308118)

## And Solder!

Heat up your iron and solder in one header connection on the right.

Once it is soldered, put down the solder and reheat the solder point with your iron while straightening the HAT so it isn't leaning down

_(For tips on soldering, be sure to check out our_ [_Guide to Excellent Soldering_](http://learn.adafruit.com/adafruit-guide-excellent-soldering)_)._

![raspberry_pi_tack.jpg](https://cdn-learn.adafruit.com/assets/assets/000/022/679/medium640/raspberry_pi_tack.jpg?1422308136)

![raspberry_pi_adjust.jpg](https://cdn-learn.adafruit.com/assets/assets/000/022/680/medium640/raspberry_pi_adjust.jpg?1422308181)

Solder one point on the opposite side of the connector

![raspberry_pi_tack2.jpg](https://cdn-learn.adafruit.com/assets/assets/000/022/681/medium640/raspberry_pi_tack2.jpg?1422308204)

Solder each of the connections for the top row

![raspberry_pi_solder2.jpg](https://cdn-learn.adafruit.com/assets/assets/000/022/682/medium640/raspberry_pi_solder2.jpg?1422308229)

![raspberry_pi_solder3.jpg](https://cdn-learn.adafruit.com/assets/assets/000/022/683/medium640/raspberry_pi_solder3.jpg?1422308240)

![raspberry_pi_solder4.jpg](https://cdn-learn.adafruit.com/assets/assets/000/022/684/medium640/raspberry_pi_solder4.jpg?1422308243)

Flip the board around and solder all the connections for the other half of the 2x20 header

![raspberry_pi_solder5.jpg](https://cdn-learn.adafruit.com/assets/assets/000/022/685/medium640/raspberry_pi_solder5.jpg?1422308256)

![raspberry_pi_solder6.jpg](https://cdn-learn.adafruit.com/assets/assets/000/022/686/medium640/raspberry_pi_solder6.jpg?1422308260)

![raspberry_pi_solder7.jpg](https://cdn-learn.adafruit.com/assets/assets/000/022/687/medium640/raspberry_pi_solder7.jpg?1422308279)

![raspberry_pi_solder8.jpg](https://cdn-learn.adafruit.com/assets/assets/000/022/688/medium640/raspberry_pi_solder8.jpg?1422308285)

Check over your work so far, make sure each solder point is shiny, and isn't bridged or dull or cracked

![raspberry_pi_soldered.jpg](https://cdn-learn.adafruit.com/assets/assets/000/022/689/medium640/raspberry_pi_soldered.jpg?1422308306)

Now grab the 3.5mm-spaced terminal blocks. These will let you quickly connect up your motor and power supply using only a screw driver

You will have 3 x 2-pin terminal blocks and 2 x 3-pin terminal blocks

Slide each of the 3-pin terminal blocks into a 2-pin to create two 5-pin blocks

![raspberry_pi_terminals.jpg](https://cdn-learn.adafruit.com/assets/assets/000/022/690/medium640/raspberry_pi_terminals.jpg?1422308332)

Slide the terminal blocks along the edge of the HAT, so that the 'mouth' of each block is facing out.

You can use scotch or other plain tape to keep the terminal blocks flat against the PCB while you solder

![raspberry_pi_termplace.jpg](https://cdn-learn.adafruit.com/assets/assets/000/022/691/medium640/raspberry_pi_termplace.jpg?1422308408)

Flip over the board and solder in all of the terminal block pins

![raspberry_pi_termsolder1.jpg](https://cdn-learn.adafruit.com/assets/assets/000/022/692/medium640/raspberry_pi_termsolder1.jpg?1422308629)

![raspberry_pi_termsolder3.jpg](https://cdn-learn.adafruit.com/assets/assets/000/022/693/medium640/raspberry_pi_termsolder3.jpg?1422308649)

![raspberry_pi_termsolder4.jpg](https://cdn-learn.adafruit.com/assets/assets/000/022/694/medium640/raspberry_pi_termsolder4.jpg?1422308667)

Check over your work so far, make sure each solder point is shiny, and isn't bridged or dull or cracked

You're done! You can now move onto the software side

![raspberry_pi_termsoldered.jpg](https://cdn-learn.adafruit.com/assets/assets/000/022/695/medium640/raspberry_pi_termsoldered.jpg?1422308682)

# Robotic AI Bear using ChatGPT

## Wiring

The wiring for the new electronics going into the bear is fairly straightforward. Make sure you have assembled the [Adafruit DC and Stepper Motor Hat](https://www.adafruit.com/product/2348) first.

## USB Cable Modification Option

To power the motors, you are going to use 5V directly from the USB Power Bank. While it could be powered from the Pi, the output isn't as high and the motors are noisy which may be heard through the speakers.

For the more compact build option, you will shorten the wiring with the following procedure.

Start with the USB to 2.1mm adapter cable.

![hacks_IMG_4817.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/899/medium640/hacks_IMG_4817.jpeg?1680048992)

Cut the cable with about 6 inches of wire length from the USB plug and strip the ends.

![hacks_IMG_4818.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/900/medium640/hacks_IMG_4818.jpeg?1680049464)

For a better connection, crimp some wire ferrules to the ends.

![hacks_IMG_4819.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/901/medium640/hacks_IMG_4819.jpeg?1680049533)

The side with the white stripes is the negative side.

![hacks_IMG_4820.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/966/medium640/hacks_IMG_4820.jpeg?1680197514)

## USB Cable Adapter Option

For the easier build option, you can create a little adapter for the USB cable. This method is less compact, but non-destructive.

For this you will need:

1 x USB to 2.1mm adapter cable

1 x Female DC Power Adapter

2 x Jumper Wires

&nbsp;

![hacks_IMG_4873.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/973/medium640/hacks_IMG_4873.jpeg?1680211319)

Install the jumper wires in the female DC power adapter. It's a good idea to use different colors so it's easier to tell which side is positive and which side is negative.

![hacks_IMG_4874.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/974/medium640/hacks_IMG_4874.jpeg?1680211428)

Just plug the cable into the DC power adapter and you're done.

![hacks_IMG_4876.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/976/medium640/hacks_IMG_4876.jpeg?1680211589)

## Foot Button Connection

You will want to connect the other half of the JST SM connection pair to the Motor HAT. If you are soldering the white wires directly to the HAT, you should have already prepared them in the **Modifying the Bear** step.

Prepare the receptacle half of the connection by stripping and tinning the wires.

![hacks_IMG_4816.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/917/medium640/hacks_IMG_4816.jpeg?1680104343)

Solder the wires on the **GPIO #16** and one of the **GND** pads on the DC Motor HAT.

![hacks_IMG_4815.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/918/medium640/hacks_IMG_4815.jpeg?1680104595)

![hacks_IMG_4815_Closeup.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/919/medium640/hacks_IMG_4815_Closeup.jpeg?1680104723)

## MAX98357 I2S Amplifier

Because the project is using a 3W amplifier with a 0.25W or 0.5W speaker, it's a good idea to reduce the gain as much as possible because too much can actually heat the speaker coil to the point of melting the speaker cone. This can be accomplished by connecting a 100K resistor between Gain and Vin.

Prepare a 4-inch wire by cutting and stripping it. You can just use one of the jumper wires with both ends cut off if you don't have extra wire. You will also need a 100K resistor and the MAX98357 with only the terminal soldered on. Optionally, you could just solder the speaker directly to the MAX98357 instead of using the terminal.

![hacks_IMG_4822.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/922/medium640/hacks_IMG_4822.jpeg?1680113628)

Start by soldering the wire to the **Vin** pin on the MAX98357

![hacks_Red_Wire_Only.jpg](https://cdn-learn.adafruit.com/assets/assets/000/119/927/medium640/hacks_Red_Wire_Only.jpg?1680115105)

Next, take the resistor and fold the leads down at a 90 degree angle so that they are parallel to each other.

About 5mm further down from the resistor, add a 90 degree bend in the leads keeping them parallel. Cut one side of the resistor so that the cut side touches the underside of the **Vin** wire and the remaining lead can be soldered to **Gain** pin.

![hacks_IMG_4823.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/923/medium640/hacks_IMG_4823.jpeg?1680113812)

![hacks_IMG_4825.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/924/medium640/hacks_IMG_4825.jpeg?1680113824)

![hacks_IMG_4826.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/925/medium640/hacks_IMG_4826.jpeg?1680113836)

![hacks_IMG_4827.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/926/medium640/hacks_IMG_4827.jpeg?1680114026)

Prepare four more wires so that they are about the same length as the first wire.

![hacks_IMG_4831.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/930/medium640/hacks_IMG_4831.jpeg?1680115431)

Solder these wires to the **LRC** , **BCLK** , **DIN** , and **GND** pins of the MAX98357.

![hacks_IMG_4832.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/931/medium640/hacks_IMG_4832.jpeg?1680115484)

Solder the remaining connections according the **Circuit Diagram** page of this guide.

That's it! Everything should now be ready for assembly.

![hacks_IMG_4833.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/932/medium640/hacks_IMG_4833.jpeg?1680115598)

# Robotic AI Bear using ChatGPT

## Raspberry Pi Setup

## Install Raspberry Pi OS 64-bit Lite

For the bear, you will need the 64-bit version of Bookworm Raspberry Pi OS Lite because the OpenAI libraries will only install on that version. Since the project uses a voice interface, a desktop isn't required. You can refer to the [CircuitPython Libraries on Linux and Raspberry Pi](https://learn.adafruit.com/circuitpython-on-raspberrypi-linux) guide for more help setting it up.

Once you have everything set up, you will need to open a terminal and install Blinka. Refer to the [Installing CircuitPython Libraries on Raspberry Pi](https://learn.adafruit.com/circuitpython-on-raspberrypi-linux/installing-circuitpython-on-raspberry-pi) page to quickly get up and running.

Warning: 

## Audio System and Drivers

Before you can configure the audio devices, you will need to install some additional audio libraries:

```terminal
sudo apt install libpulse-dev pulseaudio apulse
```

Sometimes these installations create default incompatible configuration files that cause errors. These configuration files are not necessary for the audio system to run. Run the following to remove any existing sound configuration files:

```terminal
rm ~/.asoundrc
sudo rm /etc/asound.conf
```

## I2S Audio Setup for Compact Build Option

If you installed the MAX98357, you will need to install some software to use it. Follow the [Raspberry Pi Setup](https://learn.adafruit.com/adafruit-max98357-i2s-class-d-mono-amp/raspberry-pi-usage) instructions from the [Adafruit MAX98357 guide](https://learn.adafruit.com/adafruit-max98357-i2s-class-d-mono-amp).

Afterwards follow the [Raspberry Pi Test](https://learn.adafruit.com/adafruit-max98357-i2s-class-d-mono-amp/raspberry-pi-test) procedure to make sure sound is playing.

## USB Audio Selection for Easier Build Option

If you went with the easier build option, most likely it will just work without any changes. If not, you can tell the system which audio device to use by typing:

```terminal
sudo raspi-config
```

Select **System Options** → **Audio**. Make sure **USB Audio** is selected and then tab over to **Ok** to select it. After that, you can exit to the command line and that's it.

![hacks_Screen_Shot_2023-03-31_at_10.20.30_AM.png](https://cdn-learn.adafruit.com/assets/assets/000/120/005/medium640/hacks_Screen_Shot_2023-03-31_at_10.20.30_AM.png?1680283535)

The volume can be adjusted by running:

```terminal
alsamixer
```

You can just adjust the **Master Volume** or if you want to adjust for the speaker only, you can press **F6** and choose **UACDemoV1.0** from the device list.

![hacks_Screen_Shot_2023-03-31_at_11.19.37_AM.png](https://cdn-learn.adafruit.com/assets/assets/000/120/007/medium640/hacks_Screen_Shot_2023-03-31_at_11.19.37_AM.png?1680286795)

## Install Required Libraries

You will need to have a few libraries installed before the script will run on your computer.&nbsp; Make sure your **venv** is active and start with some prerequisite libraries:

```terminal
sudo apt install python3-pyaudio build-essential libssl-dev libasound2 wget libssl1.1
pip3 install SpeechRecognition
```

Next install the MotorKit CircuitPython library:

```terminal
pip3 install adafruit-circuitpython-motorkit
```

Next install the OpenAI library:

```terminal
pip3 install --upgrade openai
```

Install the Azure Speech Services library:

```terminal
pip3 install --upgrade azure-cognitiveservices-speech
```

Finally, download the **keys.txt** file for adding your keys to:

```terminal
cd ~
wget https://github.com/adafruit/Adafruit_Learning_System_Guides/raw/main/ChatGPT_Bear/keys.txt
```

# Robotic AI Bear using ChatGPT

## Create an Account with OpenAI

Info: 

In your web browser, visit [https://platform.openai.com/](https://platform.openai.com/)

Click the "sign up" link. Then, you can use your e-mail to sign up, or an existing Google or Microsoft account.

OpenAI may require additional steps such as e-mail or phone verification before you can log in to your account.

![circuitpython_Screenshot_2023-03-08_08-43-40.png](https://cdn-learn.adafruit.com/assets/assets/000/119/295/medium640/circuitpython_Screenshot_2023-03-08_08-43-40.png?1678286661)

Once you have completed the verification process and logged in, you will next create an API key. Use the menu in the far upper right corner (probably labeled "Personal") and then select "View API Keys".

![circuitpython_ksnip_20230308-084810.png](https://cdn-learn.adafruit.com/assets/assets/000/119/296/medium640/circuitpython_ksnip_20230308-084810.png?1678286921)

Then, create a fresh API key by clicking "Create new secret key".

![circuitpython_ksnip_20230308-084917.png](https://cdn-learn.adafruit.com/assets/assets/000/119/298/medium640/circuitpython_ksnip_20230308-084917.png?1678287073)

Add this secret key to the `keys.txt` file you downloaded in the Raspberry Pi Setup step. From the command line, you can open it in your favorite editor and change the value so it reads something like:

```
OPENAI\_API\_KEY = sk-b6j4FFt78209dkifJhld783GtkP5
```

&nbsp;

![circuitpython_ksnip_20230308-084955.png](https://cdn-learn.adafruit.com/assets/assets/000/119/299/medium640/circuitpython_ksnip_20230308-084955.png?1678287111)

At the time of writing, OpenAI provides a free credit with new accounts. After the free credit is used or expires, you'll need to enter a credit card in your billing information to keep using the service.

Using the project tends to cost a few cents per session at most, and it's easy to limit your monthly bill to a pre-set amount such as $8.00.

To set a hard usage limit per month, visit the "Usage Limits" section of the OpenAI website.

![circuitpython_ksnip_20230310-085720.png](https://cdn-learn.adafruit.com/assets/assets/000/119/338/medium640/circuitpython_ksnip_20230310-085720.png?1678460269)

![circuitpython_ksnip_20230310-085702.png](https://cdn-learn.adafruit.com/assets/assets/000/119/339/medium640/circuitpython_ksnip_20230310-085702.png?1678460280)

# Robotic AI Bear using ChatGPT

## Create an Account with Azure

Info: 

In your web browser, visit [https://azure.microsoft.com/](https://azure.microsoft.com/)

Click the **Free account** link at the top, then click the **Start free** &nbsp;button. Then, you can use your e-mail to sign up, or sign into an existing Microsoft account.

Microsoft may require additional steps such as e-mail&nbsp; verification before you can log in to your account.

![hacks_Screen_Shot_2023-03-31_at_12.09.03_PM.png](https://cdn-learn.adafruit.com/assets/assets/000/120/009/medium640/hacks_Screen_Shot_2023-03-31_at_12.09.03_PM.png?1680289892)

![hacks_Screen_Shot_2023-03-31_at_12.12.09_PM.png](https://cdn-learn.adafruit.com/assets/assets/000/120/010/medium640/hacks_Screen_Shot_2023-03-31_at_12.12.09_PM.png?1680289961)

Once you have completed the verification process and are logged in, go to the [Speech Services](https://portal.azure.com/#create/Microsoft.CognitiveServicesSpeechServices) section under AI + Machine Learning to create a Speech Service resource.

You will likely need to create a new Resource group. For the Instance Details, create a unique name. You can just choose a name you like and add some random numbers to the end. For Pricing Tier, there's only one choice since it's a free account.

Click **Review and Create** at the bottom.

![hacks_Screen_Shot_2023-03-31_at_1.12.25_PM.png](https://cdn-learn.adafruit.com/assets/assets/000/120/015/medium640/hacks_Screen_Shot_2023-03-31_at_1.12.25_PM.png?1680293685)

Review your settings and click **Create**.

![hacks_Screen_Shot_2023-03-31_at_1_25_47_PM.jpg](https://cdn-learn.adafruit.com/assets/assets/000/120/021/medium640/hacks_Screen_Shot_2023-03-31_at_1_25_47_PM.jpg?1680294485)

Once it is created, click the **Go to resource** Button.

![hacks_Screen_Shot_2023-03-31_at_1_29_21_PM.jpg](https://cdn-learn.adafruit.com/assets/assets/000/120/023/medium640/hacks_Screen_Shot_2023-03-31_at_1_29_21_PM.jpg?1680294690)

Under overview, click the **copy button** on **Key 1** to copy it to your clipboard. You can click the **Show Keys** button as well if you want to view it.

Add this secret key to the `keys.txt` file you downloaded in the Raspberry Pi Setup step. From the command line, you can open it in your favorite editor and change the value so it reads something like:

```
SPEECH\_KEY = 4f1d576925be89abegfcb584fbac02a9
SPEECH\_REGION = eastus
```
![hacks_Screen_Shot_2023-03-31_at_1_32_57_PM.jpg](https://cdn-learn.adafruit.com/assets/assets/000/120/025/medium640/hacks_Screen_Shot_2023-03-31_at_1_32_57_PM.jpg?1680294948)

## Using a Different Voice

Azure Speech Services includes a number of different voices. In their Voice Gallery, you can listen to the different voices and get the Voice Name to change in your code.

Click the **Go to speech Studio** button.

![hacks_speech_studio.jpg](https://cdn-learn.adafruit.com/assets/assets/000/120/027/medium640/hacks_speech_studio.jpg?1680297236)

Under **Text-to-speech** , click **Voice Gallery**.

![hacks_Screen_Shot_2023-03-31_at_2.13.28_PM.png](https://cdn-learn.adafruit.com/assets/assets/000/120/028/medium640/hacks_Screen_Shot_2023-03-31_at_2.13.28_PM.png?1680297310)

You can listen to the different voices. Once you find one that you are happy with, select Sample code and change to Python.

Look for the value of `speech_config.speech_synthesis_voice_name `

It should be something like **en-US-GuyNeural**. You can change this in your code later.

![hacks_Screen_Shot_2023-03-31_at_2_18_30_PM.jpg](https://cdn-learn.adafruit.com/assets/assets/000/120/029/medium640/hacks_Screen_Shot_2023-03-31_at_2_18_30_PM.jpg?1680297619)

# Robotic AI Bear using ChatGPT

## Code the Bear

This is the code that will run on the bear. Since the API keys are stored in your environment variables, there's no need to modify the code.

https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/ChatGPT_Bear/assistant.py

## Downloading the Code

To download the code onto your Pi, just run the following to download:

```terminal
cd ~
wget https://raw.githubusercontent.com/adafruit/Adafruit_Learning_System_Guides/main/ChatGPT_Bear/assistant.py
```

## How the Python Code Works

This is an overview about how the code works. It's mostly a combination of code to interface between:

- Azure Speech Services API
- OpenAI ChatGPT API
- OpenAI Whisper API
- SpeechRecognition Library
- CircuitPython Motor Library

The code uses threading and events in order to be able to move the mouth motors at the same time the audio output from the Azure Speech Services is playing.

### Parameters

The code starts out with a number of parameters that can be altered. Here are the main parameters that you might want to change:

- The `SYSTEM_ROLE` parameter is a description to ChatGPT about how it should act.
- The `CHATGPT_MODEL` and `WHISPER_MODEL` parameters can be updated as newer versions of the API become available.
- The `AZURE_SPEECH_VOICE` is the voice name that can be altered to change how the bear sounds. See the **Create an account with Azure** page for more details on selecting a different voice in Azure Speech Services.
- The `RECORD_TIMEOUT` is the amount of time in seconds that the bear will listen after pushing the button on the foot.
- The `DEVICE_ID` is for specifying the ID of a particular Audio Output Device. See the **Troubleshooting** section on the **Usage** page of this guide to find the right value. Leaving it set to `None` will try and use the system default device.

The remaining parameters have already been tuned pretty well, but you are welcome to experiment with them.

```python
# ChatGPT Parameters
SYSTEM_ROLE = (
    "You are a helpful voice assistant in the form of a talking teddy bear"
    " that answers questions and gives information"
)
CHATGPT_MODEL = "gpt-3.5-turbo"
WHISPER_MODEL = "whisper-1"

# Azure Parameters
AZURE_SPEECH_VOICE = "en-GB-OliverNeural"
DEVICE_ID = None

# Speech Recognition Parameters
ENERGY_THRESHOLD = 1000  # Energy level for mic to detect
PHRASE_TIMEOUT = 3.0  # Space between recordings for sepating phrases
RECORD_TIMEOUT = 30

# Motor Parameters
ARM_MOVEMENT_TIME = 0.5
BASE_MOUTH_DURATION = 0.2  # A higher number means slower mouth movement
SPEECH_VARIANCE = 0.1  # Higher allows more mouth movement variance.
                       # It pauses for BASE_MOUTH_DURATION ± SPEECH_VARIANCE
MOTOR_DUTY_CYCLE = 1.0  # Lower provides less power to the motors
```

### Initialization

Grab the API parameters from the keys.txt file and create the speech configuration.

```python
# Do some checks and Import API keys from API_KEYS_FILE
config = configparser.ConfigParser()

username = os.environ["USER"]
user_homedir = os.path.expanduser(f"~{username}")
API_KEYS_FILE = API_KEYS_FILE.replace("~", user_homedir)

def get_config_value(section, key, min_length=None):
    if not config.has_section(section):
        print("Please make sure API_KEYS_FILE points to "
              f"a valid file and has an [{section}] section.")
        sys.exit(1)
    if key not in config[section]:
        print(
            f"Please make sure your API keys file contains an {key} under the {section} section."
        )
        sys.exit(1)
    value = config[section][key]
    if min_length and len(value) &lt; min_length:
        print(f"Please set {key} in your API keys file with a valid key.")
        sys.exit(1)
    return config[section][key]

print(os.path.expanduser(API_KEYS_FILE))
config.read(os.path.expanduser(API_KEYS_FILE))
openai = OpenAI(
    # This is the default and can be omitted
    api_key=get_config_value("openai", "OPENAI_API_KEY", 10)
)

speech_key = get_config_value("azure", "SPEECH_KEY", 15)
service_region = get_config_value("azure", "SPEECH_REGION")

speech_config = speechsdk.SpeechConfig(subscription=speech_key, region=service_region)
speech_config.speech_synthesis_voice_name = AZURE_SPEECH_VOICE
```

### OpenAI API Interface Helpers

The `sendchat` and `transcribe` functions are for packaging and sending data to the **ChatGPT** and **Whisper** APIs respectively.

```python
def sendchat(prompt):
    response = ""
    stream = openai.chat.completions.create(
        model=CHATGPT_MODEL,
        messages=[
            {"role": "system", "content": SYSTEM_ROLE},
            {"role": "user", "content": prompt},
        ],
        stream=True,
    )
    # Send the heard text to ChatGPT and return the result
    for chunk in stream:
        if chunk.choices[0].delta.content is not None:
            response += chunk.choices[0].delta.content

    # Send the heard text to ChatGPT and return the result
    return response


def transcribe(wav_data):
    # Read the transcription.
    print("Transcribing...")
    attempts = 0
    while attempts &lt; 3:
        try:
            with NamedTemporaryFile(suffix=".wav") as temp_file:
                result = openai.Audio.translate_raw(
                    WHISPER_MODEL, wav_data, temp_file.name
                )
                return result["text"].strip()
        except (openai.error.ServiceUnavailableError, openai.error.APIError):
            time.sleep(3)
        attempts += 1
    return "I wasn't able to understand you. Please repeat that."
```

### The Listener Class

The `Listener` class is now in its own file and interfaces with the SpeechRecognition library to handle listening for speech and returning the prepared audio data.

https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/ChatGPT_Bear/listener.py

### The Bear Class

The `Bear` class initializes and sets up the motors and button. It handles the timing of the motors and the speech synthesis.

One interesting function inside of this class is the `move_mouth` function which is threaded. It is in a constant loop and will constantly move the mouth while the `do_mouth_movement` variable is true. This makes turning the mouth movement on and off very easy.

In the initialization, there are also a couple of events that are triggered by the Azure Speech Services API to time the mouth movement to the speech much better. The way these events are set up is by using the `connect` function and passing in the function that will be called when triggered.

```python
class Bear:
    def __init__(self, azure_speech_config):
        kit = MotorKit(i2c=board.I2C())
        self._arms_motor = kit.motor1
        self._mouth_motor = kit.motor2

        # Setup Foot Button
        self._foot_button = digitalio.DigitalInOut(board.D16)
        self._foot_button.direction = digitalio.Direction.INPUT
        self._foot_button.pull = digitalio.Pull.UP

        self.do_mouth_movement = False
        self._mouth_thread = threading.Thread(target=self.move_mouth, daemon=True)
        self._mouth_thread.start()
        if DEVICE_ID is None:
            audio_config = speechsdk.audio.AudioOutputConfig(use_default_speaker=True)
        else:
            audio_config = speechsdk.audio.AudioOutputConfig(device_name=DEVICE_ID)
        self._speech_synthesizer = speechsdk.SpeechSynthesizer(
            speech_config=azure_speech_config, audio_config=audio_config
        )

        self._speech_synthesizer.synthesizing.connect(self.start_moving_mouth)
        self._speech_synthesizer.synthesis_completed.connect(self.stop_moving_mouth)

    def start_moving_mouth(self, _event):
        self.do_mouth_movement = True

    def stop_moving_mouth(self, _event):
        self.do_mouth_movement = False

    def deinit(self):
        self.do_mouth_movement = False
        self._mouth_thread.join()
        self._arms_motor.throttle = None
        self._mouth_motor.throttle = None
        self._speech_synthesizer.synthesis_started.disconnect_all()
        self._speech_synthesizer.synthesis_completed.disconnect_all()

    def _move_arms_motor(self, dir_up=True):
        direction = -1 if dir_up else 1
        self._arms_motor.throttle = MOTOR_DUTY_CYCLE * direction
        time.sleep(ARM_MOVEMENT_TIME)
        # Remove Power from the motor to avoid overheating
        self._arms_motor.throttle = None

    def _move_mouth_motor(self, dir_open=True):
        duration = (
            BASE_MOUTH_DURATION
            + random.random() * SPEECH_VARIANCE
            - (SPEECH_VARIANCE / 2)
        )
        # Only power the motor while opening and let the spring close it
        self._mouth_motor.throttle = MOTOR_DUTY_CYCLE if dir_open else None
        time.sleep(duration)
        # Remove Power from the motor and let close to avoid overheating
        self._mouth_motor.throttle = None

    def foot_pressed(self):
        return not self._foot_button.value

    def move_mouth(self):
        print("Starting mouth movement thread")
        while True:
            if self.do_mouth_movement:
                self._move_mouth_motor(dir_open=True)
                self._move_mouth_motor(dir_open=False)

    def move_arms(self, hide=True):
        self._move_arms_motor(dir_up=hide)

    def speak(self, text):
        result = self._speech_synthesizer.speak_text_async(text).get()

        # Check result
        if result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted:
            print("Speech synthesized for text [{}]".format(text))
        elif result.reason == speechsdk.ResultReason.Canceled:
            cancellation_details = result.cancellation_details
            print("Speech synthesis canceled: {}".format(cancellation_details.reason))
            if cancellation_details.reason == speechsdk.CancellationReason.Error:
                print("Error details: {}".format(cancellation_details.error_details))
```

### The Main Function Loop

The main function starts off by setting up instances of the `Bear` and `Listener` classes. It also sets up a transcript that it maintains throughout interactions. This allows for you to see what is being heard and what the bear is returning in a text format.

The Main Loop waits to the foot to be presses. Once pressed, it listens for up to 30 seconds or until it determines a phase has been spoken. Once it has a phrase, it is processed and the bear moves and responds appropriately.

Once you exit the main loop, a few things are deinitialized in order to free up resources and hardware so that the bear isn't drawing excess power.

```python
def main():
    listener = Listener(openai.api_key, ENERGY_THRESHOLD, RECORD_TIMEOUT)
    bear = Bear(speech_config)

    transcription = [""]
    bear.speak(
        "Hello there! Just give my left foot a squeeze if you would like to get my attention."
    )

    while True:
        try:
            # If button is pressed, start listening
            if bear.foot_pressed():
                bear.speak("How may I help you?")
                listener.listen()

            if listener.speech_waiting():
                bear.speak("Let me think about that")
                bear.move_arms(hide=True)
                text = listener.recognize()

                if text:
                    transcription.append(text)
                    print(f"Phrase Complete. Sent '{text}' to ChatGPT.")
                    chat_response = sendchat(text)
                    transcription.append(f"&gt; {chat_response}")
                    print("Got response from ChatGPT. Beginning speech synthesis.")
                    bear.move_arms(hide=False)
                    bear.speak(chat_response)

                os.system("clear")
                for line in transcription:
                    print(line)
                print("", end="", flush=True)
                time.sleep(0.25)
        except KeyboardInterrupt:
            break
    bear.deinit()
```

# Robotic AI Bear using ChatGPT

## Assembly

![](https://cdn-learn.adafruit.com/assets/assets/000/119/888/medium800thumb/hacks_Case_Assembly_Disassembly.jpg?1680041916)

## Assembly Tool

The headers are much easier to install in the deep case by using a tool. If you have a 5mm Hex Nut Driver, then go ahead and use that. If not, you can make a tool out of a couple of extra nylon threaded standoffs. This tool works by having two standoffs with more friction extend into a third standoff that is being installed.

This tool just uses 2 of the 12mm threaded standoffs.

![hacks_IMG_4837.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/942/medium640/hacks_IMG_4837.jpeg?1680125505)

Start by completely screwing one post into another until you feel some resistance.

![hacks_IMG_4839.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/943/medium640/hacks_IMG_4839.jpeg?1680125542)

Continue tightening about an additional 1/6 turn until and line up the flat edges. Don't over-tighten or the plastic could break off. The idea is to have more friction between these two standoffs than you will have with the standoff you are installing.

![hacks_IMG_4840.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/944/medium640/hacks_IMG_4840.jpeg?1680125603)

To use, just thread the standoff that you are installing onto the threads of the tool you assembled. Just use a minimal amount of friction since you want it to come off of the tool when it's installed.

![hacks_IMG_4853.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/951/medium640/hacks_IMG_4853.jpeg?1680192349)

Screw the standoff into a nut. When it is tight enough, just hold it in place with a finger or flathead screwdriver and unscrew the tool from the installed standoff.

![hacks_IMG_4855.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/952/medium640/hacks_IMG_4855.jpeg?1680194072)

## Case Bottom
Make sure to remove any supports. A small flathead screwdriver or so small needle-nosed pliers should work well.

![hacks_IMG_4835.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/933/medium640/hacks_IMG_4835.jpeg?1680124124)

For the bottom, you'll need this hardware:

- The Case Bottom
- 4 x 12mm nylon M2.5 standoffs
- 4 x nylon M2.5 nuts

![hacks_IMG_4850.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/949/medium640/hacks_IMG_4850.jpeg?1680191934)

Insert the Raspberry Pi 4 in the bottom case. **Make sure you don't have a MicroSD card inserted!** You'll want to have the A/V ports go in first before pushing the other side down so that it is sitting flat.

![hacks_IMG_4852.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/950/medium640/hacks_IMG_4852.jpeg?1680192204)

Place a nut into the hex insert on the bottom of the case.

![hacks_IMG_4854.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/954/medium640/hacks_IMG_4854.jpeg?1680194202)

Install a standoff through the Pi and into the nut you inserted using a tool.

![hacks_IMG_4856.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/953/medium640/hacks_IMG_4856.jpeg?1680194186)

Install standoffs into the remaining corners.

![hacks_IMG_4857.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/955/medium640/hacks_IMG_4857.jpeg?1680194302)

Place the motor HAT onto the Pi. You can use the upper left side of the case (the corner furthest away from any ports) to easily align the GPIO headers.

![hacks_IMG_4858.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/956/medium640/hacks_IMG_4858.jpeg?1680194341)

## Case Top

Speaker and amp installation is only required if you are doing the compact build option.

For the top, you'll need this hardware:

- The Case Top
- 2 x Speaker Retainers of the appropriate size
- 4 x 8mm screws you set aside from disassembling the bear

![hacks_IMG_4860.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/957/medium640/hacks_IMG_4860.jpeg?1680194539)

Place the speaker into the speaker holder.

![hacks_IMG_4861.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/958/medium640/hacks_IMG_4861.jpeg?1680194686)

Install the speaker retainers on each side of the speaker using the screws from the bear.

![hacks_IMG_4863.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/959/medium640/hacks_IMG_4863.jpeg?1680196313)

The wires are a bit of a tight fit, so it's easier to install them in the MAX98357 terminal first. Place the wires in the appropriate terminal so that they have enough length once installed.

![hacks_IMG_4865.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/960/medium640/hacks_IMG_4865.jpeg?1680196379)

Once installed, you may need to bend the wires a little to the sides to give them enough room to fit.

![hacks_IMG_4867.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/961/medium640/hacks_IMG_4867.jpeg?1680196454)

Install the MAX98357 using 2 more screws from the bear.

![hacks_IMG_4868.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/962/medium640/hacks_IMG_4868.jpeg?1680196493)

## Final Case Assembly
Place the wiring for the foot in the slot in the case.

![hacks_IMG_4870_2.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/964/medium640/hacks_IMG_4870_2.jpeg?1680196820)

Tie a knot in the wiring close to the case, just on the outside.

![hacks_IMG_4890.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/969/medium640/hacks_IMG_4890.jpeg?1680210963)

Now lift up the wire and place it so the knot so it is on the inside. This will act as a strain relief.

![hacks_IMG_4891.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/970/medium640/hacks_IMG_4891.jpeg?1680211046)

This is a good time to install the wiring for the motor power. On the USB cable, the negative wire is the side with the white stripes. **Be sure to install correctly to avoid any damage.**

![hacks_IMG_4892.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/971/medium640/hacks_IMG_4892.jpeg?1680211129)

If you built an adapter, just use the jumper wires instead.

![hacks_IMG_4877.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/977/medium640/hacks_IMG_4877.jpeg?1680211637)

Install the lid by placing it directly over the case bottom and lowering it. If the strain relief knot is in the way, you can push it in temporarily while placing the lid. It may take a little bit of adjusting if some of the wires are in the way.

![hacks_IMG_4880.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/985/medium640/hacks_IMG_4880.jpeg?1680215351)

You will need four 10mm nylon screws to attach the lid.

![hacks_IMG_4882.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/983/medium640/hacks_IMG_4882.jpeg?1680215182)

Install the screws into the top. Only turn just enough that it feels a little snug. **It's very easy to overturn the screws and break them**.

![hacks_IMG_4884.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/984/medium640/hacks_IMG_4884.jpeg?1680215240)

You may also want to loosen the appropriate screws for the motor wire terminals. However, those can be installed after the case is assembled.

![hacks_IMG_4886.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/972/medium640/hacks_IMG_4886.jpeg?1680211170)

When you connect the wires from the bear, the wire order is important. Install the wires to the M2 and M2 terminals as shown in the photo.

![hacks_IMG_4893_marked.jpg](https://cdn-learn.adafruit.com/assets/assets/000/119/980/medium640/hacks_IMG_4893_marked.jpg?1680212928)

## USB Speaker
If you went with the easier install option, just plug the speaker into one of the USB ports of the Raspberry Pi. We'll show you how to configure it later.

![hacks_IMG_4894.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/986/medium640/hacks_IMG_4894.jpeg?1680219312)

## USB Microphone
Be sure to install the USB microphone.

![hacks_IMG_4895.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/987/medium640/hacks_IMG_4895.jpeg?1680221973)

If you would like to be able to control where the sound is picked up, you could use a simple USB extension cable.

![hacks_IMG_4896.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/988/medium640/hacks_IMG_4896.jpeg?1680219486)

## Power Connections
To power the Raspberry Pi and motors, you'll want the USB power bank along with a short USB cable. If you don't have any extras, you can use the USB cable that came with the power bank.

![hacks_IMG_4897.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/989/medium640/hacks_IMG_4897.jpeg?1680221119)

Connect the USB cable between one port of the power Bank and the Raspberry Pi.

Connect the other USB cable for motor power to the other port.

If the power bank turns on automatically, you can force it back off by double-pressing the power button.

![hacks_IMG_4900.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/119/990/medium640/hacks_IMG_4900.jpeg?1680222092)

## Final Bear Assembly
Remove as much stuffing as you need. Depending on the build options you decided on, you may need to remove a little or a lot of the stuffing from the bear.

![hacks_IMG_4906.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/120/084/medium640/hacks_IMG_4906.jpeg?1680562813)

If you used the external speaker, place it inside the head. Keep taking out stuffing as needed. The fit is a bit tight.

If you placed your microphone on an extension, you will want to place this in the head at the same time. Try and keep it as close to the surface as possible so the stuffing doesn't muffle the sound too much.

Replace some of the stuffing back into the head afterwards until if feels like it is held in place and the head looks normal.&nbsp;

![hacks_IMG_4909.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/120/085/medium640/hacks_IMG_4909.jpeg?1680562836)

Place any excessively long cords into the bear next. Keep the USB plugs that go into the battery accessible.

![hacks_IMG_4910.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/120/086/medium640/hacks_IMG_4910.jpeg?1680562905)

Place the enclosure into the bear next. There's a small hole so you can see the status lights. Having that face down lets you easily know if the Pi is powered up or not. Continue adding stuffing, but leave room for the battery.

![hacks_IMG_4913.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/120/088/medium640/hacks_IMG_4913.jpeg?1680563245)

Place the battery in. Add some more stuffing.&nbsp; Add just enough so the body looks natural. Remember, you will need to remove the battery pack to charge it or turn it off and on.

Be careful of the plugs sticking out of the Pi. It's easy to accidentally break off connectors with everything jammed in so tight.

![hacks_IMG_4914.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/120/089/medium640/hacks_IMG_4914.jpeg?1680563302)

Finally close the flap using the velcro under the tail.

![hacks_IMG_4915.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/120/090/medium640/hacks_IMG_4915.jpeg?1680563355)

Check how well the bear sits. You may need to shift things around a bit or add or remove stuffing if it doesn't look right.

Keep in mind, the speaker in the head can make it a bit top heavy, which can cause it to fall over when the arms move. Try and keep most of the weight a bit lower if possible.

![hacks_IMG_4916.jpeg](https://cdn-learn.adafruit.com/assets/assets/000/120/091/medium640/hacks_IMG_4916.jpeg?1680563452)

# Robotic AI Bear using ChatGPT

## Usage

![](https://cdn-learn.adafruit.com/assets/assets/000/120/094/medium800thumb/hacks_Main_Image_Tighter.jpg?1680622980)

When you are ready to use the bear, open the flap on the bottom and just give it a final check to make sure the battery is charged and you have all of the cables connected. Make sure the battery and Pi are powered on.

Connect to the bear over WiFi using SSH. Once you are logged in, type the following:

```terminal
cd ~
python3 assistant.py
```

The bear should start talking and prompt you to squeeze its foot. Squeeze the foot and then ask it a question or request something.

Here are a few examples of requests to try:

- Tell me a joke
- Tell me a story about a robotic bear
- Tell me a poem about video game characters
- Tell me about CircuitPython

When you are finished. Just press **Control+C** a couple of times. Because of the multi-threading, sometimes it takes a moment to stop.

## Troubleshooting

### No Keys

Make sure you have specified your API keys before running the script. It should let you know if it wasn't able to find those values. Save your values in **keys.txt** , which should reside in your home directory.

### No Audio

If you hear no sound when you run the script, it could be caused by a few things. To begin with, run through the tests specific to the way you set up device.

You can also try running the following command to test the audio:

```terminal
speaker-test
```

If you have verified that sound comes through with speaker-test, you may need to set the `DEVICE_ID`. To determine the Device ID, just run the following command:

```terminal
aplay -L | grep plughw:
```

You should get a list of IDs. that begin with `plughw` like this:

![](https://cdn-learn.adafruit.com/assets/assets/000/120/081/medium800/hacks_Screen_Shot_2023-04-03_at_3.48.49_PM.png?1680562160)

For instance, if you have the USB Speaker, you should see a device like **plughw:CARD=UACDemoV10,DEV=0**. Set the `DEVICE_ID` variable to that value and it should use that.

```python
DEVICE_ID = "plughw:CARD=UACDemoV10,DEV=0"
```

### No Motor Movement

Make sure you are supplying 5-12v power to the power input header on the Motor HAT.


## Featured Products

### Raspberry Pi 4 Model B

[Raspberry Pi 4 Model B](https://www.adafruit.com/product/4297)
The Raspberry Pi 4 Model B is the newest Raspberry Pi computer made, and the Pi Foundation knows you can always make a good thing _better_! And what could make the Pi 4 better than the 3? How about a&nbsp;_faster_ processor, USB 3.0 ports, and updated Gigabit Ethernet chip with...

Out of Stock
[Buy Now](https://www.adafruit.com/product/4297)
[Related Guides to the Product](https://learn.adafruit.com/products/4297/guides)
### Adafruit DC & Stepper Motor HAT for Raspberry Pi - Mini Kit

[Adafruit DC & Stepper Motor HAT for Raspberry Pi - Mini Kit](https://www.adafruit.com/product/2348)
Let your robotic dreams come true with the new DC+Stepper Motor HAT from Adafruit. This Raspberry Pi add-on is perfect for any motion project as it can drive up to 4 DC or 2 Stepper motors with full PWM speed control.

**Raspberry Pi and motors are not included. Works with any and...**

In Stock
[Buy Now](https://www.adafruit.com/product/2348)
[Related Guides to the Product](https://learn.adafruit.com/products/2348/guides)
### Adafruit I2S 3W Class D Amplifier Breakout - MAX98357A

[Adafruit I2S 3W Class D Amplifier Breakout - MAX98357A](https://www.adafruit.com/product/3006)
Listen to this good news - we now have an all in one digital audio amp breakout board that works incredibly well with the&nbsp;[Raspberry Pi](https://www.adafruit.com/category/105)! If you're looking for an easy and low cost way to get your digital sound files...

In Stock
[Buy Now](https://www.adafruit.com/product/3006)
[Related Guides to the Product](https://learn.adafruit.com/products/3006/guides)
### Black Nylon Machine Screw and Stand-off Set – M2.5 Thread

[Black Nylon Machine Screw and Stand-off Set – M2.5 Thread](https://www.adafruit.com/product/3299)
Totaling 380 pieces, this **M2.5 Screw Set** &nbsp;is a must-have for your workstation.&nbsp;You'll have enough screws, nuts, and hex standoffs to fuel your maker tendencies&nbsp;for days on end! M2.5 size screws fit almost all of the Adafruit breakout/dev board mounting holes...

In Stock
[Buy Now](https://www.adafruit.com/product/3299)
[Related Guides to the Product](https://learn.adafruit.com/products/3299/guides)
### Mini USB Microphone

[Mini USB Microphone](https://www.adafruit.com/product/3367)
Hey, listen up! It's the world's smallest USB microphone! OK maybe it's not in the Guinness Record Book, but it is _pretty darn small_! This plug-and-play **Mini USB Microphone** needs no driver, and its USB interface means you can use it with any computer,...

Out of Stock
[Buy Now](https://www.adafruit.com/product/3367)
[Related Guides to the Product](https://learn.adafruit.com/products/3367/guides)
### Aluminum Heat Sink for Raspberry Pi 3 - 14 x 14 x 8mm

[Aluminum Heat Sink for Raspberry Pi 3 - 14 x 14 x 8mm](https://www.adafruit.com/product/3083)
Looking for a nice way to cool down your&nbsp;[Raspberry Pi 3](https://www.adafruit.com/products/3055)? Check out this&nbsp; **14x14x8 Heat Sink!**

This heat sink is made from high quality aluminum and will work perfectly with any&nbsp;<a...></a...>

In Stock
[Buy Now](https://www.adafruit.com/product/3083)
[Related Guides to the Product](https://learn.adafruit.com/products/3083/guides)
### USB to 2.1mm Male Barrel Jack Cable

[USB to 2.1mm Male Barrel Jack Cable](https://www.adafruit.com/product/2697)
There's two standard ways to power electronics - USB or 5.5mm/2.1mm DC barrel jack. This or that! With this **USB to 2.1mm Male Barrel Jack Cable** , you can now power 5V DC powered electronics that have a DC jack from a USB jack with a handy 1 meter long...

Out of Stock
[Buy Now](https://www.adafruit.com/product/2697)
[Related Guides to the Product](https://learn.adafruit.com/products/2697/guides)
### Premium Male/Male Jumper Wires - 20 x 6" (150mm)

[Premium Male/Male Jumper Wires - 20 x 6" (150mm)](https://www.adafruit.com/product/1957)
These Male/Male Jumper Wires are handy for making wire harnesses or jumpering between headers on PCB's. These premium jumper wires are 6" (150mm) long and come in a 'strip' of 20 (2&nbsp;pieces of each of ten rainbow colors). They have 0.1" male header contacts on either...

In Stock
[Buy Now](https://www.adafruit.com/product/1957)
[Related Guides to the Product](https://learn.adafruit.com/products/1957/guides)

## Related Guides

- [Adafruit MAX98357 I2S Class-D Mono Amp](https://learn.adafruit.com/adafruit-max98357-i2s-class-d-mono-amp.md)
- [Magic Band Reader](https://learn.adafruit.com/magic-band-reader.md)
- [Soundboard Speaker for Bikes & Scooters](https://learn.adafruit.com/soundboard-speaker-for-bikes-scooters.md)
- [CircuitPython Powered Sip & Puff with ST LPS33HW Pressure Sensor](https://learn.adafruit.com/st-lps33-and-circuitpython-sip-and-puff.md)
- [Personal and Portable ESP32-S2 Web Server](https://learn.adafruit.com/wordle-personal-esp32-s2-web-server.md)
- [Raspberry Pi Halloween Costume Detector](https://learn.adafruit.com/raspberry-pi-halloween-costume-detector.md)
- [Solderless Robot Toy Xylophone](https://learn.adafruit.com/solderless-robot-toy-xylophone.md)
- [reef-pi Guide 2: Power Controller](https://learn.adafruit.com/reef-pi-power-controller.md)
- [Bluefruit Ouija Board](https://learn.adafruit.com/bluefruit-ouija-board.md)
- [Adafruit DC and Stepper Motor HAT for Raspberry Pi](https://learn.adafruit.com/adafruit-dc-and-stepper-motor-hat-for-raspberry-pi.md)
- [Walkmp3rson: Personal MP3 'Tape' Player](https://learn.adafruit.com/walkmp3rson-personal-mp3-tape-player.md)
- [CircuitPython Trombone Champ Controller](https://learn.adafruit.com/circuitpython-trombone-champ-controller.md)
- [Stepper Motor Turntable](https://learn.adafruit.com/stepper-motor-turntable.md)
- [Animating Animatronics](https://learn.adafruit.com/animating-animatronics.md)
- [New Years Eve Ball Drop](https://learn.adafruit.com/new-years-eve-ball-drop.md)
- [Light Up Prop with Prop-Maker](https://learn.adafruit.com/prop-maker-light-wand.md)
