openai-agents-python
AGENTS.md30k starsChanged 3 months agoMITView on GitHub
Agents are the core building block in your apps. An agent is a large language model (LLM) configured with instructions, tools, and optional runtime behavior such as handoffs, guardrails, and structured outputs. Use this page when you want to define or customize a single base Agent rather than a SandboxAgent. If you are deciding how multiple agents should collaborate, read Agent orchestration. If the agent should run inside an isolated workspace with manifest-defined files and sandbox-native capabilities, read Sandbox agent…
Adopted by
Steady: 0 new projects took it in the last 4 weeks, none the 4 weeks before.thin data
Who's talking about openai/openai-agents-python
- langgenius/dify“Proposal: Package manager migration from `poetry` to `uv`”GitHub · Mar 20, 2025 · 10 reactions
- @stevenheidel.com“2025 is the year of agents. we're excited to bring you a new SDK and new tools to the API to help you build …”Bluesky · Mar 11, 2025 · 9 likes
- OpenHands/OpenHands“Proposal: Minimal Python SDK”GitHub · Aug 22, 2025 · 7 reactions
- A Hacker News story“OpenAI rejects 1,200-line community PR for Google's A2A agent protocol”Hacker News · Oct 30, 2025 · 6 points
- A Hacker News story“OpenAI Agents SDK”Hacker News · Mar 11, 2025 · 6 points
The biggest 5 of 65 mentions linking to the repository that our crawl found. Each line is their own headline.
See all 65
Talked about on GitHub, Bluesky and Hacker News (65 times).
On GitHub · 50
- Mar 20, 2025Proposal: Package manager migration from `poetry` to `uv` — langgenius/dify10 reactions · 4 comments
- Aug 22, 2025Proposal: Minimal Python SDK — OpenHands/OpenHands7 reactions · 16 comments
- Jan 23, 2026feat(provider): support responses api for `@ai-sdk/openai-compatible` providers — anomalyco/opencode5 reactions · 3 comments
- Sep 2, 2025feat: fix #272 add memory feature — openai/openai-agents-js3 reactions · 13 comments
- May 20, 2026feat: add opt-in recovery for missing function tools — openai/openai-agents-js2 reactions · 1 comment
45 more on GitHub
- Jan 14, 2026Pydantic 2.12+ Serialization Warnings with Claude Models in openai-agents when using LiteLLM — BerriAI/litellm2 reactions · 17 comments
- Mar 11, 2025OpenAI Agents Framework instrumentation — pydantic/logfire2 reactions · 5 comments
- Oct 24, 2026chore(deps): bump openai-agents from 0.23.1 to 0.24.0 in /.github/requirements — bmdhodl/agent471 reaction · 2 comments
- Oct 10, 2026chore(deps): bump openai-agents from 0.22.3 to 0.23.1 in /.github/requirements — bmdhodl/agent471 reaction · 1 comment
- Sep 20, 2026docs: clarify Unix-local execution limits — openai/openai-agents-js1 reaction · 2 comments
- Aug 15, 2026Fail closed on provider redirects — arnavsri993/kestrel-agent1 reaction
- Aug 15, 2026feat: add trusted process environment values — openai/openai-agents-js1 reaction · 2 comments
- Aug 15, 2026fix(realtime): handle non-finite audio rates — openai/openai-agents-js1 reaction · 1 comment
- Aug 7, 2026feat(models): preserve raw usage payloads — openai/openai-agents-js1 reaction · 1 comment
- Aug 5, 2026feat(core): pass run context to custom sessions — openai/openai-agents-js1 reaction · 1 comment
- Aug 4, 2026fix(openai-agents): Patch correct `run_single_turn_streamed` reference — getsentry/sentry-python1 reaction · 1 comment
- Aug 2, 2026fix(realtime): apply output guardrails to text deltas — openai/openai-agents-js1 reaction · 1 comment
- Aug 2, 2026feat: support MCP SDK v2 negotiation — openai/openai-agents-js1 reaction · 1 comment
- Aug 2, 2026fix: include all paginated MCP tools — openai/openai-agents-js1 reaction · 1 comment
- Jul 31, 2026feat: preserve sandbox environment secret references — openai/openai-agents-js1 reaction · 1 comment
- Jul 29, 2026feat(runtime): Establish authoritative agent lifecycle — MLGBJDLW/Nexa1 reaction
- Jul 22, 2026fix(extensions): pin and verify rclone sandbox installs — openai/openai-agents-js1 reaction · 1 comment
- Jul 21, 2026fix(core): parse SELinux permission markers — openai/openai-agents-js1 reaction · 1 comment
- Jul 20, 2026feat(extensions): add Vercel cloud bucket mounts — openai/openai-agents-js1 reaction · 1 comment
- Jul 6, 2026feat: add invalid final output recovery handler — openai/openai-agents-js1 reaction · 1 comment
- Jun 23, 2026fix(core): distinguish remote mount edit guidance — openai/openai-agents-js1 reaction · 1 comment
- Jun 23, 2026fix(core): parse special permission bits by position — openai/openai-agents-js1 reaction · 1 comment
- Jun 23, 2026fix(core): await sibling guardrails after failures — openai/openai-agents-js1 reaction · 1 comment
- Jun 23, 2026fix(core): preserve empty array tool outputs — openai/openai-agents-js1 reaction · 1 comment
- Jun 23, 2026fix(core): avoid reevaluating resolved tool approvals — openai/openai-agents-js1 reaction · 1 comment
- Jun 23, 2026fix(realtime): prevent ambiguous tool dispatch — openai/openai-agents-js1 reaction · 1 comment
- Jun 12, 2026fix: expose sandbox error retryability metadata — openai/openai-agents-js1 reaction · 1 comment
- May 22, 2026feat: add SDK-only custom data for tool outputs — openai/openai-agents-js1 reaction · 1 comment
- May 10, 2026fix: align Chat Completions strict validation — openai/openai-agents-js1 reaction · 1 comment
- May 9, 2026fix(core): validate sandbox GitRepo subpaths — openai/openai-agents-js1 reaction · 1 comment
- Feb 19, 2026feat: support ImageContent in tool return value — livekit/agents1 reaction · 9 comments
- Feb 8, 2026OpenAI Agents integration crashes on startup with openai-agents >= 0.7.0 (AttributeError: AgentRunner._get_all_tools) — getsentry/sentry-python1 reaction · 2 comments
- Jan 22, 2026Missing extra_content.google.thought_signature — openai/openai-openapi1 reaction
- Dec 3, 2025Gemini 3 Pro: Multi-turn tool calls fail because thought_signature is not preserved via OpenAI compatibility layer — openai/codex1 reaction · 2 comments
- Nov 10, 2025Rely on OpenAI SDK for retry mechanism — Choice-of-Law-Dataverse/cold-case-analysis1 reaction
- Oct 31, 2025Subagent ideas — tidyverse/ellmer1 reaction · 4 comments
- Oct 29, 2025Please ship cloudflare/sandbox with stable Python ≥3.12 — cloudflare/sandbox-sdk1 reaction · 4 comments
- Oct 5, 2025Agentic workflow — Choice-of-Law-Dataverse/cold-case-analysis1 reaction
- Aug 11, 2025FunctionTool - Error Handling — nlpodyssey/openai-agents-go1 reaction
- Jul 9, 2025Allow agent to return logprobs — openai/openai-agents-js1 reaction · 3 comments
- Jun 20, 2025Plan for implementing OpenAI Agents SDK — InfinitIQ-Tech/GPT-Bridge1 reaction
- May 6, 2025Update pyproject.toml openai-agents minimal version to 0.0.14 — ed-donner/agents1 reaction · 1 comment
- Apr 6, 2025422 Validation failed when viewing most frequent contributor — github/github-mcp-server1 reaction · 2 comments
- Nov 23, 2026Request for unified action logging, replay, and audit across agent frameworks — JaredKlopstein/lacre0 reactions
- Nov 23, 2026Weekly spot-check 2026-11-23 — StefanKasamakov/ai-compass0 reactions
On Bluesky · 13
- Mar 11, 20252025 is the year of agents. we're excited to bring you a new SDK and new tools to the API to help you build your own agents.… — @stevenheidel.com9 likes and reposts
- Jun 28, 2025openai-agents-python A lightweight, powerful framework for multi-agent workflows. https://github.com/openai/openai-agents-python — @pythonhub.dev3 likes and reposts
- Apr 16, 2026🔥 Hot Repo! 🔥 (100+ new stars) 📦 openai / openai-agents-python ⭐ 20,953 (+110) 🗒 Python A lightweight, powerful framework for… — @github-trending.bsky.social2 likes and reposts
- May 14, 2026🚀 GitHub Intelligence Drop gitleaks (Go • 🟢) ⭐ 26.9K → https://github.com/gitleaks/gitleaks openai-agents-python (Python • 🟢) ⭐ 26.3K →… — @githubfeed.bsky.social1 likes and repost
- May 12, 2026OpenAI just launched their Agents SDK with 25.6K stars at github.com/openai/open.... As someone who's built production harnesses for… — @therobertta.bsky.social1 likes and repost · 1 reply
8 more on Bluesky
- Mar 3, 2026https://github.com/openai/openai-agents-python — @tom-doerr.bsky.social1 likes and repost
- Jun 3, 2025They also released the Python version github.com/openai/opena... "It's a production-ready upgrade of our previous experimentation for… — @qianli.dev1 likes and repost · 1 reply
- May 14, 2025OpenAIのAgentSDK、早く試さないと… GitHub - openai/openai-agents-python: A lightweight, powerful framework for multi-agent workflows… — @mikoshibaq.bsky.social1 likes and repost
- Oct 20, 2026Stage 5: Patterns to production GenAI_Agents, 50+ agent tutorials (24k+ stars) github.com/NirDiamant/... OpenAI Agents SDK, open source… — @astrodevil1.bsky.social0 likes and reposts · 1 reply
- May 10, 2026Repo → https://github.com/openai/openai-agents-python 3. google/adk-python Google's Agent Development Kit. The official toolkit for… — @adityamitra.bsky.social0 likes and reposts · 1 reply
- Apr 30, 2026Source: github.com/openai/open.... The SDK is provider-agnostic — works with any LLM. That's a strategic choice. — @therobertta.bsky.social0 likes and reposts · 1 reply
- Apr 20, 2026🎉 Celebrating! 🎉 (500+ new stars) 📦 openai / openai-agents-python ⭐ 23,674 (+752) 🗒 Python A lightweight, powerful framework for… — @github-trending.bsky.social0 likes and reposts · 1 reply
- Jun 11, 2025GitHub repo → github.com/openai/open... — @arindam-1729.bsky.social0 likes and reposts · 1 reply
On Hacker News · 2
- Oct 30, 2025OpenAI rejects 1,200-line community PR for Google's A2A agent protocol6 points · 3 comments
- Mar 11, 2025OpenAI Agents SDK6 points · 1 comment
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository25 other files it gives its agents.
- AGENTS.mdAGENTS.md
- docs/ja/agents.mdAGENTS.md
- docs/ko/agents.mdAGENTS.md
- docs/zh/agents.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- docs/llms-full.txtllms.txt
- docs/llms.txtllms.txt
- code-change-verificationSkill
- docs-syncSkill
- examples-run-analysisSkill
- final-release-reviewSkill
- implementation-final-reviewSkill
- implementation-kickoffSkill
- implementation-strategySkill
- maintainer-reviewSkill
- openai-knowledgeSkill
- pr-draft-summarySkill
- release-candidate-prepSkill
- runtime-behavior-probeSkill
- sensitive-logging-auditSkill
- test-coverage-improverSkill
- credit-note-fixerSkill
- prior-auth-packet-builderSkill
- playwrightSkill
- csv-workbenchSkill
The file
We split this agents.md into the rules it gives an agent
7 rules. About 0 are common, 2 are distinctive, and 5 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
5
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 11
Use this page as the hub for agent definition.
- Very specific: line 75
Create a new prompt variable, poem_style.
- Distinctive: line 76
Create a system prompt with the content:
- Very specific: line 82
Run the example with the --prompt-id flag.
- Very specific: line 132
Read the context guide for the full RunContextWrapper surface, shared usage tracking, nested tool_input, and serialization caveats.
- Very specific: line 183
When you pass an output_type, that tells the model to use structured outputs instead of regular plain text responses.
- Very specific: line 283
Use RunHooks when you want a single observer for the whole workflow, and AgentHooks when you want lifecycle callbacks scoped to a specific …
≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Agents
Agents are the core building block in your apps. An agent is a large language model (LLM) configured with instructions, tools, and optional runtime behavior such as handoffs, guardrails, and structured outputs.
Use this page when you want to define or customize a single base Agent rather than a SandboxAgent. If you are deciding how multiple agents should collaborate, read Agent orchestration. If the agent should run inside an isolated workspace with manifest-defined files and sandbox-native capabilities, read Sandbox agent concepts.
The SDK uses the Responses API by default for OpenAI models, but the distinction here is orchestration: Agent plus Runner lets the SDK manage turns, tools, guardrails, handoffs, and sessions for you. If you want to own that loop yourself, use the Responses API directly instead.
Choose the next guide
Use this page as the hub for agent definition. Jump to the adjacent guide that matches the next decision you need to make.
| If you want to... | Read next |
| Choose a model or provider setup | Models |
| Add capabilities to the agent | Tools |
| Run an agent against a real repo, document bundle, or isolated workspace | Sandbox agents quickstart |
| Decide between manager-style orchestration and handoffs | Agent orchestration |
| Configure handoff behavior | Handoffs |
| Run turns, stream events, or manage conversation state | Running agents |
| Inspect final output, run items, or resumable state | Results |
| Share local dependencies and runtime state | Context management |
Basic configuration
The most common properties of an agent are:
| Property | Required | Description |
name | yes | Human-readable agent name. |
instructions | no | System prompt or dynamic instructions callback. Strongly recommended. See Dynamic instructions. |
prompt | no | OpenAI Responses API prompt configuration. Accepts a static prompt object or a function. See Prompt templates. |
handoff_description | no | Short description exposed when this agent is offered as a handoff target. |
handoffs | no | Delegate the conversation to specialist agents. See handoffs. |
model | no | Which LLM to use. See Models. |
model_settings | no | Model tuning parameters such as temperature, top_p, and tool_choice. |
tools | no | Tools the agent can call. See Tools. |
mcp_servers | no | MCP servers that provide MCP-backed tools to the agent. See the MCP guide. |
mcp_config | no | Fine-tune how MCP tools are prepared, such as converting their schemas to strict mode and formatting MCP failures. See the MCP guide. |
input_guardrails | no | Guardrails that run on the first user input for this agent chain. See Guardrails. |
output_guardrails | no | Guardrails that run on the final output for this agent. See Guardrails. |
output_type | no | Structured output type instead of plain text. See Output types. |
hooks | no | Agent-scoped lifecycle callbacks. See Lifecycle events (hooks). |
tool_use_behavior | no | Control whether tool results loop back to the model or end the run. See Tool use behavior. |
reset_tool_choice | no | Reset tool_choice after a tool call (default: True) to avoid tool-use loops. See Forcing tool use. |
from agents import Agent
from agents.decorators import tool
@tool
def get_weather(city: str) -> str:
"""returns weather info for the specified city."""
return f"The weather in {city} is sunny"
agent = Agent(
name="Haiku agent",
instructions="Always respond in haiku form",
model="gpt-5-nano",
tools=[get_weather],
)Everything in this section applies to Agent. SandboxAgent builds on the same ideas, then adds default_manifest, base_instructions, capabilities, and run_as for workspace-scoped runs. See Sandbox agent concepts.
Prompt templates
You can reference a prompt template created in the OpenAI platform by setting prompt. This works when OpenAI models are accessed through the Responses API.
To use it, please:
- Go to https://platform.openai.com/playground/prompts
- Create a new prompt variable,
poem_style. Create a system prompt with the content:
Write a poem in {{poem_style}}- Run the example with the
--prompt-idflag.
from agents import Agent
agent = Agent(
name="Prompted assistant",
prompt={
"id": "pmpt_123",
"version": "1",
"variables": {"poem_style": "haiku"},
},
)You can also generate the prompt dynamically at run time:
from dataclasses import dataclass
from agents import Agent, GenerateDynamicPromptData, Runner
@dataclass
class PromptContext:
prompt_id: str
poem_style: str
async def build_prompt(data: GenerateDynamicPromptData):
ctx: PromptContext = data.context.context
return {
"id": ctx.prompt_id,
"version": "1",
"variables": {"poem_style": ctx.poem_style},
}
agent = Agent(name="Prompted assistant", prompt=build_prompt)
result = await Runner.run(
agent,
"Say hello",
context=PromptContext(prompt_id="pmpt_123", poem_style="limerick"),
)Context
Agents are generic on their context type. Context is a dependency-injection tool: it's an object you create and pass to Runner.run(), that is passed to every agent, tool, handoff etc, and it serves as a grab bag of dependencies and state for the agent run. You can provide any Python object as the context.
Read the context guide for the full RunContextWrapper surface, shared usage tracking, nested tool_input, and serialization caveats.
from dataclasses import dataclass
@dataclass
class Purchase:
id: str
@dataclass
class UserContext:
name: str
uid: str
is_pro_user: bool
async def fetch_purchases(self) -> list[Purchase]:
# implement your logic here
return []
agent = Agent[UserContext](
...,
)Output types
By default, agents produce plain text (i.e. str) outputs. If you want the agent to produce a particular type of output, you can use the output_type parameter. A common choice is to use Pydantic objects, but we support any type that can be wrapped in a Pydantic TypeAdapter - dataclasses, lists, TypedDict, etc.
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,
)!!! note
When you pass an `output_type`, that tells the model to use [structured outputs](https://platform.openai.com/docs/guides/structured-outputs) instead of regular plain text responses.Multi-agent system design patterns
There are many ways to design multi‑agent systems, but we commonly see two broadly applicable patterns:
- Manager (agents as tools): A central manager/orchestrator invokes specialized sub‑agents as tools and retains control of the conversation.
- Handoffs: Peer agents hand off control to a specialized agent that takes over the conversation. This is decentralized.
See our practical guide to building agents for more details.
Manager (agents as tools)
The customer_facing_agent handles all user interaction and invokes specialized sub‑agents exposed as tools. Read more in the tools documentation.
from agents import Agent
booking_agent = Agent(...)
refund_agent = Agent(...)
customer_facing_agent = Agent(
name="Customer-facing agent",
instructions=(
"Handle all direct user communication. "
"Call the relevant tools when specialized expertise is needed."
),
tools=[
booking_agent.as_tool(
tool_name="booking_expert",
tool_description="Handles booking questions and requests.",
),
refund_agent.as_tool(
tool_name="refund_expert",
tool_description="Handles refund questions and requests.",
),
],
)Handoffs
Configured handoff targets are sub‑agents to which the agent can delegate. When a handoff occurs, the delegated agent receives the conversation history and takes over the conversation. This pattern enables modular, specialized agents that excel at a single task. Read more in the handoffs documentation.
from agents import Agent
booking_agent = Agent(...)
refund_agent = Agent(...)
triage_agent = Agent(
name="Triage agent",
instructions=(
"Help the user with their questions. "
"If they ask about booking, hand off to the booking agent. "
"If they ask about refunds, hand off to the refund agent."
),
handoffs=[booking_agent, refund_agent],
)Dynamic instructions
In most cases, you can provide instructions when you create the agent. However, you can also provide dynamic instructions via a function. The function will receive the agent and context, and must return the prompt. Both regular and async functions are accepted.
from agents import Agent, RunContextWrapper
def dynamic_instructions(context: RunContextWrapper[UserContext], agent: Agent[UserContext]) -> str:
return f"The user's name is {context.context.name}. Help them with their questions."
agent = Agent[UserContext](
name="Triage agent",
instructions=dynamic_instructions,
)Lifecycle events (hooks)
Sometimes, you want to observe the lifecycle of an agent. For example, you may want to log events, pre-fetch data, or record usage when certain events occur.
There are two hook scopes:
- [
RunHooks][agents.lifecycle.RunHooks] observe the entireRunner.run(...)invocation, including handoffs to other agents. - [
AgentHooks][agents.lifecycle.AgentHooks] are attached to a specific agent instance viaagent.hooks.
The callback context also changes depending on the event:
- Agent start/end hooks receive [
AgentHookContext][agents.run_context.AgentHookContext], which wraps your original context and carries the shared run usage state. - LLM, tool, and handoff hooks receive [
RunContextWrapper][agents.run_context.RunContextWrapper].
Typical hook timing:
on_agent_start: when a specific agent begins running;on_agent_end: when that agent finishes producing a final output.on_llm_start/on_llm_end: immediately around each model call.on_tool_start/on_tool_end: around each local tool invocation. For function tools, the hookcontextis typically aToolContext, so you can inspect tool-call metadata such astool_call_id.on_handoff: when control moves from one agent to another.
Use RunHooks when you want a single observer for the whole workflow, and AgentHooks when you want lifecycle callbacks scoped to a specific agent.
from agents import Agent, RunHooks, Runner
class LoggingHooks(RunHooks):
async def on_agent_start(self, context, agent):
print(f"Starting {agent.name}")
async def on_llm_end(self, context, agent, response):
print(f"{agent.name} produced {len(response.output)} output items")
async def on_agent_end(self, context, agent, output):
print(f"{agent.name} finished with usage: {context.usage}")
agent = Agent(name="Assistant", instructions="Be concise.")
result = await Runner.run(agent, "Explain quines", hooks=LoggingHooks())
print(result.final_output)For the full callback surface, see the Lifecycle API reference.
Guardrails
Guardrails allow you to run checks/validations on user input in parallel to the agent running, and on the agent's output once it is produced. For example, you could screen the user's input and agent's output for relevance. Read more in the guardrails documentation.
Cloning/copying agents
By using the clone() method on an agent, you can duplicate an Agent, and optionally change any properties you like.
pirate_agent = Agent(
name="Pirate",
instructions="Write like a pirate",
model="gpt-5.6-sol",
)
robot_agent = pirate_agent.clone(
name="Robot",
instructions="Write like a robot",
)clone() uses dataclasses.replace, so it performs a shallow copy. A list attribute that you do not override, such as tools, handoffs, mcp_servers, input_guardrails, or output_guardrails, remains the exact list held by the original agent. Mutating that list through either agent therefore affects both agents. To give the clone an independent list container, pass a new list, for example pirate_agent.clone(tools=[*pirate_agent.tools, extra_tool]). The entries copied into that new list remain the same tool or handoff objects unless you replace those entries too.
Forcing tool use
Supplying a list of tools doesn't always mean the LLM will use a tool. You can force tool use by setting [ModelSettings.tool_choice][agents.model_settings.ModelSettings.tool_choice]. Valid values are:
auto, which allows the LLM to decide whether or not to use a tool.required, which requires the LLM to use a tool (but it can intelligently decide which tool).none, which requires the LLM to not use a tool.- Setting a specific string e.g.
my_tool, which requires the LLM to use that specific tool.
When you are using OpenAI Responses tool search, named tool choices are more limited: you cannot target bare namespace names or deferred-only tools with tool_choice, and tool_choice="tool_search" does not target [ToolSearchTool][agents.tool.ToolSearchTool]. In those cases, prefer auto or required. See Hosted tool search for the Responses-specific constraints.
from agents import Agent, ModelSettings
from agents.decorators import tool
@tool
def get_weather(city: str) -> str:
"""Returns weather info for the specified city."""
return f"The weather in {city} is sunny"
agent = Agent(
name="Weather Agent",
instructions="Retrieve weather details.",
tools=[get_weather],
model_settings=ModelSettings(tool_choice="get_weather"),
)Tool use behavior
The tool_use_behavior parameter in the Agent configuration controls how tool outputs are handled:
"run_llm_again": The default. Tools are run, and the LLM processes the results to produce a final response."stop_on_first_tool": The output of the first tool call is used as the final response, without further LLM processing.
from agents import Agent
from agents.decorators import tool
@tool
def get_weather(city: str) -> str:
"""Returns weather info for the specified city."""
return f"The weather in {city} is sunny"
agent = Agent(
name="Weather Agent",
instructions="Retrieve weather details.",
tools=[get_weather],
tool_use_behavior="stop_on_first_tool",
)StopAtTools(stop_at_tool_names=[...]): Stops if any specified tool is called, using its output as the final response.
from agents import Agent
from agents.agent import StopAtTools
from agents.decorators import tool
@tool
def get_weather(city: str) -> str:
"""Returns weather info for the specified city."""
return f"The weather in {city} is sunny"
@tool
def sum_numbers(a: int, b: int) -> int:
"""Adds two numbers."""
return a + b
agent = Agent(
name="Stop At Stock Agent",
instructions="Get weather or sum numbers.",
tools=[get_weather, sum_numbers],
tool_use_behavior=StopAtTools(stop_at_tool_names=["get_weather"]),
)ToolsToFinalOutputFunction: A custom function that processes tool results and decides whether to end the run with a final output or continue processing with the LLM.
from agents import Agent, FunctionToolResult, RunContextWrapper
from agents.agent import ToolsToFinalOutputResult
from agents.decorators import tool
from typing import List, Any
@tool
def get_weather(city: str) -> str:
"""Returns weather info for the specified city."""
return f"The weather in {city} is sunny"
def custom_tool_handler(
context: RunContextWrapper[Any], tool_results: List[FunctionToolResult]
) -> ToolsToFinalOutputResult:
"""Processes tool results to decide final output."""
for result in tool_results:
if result.output and "sunny" in result.output:
return ToolsToFinalOutputResult(
is_final_output=True, final_output=f"Final weather: {result.output}"
)
return ToolsToFinalOutputResult(is_final_output=False, final_output=None)
agent = Agent(
name="Weather Agent",
instructions="Retrieve weather details.",
tools=[get_weather],
tool_use_behavior=custom_tool_handler,
)!!! note
To prevent infinite loops, the framework automatically resets `tool_choice` to "auto" after a tool call. This behavior is configurable via [`agent.reset_tool_choice`][agents.agent.Agent.reset_tool_choice]. The infinite loop is because tool results are sent to the LLM, which then generates another tool call because of `tool_choice`, ad infinitum.Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

