OpenAI and Anthropic Agent Development
Two providers, several levels of help. Know which part of the loop each tool runs for you.
The OpenAI Agents SDK runs the agent loop in your process and adds handoffs, guardrails, sessions, approvals and tracing. Anthropic offers a client SDK for the Messages API, including a tool runner that drives the loop over your functions, and the Claude Agent SDK, which gives your program the tools, loop and context management of Claude Code. A separate hosted service, Managed Agents, runs agents on Anthropic's side.
What you will learn: what each tool does for you, two runnable offline examples, how approvals and guardrails work, how to configure a coding-style agent safely, and how the OpenAI SDK compares with LangGraph.
Prerequisites: The Agent Loop: Observe, Reason, Plan, Act, Reflect and Choosing Frameworks: Lock-In, Upgrades and Benchmarks.
Checked in November 2026. The two examples that print output were run with openai-agents 0.26.0 and anthropic 2.14.0, using scripted stand-ins instead of a model, so they need no API key or network. The Claude Agent SDK listing (version 0.2.189) was only loaded to confirm its imports and option names; it was not run against a model.
The options at a glance
| Tool | Who runs the loop | Comes with | Typical use |
|---|---|---|---|
| A provider's client SDK | You write it | Typed requests and responses | Full control, simple agents |
| Anthropic tool runner | The client SDK, in your process | Tool schemas from functions | Your tools, little plumbing |
| OpenAI Agents SDK | The SDK, in your process | Handoffs, guardrails, sessions, tracing | Application agents and teams |
| Claude Agent SDK | The SDK, in your process | File, command and web tools, hooks, permissions, subagents, MCP | Agents that work on files and systems |
| Anthropic Managed Agents | Anthropic, as a hosted service | Hosted runs and sandbox | Long tasks without your own infrastructure |
When a tool runs in your process it can reach whatever your process can reach. The SDK does not make a tool safe. Limit credentials, validate arguments and require approval for actions that change things. See Tool Permissions, Approvals and Abuse Risks.
OpenAI Agents SDK
The SDK is a small set of parts. An agent is a model with instructions and tools. A handoff lets one agent pass the conversation to another. A guardrail checks input or output and can stop a run. A session keeps conversation history between runs. Tracing records what happened. A Runner drives the loop. The Python package needs Python 3.10 or later, and its version number is still below 1.0, so read release notes before upgrading.
The smallest useful shape
Install openai-agents, set your API key, define an Agent with a function decorated by @function_tool, and call Runner.run_sync(agent, "your request"). The function's name, type hints and docstring become the tool description the model reads, so write them for the model as well as for colleagues.
A support flow you can run
This example has a triage agent that hands billing questions to a second agent. The refund tool requires approval, and an input guardrail rejects messages containing something that looks like a card number. ScriptedModel replaces the real model and returns one prepared item per call.
import asyncio
import json
import re
from agents import (Agent, GuardrailFunctionOutput,
InputGuardrailTripwireTriggered, Runner,
function_tool, input_guardrail, set_tracing_disabled)
from agents.items import ModelResponse
from agents.models.interface import Model
from agents.usage import Usage
from openai.types.responses import (ResponseFunctionToolCall,
ResponseOutputMessage,
ResponseOutputText)
set_tracing_disabled(True) # tracing is on by default and uploads runs
REFUNDS = []
class ScriptedModel(Model):
"""Offline stand-in: returns one prepared item per model call."""
def __init__(self, *steps):
self.steps = list(steps)
async def get_response(self, *args, **kwargs):
step = self.steps.pop(0)
if isinstance(step, str):
text = ResponseOutputText(type="output_text", text=step,
annotations=[])
item = ResponseOutputMessage(
id="msg", type="message", role="assistant",
status="completed", content=[text])
else:
name, arguments = step
item = ResponseFunctionToolCall(
type="function_call", call_id=f"call_{name}", name=name,
arguments=json.dumps(arguments))
return ModelResponse(output=[item], usage=Usage(), response_id=None)
def stream_response(self, *args, **kwargs):
raise NotImplementedError
@function_tool(needs_approval=True)
def issue_refund(order_id: str, amount: float) -> str:
"""Refund part or all of an order."""
REFUNDS.append((order_id, amount))
return f"refunded {amount:.2f} on {order_id}"
@input_guardrail(run_in_parallel=False) # finish before the model starts
def no_card_numbers(ctx, agent, user_input) -> GuardrailFunctionOutput:
found = bool(re.search(r"\b\d{13,16}\b", str(user_input)))
return GuardrailFunctionOutput(output_info={"card_number": found},
tripwire_triggered=found)
billing = Agent(
name="Billing agent",
instructions="Handle refunds. Use the tool; never invent a result.",
tools=[issue_refund],
model=ScriptedModel(
("issue_refund", {"order_id": "A-17", "amount": 25.0}),
"Your 25.00 refund on order A-17 has been issued."),
)
triage = Agent(
name="Triage agent",
instructions="Route billing questions to the billing agent.",
handoffs=[billing],
input_guardrails=[no_card_numbers],
model=ScriptedModel(("transfer_to_billing_agent", {})),
)
async def main():
result = await Runner.run(triage, "Refund 25 on order A-17",
max_turns=6)
for pending in result.interruptions:
print("paused for approval:", pending.name, pending.arguments)
print("refunds so far:", REFUNDS)
state = result.to_state() # serializable with state.to_string()
for pending in result.interruptions:
state.approve(pending) # a person decides this, not the model
result = await Runner.run(triage, state)
print("answered by:", result.last_agent.name)
print("answer:", result.final_output)
print("refunds:", REFUNDS)
try:
await Runner.run(triage, "My card is 4111111111111111")
except InputGuardrailTripwireTriggered as error:
name = error.guardrail_result.guardrail.get_name()
print("blocked by guardrail:", name)
asyncio.run(main())
Output:
paused for approval: issue_refund {"order_id": "A-17", "amount": 25.0}
refunds so far: []
answered by: Billing agent
answer: Your 25.00 refund on order A-17 has been issued.
refunds: [('A-17', 25.0)]
blocked by guardrail: no_card_numbers
Read the output in order. The run stops with an interruption and no refund has happened. After approval, the same run resumes, the billing agent is still the one answering, and exactly one refund is recorded. The last request never reaches the model, because the guardrail finished first and tripped.
Approvals
needs_approval=True pauses the run before the tool executes. result.to_state() captures the paused run, which can be turned into a string and stored while a person decides. Your application must add the parts around it: show the reviewer the exact arguments, check who may approve, expire old requests and record the decision. Rejecting is also a normal outcome, so test it.
Guardrails
Input guardrails run in parallel with the agent by default, which saves time but means model work, and possibly tool calls, may start before the check finishes. The example sets run_in_parallel=False so the check completes first. A pattern match like this one catches only simple cases; it illustrates the mechanism and is not a data protection control.
The SDK records traces and sends them to OpenAI unless you disable it or replace the exporter. Traces can contain prompts and tool data. Decide this before real information flows; the example turns tracing off with set_tracing_disabled(True).
Handoffs or agents as tools
| Aspect | Handoff | Agent used as a tool |
|---|---|---|
| Who talks to the user next | The receiving agent | The calling agent |
| What the other agent sees | The conversation, unless filtered | The request passed to it |
| Good for | Routing to a specialist | Asking a specialist for a piece of work |
| Watch for | Loops between agents, leaked context | Lost detail in summaries |
Handoffs, Routing, Shared State and Communication covers how to design the information that crosses either boundary.
Anthropic: your tools with the client SDK
The Messages API returns tool_use blocks when the model wants a tool. Your program runs it and sends back a tool_result block. You can write that loop yourself, or use the client SDK's tool runner, found under client.beta.messages. The beta namespace signals that its interface may still change.
The example uses the real SDK and replaces only the network: a mock transport answers in the API's response format.
import json
import anthropic
import httpx2
from anthropic import beta_tool
ORDERS = {"A-17": {"status": "delayed", "eta_days": 3}}
SCRIPT = [
([{"type": "tool_use", "id": "toolu_1", "name": "order_status",
"input": {"order_id": "A-17"}}], "tool_use"),
([{"type": "text",
"text": "Order A-17 is delayed and due in 3 days."}], "end_turn"),
]
def fake_api(request):
"""Offline stand-in for the Messages API."""
body = json.loads(request.content)
last = body["messages"][-1]["content"]
if isinstance(last, list):
print("tool result sent back:", last[0]["content"])
content, stop = SCRIPT.pop(0)
return httpx2.Response(200, json={
"id": "msg_1", "type": "message", "role": "assistant",
"model": body["model"], "content": content, "stop_reason": stop,
"usage": {"input_tokens": 1, "output_tokens": 1}})
@beta_tool
def order_status(order_id: str) -> str:
"""Look up the delivery status of one order.
Args:
order_id: Order reference such as A-17.
"""
order = ORDERS.get(order_id)
return json.dumps(order or {"error": "unknown order id"})
client = anthropic.Anthropic(
api_key="test-key-not-real",
http_client=httpx2.Client(transport=httpx2.MockTransport(fake_api)))
runner = client.beta.messages.tool_runner(
model="claude-sonnet-5-5",
max_tokens=500,
max_iterations=5, # always bound the loop
tools=[order_status],
messages=[{"role": "user", "content": "Where is order A-17?"}],
)
for message in runner:
for block in message.content:
if block.type == "tool_use":
print("model asked for:", block.name, block.input)
elif block.type == "text":
print("answer:", block.text)
print("schema sent to the model:")
print(json.dumps(order_status.to_dict()["input_schema"], indent=2))
Output:
model asked for: order_status {'order_id': 'A-17'}
tool result sent back: {"status": "delayed", "eta_days": 3}
answer: Order A-17 is delayed and due in 3 days.
schema sent to the model:
{
"additionalProperties": false,
"properties": {
"order_id": {
"description": "Order reference such as A-17.",
"title": "Order Id",
"type": "string"
}
},
"required": [
"order_id"
],
"type": "object"
}
The decorator built the input schema from the type hint and the docstring, which is what the model sees. The runner called the function, sent its result back and stopped when the model ended its turn. max_iterations bounds the number of rounds; check the final stop reason in real code so that a truncated run is not mistaken for a finished one.
Patterns that need no framework
| Pattern | How it looks in code |
|---|---|
| Prompt chaining | Call the model, check the result, call again |
| Routing | One short classification call, then a chosen path |
| Parallel calls | Independent requests run together, then combined |
| Orchestrator and workers | One call plans subtasks, others carry them out |
| Evaluator and optimizer | Draft, critique against criteria, revise within a limit |
Start with the simplest pattern that passes your evaluation set. Each added call costs money and creates another place to fail. Single-Agent vs Multi-Agent Systems helps decide when more agents are justified.
Claude Agent SDK
The Agent SDK is Claude Code used as a library, available for Python and TypeScript. It was previously called the Claude Code SDK; the Python package is now claude-agent-sdk and the options class is ClaudeAgentOptions. It includes tools to read, write and edit files, run commands and search the web, together with hooks, permissions, subagents, MCP connections and resumable sessions. Anthropic's documentation directs third-party products to API key authentication and not to claude.ai sign-in unless approved.
A read-only code reviewer looks like this. It needs the SDK, credentials and a repository, and was not executed for this page.
import asyncio
from claude_agent_sdk import ClaudeAgentOptions, ResultMessage, query
options = ClaudeAgentOptions(
system_prompt="You review code. Report findings; do not edit files.",
tools=["Read", "Grep", "Glob"], # what exists at all
allowed_tools=["Read", "Grep", "Glob"], # what runs without asking
permission_mode="dontAsk", # deny anything else
max_turns=12,
cwd="./repo",
)
async def main():
async for message in query(prompt="Find unhandled errors in src/",
options=options):
if isinstance(message, ResultMessage):
print(message.subtype, message.result)
asyncio.run(main())
Availability and permission are different
| Option | Effect |
|---|---|
tools | Which built-in tools exist for the model at all |
allowed_tools | Which tools run without asking; it does not remove the others |
disallowed_tools | Removed from the model's context |
permission_mode | What happens to everything not already decided |
max_turns, max_budget_usd | Limits on length and spend |
The common mistake is to list a few names in allowed_tools and assume nothing else can run. To restrict, set tools as well and choose a mode that denies the rest. Settings, project files and connected servers can add configuration, so check what a deployed agent actually loads, and run it in an isolated environment with only the files and network access it needs.
A mode that skips permission checks belongs only inside a disposable, isolated environment. A prompt injection in a file or web page then has nothing standing between it and your tools. See Tool Permissions, Approvals and Abuse Risks.
Picking among the Anthropic options
| If you are | Use |
|---|---|
| Calling your own business functions in an application | Client SDK, with or without the tool runner |
| Building an agent that explores files and runs commands | Claude Agent SDK |
| Running long asynchronous work without managing sandboxes | Managed Agents |
| Working interactively in a terminal | Claude Code itself |
OpenAI Agents SDK or LangGraph
They answer different questions. The Agents SDK is organized around agents that call tools and hand off to each other, with the runtime managing turns. LangGraph is organized around an explicit graph of steps over shared state, with checkpoints.
| Aspect | OpenAI Agents SDK | LangGraph |
|---|---|---|
| Main idea | Agents, tools and handoffs | Nodes, edges and state |
| Who decides the path | Mostly the model, within your limits | Your graph, with model choices where you place them |
| Pause and resume | Interruptions and serializable run state | Checkpointers and interrupts |
| Conversation history | Sessions | State saved per thread |
| Other providers | Possible through model adapters; test features | Through LangChain model integrations |
| Fits best | Conversational routing and tool use | Defined processes with branches and long waits |
Combining them is possible but doubles the concepts to debug. Decide which one owns the state. See LangChain and LangGraph.
Testing without the model
Both examples show the same technique at different seams. The first swaps the model object; the second swaps the HTTP transport. The second also exercises request building and response parsing, so it catches more after an SDK upgrade.
Write tests for an approval refused, a tool that raises, an unknown tool name, a step limit reached and a guardrail trip. A fake proves nothing about how a real model chooses; that needs Agent Evaluation Framework.
Before production
- Model names and versions are configuration, and changes are evaluated
- Every run has a turn limit, a time limit and a spending limit
- Actions with effects use an operation key, so a retry cannot repeat them
- Paused runs are stored durably and tied to the person who may approve
- Trace destinations and retention are agreed with whoever owns the data
- Rate limit and overload errors have a tested fallback
Common mistakes
| Mistake | Better practice |
|---|---|
| Treating a guardrail as access control | Enforce permissions inside the tool and the service |
| Assuming parallel guardrails block first | Run blocking checks before the model |
Reading allowed_tools as a restriction | Set available tools and the permission mode |
| Leaving default tracing on with sensitive data | Configure or disable it deliberately |
| No loop limit | Set turn limits and handle reaching them |
| Floating a pre-1.0 version | Pin it and test upgrades |
Checklist
- The chosen tool matches who should run the loop and where tools execute
- Tool descriptions and schemas were read as the model sees them
- Approval, refusal and guardrail paths are tested
- Limits and stop reasons are handled
- Coding-style agents run isolated with the smallest tool set
- Versions are pinned and checked against current documentation
Frequently asked questions
Can the OpenAI Agents SDK use other model providers?
It supports adapters for other models. Features such as hosted tools or structured output may not behave the same, so test the ones you rely on.
Is the Claude Agent SDK needed to call tools with Claude?
No. Tool use is part of the Messages API. The Agent SDK is for agents that want Claude Code's built-in tools and loop.
Do these SDKs keep a run alive across restarts?
They provide state or sessions you can store, but you choose the storage and recovery process. Check what survives a killed process.
Which should a beginner start with?
Write one tool loop with a client SDK first. After that, the features of an agent SDK are easier to understand and judge.
References and further reading
- OpenAI Agents SDK documentation
- Claude Agent SDK overview
- Claude Agent SDK migration guide
- Anthropic client SDKs
- Anthropic Managed Agents overview
Next steps
LangChain and LangGraph
Agents on an explicit graph.
Reliable Tool Execution and Error Recovery
Make actions safe to retry.
Human-in-the-Loop and Approval Gates
Design approvals properly.