Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/dark-melons-go.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@openai/agents-core': patch
---

fix(interruptions): avoid double outputting function calls for approval requests
5 changes: 5 additions & 0 deletions .changeset/weak-views-care.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@openai/agents-core': patch
---

fix(interruptions): avoid accidental infinite loop if all interruptions were not cleared. expose interruptions helper on state
1 change: 1 addition & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export default tseslint.config(
'**/docs/.astro/**',
'examples/realtime-next/**',
'examples/realtime-demo/**',
'examples/nextjs/**',
'integration-tests//**',
]),
eslint.configs.recommended,
Expand Down
41 changes: 41 additions & 0 deletions examples/nextjs/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*

# env files (can opt-in for committing if needed)
.env*

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
28 changes: 28 additions & 0 deletions examples/nextjs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Next.js Demo

This example shows a basic example of how to use human-in-the-loop in a Next.js application.

Right now it only uses a synchronous approach without streaming and storing in an in-memory DB.

Eventually we will add more examples.

## Run the example

Set the `OPENAI_API_KEY` environment variable and run:

```bash
pnpm -F nextjs dev
```

Open [http://localhost:3000](http://localhost:3000) in your browser and ask `What is the weather in San Francisco and Oakland?`

## Endpoints

- **`/`** – The basic example that actually handles receiving the approval requests and sending messages to the API. Code in `src/app/page.tsx`.
- **`/api/basic`** – The endpoint that gets triggered to run the agent. Code in `src/app/websocket/page.tsx`.

## Other files

- `src/components/Approvals.tsx` — renders the approval dialog
- `src/agents.ts` — contains the basic Agent configuration
- `src/db.ts` — contains the mock database implementation
21 changes: 21 additions & 0 deletions examples/nextjs/components.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/app/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}
7 changes: 7 additions & 0 deletions examples/nextjs/next.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import type { NextConfig } from 'next';

const nextConfig: NextConfig = {
/* config options here */
};

export default nextConfig;
35 changes: 35 additions & 0 deletions examples/nextjs/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"name": "nextjs",
"private": true,
"scripts": {
"dev": "next dev --turbopack",
"build": "next build",
"start": "next start",
"lint": "next lint",
"build-check": "tsc --noEmit"
},
"dependencies": {
"@openai/agents": "workspace:*",
"@radix-ui/react-dialog": "^1.1.14",
"@radix-ui/react-slot": "^1.2.3",
"@tanstack/react-query": "^5.80.7",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.515.0",
"next": "15.3.2",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"tailwind-merge": "^3.3.1",
"wavtools": "^0.1.5",
"zod": "~3.25.40"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"tailwindcss": "^4",
"tw-animate-css": "^1.3.4",
"typescript": "^5"
}
}
5 changes: 5 additions & 0 deletions examples/nextjs/postcss.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const config = {
plugins: ['@tailwindcss/postcss'],
};

export default config;
1 change: 1 addition & 0 deletions examples/nextjs/public/file.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions examples/nextjs/public/globe.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions examples/nextjs/public/next.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions examples/nextjs/public/vercel.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions examples/nextjs/public/window.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
21 changes: 21 additions & 0 deletions examples/nextjs/src/agents.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Agent, tool } from '@openai/agents';
import z from 'zod';

const getWeather = tool({
name: 'getWeather',
description: 'Get the weather for a given city',
parameters: z.object({
city: z.string(),
}),
execute: async ({ city }) => {
return `The weather in ${city} is sunny.`;
},

needsApproval: true,
});

export const agent = new Agent({
name: 'Basic Agent',
instructions: 'You are a basic agent.',
tools: [getWeather],
});
114 changes: 114 additions & 0 deletions examples/nextjs/src/app/api/basic/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import { NextRequest, NextResponse } from 'next/server';
import { randomUUID } from 'node:crypto';

import { agent } from '@/agents';
import {
AgentInputItem,
Runner,
RunState,
RunToolApprovalItem,
} from '@openai/agents';
import { db } from '@/db';

function generateConversationId() {
return `conv_${randomUUID().replace(/-/g, '').slice(0, 24)}`;
}

export async function POST(req: NextRequest) {
try {
const data = await req.json();
let { messages, conversationId, decisions } = data;

if (!messages) {
messages = [];
}

if (!conversationId) {
// we will generate a conversation ID so we can keep track of the state in case of conversations
// this is just a key that we can use to store information in the database
conversationId = generateConversationId();
}

if (!decisions) {
decisions = null;
}

const runner = new Runner({
groupId: conversationId,
});

let input: AgentInputItem[] | RunState<any, any>;
if (
Object.keys(decisions).length > 0 &&
data.conversationId /* original conversationId */
) {
// If we receive a new request with decisions, we will look up the current state in the database
const stateString = await db().get(data.conversationId);

if (!stateString) {
return NextResponse.json(
{ error: 'Conversation not found' },
{ status: 404 },
);
}

// We then deserialize the state so we can manipulate it and continue the run
const state = await RunState.fromString(agent, stateString);

const interruptions = state.getInterruptions();

interruptions.forEach((item: RunToolApprovalItem) => {
// For each interruption, we will then check if the decision is to approve or reject the tool call
if (item.type === 'tool_approval_item' && 'callId' in item.rawItem) {
const callId = item.rawItem.callId;

if (decisions[callId] === 'approved') {
state.approve(item);
} else if (decisions[callId] === 'rejected') {
state.reject(item);
}
}
});

// We will use the new updated state to continue the run
input = state;
} else {
// If we don't have any decisions, we will just assume this is a regular chat and use the messages
// as input for the next run
input = messages;
}

const result = await runner.run(agent, input);

if (result.interruptions.length > 0) {
// If the run resulted in one or more interruptions, we will store the current state in the database

// store the state in the database
await db().set(conversationId, JSON.stringify(result.state));

// We will return all the interruptions as approval requests to the UI/client so it can generate
// the UI for approvals
// We will also still return the history that contains the tool calls and potentially any interim
// text response the agent might have generated (like announcing that it's calling a function)
return NextResponse.json({
conversationId,
approvals: result.interruptions
.filter((item) => item.type === 'tool_approval_item')
.map((item) => item.toJSON()),
history: result.history,
});
}

return NextResponse.json({
response: result.finalOutput,
history: result.history,
conversationId,
});
} catch (error) {
console.error(error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 },
);
}
}
Binary file added examples/nextjs/src/app/favicon.ico
Binary file not shown.
Loading