Skip to content
Open
Show file tree
Hide file tree
Changes from 30 commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
8f8d768
add chat to beta
404Wolf Dec 1, 2025
1260ec6
start adding option for new iterator
404Wolf Dec 1, 2025
4a71943
more progress on iterative tool calls
404Wolf Dec 1, 2025
55d2d77
fix type issues
404Wolf Dec 1, 2025
4864dca
finish port
404Wolf Dec 2, 2025
8e55b1e
add support for options
404Wolf Dec 2, 2025
95694b6
update to new async iterable pattern
404Wolf Dec 2, 2025
c4f95d4
fix E2E test
404Wolf Dec 2, 2025
f2834e9
fix more tests
404Wolf Dec 2, 2025
34421a0
fix more tests
404Wolf Dec 2, 2025
d224d00
most tests passing
404Wolf Dec 3, 2025
d1fb561
add more examples
404Wolf Dec 3, 2025
1093bd0
throw when n>1
404Wolf Dec 3, 2025
844c5a4
update another test
404Wolf Dec 3, 2025
49bbff6
make tool runner beta only
404Wolf Dec 3, 2025
f730423
update snapshot
404Wolf Dec 3, 2025
337d05e
make executable
404Wolf Dec 3, 2025
410d410
tests passing
404Wolf Dec 3, 2025
51b200d
fix type errors
404Wolf Dec 3, 2025
d36648c
unformat mistakenly formatted jsons
404Wolf Dec 3, 2025
4a23c9d
make nock dev dep
404Wolf Dec 3, 2025
444f9b0
more minimal package changes
404Wolf Dec 3, 2025
afb98d2
don't await the promise
404Wolf Dec 3, 2025
4c95b49
use zod v4
404Wolf Dec 3, 2025
5b52aa9
catch with separate update
404Wolf Dec 3, 2025
cdeb4e6
PR feedback
404Wolf Dec 3, 2025
3f96a58
start working on docs
404Wolf Dec 3, 2025
c1dd29b
more readme work
404Wolf Dec 3, 2025
5a9cb4b
remove object check
404Wolf Dec 3, 2025
d18bbfb
add image tool
404Wolf Dec 3, 2025
658afef
pass directly
404Wolf Dec 4, 2025
9b0b3df
add test for top level array
404Wolf Dec 4, 2025
d75a202
rename BetaRunnableTool
404Wolf Dec 4, 2025
3c8bdba
Solve more TODOs
404Wolf Dec 4, 2025
1066d30
add doc
404Wolf Dec 4, 2025
b0f8818
improve names
404Wolf Dec 4, 2025
6574f39
Merge remote-tracking branch 'upstream/master' into add-new-tool-call…
404Wolf Dec 4, 2025
8eb6c3d
remove debugging
404Wolf Dec 4, 2025
949d8a0
fix more naming
404Wolf Dec 4, 2025
20f39a5
rename to parameters
404Wolf Dec 5, 2025
ec31a58
allow object
404Wolf Dec 5, 2025
ded0bd1
make linter happy
404Wolf Dec 5, 2025
ac91ad0
clean up
404Wolf Dec 5, 2025
c0a0bb0
change anys to unknowns
404Wolf Dec 5, 2025
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
85 changes: 85 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,91 @@ await client.files.create({
});
```

## Streaming Helpers

The SDK makes it easy to stream responses, by providing an emitter helper via `.stream()`:

```ts
import OpenAI from 'openai';

const client = new OpenAI();

async function main() {
const stream = client.chat.completions
.stream({
model: 'gpt-4o',
max_tokens: 1024,
messages: [
{
role: 'user',
content: 'Say hi!',
},
],
})
.on('chunk', (text) => {
console.log(text);
});

const message = await stream.finalMessage();
console.log(message);
}

main();
```

With `.stream()` you get event handlers, accumulation, and an async iterable.

Alternatively, you can use `client.chat.completions({ ..., stream: true })` which only returns an async iterable of the events in the stream and thus uses less memory (it does not build up a final message object for you).

## Tool Helpers

The SDK makes it easy to create and run [function tools with the chats API](https://platform.openai.com/docs/guides/function-calling). You can use Zod schemas or direct JSON schemas to describe the shape of tool input, and then you can run the tools using the `client.beta.messages.toolRunner` method. This method will automatically handle passing the inputs generated by the model into your tools and providing the results back to the model.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI looks like the primary examples in those linked docs are for the Responses API, not Chat Completions.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's where they explain what a function tool call actually is, but yes it focuses on the responses API. Should we re-explain it here instead and not link to it, since it could cause confusion?


```ts
import OpenAI from 'openai';

import { betaZodFunctionTool } from 'openai/helpers/beta/zod';
import { z } from 'zod/v4';

const client = new OpenAI();

async function main() {
const addTool = betaZodFunctionTool({
name: 'add',
parameters: z.object({
a: z.number(),
b: z.number(),
}),
description: 'Add two numbers together',
run: (input) => {
return String(input.a + input.b);
},
});

const multiplyTool = betaZodFunctionTool({
name: 'multiply',
parameters: z.object({
a: z.number(),
b: z.number(),
}),
description: 'Multiply two numbers together',
run: (input) => {
return String(input.a * input.b);
},
});

const finalMessage = await client.beta.chat.completions.toolRunner({
model: 'gpt-4o',
max_tokens: 1000,
messages: [{ role: 'user', content: 'What is 5 plus 3, and then multiply that result by 4?' }],
tools: [addTool, multiplyTool],
});
console.log(finalMessage);
}

main();
```

## Webhook Verification

Verifying webhook signatures is _optional but encouraged_.
Expand Down
105 changes: 105 additions & 0 deletions examples/tool-calls-beta-zod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
#!/usr/bin/env -S npm run tsn -T

import OpenAI from 'openai';
import { betaZodFunctionTool } from 'openai/helpers/beta/zod';
import { z } from 'zod';

const client = new OpenAI();

async function main() {
const runner = client.beta.chat.completions.toolRunner({
messages: [
{
role: 'user',
content: `I'm planning a trip to San Francisco and I need some information. Can you help me with the weather, current time, and currency exchange rates (from EUR)? Please use parallel tool use.`,
},
],
tools: [
betaZodFunctionTool({
name: 'getWeather',
description: 'Get the weather at a specific location',
parameters: z.object({
location: z.string().describe('The city and state, e.g. San Francisco, CA'),
}),
run: ({ location }) => {
return `The weather is sunny with a temperature of 20°C in ${location}.`;
},
}),
betaZodFunctionTool({
name: 'getTime',
description: 'Get the current time in a specific timezone',
parameters: z.object({
timezone: z.string().describe('The timezone, e.g. America/Los_Angeles'),
}),
run: ({ timezone }) => {
return `The current time in ${timezone} is 3:00 PM.`;
},
}),
betaZodFunctionTool({
name: 'getCurrencyExchangeRate',
description: 'Get the exchange rate between two currencies',
parameters: z.object({
from_currency: z.string().describe('The currency to convert from, e.g. USD'),
to_currency: z.string().describe('The currency to convert to, e.g. EUR'),
}),
run: ({ from_currency, to_currency }) => {
return `The exchange rate from ${from_currency} to ${to_currency} is 0.85.`;
},
}),
],
model: 'gpt-4o',
max_tokens: 1024,
// This limits the conversation to at most 10 back and forth between the API.
max_iterations: 10,
});

console.log(`\n🚀 Running tools...\n`);

for await (const message of runner) {
if (!message) continue;

console.log(`┌─ Message ${message.id} `.padEnd(process.stdout.columns, '─'));
console.log();

const { choices } = message;
const firstChoice = choices.at(0)!;

// When we get a tool call request it's null
if (firstChoice.message.content !== null) {
console.log(`${firstChoice.message.content}\n`);
} else {
// each tool call (could be many)
for (const toolCall of firstChoice.message.tool_calls ?? []) {
if (toolCall.type === 'function') {
console.log(`${toolCall.function.name}(${JSON.stringify(toolCall.function.arguments, null, 2)})\n`);
}
}
}

console.log(`└─`.padEnd(process.stdout.columns, '─'));
console.log();
console.log();

const defaultResponse = await runner.generateToolResponse();
if (defaultResponse && Array.isArray(defaultResponse)) {
console.log(`┌─ Response `.padEnd(process.stdout.columns, '─'));
console.log();

for (const toolResponse of defaultResponse) {
if (toolResponse.role === 'tool') {
const toolCall = firstChoice.message.tool_calls?.find((tc) => tc.id === toolResponse.tool_call_id);
if (toolCall && toolCall.type === 'function') {
console.log(`${toolCall.function.name}(): ${toolResponse.content}`);
}
}
}

console.log();
console.log(`└─`.padEnd(process.stdout.columns, '─'));
console.log();
console.log();
}
}
}

main();
109 changes: 109 additions & 0 deletions examples/tool-helpers-advanced-streaming.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
#!/usr/bin/env -S npm run tsn -T

import OpenAI from 'openai';
import { betaZodFunctionTool } from 'openai/helpers/beta/zod';
import { z } from 'zod';

const client = new OpenAI();

async function main() {
const runner = client.beta.chat.completions.toolRunner({
messages: [
{
role: 'user',
content: `I'm planning a trip to San Francisco and I need some information. Can you help me with the weather, current time, and currency exchange rates (from EUR)? Please use parallel tool use`,
},
],
tools: [
betaZodFunctionTool({
name: 'getWeather',
description: 'Get the weather at a specific location',
parameters: z.object({
location: z.string().describe('The city and state, e.g. San Francisco, CA'),
}),
run: ({ location }) => {
return `The weather is sunny with a temperature of 20°C in ${location}.`;
},
}),
betaZodFunctionTool({
name: 'getTime',
description: 'Get the current time in a specific timezone',
parameters: z.object({
timezone: z.string().describe('The timezone, e.g. America/Los_Angeles'),
}),
run: ({ timezone }) => {
return `The current time in ${timezone} is 3:00 PM.`;
},
}),
betaZodFunctionTool({
name: 'getCurrencyExchangeRate',
description: 'Get the exchange rate between two currencies',
parameters: z.object({
from_currency: z.string().describe('The currency to convert from, e.g. USD'),
to_currency: z.string().describe('The currency to convert to, e.g. EUR'),
}),
run: ({ from_currency, to_currency }) => {
return `The exchange rate from ${from_currency} to ${to_currency} is 0.85.`;
},
}),
],
model: 'gpt-4o',
max_tokens: 1024,
// This limits the conversation to at most 10 back and forth between the API.
max_iterations: 10,
stream: true,
});

console.log(`\n🚀 Running tools...\n`);

let prevMessageStarted = '';
let prevToolStarted = '';
let prevWasToolCall = false;

for await (const messageStream of runner) {
for await (const event of messageStream) {
const hadToolCalls = !!event.choices?.[0]?.delta?.tool_calls;

if (hadToolCalls) {
if (!prevMessageStarted) {
console.log(`┌─ Message ${event.id} `.padEnd(process.stdout.columns, '─'));
prevMessageStarted = event.id;
}

prevWasToolCall = true;
const toolCalls = event.choices[0]!.delta.tool_calls!;

for (const toolCall of toolCalls) {
if (toolCall.function?.name && prevToolStarted !== toolCall.function.name) {
process.stdout.write(`\n${toolCall.function.name}: `);
prevToolStarted = toolCall.function.name;
} else if (toolCall.function?.arguments) {
process.stdout.write(toolCall.function.arguments);
}
}
} else if (event.choices?.[0]?.delta?.content) {
if (prevWasToolCall) {
console.log();
console.log();
console.log(`└─`.padEnd(process.stdout.columns, '─'));
console.log();
prevWasToolCall = false;
}

if (prevMessageStarted !== event.id) {
console.log(`┌─ Message ${event.id} `.padEnd(process.stdout.columns, '─'));
console.log();
prevMessageStarted = event.id;
}

process.stdout.write(event.choices[0].delta.content);
}
}
}

console.log();
console.log();
console.log(`└─`.padEnd(process.stdout.columns, '─'));
}

main();
38 changes: 38 additions & 0 deletions examples/tool-helpers-advanced.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#!/usr/bin/env -S npm run tsn -T

import OpenAI from 'openai';
import { betaZodFunctionTool } from 'openai/helpers/beta/zod';
import { z } from 'zod';

const client = new OpenAI();

async function main() {
const message = await client.beta.chat.completions.toolRunner({
messages: [
{
role: 'user',
content: `What is the weather in SF?`,
},
],
tools: [
betaZodFunctionTool({
name: 'getWeather',
description: 'Get the weather at a specific location',
parameters: z.object({
location: z.string().describe('The city and state, e.g. San Francisco, CA'),
}),
run: ({ location }) => {
return `The weather is foggy with a temperature of 20°C in ${location}.`;
},
}),
],
model: 'gpt-4o',
max_tokens: 1024,
// the maximum number of iterations to run the tool
max_iterations: 10,
});

console.log('Final response:', message.content);
}

main();
44 changes: 44 additions & 0 deletions examples/tool-helpers-json-schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#!/usr/bin/env -S npm run tsn -T

import OpenAI from 'openai';
import { betaTool } from 'openai/helpers/beta/json-schema';

const client = new OpenAI();

async function main() {
const message = await client.beta.chat.completions.toolRunner({
messages: [
{
role: 'user',
content: `What is the weather in SF?`,
},
],
tools: [
betaTool({
name: 'getWeather',
description: 'Get the weather at a specific location',
inputSchema: {
type: 'object',
properties: {
location: {
type: 'string',
description: 'The city and state, e.g. San Francisco, CA',
},
},
required: ['location'],
},
run: ({ location }) => {
return `The weather is foggy with a temperature of 20°C in ${location}.`;
},
}),
],
model: 'gpt-4o',
max_tokens: 1024,
// the maximum number of iterations to run the tool
max_iterations: 10,
});

console.log('Final response:', message.content);
}

main();
Loading