📘 Introduction

Chatbots are becoming smarter and more useful thanks to agent frameworks. Instead of just responding to messages, agents can plan, call tools, and take actions. With the OpenAI Agents SDK, you can build intelligent assistants that do more than just chat—they can search, calculate, and even connect to APIs. Paired with Gradio, you’ll have a clean and interactive interface for your chatbot in just a few lines of code.

In this tutorial, you’ll learn how to build a chatbot using Gradio’s ChatInterface and the OpenAI Agents SDK. By the end, you’ll have a working chatbot that can reason, respond, and extend beyond simple conversations.

✅ Prerequisites

Before starting, make sure you have the following:

🐍☑️ Python installed
📦☑️ Pip installed
🌐☑️ A virtual environment (venv) created and activated
🔑☑️ An OpenAI API key generated (get one from OpenAI)
🔐☑️ OpenAI API key set as environment variable OPENAI_API_KEY

💡
No front-end skills needed — Gradio handles that for you! 🎨

📦1️⃣ Install Libraries

Install the following Python packages using pip:

pip install gradio openai-agents

📥2️⃣ Import Libraries

Create a new file called app.py and import the required Python modules:

import asyncio
import gradio as gr
from agents import Agent, Runner

🤖3️⃣ Create the Agent

Before building the interface, we need an agent that powers our chatbot.
Here we also define a helper function to run the agent to call asynchronously. Using an  async function is necessary because the OpenAI Agents SDK uses asyncio internally.

Add this to app.py:

# Create an agent
agent = Agent(
    name="Assistant",
    instructions="You are a helpful assistant."
)

# Async function to query the agent
async def query_agent(user_input: str) -> str:
    """Send a user input to the agent and return its response."""
    try:
        result = await Runner.run(agent, user_input)
        return result.final_output
    except Exception as e:
        return f"⚠️ Error: {e}"

You can view this post with the tier: Academy Membership

Join academy now to read the post and get access to the full library of premium posts for academy members only.

Join Academy Already have an account? Sign In