Skip to content
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
45 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
4cad7b2
don't mention anthropic
404Wolf Dec 8, 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
100 changes: 100 additions & 0 deletions examples/tool-calls-beta-zod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
#!/usr/bin/env -S npm run tsn -T

import OpenAI from 'openai';
import { betaZodTool } from 'openai/helpers/beta/zod';
// import { BetaToolUseBlock } from 'openai/helpers/beta';
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: [
betaZodTool({
name: 'getWeather',
description: 'Get the weather at a specific location',
inputSchema: 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}.`;
},
}),
betaZodTool({
name: 'getTime',
description: 'Get the current time in a specific timezone',
inputSchema: 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.`;
},
}),
betaZodTool({
name: 'getCurrencyExchangeRate',
description: 'Get the exchange rate between two currencies',
inputSchema: 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) {
console.log(`┌─ Message ${message.id} `.padEnd(process.stdout.columns, '─'));
console.log();

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

console.log(`${firstChoice.message.content}\n`); // text
// 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 && typeof defaultResponse.content !== 'string') {
// console.log(`┌─ Response `.padEnd(process.stdout.columns, '─'));
// console.log();

// for (const block of defaultResponse.content) {
// if (block.type === 'tool_result') {
// const toolUseBlock = message.content.find((b): b is BetaToolUseBlock => {
// return b.type === 'tool_use' && b.id === block.tool_use_id;
// })!;
// console.log(`${toolUseBlock.name}(): ${block.content}`);
// }
// }

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

main();
Empty file added src/helpers/beta/betaZodTool.ts
Empty file.
130 changes: 130 additions & 0 deletions src/helpers/beta/zod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import { transformJSONSchema } from '../..//lib/transform-json-schema';
import type { infer as zodInfer, ZodType } from 'zod';
import * as z from 'zod';
Copy link
Collaborator

Choose a reason for hiding this comment

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

import { OpenAIError } from '../../core/error';
import type { BetaRunnableTool, Promisable } from '../../lib/beta/BetaRunnableTool';
import type { AutoParseableBetaOutputFormat } from '../../lib/beta-parser';
// import { AutoParseableBetaOutputFormat } from '../../lib/beta-parser';
// import { BetaRunnableTool, Promisable } from '../../lib/tools/BetaRunnableTool';
// import { BetaToolResultContentBlockParam } from '../../resources/beta';
/**
* Creates a JSON schema output format object from the given Zod schema.
*
* If this is passed to the `.parse()` method then the response message will contain a
* `.parsed` property that is the result of parsing the content with the given Zod object.
*
* This can be passed directly to the `.create()` method but will not
* result in any automatic parsing, you'll have to parse the response yourself.
*/
export function betaZodOutputFormat<ZodInput extends ZodType>(
zodObject: ZodInput,
): AutoParseableBetaOutputFormat<zodInfer<ZodInput>> {
let jsonSchema = z.toJSONSchema(zodObject, { reused: 'ref' });

jsonSchema = transformJSONSchema(jsonSchema);

return {
type: 'json_schema',
schema: {
...jsonSchema,
},
parse: (content) => {
const output = zodObject.safeParse(JSON.parse(content));

if (!output.success) {
throw new OpenAIError(
`Failed to parse structured output: ${output.error.message} cause: ${output.error.issues}`,
);
}

return output.data;
},
};
}

/**
* Creates a tool using the provided Zod schema that can be passed
* into the `.toolRunner()` method. The Zod schema will automatically be
* converted into JSON Schema when passed to the API. The provided function's
* input arguments will also be validated against the provided schema.
*/
export function betaZodTool<InputSchema extends ZodType>(options: {
name: string;
inputSchema: InputSchema;
Copy link
Collaborator

Choose a reason for hiding this comment

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

nit: this should be parameters to match the API shape

description: string;
run: (args: zodInfer<InputSchema>) => Promisable<string | Array<BetaToolResultContentBlockParam>>;
}): BetaRunnableTool<zodInfer<InputSchema>> {
const jsonSchema = z.toJSONSchema(options.inputSchema, { reused: 'ref' });

if (jsonSchema.type !== 'object') {
throw new Error(`Zod schema for tool "${options.name}" must be an object, but got ${jsonSchema.type}`);
}

// TypeScript doesn't narrow the type after the runtime check, so we need to assert it
const objectSchema = jsonSchema as typeof jsonSchema & { type: 'object' };
Copy link
Collaborator

Choose a reason for hiding this comment

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

nit: I don't think we need this check? I think we should be able to just do parameters: objectSchema below?


// return {
// type: 'function', // TODO: should this be custom or function?
// name: options.name,
// input_schema: objectSchema,
// description: options.description,
// run: options.run,
// parse: (args: unknown) => options.inputSchema.parse(args) as zodInfer<InputSchema>,
// };
return {
type: 'function',
function: {
name: options.name,
// input_schema: objectSchema,
description: options.description,
// run: options.run,
// parse: (args: unknown) => options.inputSchema.parse(args) as zodInfer<InputSchema>,
parameters: {
type: 'object',
properties: objectSchema.properties,
},
},
};
}

// /**
// * Creates a tool using the provided Zod schema that can be passed
// * into the `.toolRunner()` method. The Zod schema will automatically be
// * converted into JSON Schema when passed to the API. The provided function's
// * input arguments will also be validated against the provided schema.
// */
// export function betaZodTool<InputSchema extends ZodType>(options: {
// name: string;
// inputSchema: InputSchema;
// description: string;
// run: (args: zodInfer<InputSchema>) => Promisable<string | Array<any>>;
// }): BetaRunnableTool<zodInfer<InputSchema>> {
// const jsonSchema = z.toJSONSchema(options.inputSchema, { reused: 'ref' });

// if (jsonSchema.type !== 'object') {
// throw new Error(`Zod schema for tool "${options.name}" must be an object, but got ${jsonSchema.type}`);
// }

// // TypeScript doesn't narrow the type after the runtime check, so we need to assert it
// const objectSchema = jsonSchema as typeof jsonSchema & { type: 'object' };

// // return {
// // type: 'function', // TODO: should this be custom or function?
// // name: options.name,
// // input_schema: objectSchema,
// // description: options.description,
// // run: options.run,
// // parse: (args: unknown) => options.inputSchema.parse(args) as zodInfer<InputSchema>,
// // };
// return {
// type: 'function',
// function: {
// name: options.name,
// // input_schema: objectSchema,
// description: options.description,
// // run: options.run,
// // parse: (args: unknown) => options.inputSchema.parse(args) as zodInfer<InputSchema>,
// parameters: objectSchema.properties ?? {}, // the json schema
// },
// };
// }
7 changes: 7 additions & 0 deletions src/internal/utils/values.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,3 +103,10 @@ export const safeJSON = (text: string) => {
return undefined;
}
};

// Gets a value from an object, deletes the key, and returns the value (or undefined if not found)
export const pop = <T extends Record<string, any>, K extends string>(obj: T, key: K): T[K] => {
const value = obj[key];
delete obj[key];
return value;
};
105 changes: 105 additions & 0 deletions src/lib/beta-parser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { OpenAIError } from '../core/error';
import {
BetaContentBlock,
BetaJSONOutputFormat,
BetaMessage,
BetaTextBlock,
MessageCreateParams,
} from '../resources/beta/messages/messages';

// vendored from typefest just to make things look a bit nicer on hover
type Simplify<T> = { [KeyType in keyof T]: T[KeyType] } & {};

export type BetaParseableMessageCreateParams = Simplify<
Omit<MessageCreateParams, 'output_format'> & {
output_format?: BetaJSONOutputFormat | AutoParseableBetaOutputFormat<any> | null;
}
>;

export type ExtractParsedContentFromBetaParams<Params extends BetaParseableMessageCreateParams> =
Params['output_format'] extends AutoParseableBetaOutputFormat<infer P> ? P : null;

export type AutoParseableBetaOutputFormat<ParsedT> = BetaJSONOutputFormat & {
parse(content: string): ParsedT;
};

export type ParsedBetaMessage<ParsedT> = BetaMessage & {
content: Array<ParsedBetaContentBlock<ParsedT>>;
parsed_output: ParsedT | null;
};

export type ParsedBetaContentBlock<ParsedT> =
| (BetaTextBlock & { parsed: ParsedT | null })
| Exclude<BetaContentBlock, BetaTextBlock>;

export function maybeParseBetaMessage<Params extends BetaParseableMessageCreateParams | null>(
message: BetaMessage,
params: Params,
): ParsedBetaMessage<ExtractParsedContentFromBetaParams<NonNullable<Params>>> {
if (!params || !('parse' in (params.output_format ?? {}))) {
return {
...message,
content: message.content.map((block) => {
if (block.type === 'text') {
return {
...block,
parsed: null,
};
}
return block;
}),
parsed_output: null,
} as ParsedBetaMessage<ExtractParsedContentFromBetaParams<NonNullable<Params>>>;
}

return parseBetaMessage(message, params);
}

export function parseBetaMessage<Params extends BetaParseableMessageCreateParams>(
message: BetaMessage,
params: Params,
): ParsedBetaMessage<ExtractParsedContentFromBetaParams<Params>> {
let firstParsed: ReturnType<typeof parseBetaOutputFormat<Params>> | null = null;

const content: Array<ParsedBetaContentBlock<ExtractParsedContentFromBetaParams<Params>>> =
message.content.map((block) => {
if (block.type === 'text') {
const parsed = parseBetaOutputFormat(params, block.text);

if (firstParsed === null) {
firstParsed = parsed;
}

return {
...block,
parsed,
};
}
return block;
});

return {
...message,
content,
parsed_output: firstParsed,
} as ParsedBetaMessage<ExtractParsedContentFromBetaParams<Params>>;
}

function parseBetaOutputFormat<Params extends BetaParseableMessageCreateParams>(
params: Params,
content: string,
): ExtractParsedContentFromBetaParams<Params> | null {
if (params.output_format?.type !== 'json_schema') {
return null;
}

try {
if ('parse' in params.output_format) {
return params.output_format.parse(content);
}

return JSON.parse(content);
} catch (error) {
throw new OpenAIError(`Failed to parse structured output: ${error}`);
}
}
10 changes: 10 additions & 0 deletions src/lib/beta/BetaRunnableTool.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import type { ChatCompletionTool } from '../../resources';

export type Promisable<T> = T | Promise<T>;

// this type is just an extension of BetaTool with a run and parse method
// that will be called by `toolRunner()` helpers
export type BetaRunnableTool<Input = any> = ChatCompletionTool & {
run: (args: Input) => Promisable<string | Array<BetaToolResultContentBlockParam>>;
parse: (content: unknown) => Input;
};
Loading