Loading...
Loading...
OpenAI Agents SDK for JavaScript/TypeScript (text + voice agents). Use for multi-agent workflows, tools, guardrails, or encountering Zod errors, MCP failures, infinite loops, tool call issues.
npx skill4agent add secondsky/claude-skills openai-agentsbun add @openai/agents zod@3
bun add @openai/agents-realtime # For voice agentsexport OPENAI_API_KEY="your-api-key"import { Agent, run, tool } from '@openai/agents';
import { z } from 'zod';
const agent = new Agent({
name: 'Assistant',
instructions: 'You are helpful.',
tools: [tool({
name: 'get_weather',
parameters: z.object({ city: z.string() }),
execute: async ({ city }) => `Weather in ${city}: sunny`,
})],
model: 'gpt-4o-mini',
});
const result = await run(agent, 'What is the weather in SF?');// Voice agent
const voiceAgent = new RealtimeAgent({
voice: 'alloy',
model: 'gpt-4o-realtime-preview',
});
// Browser session
const session = new RealtimeSession(voiceAgent, {
apiKey: sessionApiKey, // From backend!
transport: 'webrtc',
});
// Multi-agent handoffs
const triageAgent = Agent.create({
handoffs: [billingAgent, techAgent],
});templates/// ❌ Can cause type errors
parameters: mySchema
// ✅ Works reliably
parameters: z.object({ field: z.string() })import { initializeTracing } from '@openai/agents/tracing';
await initializeTracing();const result = await run(agent, input, {
maxTurns: 20,
});
// Or improve instructions
instructions: `After using tools, provide a final answer.
Do not loop endlessly.`references/common-errors.mdreferences/agent-patterns.mdreferences/common-errors.mdreferences/realtime-transports.mdreferences/cloudflare-integration.mdreferences/official-links.mdrequiresApproval: truetemplates/text-agents/templates/realtime-agents/// Basic
const result = await run(agent, 'Your question');
// Streaming
const stream = await run(agent, input, { stream: true });
// Structured output
const agent = new Agent({
outputType: z.object({ sentiment: z.enum([...]), confidence: z.number() }),
});templates/text-agents/const voiceAgent = new RealtimeAgent({
voice: 'alloy', // alloy, echo, fable, onyx, nova, shimmer
model: 'gpt-4o-realtime-preview',
});
const session = new RealtimeSession(voiceAgent, {
apiKey: sessionApiKey,
transport: 'webrtc', // or 'websocket'
});templates/realtime-agents/references/realtime-transports.mdexport default {
async fetch(request: Request, env: Env) {
const { message } = await request.json();
process.env.OPENAI_API_KEY = env.OPENAI_API_KEY;
const agent = new Agent({
name: 'Assistant',
instructions: 'Be helpful and concise',
model: 'gpt-4o-mini',
});
const result = await run(agent, message, { maxTurns: 5 });
return new Response(JSON.stringify({
response: result.finalOutput,
tokens: result.usage.totalTokens,
}));
},
};templates/cloudflare-workers/references/cloudflare-integration.md// app/api/agent/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { Agent, run } from '@openai/agents';
export async function POST(request: NextRequest) {
const { message } = await request.json();
const agent = new Agent({ /* ... */ });
const result = await run(agent, message);
return NextResponse.json({ response: result.finalOutput });
}templates/nextjs/// Input/output guardrails
const agent = new Agent({
inputGuardrails: [homeworkDetectorGuardrail],
outputGuardrails: [piiFilterGuardrail],
});
// Human approval
const tool = tool({
requiresApproval: true,
execute: async ({ amount }) => `Refunded $${amount}`,
});
// Handle approval loop
while (result.interruption?.type === 'tool_approval') {
result = (await promptUser(result.interruption))
? await result.state.approve(result.interruption)
: await result.state.reject(result.interruption);
}templates/text-agents/agent-guardrails-*.tsagent-human-approval.tsreferences/agent-patterns.mdtemplates/text-agents/agent-parallel.tsprocess.env.DEBUG = '@openai/agents:*';
const result = await run(agent, input);
console.log('Tokens:', result.usage.totalTokens, 'Turns:', result.history.length);templates/shared/tracing-setup.tsOPENAI_API_KEYmaxTurnsgpt-4o-miniopenai-api| Task | Without Skill | With Skill | Savings |
|---|---|---|---|
| Multi-agent setup | ~12k tokens | ~5k tokens | 58% |
| Voice agent | ~10k tokens | ~4k tokens | 60% |
| Error debugging | ~8k tokens | ~3k tokens | 63% |
| Average | ~10k | ~4k | ~60% |
agent-basic.tsagent-handoffs.tsagent-structured-output.tsagent-streaming.tsagent-guardrails-input.tsagent-guardrails-output.tsagent-human-approval.tsagent-parallel.tsrealtime-agent-basic.tsrealtime-session-browser.tsxrealtime-handoffs.tsworker-text-agent.tsworker-agent-hono.tsapi-agent-route.tsapi-realtime-route.tserror-handling.tstracing-setup.tsagent-patterns.mdcommon-errors.mdrealtime-transports.mdcloudflare-integration.mdofficial-links.md