Skip to main content
Welcome back! In this lesson we’ll build a simple interactive chatbot using OpenAI’s Agents model. Before diving into code, take a few minutes to explore the OpenAI Agents SDK repository and docs — understanding where examples and patterns live will speed up development.
The image shows a webpage titled "OpenAI Agents SDK", detailing the features and usage of the SDK, with navigation options on the left and additional content on the right.
Start with the Quickstart and the Examples folder in the Agents SDK to see common integrations and agent patterns you can reuse. These resources demonstrate how tools, outputs, and agent behaviors are wired together.
The image shows a webpage from the OpenAI Agents SDK documentation, highlighting example implementations and categories such as agent patterns and basic capabilities.
Use the documentation as your reference for configuring agents, registering tools, and customizing outputs. Example: typed outputs with Pydantic Here’s a concise example showing how to define a typed output using Pydantic and create an Agent. Typed outputs make it easier to validate and consume structured results from your agent.
from pydantic import BaseModel
from agents import Agent

class CalendarEvent(BaseModel):
    name: str
    date: str
    participants: list[str]

agent = Agent(
    name="Calendar extractor",
    instructions="Extract calendar events from text",
    output_type=CalendarEvent,
)
Building the chatbot Below we’ll create a simple interactive chatbot that:
  • Loads environment variables securely (do not hard-code API keys).
  • Defines an Agent with clear role-based instructions.
  • Uses an asynchronous main loop to run the agent via Runner.run.
  • Stores and displays a simple chat history.
  • Supports the history, exit, and quit commands.
Make sure you have a .env file with OPENAI_API_KEY set, or set the environment variable in another secure way. Do not hard-code API keys in your script.
Complete chatbot script This consolidated script demonstrates the full flow. It uses python-dotenv to load the API key, defines an Agent with instructions, awaits Runner.run, and manages conversation memory.
# chatbot_agent.py
from dotenv import load_dotenv
import os
import asyncio
from agents import Agent, Runner

# Load environment variables from .env
load_dotenv()

if not os.getenv("OPENAI_API_KEY"):
    raise RuntimeError("OPENAI_API_KEY not found in environment. Add it to your .env file.")

# Define the chatbot agent
agent = Agent(
    name="Police Sketch Artist",
    instructions=(
        "You are a police sketch artist. Collect specific details about the individual being sketched. "
        "Ask follow-up questions to clarify features (hair, eyes, nose, mouth, clothing, build, distinctive marks)."
    ),
)

async def main():
    chat_history: list[tuple[str, str]] = []

    print("Police Sketch Artist chatbot. Type 'history' to view conversation, 'exit' or 'quit' to end.\n")

    while True:
        user_input = input("Provide specific details about the individual: ").strip()
        if not user_input:
            continue

        # Exit commands
        if user_input.lower() in ("exit", "quit"):
            print("Goodbye!")
            break

        # Show chat history
        if user_input.lower() == "history":
            print("\n--- Chat History ---")
            if not chat_history:
                print("(no messages yet)")
            for i, (u, b) in enumerate(chat_history, start=1):
                print(f"{i}. You: {u}\n   ChatBot: {b}\n")
            print("---------------\n")
            continue

        # Run the agent and collect the response
        result = await Runner.run(agent, user_input)

        # The agent's response may be in result.final_output or result.output depending on SDK behavior
        response = getattr(result, "final_output", None)
        if response is None:
            response = getattr(result, "output", str(result))

        # Save to history and display
        chat_history.append((user_input, response))
        print("\nChatBot:", response)
        print("To end chat, type 'exit' or 'quit'. Type 'history' to view past conversations.\n")

if __name__ == "__main__":
    asyncio.run(main())
What this script does
  • Loads environment variables safely via python-dotenv.
  • Defines an Agent with a role-based instruction set so the model acts like a police sketch artist.
  • Runs an asynchronous loop that:
    • Accepts and validates user input.
    • Handles history, exit, and quit commands.
    • Invokes the agent using await Runner.run(agent, user_input).
    • Extracts the agent’s output (final_output or output) and appends each turn to chat_history.
    • Prints the agent response and usage reminders.
Quick command reference
CommandDescription
historyPrints the conversation history collected during this session
exit / quitEnds the chat session and exits the program
Testing and extending the bot Try providing details like hair color, facial features, build, clothing, or distinctive marks. The agent should ask clarifying questions to gather a structured description. Once you collect attributes, you can extend the pipeline to call an image generation API (for example, DALL·E) to create sketches from the description. Example interaction (screenshot)
The image shows a chat interface where a user is describing a person who looks like a Viking to a chatbot. The chatbot prompts for details such as facial features, eyes, nose, mouth, clothing, build, and distinctive marks.
References and next steps Thank you for reading.

Watch Video

Practice Lab