0% found this document useful (0 votes)
29 views6 pages

OpenAI Agents Python Quickstart Guide

This document provides a quickstart guide for creating and managing agents using the OpenAI Agents SDK. It details the steps for setting up a project, activating a virtual environment, installing the SDK, and defining agents with specific instructions and handoff options. Additionally, it includes examples of running agent orchestration and implementing guardrails for input validation.

Uploaded by

Blondy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views6 pages

OpenAI Agents Python Quickstart Guide

This document provides a quickstart guide for creating and managing agents using the OpenAI Agents SDK. It details the steps for setting up a project, activating a virtual environment, installing the SDK, and defining agents with specific instructions and handoff options. Additionally, it includes examples of running agent orchestration and implementing guardrails for input validation.

Uploaded by

Blondy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Quickstart

Create a project and virtual environment


You'll only need to do this once.

mkdir my_project
cd my_project
python -m venv .venv

Activate the virtual environment


Do this every time you start a new terminal session.

source .venv/bin/activate

Install the Agents SDK


pip install openai-agents # or `uv add openai-agents`,
etc

Set an OpenAI API key


If you don't have one, follow these instructions to create an OpenAI
API key.

export OPENAI_API_KEY=sk-...

Create your first agent


Agents are defined with instructions, a name, and optional config
(such as model_config )

from agents import Agent

agent = Agent(
name="Math Tutor",
instructions="You provide help with math problems.
Explain your reasoning at each step and include
examples",
)

Add a few more agents


Additional agents can be defined in the same way.
handoff_descriptions provide additional context for determining
handoff routing

from agents import Agent

history_tutor_agent = Agent(
name="History Tutor",
handoff_description="Specialist agent for
historical questions",
instructions="You provide assistance with
historical queries. Explain important events and
context clearly.",
)

math_tutor_agent = Agent(
name="Math Tutor",
handoff_description="Specialist agent for math
questions",
instructions="You provide help with math problems.
Explain your reasoning at each step and include
examples",
)
Define your handoffs
On each agent, you can define an inventory of outgoing handoff
options that the agent can choose from to decide how to make
progress on their task.

triage_agent = Agent(
name="Triage Agent",
instructions="You determine which agent to use
based on the user's homework question",
handoffs=[history_tutor_agent, math_tutor_agent]
)

Run the agent orchestration


Let's check that the workflow runs and the triage agent correctly
routes between the two specialist agents.

from agents import Runner

async def main():


result = await [Link](triage_agent, "What is
the capital of France?")
print(result.final_output)

Add a guardrail
You can define custom guardrails to run on the input or output.

from agents import GuardrailFunctionOutput, Agent,


Runner
from pydantic import BaseModel

class HomeworkOutput(BaseModel):
is_homework: bool
reasoning: str
guardrail_agent = Agent(
name="Guardrail check",
instructions="Check if the user is asking about
homework.",
output_type=HomeworkOutput,
)

async def homework_guardrail(ctx, agent, input_data):


result = await [Link](guardrail_agent,
input_data, context=[Link])
final_output =
result.final_output_as(HomeworkOutput)
return GuardrailFunctionOutput(
output_info=final_output,
tripwire_triggered=not
final_output.is_homework,
)

Put it all together


Let's put it all together and run the entire workflow, using handoffs
and the input guardrail.

from agents import Agent,


InputGuardrail,GuardrailFunctionOutput, Runner
from pydantic import BaseModel
import asyncio

class HomeworkOutput(BaseModel):
is_homework: bool
reasoning: str

guardrail_agent = Agent(
name="Guardrail check",
instructions="Check if the user is asking about
homework.",
output_type=HomeworkOutput,
)
math_tutor_agent = Agent(
name="Math Tutor",
handoff_description="Specialist agent for math
questions",
instructions="You provide help with math problems.
Explain your reasoning at each step and include
examples",
)

history_tutor_agent = Agent(
name="History Tutor",
handoff_description="Specialist agent for
historical questions",
instructions="You provide assistance with
historical queries. Explain important events and
context clearly.",
)

async def homework_guardrail(ctx, agent, input_data):


result = await [Link](guardrail_agent,
input_data, context=[Link])
final_output =
result.final_output_as(HomeworkOutput)
return GuardrailFunctionOutput(
output_info=final_output,
tripwire_triggered=not
final_output.is_homework,
)

triage_agent = Agent(
name="Triage Agent",
instructions="You determine which agent to use
based on the user's homework question",
handoffs=[history_tutor_agent, math_tutor_agent],
input_guardrails=[

InputGuardrail(guardrail_function=homework_guardrail),
],
)
async def main():
result = await [Link](triage_agent, "who was
the first president of the united states?")
print(result.final_output)

result = await [Link](triage_agent, "what is


life")
print(result.final_output)

if __name__ == "__main__":
[Link](main())

View your traces


To review what happened during your agent run, navigate to the
Trace viewer in the OpenAI Dashboard to view traces of your agent
runs.

Next steps
Learn how to build more complex agentic flows:
Learn about how to configure Agents.
Learn about running agents.
Learn about tools, guardrails and models.

Common questions

Powered by AI

The steps to set up and activate a virtual environment for running OpenAI agents involve creating a virtual environment using commands such as `python -m venv .venv`, activating it with `source .venv/bin/activate`, and installing the necessary packages using `pip install openai-agents` .

The system uses a guardrail agent to determine if a query relates to homework by checking the input against defined criteria laid out in 'HomeworkOutput'. The guardrail agent analyzes the input and uses this model output to confirm whether the task fits as a homework query .

The handoff mechanism in the OpenAI agents framework involves defining a set of outgoing options that an agent can use to delegate tasks, ensuring that a specific question is directed to the most suitable agent. This is important for efficiently managing tasks based on the agents' capabilities, improving response relevance and accuracy .

Outputs of a tutoring agent can be customized by defining comprehensive instructions and examples in its setup. For instance, a 'Math Tutor' agent is programmed to explain reasoning at each step of a solution process, enhancing the learning experience. Customization can further involve configuring specific model or task outputs to fit educational requirements .

Using a subclass like 'HomeworkOutput' in agent configuration allows for structured output validation and specification. It serves as a schema that defines expected output properties such as 'is_homework' and 'reasoning', ensuring that agent outputs are consistent with the desired format and criteria for a particular task or evaluation .

Reviewing trace histories is beneficial as it provides detailed insights into agent performance, error handling, and task progression. Such analysis helps in optimizing agent functionality and identifying issues. Traces can be accessed through the Trace Viewer on the OpenAI Dashboard, allowing for meticulous review and analysis of agent runs .

Specialized agents in educational environments can be employed for personalized tutoring, where each agent provides support in a specific subject matter. For instance, a Math Tutor agent can help students understand complex math problems, while a History Tutor agent can provide context for historical events. Such agents can facilitate interactive learning experiences, offer tailored educational content, and provide immediate feedback or assistance .

Integrating multiple agents enhances efficiency by allowing different agents to specialize in specific domains, such as mathematics or history, thereby directing each query to the most knowledgeable agent. This systematic distribution of queries optimizes resource allocation and improves response quality and accuracy .

The Triage Agent plays the role of determining which specialized agent to route a user's question to based on the nature of the query. It acts as a decision-maker that can apply predefined handoff criteria to manage the flow of tasks among different specialist agents like 'History Tutor' or 'Math Tutor' .

The Guardrail functions as a strategic check to ensure that the input and output of agents adhere to certain conditions or constraints. It prevents agents from executing tasks that may not meet predefined criteria, helping ensure the integrity and appropriateness of the agent's operations .

You might also like