pip install openai

Ma Mahalakshmi V Updated 16 Sep 2026
6 min read ·Lesson 48 of 224

Installing the Agents SDK

The Agents SDK is a separate package from the base openai package this course has used since Unit 1, installed independently.

pip install openai-agents

Note: The exact package name and installation command can change between versions and providers of agent frameworks built on this platform. Confirm the current package name against the current official documentation before installing it in a real project.

Having both openai and openai-agents installed is normal and expected — the Agents SDK builds on top of the same underlying model and API access this course has used throughout, rather than replacing it. Authentication continues to work the same way Unit 1, Lesson 3 established: an API key available as an environment variable, which the Agents SDK reads the same way the base SDK's client does.

Defining an Agent

An Agent is defined with, at minimum, a name and a set of instructions — conceptually the same instructions parameter Unit 2, Lesson 2 introduced for client.responses.create(), just attached to a reusable object rather than passed fresh on every call.

from agents import Agent

support_agent = Agent(
    name="Support Agent",
    instructions="You help customers with questions about their orders. Be concise and friendly.",
    model="gpt-5.6-terra",
)

The name field isn't just documentation — it's what appears in tracing (Lesson 6) and in handoff-related output (Lesson 4) when multiple agents are involved in a single interaction, so a clear, specific name pays off as soon as a system has more than one agent. The instructions field plays exactly the role Unit 3 established for prompting generally: it's where an agent's persistent behavior, tone, and scope get defined, distinct from the input a specific run provides.

Running an Agent

An agent, once defined, is run against a specific input using the SDK's Runner.

from agents import Agent, Runner

support_agent = Agent(
    name="Support Agent",
    instructions="You help customers with questions about their orders. Be concise and friendly.",
    model="gpt-5.6-terra",
)

result = Runner.run_sync(support_agent, "Where is my order #4471?")
print(result.final_output)

Runner.run_sync() is the synchronous entry point: it blocks until the agent has finished running — potentially after several internal steps, as Lesson 1 described — and returns a result object once a final answer is ready. result.final_output holds the agent's final response, the same underlying value response.output_text gave you in every prior unit's client.responses.create() calls, just accessed through the Agents SDK's own result object rather than the base SDK's response object.

Running an Agent Asynchronously

Real applications, particularly ones serving multiple users concurrently, often need to run agents without blocking the rest of the program while waiting for a response. The Agents SDK provides an async equivalent for exactly this case.

import asyncio
from agents import Agent, Runner

support_agent = Agent(
    name="Support Agent",
    instructions="You help customers with questions about their orders.",
    model="gpt-5.6-terra",
)

async def main():
    result = await Runner.run(support_agent, "Where is my order #4471?")
    print(result.final_output)

asyncio.run(main())

Runner.run() (as opposed to Runner.run_sync()) is a coroutine, following the same synchronous-versus-asynchronous distinction Unit 12 covers in depth for the base SDK's own async client — a synchronous call is simpler to reason about and appropriate for a script or a single-request context, while an asynchronous call is what a production server handling many concurrent requests generally needs, so as not to block on one user's agent run while another user's request is waiting.

What the Result Object Contains

Beyond final_output, a run's result carries additional information about what happened during the run — useful for debugging or for building on top of the interaction rather than just displaying the final text.

result = Runner.run_sync(support_agent, "Where is my order #4471?")

print(f"Final output: {result.final_output}")
print(f"Last agent that responded: {result.last_agent.name}")

Note: The exact fields available on a run's result object, and their names, can vary by SDK version. Confirm the current result object's shape against the current official documentation before relying on a specific field in production code.

result.last_agent matters once handoffs are introduced in Lesson 4: a run might start with one agent and end with a different one after a handoff occurs, and knowing which agent actually produced the final answer is often necessary for logging, analytics, or deciding how to route a follow-up message.

Controlling How Many Steps a Run Can Take

Lesson 1's hand-rolled loop used a max_rounds parameter as a safety cap against a runaway interaction that never produces a final answer. The Runner provides an equivalent safeguard, since an agent that keeps calling tools without ever settling on a final response is just as much a real risk here as it was for the manual loop in Unit 8, Lesson 3.

result = Runner.run_sync(support_agent, "Where is my order #4471?", max_turns=10)

Note: The exact parameter name and default value for limiting the number of steps in a run can vary by SDK version. Confirm the current parameter name and its default against the current official documentation.

This exists for exactly the same reason Unit 8, Lesson 3 introduced max_rounds: without some bound, an agent stuck in a loop — repeatedly calling a tool, never satisfied with the result, never producing a final answer — would otherwise run indefinitely, consuming cost and time with no useful outcome. Setting this explicitly, rather than relying purely on whatever default the SDK ships with, is a reasonable habit for any agent that has access to tools it could plausibly call more than a handful of times.

Comparing an Agent Run to client.responses.create() Directly

It's worth being explicit about what maps to what, since nearly everything here has a direct counterpart from earlier units.

Conceptclient.responses.create() (Units 1-10)Agents SDK (this unit)
System-level behavior instructionsinstructions parameter, passed per callinstructions on the Agent, defined once
The specific request for this turninput parameterThe argument to Runner.run() / Runner.run_sync()
Which model answersmodel parameter, passed per callmodel on the Agent, defined once
The final text answerresponse.output_textresult.final_output
Managing a multi-step tool-calling loopYour own code (Unit 8, Lesson 3)Handled internally by Runner

The practical upshot: everything you already know about writing good instructions (Unit 3), choosing an appropriate model (Unit 2, Lesson 5), and reasoning about what a response contains (Unit 2, Lesson 3) transfers directly — the Agents SDK changes how a multi-step interaction is orchestrated, not the underlying skills for getting good output from the model.

Common Mistakes

Treating the Agents SDK as an entirely separate skill from what this course has already covered, rather than recognizing that instructions, models, and the fundamentals of getting good output from the API (Units 1 through 7) apply unchanged.

Using Runner.run_sync() inside a server handling many concurrent requests, blocking the entire process on one user's agent run rather than using the async Runner.run() appropriately.

Ignoring result.last_agent in a system that uses handoffs (Lesson 4), losing track of which specific agent actually produced the final response.

Giving an agent a vague, generic name, making later tracing output (Lesson 6) and multi-agent logs harder to read than they need to be.

Best Practices

Give every agent a clear, specific name, since it appears throughout tracing output and matters immediately once a system involves more than one agent.

Use Runner.run_sync() for scripts and simple, single-request contexts, and Runner.run() for a server handling concurrent requests, following the same synchronous-versus-asynchronous reasoning Unit 12 covers for the base SDK.

Carry forward everything already established about writing effective instructions (Unit 3), since an Agent's instructions field plays exactly the same role as the instructions parameter used throughout Units 1 through 10.

Inspect the full result object, not just final_output, when debugging a multi-agent or multi-step run, since fields like last_agent carry information a single text string doesn't.

0 Comments

Reviewed before they appear

No comments yet.

OpenAI SDK
Introduction to the OpenAI SDK Setting Up Python Creating an API Key Your First Call — client.responses.create() and response.output_text Understanding Billing, Credits, and What a Request Costs Why Responses Replaced Chat Completions Anatomy of a Request: model, input, and instructions Anatomy of a Response: The Typed output Array, Not Just Text Roles: User, Assistant, and Developer/System Choosing a Model, and Reading the Models Page Instead of Memorizing Names Instructions vs. Input Writing Prompts That Get Consistent Results Few-Shot Examples Reasoning Models and the reasoning Parameter Debugging a Prompt That Misbehaves Why Streaming Matters for User Experience stream=True and Iterating Over Events Handling the Event Types You Actually Care About Background Mode for Long-Running Jobs Project — Add Live Streaming to Your Chatbot The Problem With Parsing Free Text JSON Schema and Strict Mode Pydantic Models With the SDK's Parse Helpers Handling Refusals and Validation Failures Project — A Resume-to-JSON Extractor Working With input_image input_file, PDFs, and the Files API Image Generation Speech-to-Text and Text-to-Speech Project: A PDF Question-Answering Script What Function Calling Is Defining a Tool Schema The Full Loop Multiple Tools Errors, Timeouts, and Untrusted Arguments Project: A Weather Assistant Web Search File Search and Vector Stores Code Interpreter Remote MCP Servers and Connectors Project: A Research Assistant What an Embedding Is, Without the Maths Generating and Storing Embeddings Similarity Search From Scratch Hosted Vector Stores vs. Rolling Your Own A Small RAG App Over a Folder of Notes Agents vs. a Single API Call — When You Need One pip install openai Giving Agents Tools Handoffs and Multi-Agent Triage Guardrails and Approvals Tracing and Observing What Your Agent Did A Multi-Agent Support Desk Error Codes and What Each One Means Retries, Timeouts, and Backoff Rate Limits and Spend Limits Prompt Caching and Cost Optimisation The Batch API for Bulk Work Async Clients and Concurrency Moderation and Safety Best Practices Designing the App Backend With FastAPI Streaming to a Simple Frontend Deploying and a Cost/Safety Checklist Why Web Search Is Useful for Current Information Using the Web Search Tool with the Responses API Configuring Search Behavior for Application Use Cases Understanding Citations and Source Attribution Where to Go Next Building a Research Assistant with Web Search Combining Web Search with Structured Outputs Handling Conflicting or Low-Quality Web Sources Reducing Unsupported Claims with Grounded Generation Testing Freshness-Sensitive AI Answers Production Considerations for Web-Grounded Applications Understanding File Search and Retrieval-Augmented Generation Creating and Organizing Vector Stores Uploading Documents for Retrieval Connecting Vector Stores to Responses API Requests Designing Document Metadata and Filtering Strategies Building a PDF Question-Answering Application Improving Retrieval Quality With Better Document Preparation Handling Missing Evidence and Retrieval Failures Combining File Search With Web Search Building a Production Knowledge-Base Assistant What the Code Interpreter Tool Is Designed For Running Python-Based Analysis Through the OpenAI SDK Uploading Datasets for Analysis Analyzing CSV and Spreadsheet Data Generating Charts and Data Summaries Handling Generated Files and Downloadable Artifacts Building a Data-Analysis Assistant Combining Code Execution with Structured Outputs Validating Generated Calculations and Results Security and Sandbox Considerations for Code Execution Understanding Multimodal Input with the OpenAI SDK Sending Images to a Model Image Analysis from URLs and Uploaded Files Extracting Text and Information from Screenshots Building an Image-Question-Answering Application Combining Image Input with Structured Output Analyzing Multiple Images in One Request Handling Image Quality and Input Limitations Designing Multimodal Prompts for Reliable Results Building a Practical Vision-Powered Python Application Understanding Speech-to-Text and Text-to-Speech Workflows Transcribing Audio with the OpenAI SDK Working with Uploaded Audio Files Handling Timestamps and Transcription Metadata Building a Meeting Transcription Workflow Generating Spoken Responses from Text Handling Long Audio and Processing Failures Combining Audio with Text and Tool Calling Building an End-to-End Python Voice Application What Embeddings Are and When to Use Them Generating Embeddings With the OpenAI API Preparing Text for Embedding Comparing Vectors With Cosine Similarity Building a Simple Semantic Search Engine in Python Storing Embeddings in a Database Metadata Filtering for Semantic Search Chunking Strategies for Better Retrieval Evaluating Semantic Search Quality Building a Document Similarity Application When Batch Processing Makes Sense Designing Large-Volume AI Processing Pipelines Using Asynchronous Python with the OpenAI SDK Running Concurrent Requests Safely Controlling Concurrency and Avoiding Rate Limits Tracking Batch Job Progress Handling Partial Failures in Bulk Workloads Retrying Failed Items Without Duplicating Successful Work Designing Resumable AI Processing Jobs Building a Production Batch-Processing Pipeline Batch Processing Makes Sense Large-Scale AI Processing Pipelines Async Python with OpenAI SDK Safe Concurrent Requests Concurrency & Rate Limits Batch Progress Tracking Partial Failure Handling Safe Retry Handling Resumable AI Jobs Production Batch Pipeline System–User Data Separation Reusable App Instructions Prompt Templates & Variables Extraction & Classification Prompts Summarization & Transformation Prompts Explicit Output Requirements Prompt Version Management Prompt Testing & Evaluation Reusable Python Prompt Library API Key Security Secure API Key Storage Secure Secret Management Prompt Injection Prevention Trusted vs. Untrusted Content Tool Argument Validation Sensitive Data Handling Secure Logging AI Action Authorization Production AI Security Checklist Why AI Applications Need Evaluation Beyond Unit Tests Unit Testing OpenAI SDK Integration Code Mocking API Responses in Python Tests Testing Structured Outputs Against Schemas Testing Tool-Calling Workflows Building a Small Evaluation Dataset Measuring Accuracy, Consistency, and Failure Rates Regression Testing Prompts and Model Changes Human Evaluation Versus Automated Evaluation Creating a Repeatable Evaluation Pipeline AI Request Monitoring Token Cost Management Usage Metrics Design Reducing Model Calls Prompt & Context Optimization Model Selection & Optimization AI Caching Strategies Interactive Latency Optimization Usage Dashboards & Budget Alerts Performance & Cost Checklist Every API Call Starts Fresh Fixing API Statelessness Server-Side Conversation Memory Limits of Response Chaining What We're Building Conversation Memory Challenges Preparing an OpenAI SDK Application for Deployment Environment-Specific Configuration for Development and Production Deploying a Python AI Service with Docker Container Health Checks and Startup Configuration Managing Secrets in Cloud Deployments Background Workers for Long-Running AI Tasks Queues and Asynchronous Job Architectures Scaling AI Workloads Horizontally Monitoring Production Incidents and Failures Production Deployment Checklist for OpenAI SDK Applications Reusable OpenAI Service Classes AI Client Dependency Injection Typed AI Responses Python Configuration Management AI Request Decorators Centralized AI Error Handling Clean SDK Abstractions Reusable OpenAI Utilities Internal AI Python Libraries SDK Integration Maintenance Production AI Chatbot Document Q&A System Web Research Assistant Customer Support Agent AI Data Analysis Assistant Image Analysis App Meeting Transcription & Summary Semantic Document Search Multi-Tool AI Agent Production OpenAI SDK App Why "It Looked Fine When I Tested It" Isn't Enough Timing Note Status Note Pre-Decision Status Note Current Availability Note
Ask about this post
AI Ask about this post

Ask questions about pip install openai and get answers drawn from it.

Signed-in readers only.