SPB Git

Repository Public

define-agents.md 9.5 KB 249 lines markdown

1# Agent definitions23> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.45An agent is the core unit of an SDK-based workflow. It packages a model, instructions, and optional runtime behavior such as tools, guardrails, MCP servers, handoffs, and structured outputs.67## What belongs on an agent89Use agent configuration for decisions that are intrinsic to that specialist:1011| Property                                                                                                          | Use it for                                                  | Read next                                                                                |12| ----------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | ---------------------------------------------------------------------------------------- |13| `name`                                                                                                            | Human-readable identity in traces and tool/handoff surfaces | This page                                                                                |14| `instructions`                                                                                                    | The job, constraints, and style for that agent              | This page                                                                                |15| `prompt`                                                                                                          | Stored prompt configuration for Responses-based runs        | [Models and providers](https://developers.openai.com/api/docs/guides/agents/models)                                   |16| `model` and model settings                                                                                        | Choosing the model and tuning behavior                      | [Models and providers](https://developers.openai.com/api/docs/guides/agents/models)                                   |17| `tools`                                                                                                           | Capabilities the agent can call directly                    | [Using tools](https://developers.openai.com/api/docs/guides/tools#usage-in-the-agents-sdk)                            |18| `handoffDescription` in TypeScript or `handoff_description` in Python | Hinting when another agent should delegate here             | [Orchestration and handoffs](https://developers.openai.com/api/docs/guides/agents/orchestration)                      |19| `handoffs`                                                                                                        | Delegating to another agent                                 | [Orchestration and handoffs](https://developers.openai.com/api/docs/guides/agents/orchestration)                      |20| `outputType` in TypeScript or `output_type` in Python                 | Returning structured output instead of plain text           | This page                                                                                |21| Guardrails and approvals                                                                                          | Validation, blocking, and review flows                      | [Guardrails and human review](https://developers.openai.com/api/docs/guides/agents/guardrails-approvals)              |22| MCP servers and hosted MCP tools                                                                                  | Attaching MCP-backed capabilities                           | [Integrations and observability](https://developers.openai.com/api/docs/guides/agents/integrations-observability#mcp) |2324## Start with one focused agent2526Define the smallest agent that can own a clear task. Add more agents only when you need separate ownership, different instructions, different tool surfaces, or different approval policies.2728Define a single agent2930```javascript31import { Agent, tool } from "@openai/agents";32import { z } from "zod";3334const getWeather = tool({35  name: "get_weather",36  description: "Return the weather for a given city.",37  parameters: z.object({ city: z.string() }),38  async execute({ city }) {39    return `The weather in ${city} is sunny.`;40  },41});4243const agent = new Agent({44  name: "Weather bot",45  instructions: "You are a helpful weather bot.",46  model: "gpt-6-astra",47  tools: [getWeather],48});49```5051```python52from agents import Agent, function_tool535455@function_tool56def get_weather(city: str) -> str:57    """Return the weather for a given city."""58    return f"The weather in {city} is sunny."596061agent = Agent(62    name="Weather bot",63    instructions="You are a helpful weather bot.",64    model="gpt-6-astra",65    tools=[get_weather],66)67```686970## Shape instructions, handoffs, and outputs7172Three configuration choices deserve extra care:7374- Start with static `instructions`. When the guidance depends on the current user, tenant, or runtime context, switch to a dynamic instructions callback instead of stitching strings together at the call site.75- Keep `handoffDescription` in TypeScript or `handoff_description` in Python short and concrete so routing agents know when to pick this specialist.76- Use `outputType` in TypeScript or `output_type` in Python when downstream code needs typed data rather than free-form prose.7778Return structured output7980```javascript81import { Agent, run } from "@openai/agents";82import { z } from "zod";8384const calendarEvent = z.object({85  name: z.string(),86  date: z.string(),87  participants: z.array(z.string()),88});8990const agent = new Agent({91  name: "Calendar extractor",92  instructions: "Extract calendar events from text.",93  outputType: calendarEvent,94});9596const result = await run(agent, "Dinner with Priya and Sam on Friday.");9798console.log(result.finalOutput);99```100101```python102import asyncio103104from pydantic import BaseModel105106from agents import Agent, Runner107108109class CalendarEvent(BaseModel):110    name: str111    date: str112    participants: list[str]113114115agent = Agent(116    name="Calendar extractor",117    instructions="Extract calendar events from text.",118    output_type=CalendarEvent,119)120121122async def main() -> None:123    result = await Runner.run(124        agent,125        "Dinner with Priya and Sam on Friday.",126    )127    print(result.final_output)128129130if __name__ == "__main__":131    asyncio.run(main())132```133134135Use `prompt` when you want to reference a stored prompt configuration from the Responses API instead of embedding the entire system prompt in code.136137## Keep local context separate from model context138139The SDK lets you pass application state and dependencies into a run without sending them to the model. Use this for data like authenticated user info, database clients, loggers, and helper functions.140141Pass local context to tools142143```javascript144import { Agent, run, tool } from "@openai/agents";145import { z } from "zod";146147const fetchUserAge = tool({148  name: "fetch_user_age",149  description: "Return the age of the current user.",150  parameters: z.object({}),151  // TypeScript users can type this as RunContext<{ name: string; uid: number }>.152  async execute(_args, runContext) {153    return `User ${runContext?.context.name} is 47 years old`;154  },155});156157const agent = new Agent({158  name: "Assistant",159  tools: [fetchUserAge],160});161162const result = await run(agent, "What is the age of the user?", {163  context: { name: "John", uid: 123 },164});165166console.log(result.finalOutput);167```168169```python170import asyncio171from dataclasses import dataclass172173from agents import Agent, RunContextWrapper, Runner, function_tool174175176@dataclass177class UserInfo:178    name: str179    uid: int180181182@function_tool183async def fetch_user_age(wrapper: RunContextWrapper[UserInfo]) -> str:184    """Fetch the age of the current user."""185    return f"The user {wrapper.context.name} is 47 years old."186187188agent = Agent[UserInfo](189    name="Assistant",190    tools=[fetch_user_age],191)192193194async def main() -> None:195    result = await Runner.run(196        agent,197        "What is the age of the user?",198        context=UserInfo(name="John", uid=123),199    )200    print(result.final_output)201202203if __name__ == "__main__":204    asyncio.run(main())205```206207208The important boundary is:209210- Conversation history is what the model sees.211- Run context is what your code sees.212213If the model needs a fact, put it in instructions, input, retrieval, or a tool. If only your runtime needs it, keep it in local context.214215## When to split one agent into several216217Split an agent when one specialist shouldn't own the full reply or when separate capabilities are materially different. Common reasons are:218219- A specialist needs a different tool or MCP surface.220- A specialist needs a different approval policy or guardrail.221- One branch of the workflow needs a different model or output style.222- You want explicit routing in traces rather than a single large prompt.223224## Next steps225226Once one specialist is defined cleanly, move to the guide that matches the next design question.227228229230  [Models and providers231232233234        Choose models, defaults, and transport strategy for this agent.](https://developers.openai.com/api/docs/guides/agents/models)235  [Using tools236237238239        Add capabilities the agent can call directly.](https://developers.openai.com/api/docs/guides/tools#usage-in-the-agents-sdk)240  [Orchestration and handoffs241242243244        Choose how specialists collaborate once one agent is no longer enough.](https://developers.openai.com/api/docs/guides/agents/orchestration)245  [Running agents246247248249        Understand the runtime loop, state, and streaming behavior.](https://developers.openai.com/api/docs/guides/agents/running-agents)
Files main
Menu

Theme