agents/apiTHE ENCYCLOPEDIA
Integration guides

Build a Next.js order agent: server, tools & streaming

Run a complete local order-lookup example with server-side credentials, a validated function tool, and browser progress.

Browser POST
Next.js server
Agent session
Order lookup
Stream result

What you will run

The browser asks for fictional order ORDER-100. A Next.js route creates a managed session without a sandbox. The agent requests lookup_order; server code validates the arguments and checks a server-owned demo identity. The result returns to the harness, which completes its answer. The browser displays event progress, the session ID, tool results, and the final text. Running the example uses your API credits.

Create the project and add the files

Create a separate JavaScript App Router project without a src directory. Download the three files below: put order-runner.mjs in lib/, route.js in app/api/order/, and page.jsx in app/. Replace the generated page.js or page.tsx so the route has one page file. Keep the generated root layout. Install openai in this example project, not in the browser.

Example
npx create-next-app@latest order-agent --js --app --no-src-dir --use-npm
cd order-agent
npm install openai
# Files: lib/order-runner.mjs, app/api/order/route.js, app/page.jsx
# Set OPENAI_API_KEY in .env.local (never NEXT_PUBLIC_OPENAI_API_KEY).
npm run dev -- --hostname 127.0.0.1

Follow one request from end to end

Open the printed local URL and choose Look up order. The runner reads current required_actions rather than executing old history items. It returns success/output or failure/error using the pending turn_id and call_id. It stores results for repeated read-only calls during this run. The page parses newline-delimited JSON across network chunk boundaries and distinguishes a result from an interrupted transport.

Check the actual outcome

A successful fixture lookup returns order_id ORDER-100 and status shipped. Inspect toolResults as well as text: a completed root turn can still describe a tool failure. Text is assembled by item and content part, and a final output_text.done replaces its accumulated deltas. A subagent completion does not finish the root run. If the connection ends before a root outcome, preserve the displayed session ID and inspect saved state; do not immediately create another task.

Understand the access boundary

The downloaded route only runs in development, requires a loopback host and matching Origin, and submits a fixed read-only task. Bind the server to 127.0.0.1. The demo identity is not authentication. For a customer-facing application, authenticate the user, persist user-to-session ownership, validate every lookup against that identity, apply quotas, and use durable job processing. Do not expose this tutorial endpoint through a public tunnel.

Timeouts, cleanup, and verification

The route disables automatic SDK retries, sets a request timeout, and caps its local stream at 90 seconds. Closing that stream does not cancel remote agent work. No session is automatically deleted: inspect the result before cleanup using the official session management API. The downloadable code has offline tests for tool results, authorization, final text, and failed streams; live execution still requires your project's Agents API and model access.

Read the official reference

Check the source for current API fields, account requirements, and service limits.

OpenAI: functions Session events and final text

38 matching topics

What is the OpenAI Agents API?FoundationsAgents API vs Agents SDK vs Responses APIComparisonsAgents API quickstartGetting startedSessions, turns & durable stateCore conceptsHosted vs self-hosted sandboxesInfrastructureConnect MCP servers to Agents APITools & integrationsFunction calling & application toolsTools & integrationsMulti-agent orchestrationCore conceptsStreaming, webhooks & event handlingIntegration guidesFiles, outputs & published artifactsCore conceptsVaults & MCP authenticationTools & integrationsAgent security & credential boundariesProductionTracing, usage & debuggingProductionAgents API pricing & cost planningProductionOpenAI Agents API with PythonGetting startedAgents API with TypeScript & Next.jsIntegration guidesWhat is the OpenAI Agents SDK?FoundationsResponses API in the agent stackFoundationsAgent Skills & SKILL.mdTools & integrationsProgrammatic Tool CallingTools & integrationsRAG, file search & vector storesTools & integrationsWeb search & source citationsTools & integrationsChatKit & Agent BuilderIntegration guidesAgent configuration & reusable definitionsCore conceptsPlugins: connect skills and MCP toolsTools & integrationsSandbox lifecycle & executor connectionsInfrastructureWebhook verification, queues & deduplicationIntegration guidesAgent retries, timeouts & failure recoveryProductionAgent evaluations & regression testingProductionWhich parts of the agent stack do you need?FoundationsAgents API contract quick referenceIntegration guidesOrder agent reference: approval, recovery & evaluationIntegration guidesBuild a Next.js order agent: server, tools & streamingIntegration guidesPython Agents API example with a real tool loopGetting startedHuman approval & prompt injection defensesProductionAgents API troubleshooting: symptoms, checks & recoveryProductionAgent tool support & runtime ownership matrixComparisonsAgent resources, relationships & task stateCore concepts
K to open Esc to close