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
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ jobs:
workflow-streams
message-passing/introduction
message-passing/safe-message-handlers
openai-agents
polling/infrequent
)
for project in "${projects[@]}"; do
Expand Down
2 changes: 2 additions & 0 deletions .scripts/copy-shared-files.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ const GITIGNORE_EXCLUDE = [
'nestjs-exchange-rates',
];
const ESLINTRC_EXCLUDE = [
'openai-agents',
Comment thread
brianstrauch marked this conversation as resolved.
'nextjs-ecommerce-oneclick',
'monorepo-folders',
'fetch-esm',
Expand All @@ -63,6 +64,7 @@ const ESLINTIGNORE_EXCLUDE = [
];

const POST_CREATE_EXCLUDE = [
'openai-agents',
'schedules',
'timer-examples',
'query-subscriptions',
Expand Down
1 change: 1 addition & 0 deletions .scripts/list-of-samples.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"nexus-cancellation",
"nexus-hello",
"nexus-messaging",
"openai-agents",
"patching-api",
"production",
"protobufs",
Expand Down
56 changes: 37 additions & 19 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,25 @@
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->

- [samples-typescript](#samples-typescript)
- [Running](#running)
- [Locally](#locally)
- [Scaffold](#scaffold)
- [Samples](#samples)
- [Basic](#basic)
- [API demos](#api-demos)
- [Activity APIs and design patterns](#activity-apis-and-design-patterns)
- [Nexus APIs](#nexus-apis)
- [Workflow APIs](#workflow-apis)
- [Production APIs](#production-apis)
- [Advanced APIs](#advanced-apis)
- [Test APIs](#test-apis)
- [Full-stack apps](#full-stack-apps)
- [External apps \& libraries](#external-apps--libraries)
- [Contributing](#contributing)
- [Dependencies](#dependencies)
- [Upgrading the SDK version in `package.json`s](#upgrading-the-sdk-version-in-packagejsons)
- [Config files](#config-files)
- [Running](#running)
- [Locally](#locally)
- [Scaffold](#scaffold)
- [Samples](#samples)
- [Basic](#basic)
- [API demos](#api-demos)
- [Activity APIs and design patterns](#activity-apis-and-design-patterns)
- [Nexus APIs](#nexus-apis)
- [Workflow APIs](#workflow-apis)
- [Production APIs](#production-apis)
- [Advanced APIs](#advanced-apis)
- [Test APIs](#test-apis)
- [AI / LLM](#ai--llm)
- [Full-stack apps](#full-stack-apps)
- [External apps & libraries](#external-apps--libraries)
- [Contributing](#contributing)
- [Dependencies](#dependencies)
- [Upgrading the SDK version in `package.json`s](#upgrading-the-sdk-version-in-packagejsons)
- [Config files](#config-files)

<!-- END doctoc generated TOC please keep comment here to allow auto update -->

Expand Down Expand Up @@ -161,6 +161,24 @@ and you'll be given the list of sample options.
- [**Mocha with code coverage or Jest**](https://github.com/temporalio/samples-typescript/tree/main/activities-examples#testing)
- [**Time skipping**](https://github.com/temporalio/samples-typescript/tree/main/timer-examples#testing)

#### AI / LLM

- [**OpenAI Agents**](./openai-agents): Run [OpenAI Agents SDK](https://github.com/openai/openai-agents-js) agents as Temporal Workflows with the `@temporalio/openai-agents` integration. The [`openai-agents/`](./openai-agents) directory contains fourteen samples:
- [**Basic**](./openai-agents/basic): A single agent plus the building blocks — Activity-backed and inline tools, local-Activity tools, agent context, structured output, per-run model override, and dynamic instructions.
- [**Handoffs**](./openai-agents/handoffs): A triage agent routes each request to a specialist agent, using both the `Agent[]` and `handoff()` forms and a per-handoff input filter.
- [**Agent Patterns**](./openai-agents/agent-patterns): Multi-agent orchestration patterns — deterministic chaining, parallelization, LLM-as-judge, agents-as-tools, and input/output guardrails.
- [**Sessions**](./openai-agents/sessions): Conversation history with `WorkflowSafeMemorySession`, including carrying history across a `continueAsNew` boundary.
- [**Human Approval**](./openai-agents/human-approval): A human-in-the-loop tool that pauses the run for an `approve` Signal, then resumes by serializing and rehydrating the run state across `continueAsNew`.
- [**Tools**](./openai-agents/tools): Server-side hosted tools — web search, image generation, and code interpreter — executed by the model provider in the model Activity.
- [**Tracing**](./openai-agents/tracing): The three supported tracing paths — a custom `TracingProcessor`, the OpenAI hosted exporter, and OpenTelemetry — plus `temporal:*` orchestration spans.
- [**Model Providers**](./openai-agents/model-providers): Pass a custom `ModelProvider` to point an agent at any OpenAI-compatible endpoint.
- [**Reasoning Content**](./openai-agents/reasoning-content): Read a reasoning model's `reasoning_content` field by calling the `openai` SDK directly from an Activity.
- [**MCP**](./openai-agents/mcp): Stateless and stateful Model Context Protocol servers (stdio, Streamable HTTP, SSE, and prompt servers) running locally.
- [**Hosted MCP**](./openai-agents/hosted-mcp): A `HostedMCPTool` the model calls server-side, with and without a Signal-driven approval round trip.
- [**Research Bot**](./openai-agents/research-bot): A planner agent fans out concurrent web searches and a writer agent synthesizes a final report.
- [**Customer Service**](./openai-agents/customer-service): A long-running, multi-turn Workflow driven by Updates and Queries, with triage handoffs and `continueAsNew` to bound history.
- [**Nexus Tools**](./openai-agents/nexus-tools): Expose a Nexus Operation as an agent tool with `nexusOperationAsTool`.

### Full-stack apps

- **Next.js**:
Expand Down
3 changes: 3 additions & 0 deletions openai-agents/.eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
lib
.eslintrc.js
48 changes: 48 additions & 0 deletions openai-agents/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
const { builtinModules } = require('module');

const ALLOWED_NODE_BUILTINS = new Set(['assert']);

module.exports = {
root: true,
parser: '@typescript-eslint/parser',
parserOptions: {
project: './tsconfig.json',
tsconfigRootDir: __dirname,
},
plugins: ['@typescript-eslint', 'deprecation'],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
'prettier',
],
rules: {
// recommended for safety
'@typescript-eslint/no-floating-promises': 'error', // forgetting to await Activities and Workflow APIs is bad
'deprecation/deprecation': 'warn',

// code style preference
'object-shorthand': ['error', 'always'],

// relaxed rules, for convenience
'@typescript-eslint/no-unused-vars': [
'warn',
{
argsIgnorePattern: '^_',
varsIgnorePattern: '^_',
},
],
'@typescript-eslint/no-explicit-any': 'off',
},
overrides: [
{
files: ['src/*/workflows.ts', 'src/*/workflows-*.ts', 'src/*/workflows/*.ts'],
rules: {
'no-restricted-imports': [
'error',
...builtinModules.filter((m) => !ALLOWED_NODE_BUILTINS.has(m)).flatMap((m) => [m, `node:${m}`]),
],
},
},
],
};
2 changes: 2 additions & 0 deletions openai-agents/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
lib
node_modules
1 change: 1 addition & 0 deletions openai-agents/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package-lock=false
1 change: 1 addition & 0 deletions openai-agents/.nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
22
20 changes: 20 additions & 0 deletions openai-agents/.post-create
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
To begin development, install the Temporal CLI:

Mac: {cyan brew install temporal}
Other: Download and extract the latest release from https://github.com/temporalio/cli/releases/latest

Start Temporal Server:

{cyan temporal server start-dev}

Use Node version 18+ (v22.x is recommended):

Mac: {cyan brew install node@22}
Other: https://nodejs.org/en/download/

This sample has several scenarios under {cyan src/}. Using two other shells, start a Worker for one scenario and run its client (example: {cyan basic}):

{cyan OPENAI_API_KEY=<your-key> npx ts-node src/basic/worker.ts}
{cyan npx ts-node src/basic/client.ts hello-world}

See README.md for the full list of scenarios.
1 change: 1 addition & 0 deletions openai-agents/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
lib
2 changes: 2 additions & 0 deletions openai-agents/.prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
printWidth: 120
singleQuote: true
62 changes: 62 additions & 0 deletions openai-agents/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# OpenAI Agents

These samples use the `@temporalio/openai-agents` integration to run [OpenAI Agents SDK](https://github.com/openai/openai-agents-js) agents as Temporal Workflows. Agent orchestration — the agent loop, handoffs, tool calls, and guardrails — runs inside the Workflow, while model calls run as durable Activities, so they retry on failure and are not repeated during Workflow replay.

This is a single project: one `package.json` and one set of configs at the `openai-agents/` root, with each scenario in its own subdirectory. Run `npm install` once here, then run any scenario by path (see each scenario's README). The integration package itself is documented in the [`@temporalio/openai-agents` README](https://github.com/temporalio/sdk-typescript/tree/main/packages/openai-agents).

## Prerequisites

These apply to every sample in this directory:

- A running Temporal dev server: `temporal server start-dev`.
- Node 22 or later.
- An OpenAI API key: `export OPENAI_API_KEY=...`.
- Dependencies installed once at the `openai-agents/` root: `npm install`.

Each scenario's README describes how to start its Worker and run its scenarios by path.

## Samples

| Sample | Demonstrates |
| :----------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`basic`](./src/basic) | A single agent plus the core building blocks: Activity-backed and inline tools, local-Activity tools, agent context, structured output, per-run model override, and dynamic instructions. |
| [`handoffs`](./src/handoffs) | A triage agent routes each request to a specialist agent, using both the `Agent[]` and `handoff()` forms and a per-handoff input filter. |
| [`agent-patterns`](./src/agent-patterns) | Multi-agent orchestration patterns: deterministic chaining, parallelization, LLM-as-judge, agents-as-tools, and input/output guardrails. |
| [`sessions`](./src/sessions) | Conversation history with `WorkflowSafeMemorySession`, including carrying history across a `continueAsNew` boundary. |
| [`human-approval`](./src/human-approval) | A human-in-the-loop tool that pauses the run for an `approve` Signal, then resumes by serializing and rehydrating the run state across `continueAsNew`. |
| [`tools`](./src/tools) | Server-side hosted tools — web search, image generation, and code interpreter — executed by the model provider during the model Activity. |
| [`tracing`](./src/tracing) | The three supported tracing paths: a custom `TracingProcessor`, the OpenAI hosted exporter, and OpenTelemetry, plus `temporal:*` orchestration spans. |
| [`model-providers`](./src/model-providers) | Pass a custom `ModelProvider` to point an agent at any OpenAI-compatible endpoint. |
| [`reasoning-content`](./src/reasoning-content) | Read a reasoning model's `reasoning_content` field by calling the `openai` SDK directly from an Activity. |
| [`mcp`](./src/mcp) | Stateless and stateful Model Context Protocol servers (stdio, Streamable HTTP, SSE, and prompt servers) running locally. |
| [`hosted-mcp`](./src/hosted-mcp) | A `HostedMCPTool` the model calls server-side, with and without a Signal-driven approval round trip. |
| [`multi-agent`](./src/multi-agent) | A planner agent fans out concurrent web searches and a writer agent synthesizes a final report. |
| [`stateful-conversation`](./src/stateful-conversation) | A long-running, multi-turn Workflow driven by Updates and Queries, with triage handoffs and `continueAsNew` to bound history. |
| [`nexus-tools`](./src/nexus-tools) | Expose a [Nexus](https://docs.temporal.io/nexus) Operation as an agent tool with `nexusOperationAsTool`. |

## Feature support

Any OpenAI Agents SDK `ModelProvider` can drive the model Activity. The provider runs in the Activity, never inside the Workflow sandbox.

| Feature | Status | Notes |
| :---------------------- | :------------ | :-------------------------------------------------------------------------------------- |
| Multi-turn agents | Supported | Agent loop runs durably in the Workflow |
| Handoffs | Supported | `Agent` and `handoff()` forms |
| Inline function tools | Supported | Must be deterministic |
| Activity-backed tools | Supported | Via `activityAsTool()` |
| Nexus operation tools | Supported | Via `nexusOperationAsTool()` |
| Nested agent tools | Supported | Via `agentAsTool()` |
| Hosted tools | Supported | Executed server-side by the model provider |
| Stateless MCP servers | Supported | Via `StatelessMCPServerProvider` and `statelessMcpServer()` |
| Stateful MCP servers | Supported | Via `StatefulMCPServerProvider` and `statefulMcpServer()` |
| Sessions | Supported | Via `WorkflowSafeMemorySession`; upstream `MemorySession` is rejected |
| Run state and approvals | Supported | Serialize with `result.state.toString()` and rehydrate with `RunState.fromString` |
| Guardrails | Supported | Guardrail callbacks must be deterministic |
| Tracing | Supported | OpenAI hosted traces, custom `TracingProcessor`s, OTel, and optional `temporal:*` spans |
| Agent context | Supported | Activity tools receive a copy |
| `continueAsNew` | Supported | Plugin config propagates to the continuation |
| Child Workflows | Supported | Plugin config propagates to children |
| Local Activities | Supported | Set `useLocalActivity: true` in `modelParams` |
| Model override per run | Supported | `runConfig.model` accepts a string model name |
| Streaming | Not supported | Use `runner.run()` |
| Voice agents | Not supported | |
46 changes: 46 additions & 0 deletions openai-agents/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
{
"name": "temporal-openai-agents",
"version": "0.1.0",
"private": true,
"scripts": {
"build": "tsc --build",
"build.watch": "tsc --build --watch",
"format": "prettier --write .",
"format:check": "prettier --check .",
"lint": "eslint .",
"test": "mocha --exit --require ts-node/register --require source-map-support/register \"src/*/mocha/*.test.ts\""
},
"dependencies": {
"@temporalio/activity": "^1.18.0",
"@temporalio/client": "^1.18.0",
"@temporalio/nexus": "^1.18.0",
"@temporalio/openai-agents": "^1.18.0",
"@temporalio/worker": "^1.18.0",
"@temporalio/workflow": "^1.18.0",
"@openai/agents-core": "^0.11.6",
"@openai/agents-openai": "^0.11.6",
"@modelcontextprotocol/sdk": "^1.29.0",
"@opentelemetry/api": "^1.9.0",
"openai": "^6.0.0",
"nexus-rpc": "^0.0.2",
"nanoid": "3.x",
"zod": "^4.0.0"
},
"devDependencies": {
"@temporalio/testing": "^1.18.0",
"@tsconfig/node22": "^22.0.0",
"@types/mocha": "8.x",
"@types/node": "^22.9.1",
"@typescript-eslint/eslint-plugin": "^8.18.0",
"@typescript-eslint/parser": "^8.18.0",
"@opentelemetry/sdk-trace-base": "^1.30.0",
"eslint": "^8.57.1",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-deprecation": "^3.0.0",
"mocha": "8.x",
"prettier": "^3.4.2",
"ts-node": "^10.9.2",
"typescript": "^5.6.3",
"source-map-support": "^0.5.21"
}
}
40 changes: 40 additions & 0 deletions openai-agents/src/agent-patterns/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# OpenAI Agents: Agent Patterns

Demonstrates common multi-agent orchestration patterns with the Temporal OpenAI Agents
integration. Each pattern is its own Workflow in `src/agent-patterns/workflows.ts`.

Scenarios:

- **deterministic** — three agents run in sequence, each gating the next (outline → draft → polish).
- **parallelization** — `Promise.all` fans out to three agents, then a judge agent picks the best answer.
- **llm-as-judge** — a generate→judge loop that retries until the judge approves.
- **agents-as-tools** — an orchestrator uses `agentAsTool` to call a specialist agent as a tool.
- **input-guardrails** — `runConfig.inputGuardrails` blocks forbidden input before the model runs.
- **output-guardrails** — `runConfig.outputGuardrails` blocks unsafe model output after the model runs.

## Run

Run these from the `openai-agents/` root (run `npm install` there once first).

```bash
# In one terminal, start the Worker (requires a local Temporal server and OPENAI_API_KEY):
OPENAI_API_KEY=sk-... npx ts-node src/agent-patterns/worker.ts

# In another terminal, start a scenario:
npx ts-node src/agent-patterns/client.ts deterministic
npx ts-node src/agent-patterns/client.ts parallelization
npx ts-node src/agent-patterns/client.ts llm-as-judge
npx ts-node src/agent-patterns/client.ts agents-as-tools
npx ts-node src/agent-patterns/client.ts input-guardrails
npx ts-node src/agent-patterns/client.ts output-guardrails
```

## Test

```bash
npx mocha --exit --require ts-node/register --require source-map-support/register "src/agent-patterns/mocha/*.test.ts"
```

Tests run a real Worker against `TestWorkflowEnvironment` with a scripted fake model, so no
`OPENAI_API_KEY` is required. Each pattern has a test asserting its mechanism (call counts,
history threading, tool round-trips, and guardrail tripwires).
Loading
Loading