OpenAI and Anthropic Agent Development

Two providers, several levels of help. Know which part of the loop each tool runs for you.

BeginnerIntermediateExpert · 13 min read · Last updated:

In short

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.

Versions used

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.

Beginner Which tool is which

The options at a glance

ToolWho runs the loopComes withTypical use
A provider's client SDKYou write itTyped requests and responsesFull control, simple agents
Anthropic tool runnerThe client SDK, in your processTool schemas from functionsYour tools, little plumbing
OpenAI Agents SDKThe SDK, in your processHandoffs, guardrails, sessions, tracingApplication agents and teams
Claude Agent SDKThe SDK, in your processFile, command and web tools, hooks, permissions, subagents, MCPAgents that work on files and systems
Anthropic Managed AgentsAnthropic, as a hosted serviceHosted runs and sandboxLong tasks without your own infrastructure
Your codestarts a run
Model callprovider API
Checklimits and approval
Your toolruns locally
Answer
↺ tool results return to the model until it answers or a limit stops the run
With an in-process SDK, tools execute with your program's permissions.
Where the code runs matters

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.

Intermediate Handoffs, approvals and guardrails

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.

Tracing is on by default

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

AspectHandoffAgent used as a tool
Who talks to the user nextThe receiving agentThe calling agent
What the other agent seesThe conversation, unless filteredThe request passed to it
Good forRouting to a specialistAsking a specialist for a piece of work
Watch forLoops between agents, leaked contextLost 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

PatternHow it looks in code
Prompt chainingCall the model, check the result, call again
RoutingOne short classification call, then a chosen path
Parallel callsIndependent requests run together, then combined
Orchestrator and workersOne call plans subtasks, others carry them out
Evaluator and optimizerDraft, 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

OptionEffect
toolsWhich built-in tools exist for the model at all
allowed_toolsWhich tools run without asking; it does not remove the others
disallowed_toolsRemoved from the model's context
permission_modeWhat happens to everything not already decided
max_turns, max_budget_usdLimits 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.

Bypass modes

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 areUse
Calling your own business functions in an applicationClient SDK, with or without the tool runner
Building an agent that explores files and runs commandsClaude Agent SDK
Running long asynchronous work without managing sandboxesManaged Agents
Working interactively in a terminalClaude Code itself
Expert Comparison, testing and operations

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.

AspectOpenAI Agents SDKLangGraph
Main ideaAgents, tools and handoffsNodes, edges and state
Who decides the pathMostly the model, within your limitsYour graph, with model choices where you place them
Pause and resumeInterruptions and serializable run stateCheckpointers and interrupts
Conversation historySessionsState saved per thread
Other providersPossible through model adapters; test featuresThrough LangChain model integrations
Fits bestConversational routing and tool useDefined 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.

Fake model objectfast; tests your control flow
Fake transportalso tests SDK parsing
Real modelslow; tests behavior on an evaluation set
Use all three, for different questions.

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

MistakeBetter practice
Treating a guardrail as access controlEnforce permissions inside the tool and the service
Assuming parallel guardrails block firstRun blocking checks before the model
Reading allowed_tools as a restrictionSet available tools and the permission mode
Leaving default tracing on with sensitive dataConfigure or disable it deliberately
No loop limitSet turn limits and handle reaching them
Floating a pre-1.0 versionPin 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

Next steps