or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

assistants.mdaudio.mdbatches-evals.mdchat-completions.mdclient-configuration.mdcontainers.mdconversations.mdembeddings.mdfiles-uploads.mdfine-tuning.mdhelpers-audio.mdhelpers-zod.mdimages.mdindex.mdrealtime.mdresponses-api.mdvector-stores.mdvideos.md

helpers-zod.mddocs/

0

# Zod Helpers

1

2

The OpenAI SDK provides helper functions for integrating with [Zod](https://www.npmjs.com/package/zod), a TypeScript-first schema validation library. These helpers enable automatic parsing and validation of API responses and function tool arguments using Zod schemas.

3

4

## Package Information

5

6

- **Package Name**: openai

7

- **Version**: 6.9.1

8

- **Language**: TypeScript

9

- **Import Path**: `openai/helpers/zod`

10

11

## Core Imports

12

13

```typescript

14

import { zodResponseFormat, zodFunction, zodTextFormat, zodResponsesFunction } from 'openai/helpers/zod';

15

import { z } from 'zod';

16

```

17

18

## Overview

19

20

The Zod helpers provide four main functions:

21

22

1. **zodResponseFormat** - Convert Zod schemas to response formats for structured outputs

23

2. **zodTextFormat** - Convert Zod schemas to text response formats

24

3. **zodFunction** - Define function tools with Zod schema validation

25

4. **zodResponsesFunction** - Define function tools for the Responses API with Zod validation

26

27

These helpers automatically:

28

- Convert Zod schemas to JSON Schema format compatible with OpenAI's API

29

- Enable type-safe parsing of API responses

30

- Provide runtime validation of function arguments

31

- Work with both Zod v3 and v4

32

33

## Capabilities

34

35

### zodResponseFormat

36

37

Creates a JSON Schema response format from a Zod schema for use with chat completions. When used with `.parse()`, `.stream()`, or `.runTools()`, responses will include a `.parsed` property with the validated, typed result.

38

39

```typescript { .api }

40

/**

41

* Creates a chat completion JSONSchema response format object from a Zod schema

42

* @param zodObject - The Zod schema defining the expected response structure

43

* @param name - A name for the schema

44

* @param props - Optional additional properties for the response format

45

* @returns An AutoParseableResponseFormat that enables automatic parsing

46

*/

47

function zodResponseFormat<ZodInput extends z.ZodType>(

48

zodObject: ZodInput,

49

name: string,

50

props?: Omit<ResponseFormatJSONSchema.JSONSchema, 'schema' | 'strict' | 'name'>

51

): AutoParseableResponseFormat<z.infer<ZodInput>>;

52

```

53

54

**Usage Example:**

55

56

```typescript

57

import { zodResponseFormat } from 'openai/helpers/zod';

58

import OpenAI from 'openai';

59

import { z } from 'zod';

60

61

const client = new OpenAI();

62

63

// Define your schema

64

const MathResponse = z.object({

65

steps: z.array(z.object({

66

explanation: z.string(),

67

output: z.string(),

68

})),

69

final_answer: z.string(),

70

});

71

72

// Use with chat completions

73

const completion = await client.chat.completions.parse({

74

model: 'gpt-4o-2024-08-06',

75

messages: [

76

{ role: 'system', content: 'You are a helpful math tutor.' },

77

{ role: 'user', content: 'solve 8x + 31 = 2' },

78

],

79

response_format: zodResponseFormat(MathResponse, 'math_response'),

80

});

81

82

// Access parsed, typed result

83

const message = completion.choices[0]?.message;

84

if (message?.parsed) {

85

console.log(message.parsed.steps);

86

console.log(`Answer: ${message.parsed.final_answer}`);

87

}

88

```

89

90

### zodTextFormat

91

92

Creates a text JSON Schema response format from a Zod schema for use with the Responses API. Similar to `zodResponseFormat` but designed for text-based structured outputs.

93

94

```typescript { .api }

95

/**

96

* Creates a text JSON Schema response format from a Zod schema

97

* @param zodObject - The Zod schema defining the expected response structure

98

* @param name - A name for the schema

99

* @param props - Optional additional properties for the format

100

* @returns An AutoParseableTextFormat that enables automatic parsing

101

*/

102

function zodTextFormat<ZodInput extends z.ZodType>(

103

zodObject: ZodInput,

104

name: string,

105

props?: Omit<ResponseFormatTextJSONSchemaConfig, 'schema' | 'type' | 'strict' | 'name'>

106

): AutoParseableTextFormat<z.infer<ZodInput>>;

107

```

108

109

**Usage Example:**

110

111

```typescript

112

import { zodTextFormat } from 'openai/helpers/zod';

113

import OpenAI from 'openai';

114

import { z } from 'zod';

115

116

const client = new OpenAI();

117

118

const UserData = z.object({

119

name: z.string(),

120

email: z.string().email(),

121

age: z.number().min(0),

122

});

123

124

const response = await client.responses.create({

125

model: 'gpt-4o',

126

input: 'Generate user data for John Smith',

127

response_format: zodTextFormat(UserData, 'user_data'),

128

});

129

```

130

131

### zodFunction

132

133

Creates a function tool with automatic argument parsing and validation using Zod schemas. Can be used with `.runTools()` for automatic function execution, or with `.parse()`/`.stream()` for automatic argument parsing.

134

135

```typescript { .api }

136

/**

137

* Creates a chat completion function tool with Zod schema validation

138

* @param options - Configuration object

139

* @param options.name - The name of the function

140

* @param options.parameters - Zod schema for function parameters

141

* @param options.function - Optional callback function to execute

142

* @param options.description - Optional description of the function

143

* @returns An AutoParseableTool with typed, validated arguments

144

*/

145

function zodFunction<Parameters extends z.ZodType>(options: {

146

name: string;

147

parameters: Parameters;

148

function?: (args: z.infer<Parameters>) => unknown | Promise<unknown>;

149

description?: string;

150

}): AutoParseableTool<{

151

arguments: Parameters;

152

name: string;

153

function: (args: z.infer<Parameters>) => unknown;

154

}>;

155

```

156

157

**Usage Example:**

158

159

```typescript

160

import { zodFunction } from 'openai/helpers/zod';

161

import OpenAI from 'openai';

162

import { z } from 'zod';

163

164

const client = new OpenAI();

165

166

// Define parameter schema

167

const WeatherParams = z.object({

168

location: z.string(),

169

unit: z.enum(['celsius', 'fahrenheit']).optional(),

170

});

171

172

// Create function tool

173

const getWeather = zodFunction({

174

name: 'get_weather',

175

parameters: WeatherParams,

176

description: 'Get the current weather for a location',

177

function: async (args) => {

178

// Args are typed and validated as { location: string, unit?: 'celsius' | 'fahrenheit' }

179

const { location, unit = 'celsius' } = args;

180

// ... fetch weather data ...

181

return { temperature: 72, conditions: 'sunny' };

182

},

183

});

184

185

// Use with runTools for automatic execution

186

const completion = await client.chat.completions.runTools({

187

model: 'gpt-4o',

188

messages: [

189

{ role: 'user', content: 'What is the weather in San Francisco?' },

190

],

191

tools: [getWeather],

192

});

193

```

194

195

**With Manual Parsing:**

196

197

```typescript

198

// Use with parse() for validation only (no automatic execution)

199

const completion = await client.chat.completions.parse({

200

model: 'gpt-4o',

201

messages: [

202

{ role: 'user', content: 'What is the weather in San Francisco?' },

203

],

204

tools: [

205

zodFunction({

206

name: 'get_weather',

207

parameters: WeatherParams,

208

}),

209

],

210

});

211

212

// Access parsed arguments

213

const toolCall = completion.choices[0]?.message.tool_calls?.[0];

214

if (toolCall?.function.parsed_arguments) {

215

// Type-safe access to validated arguments

216

const { location, unit } = toolCall.function.parsed_arguments;

217

console.log(`Getting weather for ${location}`);

218

}

219

```

220

221

### zodResponsesFunction

222

223

Creates a function tool for the Responses API with Zod schema validation. Similar to `zodFunction` but designed for use with `client.responses.create()`.

224

225

```typescript { .api }

226

/**

227

* Creates a Responses API function tool with Zod schema validation

228

* @param options - Configuration object

229

* @param options.name - The name of the function

230

* @param options.parameters - Zod schema for function parameters

231

* @param options.function - Optional callback function to execute

232

* @param options.description - Optional description of the function

233

* @returns An AutoParseableResponseTool with typed, validated arguments

234

*/

235

function zodResponsesFunction<Parameters extends z.ZodType>(options: {

236

name: string;

237

parameters: Parameters;

238

function?: (args: z.infer<Parameters>) => unknown | Promise<unknown>;

239

description?: string;

240

}): AutoParseableResponseTool<{

241

arguments: Parameters;

242

name: string;

243

function: (args: z.infer<Parameters>) => unknown;

244

}>;

245

```

246

247

**Usage Example:**

248

249

```typescript

250

import { zodResponsesFunction } from 'openai/helpers/zod';

251

import OpenAI from 'openai';

252

import { z } from 'zod';

253

254

const client = new OpenAI();

255

256

const SearchParams = z.object({

257

query: z.string(),

258

max_results: z.number().min(1).max(100),

259

});

260

261

const searchTool = zodResponsesFunction({

262

name: 'search_database',

263

parameters: SearchParams,

264

description: 'Search the database for relevant information',

265

function: async (args) => {

266

const { query, max_results } = args;

267

// ... perform search ...

268

return { results: [...] };

269

},

270

});

271

272

const response = await client.responses.create({

273

model: 'gpt-4o',

274

input: 'Find recent orders',

275

tools: [searchTool],

276

});

277

```

278

279

## Advanced Usage

280

281

### Complex Nested Schemas

282

283

```typescript

284

import { zodResponseFormat } from 'openai/helpers/zod';

285

import { z } from 'zod';

286

287

const CalendarEvent = z.object({

288

title: z.string(),

289

date: z.string().datetime(),

290

attendees: z.array(z.object({

291

name: z.string(),

292

email: z.string().email(),

293

})),

294

location: z.object({

295

name: z.string(),

296

address: z.string().optional(),

297

}).optional(),

298

});

299

300

const completion = await client.chat.completions.parse({

301

model: 'gpt-4o-2024-08-06',

302

messages: [

303

{ role: 'user', content: 'Extract calendar events from: "Team meeting tomorrow at 3pm with John and Jane"' },

304

],

305

response_format: zodResponseFormat(CalendarEvent, 'calendar_event'),

306

});

307

```

308

309

### Error Handling

310

311

```typescript

312

try {

313

const completion = await client.chat.completions.parse({

314

model: 'gpt-4o-2024-08-06',

315

messages: [...],

316

response_format: zodResponseFormat(MySchema, 'my_schema'),

317

});

318

319

const message = completion.choices[0]?.message;

320

if (message?.parsed) {

321

// Successfully parsed and validated

322

console.log(message.parsed);

323

} else if (message?.refusal) {

324

// Model refused to respond

325

console.log('Refusal:', message.refusal);

326

}

327

} catch (error) {

328

// Parsing or validation error

329

console.error('Error:', error);

330

}

331

```

332

333

## Types

334

335

### AutoParseableResponseFormat

336

337

```typescript { .api }

338

interface AutoParseableResponseFormat<T> extends ResponseFormatJSONSchema {

339

$brand: 'auto-parseable-response-format';

340

$parseRaw(content: string): T;

341

}

342

```

343

344

### AutoParseableTextFormat

345

346

```typescript { .api }

347

interface AutoParseableTextFormat<T> extends ResponseFormatTextJSONSchemaConfig {

348

$brand: 'auto-parseable-text-format';

349

$parseRaw(content: string): T;

350

}

351

```

352

353

### AutoParseableTool

354

355

```typescript { .api }

356

interface AutoParseableTool<T> extends ChatCompletionTool {

357

$brand: 'auto-parseable-tool';

358

$parseRaw(args: string): T;

359

$callback?: (args: T) => unknown | Promise<unknown>;

360

}

361

```

362

363

### AutoParseableResponseTool

364

365

```typescript { .api }

366

interface AutoParseableResponseTool<T> {

367

type: 'function';

368

name: string;

369

parameters: Record<string, unknown>;

370

strict: boolean;

371

description?: string;

372

$brand: 'auto-parseable-response-tool';

373

$parseRaw(args: string): T;

374

$callback?: (args: T) => unknown | Promise<unknown>;

375

}

376

```

377

378

## Compatibility

379

380

- Supports both Zod v3 and Zod v4

381

- Automatically detects Zod version and uses appropriate JSON Schema conversion

382

- Works with all OpenAI models that support structured outputs

383

- Requires TypeScript for full type safety benefits

384

385

## See Also

386

387

- [Chat Completions](./chat-completions.md) - Using structured outputs with chat

388

- [Responses API](./responses-api.md) - Using structured outputs with responses

389

- [Zod Documentation](https://zod.dev/) - Learn more about Zod schemas

390