Skip to content
Open
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
20 changes: 14 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,12 @@
"@swc/core": "^1.3.102",
"@swc/jest": "^0.2.29",
"@types/jest": "^29.4.0",
"@types/ws": "^8.5.13",
"@types/node": "^20.17.6",
"@types/ws": "^8.5.13",
"@typescript-eslint/eslint-plugin": "8.31.1",
"@typescript-eslint/parser": "8.31.1",
"deep-object-diff": "^1.1.9",
"@typescript-eslint/typescript-estree": "8.31.1",
"deep-object-diff": "^1.1.9",
"eslint": "^9.39.1",
"eslint-plugin-unused-imports": "^4.1.4",
"execa": "^5.1.1",
Expand All @@ -46,17 +46,17 @@
"jest": "^29.4.0",
"prettier": "^3.0.0",
"publint": "^0.2.12",
"ws": "^8.18.3",
"@types/ws": "^8.5.13",
"ts-jest": "^29.1.0",
"ts-node": "^10.5.0",
"tsc-multi": "https://github.com/stainless-api/tsc-multi/releases/download/v1.1.11/tsc-multi.tgz",
"tsconfig-paths": "^4.0.0",
"tslib": "^2.8.1",
"typescript": "5.8.3",
"typescript-eslint": "8.31.1",
"ws": "^8.18.0",
"zod": "^3.25 || ^4.0",
"typescript-eslint": "8.31.1"
"@valibot/to-json-schema": "^1.7.0",
"valibot": "^1.4.1"
},
"overrides": {
"minimatch": "^9.0.5"
Expand Down Expand Up @@ -87,14 +87,22 @@
},
"peerDependencies": {
"ws": "^8.18.0",
"zod": "^3.25 || ^4.0"
"zod": "^3.25 || ^4.0",
"@valibot/to-json-schema": "^1.0.0",
"valibot": "^1.0.0"
},
"peerDependenciesMeta": {
"ws": {
"optional": true
},
"zod": {
"optional": true
},
"@valibot/to-json-schema": {
"optional": true
},
"valibot": {
"optional": true
}
}
}
154 changes: 154 additions & 0 deletions src/helpers/valibot.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
import { ResponseFormatJSONSchema } from '../resources/index';
import * as v from 'valibot';
import {
AutoParseableResponseFormat,
AutoParseableTextFormat,
AutoParseableTool,
makeParseableResponseFormat,
makeParseableTextFormat,
makeParseableTool,
} from '../lib/parser';
import { toJsonSchema } from '@valibot/to-json-schema';
import { AutoParseableResponseTool, makeParseableResponseTool } from '../lib/ResponsesParser';
import { type ResponseFormatTextJSONSchemaConfig } from '../resources/responses/responses';
import { toStrictJsonSchema } from '../lib/transform';
import { JSONSchema } from '../lib/jsonschema';

type ValibotSchema = v.BaseSchema<unknown, unknown, v.BaseIssue<unknown>>;

function valibotToJsonSchema(schema: ValibotSchema): Record<string, unknown> {
return toStrictJsonSchema(
toJsonSchema(schema, { target: 'draft-07' }) as JSONSchema,
) as Record<string, unknown>;
}

/**
* Creates a chat completion `JSONSchema` response format object from
* the given Valibot schema.
*
* If this is passed to the `.parse()`, `.stream()` or `.runTools()`
* chat completion methods then the response message will contain a
* `.parsed` property that is the result of parsing the content with
* the given Valibot schema.
*
* ```ts
* const completion = await client.chat.completions.parse({
* model: 'gpt-4o-2024-08-06',
* messages: [
* { role: 'system', content: 'You are a helpful math tutor.' },
* { role: 'user', content: 'solve 8x + 31 = 2' },
* ],
* response_format: valibotResponseFormat(
* v.object({
* steps: v.array(v.object({
* explanation: v.string(),
* answer: v.string(),
* })),
* final_answer: v.string(),
* }),
* 'math_answer',
* ),
* });
* const message = completion.choices[0]?.message;
* if (message?.parsed) {
* console.log(message.parsed);
* console.log(message.parsed.final_answer);
* }
* ```
*
* 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 valibotResponseFormat<Schema extends ValibotSchema>(
schema: Schema,
name: string,
props?: Omit<ResponseFormatJSONSchema.JSONSchema, 'schema' | 'strict' | 'name'>,
): AutoParseableResponseFormat<v.InferOutput<Schema>> {
return makeParseableResponseFormat(
{
type: 'json_schema',
json_schema: {
...props,
name,
strict: true,
schema: valibotToJsonSchema(schema),
},
},
(content) => v.parse(schema, JSON.parse(content)),
);
}

export function valibotTextFormat<Schema extends ValibotSchema>(
schema: Schema,
name: string,
props?: Omit<ResponseFormatTextJSONSchemaConfig, 'schema' | 'type' | 'strict' | 'name'>,
): AutoParseableTextFormat<v.InferOutput<Schema>> {
return makeParseableTextFormat(
{
type: 'json_schema',
...props,
name,
strict: true,
schema: valibotToJsonSchema(schema),
},
(content) => v.parse(schema, JSON.parse(content)),
);
}

/**
* Creates a chat completion `function` tool that can be invoked
* automatically by the chat completion `.runTools()` method or automatically
* parsed by `.parse()` / `.stream()`.
*/
export function valibotFunction<Parameters extends ValibotSchema>(options: {
name: string;
parameters: Parameters;
function?: ((args: v.InferOutput<Parameters>) => unknown | Promise<unknown>) | undefined;
description?: string | undefined;
}): AutoParseableTool<{
arguments: Parameters;
name: string;
function: (args: v.InferOutput<Parameters>) => unknown;
}> {
// @ts-expect-error TODO
return makeParseableTool<any>(
{
type: 'function',
function: {
name: options.name,
parameters: valibotToJsonSchema(options.parameters),
strict: true,
...(options.description ? { description: options.description } : undefined),
},
},
{
callback: options.function,
parser: (args) => v.parse(options.parameters, JSON.parse(args)),
},
);
}

export function valibotResponsesFunction<Parameters extends ValibotSchema>(options: {
name: string;
parameters: Parameters;
function?: ((args: v.InferOutput<Parameters>) => unknown | Promise<unknown>) | undefined;
description?: string | undefined;
}): AutoParseableResponseTool<{
arguments: Parameters;
name: string;
function: (args: v.InferOutput<Parameters>) => unknown;
}> {
return makeParseableResponseTool<any>(
{
type: 'function',
name: options.name,
parameters: valibotToJsonSchema(options.parameters),
strict: true,
...(options.description ? { description: options.description } : undefined),
},
{
callback: options.function,
parser: (args) => v.parse(options.parameters, JSON.parse(args)),
},
);
}
Loading