Call OpenAI Models on Amazon Bedrock
Use Python and the OpenAI SDK to call GPT models through Amazon Bedrock.
Introduction
30 Second Summary
AI assistants are everywhere now. They answer questions, write emails, and explain code. But how do you actually connect to one from your own computer and make it do what you want?
In this project, you will build a Python script that sends prompts to OpenAI's GPT-5.6 Luna model through Amazon Bedrock and prints back AI-generated responses. Then you will upgrade it into a code explainer tool that breaks down any snippet into plain English.
What You'll Build
You type a question into your terminal, hit Enter, and within seconds a frontier AI model sends back a thoughtful answer. Then you paste in a chunk of code you don't understand and it explains every line like a patient tutor.
By the end of this project, you'll have:
- A working terminal AI tool where you type any question and get an AI response back in seconds.
- A multi-turn conversation where the AI remembers what you said earlier and responds in context.
- A code explainer that takes any snippet (Python, JavaScript, HTML) and returns a plain-English breakdown of what each line does.
- Secret Mission: Add a model switcher that compares responses from GPT-5.6 Luna and GPT-5.6 Terra side by side.
Are there any prerequisites?
None. This guide walks you through setting up every tool from scratch, including Python, VS Code, and your AWS account. If you can type in a terminal, you are ready to start.
Before We Start
Before We Start...
Before we dive in, let's lock in what you're about to build and why it matters.
Set Up Your Tools
Every piece of this project connects back to three tools. Python runs your scripts. VS Code lets you write and edit them. An AWS account gives you access to the AI models on Amazon Bedrock.
In this step, you'll install all three and verify they work. Once everything is in place, you'll be ready to generate your API key and start talking to an AI model.
In this step, get ready to:
- Install Python and VS Code on your machine.
- Create a free AWS account.
- Install the OpenAI Python SDK.
Install Python and VS Code
Python is the programming language you'll use to write every script in this project. VS Code is a free code editor that makes writing Python easy with syntax highlighting and a built-in terminal.
First, let's check whether Python is already on your machine.
- Press Cmd+Space (macOS) or the Windows key (Windows) to open your search bar.
- Type Terminal (macOS) or Command Prompt (Windows) and press Enter to open it.
- Check your Python version by running this command:
python --version
On macOS, use python3
If python --version does not work on macOS, try python3 --version instead. macOS often uses python3 as the command name.
✔️ I see version 3.7 or higher
Python is ready to go. Skip ahead to installing VS Code below.
ⓧ I see an older version
You have Python installed, but it is too old for the OpenAI SDK. You need version 3.7 or higher.
- Go to python.org/downloads in your browser.
- Click the large Download Python button at the top of the page.
- Run the installer. On Windows, check the box labeled Add python.exe to PATH before clicking Install Now.
- After installation completes, close your terminal and open a new one.
- Run python --version again to confirm you see 3.7 or higher.
ⓧ Command not found
Python is not installed yet. Let's install it now.
- Go to python.org/downloads in your browser.
- Click the large Download Python button at the top of the page. This downloads the latest version.
- Run the downloaded installer.
- On Windows: check the box labeled Add python.exe to PATH at the bottom of the installer window, then click Install Now.
- On macOS: double-click the .pkg file and follow the prompts. Python will be added to your PATH automatically.
- After installation completes, close your terminal and open a new one.
- Run python --version (or python3 --version on macOS) to confirm you see a version number 3.7 or higher.
Still seeing command not found after installing?
On Windows, the most common cause is missing the Add python.exe to PATH checkbox. Uninstall Python from Add or Remove Programs, reinstall it, and make sure to check that box. Then open a brand new terminal window.
On macOS, try typing python3 --version instead of python --version. macOS installs Python under the python3 command.
Help me fix my Python installation
Now let's install VS Code, the editor you'll use to write your Python scripts.
- Go to code.visualstudio.com in your browser.
- Click the Download button for your operating system (macOS or Windows).
- Run the downloaded installer and follow the prompts to complete installation.
- Press Cmd+Space (macOS) or the Windows key (Windows) to open your search bar.
- Type Visual Studio Code and press Enter to open it.
You should see the VS Code welcome screen. This confirms the editor is installed and ready.
Create your AWS account
Amazon Bedrock lives inside AWS. You need an AWS account to access it.
- Go to aws.amazon.com in your browser.
- Click Create an AWS Account in the top right corner.
- Enter your email address and choose an account name.
- Follow the sign-up flow. You'll need to provide a credit card for identity verification.
- Select the Basic support - Free plan when prompted.
- Once sign-up is complete, sign in to the AWS Management Console.
You should see the AWS Console home page with a search bar at the top. This confirms your account is active.
Will I be charged?
AWS requires a credit card to verify your identity, but creating the account itself is free. In this project, you will use Amazon Bedrock on a pay-per-token basis. The total cost for all the prompts you'll send is well under $0.10.
Install the OpenAI Python SDK
The OpenAI Python SDK is the library your scripts will use to talk to Amazon Bedrock. Bedrock uses the same API format as OpenAI, so you install the standard OpenAI package.
- Switch back to your terminal (the same one you used for the Python version check).
- Install the OpenAI SDK by running this command:
pip install openai
Use pip3 on macOS
If pip is not recognized on macOS, try pip3 install openai instead. This matches the python3 command name.
You should see output ending with a line that says Successfully installed openai-... along with its dependencies. This confirms the SDK is ready.
Seeing a permission error?
If you see a permissions error on macOS or Linux, try running the command with the --user flag:
pip install openai --user
On Windows, make sure you are running Command Prompt (not PowerShell) and that you installed Python with the Add python.exe to PATH option checked.
Help me fix my pip installation
Your workstation is fully set up. You have Python, VS Code, an AWS account, and the OpenAI SDK installed. Next up, you'll generate the API key that lets your scripts authenticate with Amazon Bedrock.
Get Your Bedrock API Key
Your tools are installed and your AWS account is ready. Now you need a way to prove your identity to Amazon Bedrock so it knows who is sending requests.
An API key is like a password for your code. Without one, Bedrock rejects every request. In this step, you will generate your key and store it as an environment variable so your Python scripts can use it automatically.
In this step, get ready to:
- Sign in to AWS and open the Amazon Bedrock console.
- Generate a long-term API key with a 30-day expiration.
- Store the key and base URL as environment variables on your machine.
Sign in to AWS and open the Bedrock console
You need to reach the API keys page inside the Amazon Bedrock console. The models you will use are hosted in the US East (N. Virginia) region, so you must switch to that region first.
- Open your browser and go to https://console.aws.amazon.com.
- Sign in with the email and password you used when creating your AWS account.
- In the search bar at the top of the console, type Bedrock and select Amazon Bedrock from the results.
- Look at the region selector in the top-right corner of the console. If it does not already say US East (N. Virginia), click the dropdown and select US East (N. Virginia).
Why US East (N. Virginia)?
GPT-5.6 Luna is available in US East (N. Virginia), US East (Ohio), and US West (Oregon). Picking the correct region ensures the model is accessible when you send requests later.
Generate a long-term API key
A long-term key lasts 30 days and gives your scripts permission to call any model in Bedrock's catalog. AWS automatically creates an IAM user behind the scenes and attaches the AmazonBedrockLimitedAccess policy to it.
- In the left navigation pane of the Bedrock console, click API keys.
- Click the Long-term API keys tab.
- Click Generate long-term API keys.
- In the expiration section, select 30 days.
- Click Generate.
Copy your key immediately
The key is only displayed once. Copy it now and paste it somewhere safe (a text file, a password manager, or a note on your desk). If you close this dialog without copying, you will need to generate a new key.
- Click the copy icon next to your generated key to copy it to your clipboard.
- Paste the key into a temporary text file or note so you do not lose it.
What is a long-term API key?
When you generate a long-term key, Bedrock creates an IAM user on your behalf and attaches a managed policy that grants access to core Bedrock operations. You do not need to configure IAM manually.
The key expires after 30 days, at which point you can generate a fresh one by following the same steps.
Store the key as an environment variable
Your Python scripts will read the API key from an environment variable instead of having the key pasted directly in your code. This keeps secrets out of your source files.
You need to set two variables: one for the key itself, and one for the Bedrock endpoint URL that tells the OpenAI SDK where to send requests.
Windows
- Switch to your terminal in VS Code.
- Set both environment variables by running these commands (replace your-key-here with the key you just copied):
setx OPENAI_API_KEY "your-key-here"
setx OPENAI_BASE_URL "https://bedrock-mantle.us-east-1.api.aws/openai/v1"
What do these commands do?
- setx OPENAI_API_KEY permanently saves your Bedrock API key so any program on your machine can read it.
- setx OPENAI_BASE_URL tells the OpenAI SDK to send requests to Bedrock's endpoint instead of OpenAI's servers.
You must open a new terminal
The setx command saves the variable permanently, but the current terminal window cannot see it yet. Close your terminal and open a new one before continuing.
- Close your current terminal window.
- Open a new terminal in VS Code by clicking Terminal in the top menu, then New Terminal.
macOS
- Switch to your terminal in VS Code.
- Add both environment variables to your shell config and reload it by running these commands (replace your-key-here with the key you just copied):
echo 'export OPENAI_API_KEY="your-key-here"' >> ~/.zshrc
echo 'export OPENAI_BASE_URL="https://bedrock-mantle.us-east-1.api.aws/openai/v1"' >> ~/.zshrc
source ~/.zshrc
What do these commands do?
- The first two lines append export statements to your ~/.zshrc file so the variables persist across terminal sessions.
- source ~/.zshrc reloads your shell config so the variables are available immediately without restarting your terminal.
Before you verify, think about what you expect to see. If the variable was stored correctly, what should printing it return?
Windows
- Confirm the variable is set by running this in your new terminal:
echo %OPENAI_API_KEY%
macOS
- Confirm the variable is set by running:
echo $OPENAI_API_KEY
You should see the long string of characters you copied from the Bedrock console printed back in your terminal. If you see a blank line or the literal text %OPENAI_API_KEY%, the variable was not saved correctly.
Seeing a blank line or the variable name echoed back?
- Windows: make sure you opened a new terminal after running setx. The old terminal cannot see the new variable.
- macOS: make sure you ran source ~/.zshrc after adding the exports. Without it, the current session does not reload the file.
- Double-check that you replaced your-key-here with your actual key (the long string from the Bedrock console, not the placeholder text).
Still stuck? Help me troubleshoot why my environment variable is not showing up.
Your key is live and your machine knows how to find Bedrock. Next up, you will write your first Python script and send a real prompt to GPT-5.6 Luna.
Send Your First Prompt
Your API key is generated and your environment variables are set. Everything is in place to talk to an AI model.
In this step, you'll write a short Python script that sends a question to GPT-5.6 Luna through Amazon Bedrock using the Responses API. One successful response proves your entire pipeline is wired correctly: your code, your key, and your connection to the model.
In this step, get ready to:
- Create a Python script that calls GPT-5.6 Luna through Amazon Bedrock.
- Run the script and read your first AI-generated response.
- Intentionally break and fix the script to understand error messages.
Create your project folder
You need a dedicated folder to keep your Python scripts organized. You'll create one on your Desktop so it's easy to find.
- In VS Code, open the integrated terminal by pressing Ctrl+` (the backtick key, above Tab on your keyboard).
- Move to your Desktop by running this command:
cd ~/Desktop
- Create your project folder and move into it by running these commands:
mkdir bedrock-project
cd bedrock-project
Getting a 'cannot find path' error on Windows?
If cd ~/Desktop does not work, your terminal may be using Command Prompt instead of PowerShell. Try cd %USERPROFILE%\Desktop instead. Or switch to PowerShell by clicking the dropdown arrow in the terminal panel and selecting PowerShell.
help me switch my VS Code terminal to PowerShell
Write the chat script
Your script will use the OpenAI Python SDK to connect to Amazon Bedrock and send a prompt to GPT-5.6 Luna. The SDK reads your environment variables automatically to authenticate.
- Create a new file by pressing Cmd+N (macOS) or Ctrl+N (Windows).
- Save it immediately with Cmd+S (macOS) or Ctrl+S (Windows). Navigate to the bedrock-project folder on your Desktop and name the file chat.py.
- Copy the following code into chat.py:
import os
from openai import OpenAI
# Create a client that connects to Amazon Bedrock
client = OpenAI(
api_key=os.environ.get("OPENAI_API_KEY"),
base_url=os.environ.get("OPENAI_BASE_URL")
)
# Send a prompt to GPT-5.6 Luna and store the response
response = client.responses.create(
model="openai.gpt-5.6-luna",
input="What is Amazon Bedrock and why do companies use it?"
)
# Print the AI's answer
print(response.output_text)
What does this code do?
- os.environ.get("OPENAI_API_KEY") reads the API key you saved as an environment variable in the previous step. This keeps your key out of the code itself.
- OpenAI(...) creates a client that knows how to talk to Amazon Bedrock. The base_url tells it to send requests to Bedrock's endpoint instead of OpenAI directly.
- client.responses.create(...) sends your prompt to the model and waits for a response. The model parameter specifies which AI model answers your question.
- response.output_text extracts just the text of the AI's answer from the full response object.
- Save chat.py with Cmd+S (macOS) or Ctrl+S (Windows).
Run the script and see the response
Before you run this, what do you think will happen? Will you see an error, or will the AI respond with a real answer about Amazon Bedrock?
- Run your script by entering this command in the terminal:
python chat.py
Within a few seconds, a multi-sentence AI response prints to your screen. You just called a frontier AI model through Amazon Bedrock from your own computer.
What just happened?
Your script sent a request over the internet to Amazon Bedrock's endpoint in US East (N. Virginia). Bedrock forwarded your prompt to OpenAI's GPT-5.6 Luna model, which generated a response. That response traveled back through Bedrock to your terminal. The entire round trip typically takes 2-5 seconds.
Seeing an error instead of a response?
- If you see a message about OPENAI_API_KEY being invalid or missing: close your current terminal and open a new one with Ctrl+`. On Windows, setx only takes effect in new terminal sessions. Then run cd ~/Desktop/bedrock-project and try again.
- If you see ModuleNotFoundError: No module named 'openai': the SDK is not installed in this Python environment. Run pip install openai and try again.
- If you see python: command not found: try python3 chat.py instead. On macOS, the command is often python3.
My script is throwing an error I don't recognize
✔️ Awesome, I've got everything!
Great. Double check you've saved your file, then move on to the next substep.
ⓧ I'd like to double check the full code
Here is the complete chat.py file. Make sure yours matches:
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ.get("OPENAI_API_KEY"),
base_url=os.environ.get("OPENAI_BASE_URL")
)
response = client.responses.create(
model="openai.gpt-5.6-luna",
input="What is Amazon Bedrock and why do companies use it?"
)
print(response.output_text)
Break something on purpose
Knowing what errors look like is just as important as getting things right. When something breaks later in a real project, you'll recognize the error message instantly instead of panicking.
- In chat.py, find this line:
model="openai.gpt-5.6-luna",
- Change the model name to something that does not exist:
model="openai.gpt-fake-model",
- Save the file and run it again:
python chat.py
You'll see an error message from Bedrock telling you the model was not found. This is what a bad model ID looks like in practice.
- Now fix it back by changing the model name to the correct value:
model="openai.gpt-5.6-luna",
- Save the file and run it one more time to confirm it works again:
python chat.py
Your AI response prints again. You now know exactly what a model-not-found error looks like and how to fix it.
Try one more break
Want extra practice? Temporarily rename OPENAI_API_KEY to OPENAI_API_KEY_OLD in the code (so it reads a variable that does not exist), then run the script to see what an authentication error looks like. Change it back when you're done.
Your pipeline is proven. You can send prompts, read responses, and diagnose errors. Next up, you'll turn this single-shot script into a multi-turn conversation where the AI remembers what you said.
Build a Multi-Turn Conversation
In the last step, you proved the entire pipeline works. Your code, your key, and the AI model are all connected.
There is one big problem. Every time you run chat.py, the model starts fresh with zero memory of anything you said before. Ask it your name, then ask "what's my name?" in a separate run, and it has no idea. Real AI applications need memory across messages. In this step, you will hit that limitation head-on, then fix it.
In this step, get ready to:
- Discover that single-prompt scripts have no memory between runs.
- Build a new script that passes conversation history with every request.
- Add a chat loop so you can keep talking without restarting the script.
Hit the memory wall
Your chat.py script works, but each run is completely isolated. The model receives one prompt and forgets everything the instant it responds. Let's prove this.
- In VS Code, open chat.py and find this line:
input="What is Amazon Bedrock and why do companies use it?"
- Replace the input string so the line looks like this:
input="My name is Alex."
- Save chat.py and run it by entering this command in your terminal:
python chat.py
You should see the model acknowledge the name and respond conversationally.
- Now change the input string again so it looks like this:
input="What is my name?"
- Save chat.py and run it again.
Before you hit Enter, predict: will the model remember that your name is Alex?
python chat.py
The model has no idea. It might guess, apologize, or ask you to share your name. Each call to the Responses API is completely independent. The model received only "What is my name?" with no prior context.
Why does the model forget?
AI models do not store state between API calls. Every request is a blank slate unless you explicitly send the conversation history along with it. This is by design. It keeps the API stateless and predictable.
The fix is to collect every message (yours and the assistant's) in a list, then send that full list with each new request. The model reads the entire history and responds as if it remembers.
- Revert chat.py back to its original input string so the line looks like this:
input="What is Amazon Bedrock and why do companies use it?"
- Save chat.py.
Create the conversation script
To give the model memory, you will use the Chat Completions API instead of the Responses API. This API accepts a messages list containing the full conversation history.
- Create a new file called conversation.py in VS Code by pressing Cmd+N (macOS) or Ctrl+N (Windows), then save it as conversation.py in the same folder as chat.py.
- Add the following code to set up the client and an empty message history:
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ.get("OPENAI_API_KEY"),
base_url=os.environ.get("OPENAI_BASE_URL")
)
# Start with an empty conversation history
messages = []
print("Chat with GPT-5.6 Luna on Amazon Bedrock!")
print("Type 'quit' to exit.\n")
What does this code do?
- The client setup is identical to chat.py. It reads your API key and base URL from environment variables.
- messages = [] creates an empty list that will hold every message in the conversation. This is the "memory" that gets sent to the model with each request.
- The print statements give the user a welcome message and instructions on how to exit.
- Save conversation.py and run it to confirm the setup prints correctly:
python conversation.py
You should see the welcome messages print, then the script exits. The loop is not there yet, so it has nothing else to do.
Seeing an import error?
Make sure you are running the command in the same terminal where you set your environment variables. If you opened a new terminal after using setx, the variables should already be available.
help me fix an import error when running conversation.py
Add the conversation loop
Now you will add the interactive loop that collects input, sends the full message history to the model, and prints the response.
- Add the following code below the print statements in conversation.py:
while True:
user_input = input("You: ")
if user_input.lower() == "quit":
print("Goodbye!")
break
# Add the user's message to conversation history
messages.append({"role": "user", "content": user_input})
# Send the FULL history so the model has context
response = client.chat.completions.create(
model="openai.gpt-5.6-luna",
messages=messages
)
# Extract and store the assistant's reply
assistant_message = response.choices[0].message.content
messages.append({"role": "assistant", "content": assistant_message})
print(f"\nAssistant: {assistant_message}\n")
What does this code do?
- input("You: ") waits for you to type something. Typing quit breaks out of the loop.
- Each message you send gets appended to messages with "role": "user". The model sees every previous exchange because messages grows with each turn.
- client.chat.completions.create() is the Chat Completions API. It accepts the full messages array, giving the model context of everything said so far.
- The assistant's reply gets appended too, so next time the model knows what it already said.
- Save conversation.py.
Before you run this, predict: if you tell the model your name, then ask "what is my name?" in the next message, will it remember this time?
- Run the conversation script:
python conversation.py
- Type My name is Alex and press Enter.
- After the response, type What is my name? and press Enter.
The AI correctly responds with "Alex". It remembered because you sent the full conversation history with the second request.
- Type quit to exit the script.
Model not remembering your name?
Make sure both the user message and the assistant reply are being appended to messages. If you only append user messages, the model sees gaps in the conversation and loses context.
help me debug why my conversation.py is not remembering context between messages
✔️ Awesome, I've got everything!
Great. Double check you have saved conversation.py and confirmed the AI remembers context across messages.
ⓧ I'd like to double check the full code
Here is the complete conversation.py file. Make sure yours matches exactly:
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ.get("OPENAI_API_KEY"),
base_url=os.environ.get("OPENAI_BASE_URL")
)
messages = []
print("Chat with GPT-5.6 Luna on Amazon Bedrock!")
print("Type 'quit' to exit.\n")
while True:
user_input = input("You: ")
if user_input.lower() == "quit":
print("Goodbye!")
break
messages.append({"role": "user", "content": user_input})
response = client.chat.completions.create(
model="openai.gpt-5.6-luna",
messages=messages
)
assistant_message = response.choices[0].message.content
messages.append({"role": "assistant", "content": assistant_message})
print(f"\nAssistant: {assistant_message}\n")
Your AI now has memory. It can hold a full conversation, building on everything you say. Next up, you will turn this into a practical tool: a code explainer that takes any snippet and breaks it down in plain English.
Build the Code Explainer Tool
Your conversation script can hold a back-and-forth chat, but it is still a generic chatbot. Anyone can build a generic chatbot.
In this step, you will turn your script into something you will actually use while learning to code: a code explainer tool. Paste in any code snippet and get back a beginner-friendly, numbered breakdown of what each line does. The secret ingredient is a system prompt that shapes how the AI responds to every message.
In this step, get ready to:
- Add a system prompt that tells the model to explain code line-by-line.
- Build a multi-line input that accepts pasted code snippets.
- Test the explainer with Python, HTML, and JavaScript code.
Add a system prompt that shapes the AI's behavior
A system prompt is an instruction you give the model before the user says anything. It defines the model's personality and task for the entire conversation.
- In VS Code, create a new file called explainer.py in the same folder as your other scripts.
- Add the following code to set up the client and system prompt:
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ.get("OPENAI_API_KEY"),
base_url=os.environ.get("OPENAI_BASE_URL")
)
# Tell the model exactly how to behave for every response
system_prompt = (
"You are a code explainer. When the user pastes code, explain what each "
"line does in simple English. Use numbered steps. Assume the reader is a "
"beginner who has never programmed before."
)
# Seed the conversation with the system instruction
messages = [{"role": "system", "content": system_prompt}]
print("Code Explainer - Paste code and get a plain-English explanation!")
print("Type your code, then type END on its own line when done.")
print("Type 'quit' to exit.\n")
What does this code do?
The client setup is the same as your previous scripts. The new piece is the system prompt and how it gets loaded into the conversation.
- system_prompt is a string that instructs the model to act as a code explainer, use numbered steps, and write for beginners.
- messages starts with the system message already loaded. Every user message that comes later inherits this behavior instruction.
- Save explainer.py.
- Run the file to confirm it loads without errors by running:
python explainer.py
You should see the three welcome lines print, then the script exits. That means your imports, client, and system prompt all loaded cleanly.
Seeing a ModuleNotFoundError?
Make sure you are running the command from the same folder where explainer.py lives. Also confirm the OpenAI SDK is installed by running pip install openai again.
Help me debug a ModuleNotFoundError in my Python script.
Add the multi-line input loop
Code snippets span multiple lines, so you need an input method that keeps reading until the user signals they are done. The loop below reads lines until the user types END on its own line.
- Add the following code at the bottom of explainer.py, below the print statements:
while True:
print("Paste your code below (type END when done):")
lines = []
while True:
line = input()
if line.strip().upper() == "END":
break
lines.append(line)
if not lines:
continue
code = "\n".join(lines)
user_message = f"Please explain this code:\n\n```\n{code}\n```"
messages.append({"role": "user", "content": user_message})
response = client.chat.completions.create(
model="openai.gpt-5.6-luna",
messages=messages
)
assistant_message = response.choices[0].message.content
messages.append({"role": "assistant", "content": assistant_message})
print(f"\nExplanation:\n{assistant_message}\n")
cont = input("Explain more code? (yes/quit): ")
if cont.lower() == "quit":
print("Goodbye!")
break
What does this code do?
- The inner while True loop collects lines one by one until the user types END. This lets you paste multi-line code without the script cutting you off.
- user_message wraps the pasted code in a markdown code fence. This helps the model clearly see where the code starts and ends.
- The API call uses client.chat.completions.create() with the full messages list, so the system prompt is always included.
- After printing the explanation, the script asks if you want to continue or quit.
- Save explainer.py.
- Run the script to test it with a quick snippet:
python explainer.py
- When prompted, paste this simple Python code:
name = "Alex"
print("Hello, " + name)
- Type END on its own line and press Enter.
Within a few seconds, you should see a numbered explanation of each line in plain English. The system prompt is doing the heavy lifting here, shaping the model's output format without you asking for it in every message.
Script hangs or no response?
Make sure your environment variables are still set. If you opened a new terminal window after running setx earlier, they should be available. Try running echo %OPENAI_API_KEY% to confirm.
Help me debug why my explainer.py script hangs when I paste code.
Test with different code languages
The system prompt does not mention any specific language. It should handle anything you throw at it.
- When the script asks if you want to explain more code, type yes and press Enter.
- Paste this HTML snippet, then type END:
<h1>Welcome</h1>
<p>This is my page.</p>
<a href="https://example.com">Click here</a>
The model explains HTML elements in plain English, the same way it explained Python. Now try JavaScript.
- Type yes to continue, then paste this code and type END:
const items = [1, 2, 3, 4, 5];
const doubled = items.map(x => x * 2);
console.log(doubled);
Before you read the response, predict: will the AI use numbered steps in its explanation, or will it respond in paragraph form?
It uses numbered steps every time. That is the system prompt at work. You never asked for numbered steps in your pasted code. The model follows that instruction automatically because the system message stays in the conversation history for every request.
- Type quit to exit the script.
Why does the system prompt matter?
Without a system prompt, you would need to write "explain in numbered steps for a beginner" in every single message. The system prompt says it once, and the model obeys it for the entire session.
This is how production AI tools work. A customer support bot, a code reviewer, a writing assistant are all the same model underneath. The system prompt is what makes each one different.
✔️ Awesome, I've got everything!
Great. Double check you have saved explainer.py and you are ready to move on.
ⓧ I'd like to double check the full code
Scroll up and confirm your explainer.py has both chunks in order:
- Chunk 1: imports, client setup, system_prompt string, messages list initialized with the system message, and three print() welcome lines.
- Chunk 2: the while True loop with inner line-reading loop, the API call using client.chat.completions.create(), and the yes/quit prompt at the end.
You just built a genuinely useful tool. Any time you encounter confusing code while learning, you can paste it in and get a plain-English walkthrough. Next up, the Secret Mission challenges you to compare two different models side by side.
Secret mission
Compare Two Models Side by Side
In the real world, teams evaluate multiple models before choosing one. Can you build a tool that sends the same prompt to both GPT-5.6 Luna and GPT-5.6 Terra, times each response, and prints a formatted comparison?
Clean Up Your Resources
Clean Up Your Resources
Decide whether to keep your resources running, pause them to come back later, or delete them entirely. Amazon Bedrock is purely pay-per-use with no running infrastructure, so you will not be charged unless you send additional requests.
Cost warning
GPT-5.6 Luna costs $1.10 per million input tokens and $6.60 per million output tokens. For this project, you likely used fewer than 10,000 tokens total, costing well under $0.10.
If you stop sending requests to Bedrock, no further charges will occur. There is no running infrastructure to accrue costs.
Resources you used:
- An Amazon Bedrock long-term API key (expires in 30 days automatically).
- An IAM user auto-created when you generated the API key.
- Local Python files: chat.py, conversation.py, explainer.py, compare.py.
- Environment variables: OPENAI_API_KEY and OPENAI_BASE_URL.
- The OpenAI Python SDK (installed via pip).
Keep everything running
No action needed. Choose this if you plan to keep experimenting with Bedrock. Your API key expires automatically in 30 days. With no requests, there are no charges.
- Your Python files remain on your machine ready to run again.
- Your environment variables stay set so scripts work immediately.
- Your API key stays active until its 30-day expiration.
Pause - I'll come back to this later
With no requests being sent, there are zero ongoing charges. Since Bedrock is purely pay-per-use, pausing and keeping are effectively the same.
- Do nothing. Your API key, files, and environment variables remain in place.
- When you return, run any of your scripts to pick up where you left off.
Delete - I don't want to use this again
Remove all project resources and start fresh. Follow each step below.
Delete the Bedrock API key:
- Open the Amazon Bedrock console at https://console.aws.amazon.com/bedrock.
- In the left navigation pane, select API keys.
- In the Long-term API keys section, choose your key.
- Click Actions, then select Delete.
- Confirm the deletion.
Delete the associated IAM user:
- Open the IAM console at https://console.aws.amazon.com/iam/.
- In the left navigation pane, choose Users.
- Select the checkbox next to the IAM user created by Bedrock (its name starts with "bedrock").
- At the top of the page, click Delete.
- Enter the username in the confirmation field, then click Delete.
Remove the environment variables:
On Windows, open PowerShell and run:
[Environment]::SetEnvironmentVariable("OPENAI_API_KEY", $null, "User")
[Environment]::SetEnvironmentVariable("OPENAI_BASE_URL", $null, "User")
On macOS or Linux, if you added export lines to your shell config file (.zshrc or .bashrc), remove those lines. If you only used export in a terminal session, the variables are already gone.
Delete the local Python files:
On macOS or Linux:
rm chat.py conversation.py explainer.py compare.py
On Windows (Command Prompt):
del chat.py conversation.py explainer.py compare.py
Uninstall the OpenAI Python SDK:
pip uninstall openai
That's a Wrap!
That's a Wrap!
Nice work! You just built a Python-powered AI assistant that talks to OpenAI's frontier models through Amazon Bedrock.
You've learned how to:
- Call OpenAI's GPT-5.6 Luna model from your own machine using the Responses API through Amazon Bedrock.
- Build a multi-turn conversational AI that maintains context across messages using a message array.
- Build a practical code explainer tool with a system prompt that shapes AI behavior for every response.
- Secret Mission: Compared two models (Luna vs Terra) side by side and observed differences in speed, cost, and output quality.
Ready to quiz yourself?