-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Copy pathchat_models_structured_output.int.test.ts
587 lines (536 loc) Β· 17.3 KB
/
chat_models_structured_output.int.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { AIMessage, AIMessageChunk } from "@langchain/core/messages";
import { test, expect, describe, it } from "@jest/globals";
import { concat } from "@langchain/core/utils/stream";
import { ChatOpenAI } from "../chat_models.js";
test("withStructuredOutput zod schema function calling", async () => {
const model = new ChatOpenAI({
temperature: 0,
modelName: "gpt-4o-mini",
});
const calculatorSchema = z.object({
operation: z.enum(["add", "subtract", "multiply", "divide"]),
number1: z.number(),
number2: z.number(),
});
const modelWithStructuredOutput = model.withStructuredOutput(
calculatorSchema,
{
name: "calculator",
}
);
const prompt = ChatPromptTemplate.fromMessages([
["system", "You are VERY bad at math and must always use a calculator."],
["human", "Please help me!! What is 2 + 2?"],
]);
const chain = prompt.pipe(modelWithStructuredOutput);
const result = await chain.invoke({});
// console.log(result);
expect("operation" in result).toBe(true);
expect("number1" in result).toBe(true);
expect("number2" in result).toBe(true);
});
test("withStructuredOutput with o1", async () => {
const model = new ChatOpenAI({
model: "o1",
});
const calculatorSchema = z.object({
operation: z.enum(["add", "subtract", "multiply", "divide"]),
number1: z.number(),
number2: z.number(),
});
const modelWithStructuredOutput = model.withStructuredOutput(
calculatorSchema,
{
name: "calculator",
}
);
const prompt = ChatPromptTemplate.fromMessages([
["developer", "You are VERY bad at math and must always use a calculator."],
["human", "Please help me!! What is 2 + 2?"],
]);
const chain = prompt.pipe(modelWithStructuredOutput);
const result = await chain.invoke({});
// console.log(result);
expect("operation" in result).toBe(true);
expect("number1" in result).toBe(true);
expect("number2" in result).toBe(true);
});
test("withStructuredOutput zod schema streaming", async () => {
const model = new ChatOpenAI({
temperature: 0,
modelName: "gpt-4o-mini",
});
const calculatorSchema = z.object({
operation: z.enum(["add", "subtract", "multiply", "divide"]),
number1: z.number(),
number2: z.number(),
});
const modelWithStructuredOutput = model.withStructuredOutput(
calculatorSchema,
{
name: "calculator",
}
);
const prompt = ChatPromptTemplate.fromMessages([
["system", "You are VERY bad at math and must always use a calculator."],
["human", "Please help me!! What is 2 + 2?"],
]);
const chain = prompt.pipe(modelWithStructuredOutput);
const stream = await chain.stream({});
const chunks = [];
for await (const chunk of stream) {
chunks.push(chunk);
}
expect(chunks.length).toBeGreaterThan(1);
const result = chunks.at(-1) ?? {};
expect("operation" in result).toBe(true);
expect("number1" in result).toBe(true);
expect("number2" in result).toBe(true);
});
test("withStructuredOutput zod schema JSON mode", async () => {
const model = new ChatOpenAI({
temperature: 0,
modelName: "gpt-4o-mini",
});
const calculatorSchema = z.object({
operation: z.enum(["add", "subtract", "multiply", "divide"]),
number1: z.number(),
number2: z.number(),
});
const modelWithStructuredOutput = model.withStructuredOutput(
calculatorSchema,
{
name: "calculator",
method: "jsonMode",
}
);
const prompt = ChatPromptTemplate.fromMessages([
[
"system",
`You are VERY bad at math and must always use a calculator.
Respond with a JSON object containing three keys:
'operation': the type of operation to execute, either 'add', 'subtract', 'multiply' or 'divide',
'number1': the first number to operate on,
'number2': the second number to operate on.
`,
],
["human", "Please help me!! What is 2 + 2?"],
]);
const chain = prompt.pipe(modelWithStructuredOutput);
const result = await chain.invoke({});
// console.log(result);
expect("operation" in result).toBe(true);
expect("number1" in result).toBe(true);
expect("number2" in result).toBe(true);
});
test("withStructuredOutput JSON schema function calling", async () => {
const model = new ChatOpenAI({
temperature: 0,
modelName: "gpt-4o-mini",
});
const calculatorSchema = z.object({
operation: z.enum(["add", "subtract", "multiply", "divide"]),
number1: z.number(),
number2: z.number(),
});
const modelWithStructuredOutput = model.withStructuredOutput({
schema: zodToJsonSchema(calculatorSchema),
name: "calculator",
});
const prompt = ChatPromptTemplate.fromMessages([
["system", `You are VERY bad at math and must always use a calculator.`],
["human", "Please help me!! What is 2 + 2?"],
]);
const chain = prompt.pipe(modelWithStructuredOutput);
const result = await chain.invoke({});
// console.log(result);
expect("operation" in result).toBe(true);
expect("number1" in result).toBe(true);
expect("number2" in result).toBe(true);
});
test("withStructuredOutput OpenAI function definition function calling", async () => {
const model = new ChatOpenAI({
temperature: 0,
modelName: "gpt-4o-mini",
});
const calculatorSchema = z.object({
operation: z.enum(["add", "subtract", "multiply", "divide"]),
number1: z.number(),
number2: z.number(),
});
const modelWithStructuredOutput = model.withStructuredOutput({
name: "calculator",
parameters: zodToJsonSchema(calculatorSchema),
});
const prompt = ChatPromptTemplate.fromMessages([
["system", `You are VERY bad at math and must always use a calculator.`],
["human", "Please help me!! What is 2 + 2?"],
]);
const chain = prompt.pipe(modelWithStructuredOutput);
const result = await chain.invoke({});
// console.log(result);
expect("operation" in result).toBe(true);
expect("number1" in result).toBe(true);
expect("number2" in result).toBe(true);
});
test("withStructuredOutput JSON schema JSON mode", async () => {
const model = new ChatOpenAI({
temperature: 0,
modelName: "gpt-4o-mini",
});
const calculatorSchema = z.object({
operation: z.enum(["add", "subtract", "multiply", "divide"]),
number1: z.number(),
number2: z.number(),
});
const modelWithStructuredOutput = model.withStructuredOutput(
zodToJsonSchema(calculatorSchema),
{
name: "calculator",
method: "jsonMode",
}
);
const prompt = ChatPromptTemplate.fromMessages([
[
"system",
`You are VERY bad at math and must always use a calculator.
Respond with a JSON object containing three keys:
'operation': the type of operation to execute, either 'add', 'subtract', 'multiply' or 'divide',
'number1': the first number to operate on,
'number2': the second number to operate on.
`,
],
["human", "Please help me!! What is 2 + 2?"],
]);
const chain = prompt.pipe(modelWithStructuredOutput);
const result = await chain.invoke({});
// console.log(result);
expect("operation" in result).toBe(true);
expect("number1" in result).toBe(true);
expect("number2" in result).toBe(true);
});
test("withStructuredOutput JSON schema", async () => {
const model = new ChatOpenAI({
temperature: 0,
modelName: "gpt-4o-mini",
});
const jsonSchema = {
title: "calculator",
description: "A simple calculator",
type: "object",
properties: {
operation: {
type: "string",
enum: ["add", "subtract", "multiply", "divide"],
},
number1: { type: "number" },
number2: { type: "number" },
},
};
const modelWithStructuredOutput = model.withStructuredOutput(jsonSchema);
const prompt = ChatPromptTemplate.fromMessages([
[
"system",
`You are VERY bad at math and must always use a calculator.
Respond with a JSON object containing three keys:
'operation': the type of operation to execute, either 'add', 'subtract', 'multiply' or 'divide',
'number1': the first number to operate on,
'number2': the second number to operate on.
`,
],
["human", "Please help me!! What is 2 + 2?"],
]);
const chain = prompt.pipe(modelWithStructuredOutput);
const result = await chain.invoke({});
// console.log(result);
expect("operation" in result).toBe(true);
expect("number1" in result).toBe(true);
expect("number2" in result).toBe(true);
});
test("withStructuredOutput includeRaw true", async () => {
const model = new ChatOpenAI({
temperature: 0,
modelName: "gpt-4o-mini",
});
const calculatorSchema = z.object({
operation: z.enum(["add", "subtract", "multiply", "divide"]),
number1: z.number(),
number2: z.number(),
});
const modelWithStructuredOutput = model.withStructuredOutput(
calculatorSchema,
{
name: "calculator",
includeRaw: true,
}
);
const prompt = ChatPromptTemplate.fromMessages([
["system", "You are VERY bad at math and must always use a calculator."],
["human", "Please help me!! What is 2 + 2?"],
]);
const chain = prompt.pipe(modelWithStructuredOutput);
const result = await chain.invoke({});
// console.log(result);
expect("parsed" in result).toBe(true);
// Need to make TS happy :)
if (!("parsed" in result)) {
throw new Error("parsed not in result");
}
const { parsed } = result;
expect("operation" in parsed).toBe(true);
expect("number1" in parsed).toBe(true);
expect("number2" in parsed).toBe(true);
expect("raw" in result).toBe(true);
// Need to make TS happy :)
if (!("raw" in result)) {
throw new Error("raw not in result");
}
const { raw } = result as { raw: AIMessage };
expect(raw.additional_kwargs.tool_calls?.length).toBeGreaterThan(0);
expect(raw.additional_kwargs.tool_calls?.[0].function.name).toBe(
"calculator"
);
expect(
"operation" in
JSON.parse(raw.additional_kwargs.tool_calls?.[0].function.arguments ?? "")
).toBe(true);
expect(
"number1" in
JSON.parse(raw.additional_kwargs.tool_calls?.[0].function.arguments ?? "")
).toBe(true);
expect(
"number2" in
JSON.parse(raw.additional_kwargs.tool_calls?.[0].function.arguments ?? "")
).toBe(true);
});
test("parallelToolCalls param", async () => {
const calculatorSchema = z
.object({
operation: z.enum(["add", "subtract", "multiply", "divide"]),
number1: z.number(),
number2: z.number(),
})
.describe("A tool to perform basic arithmetic operations");
const weatherSchema = z
.object({
city: z.enum(["add", "subtract", "multiply", "divide"]),
})
.describe("A tool to get the weather in a city");
const model = new ChatOpenAI({
model: "gpt-4o",
temperature: 0,
}).bindTools([
{
type: "function",
function: {
name: "calculator",
description: calculatorSchema.description,
parameters: zodToJsonSchema(calculatorSchema),
},
},
{
type: "function",
function: {
name: "weather",
description: weatherSchema.description,
parameters: zodToJsonSchema(weatherSchema),
},
},
]);
const response = await model.invoke(
["What is the weather in san francisco and what is 23716 times 27342?"],
{
parallel_tool_calls: false,
}
);
// console.log(response.tool_calls);
expect(response.tool_calls?.length).toBe(1);
});
test("Passing strict true forces the model to conform to the schema", async () => {
const model = new ChatOpenAI({
model: "gpt-4o",
temperature: 0,
maxRetries: 0,
});
const weatherTool = {
type: "function" as const,
function: {
name: "get_current_weather",
description: "Get the current weather in a location",
parameters: zodToJsonSchema(
z.object({
location: z.string().describe("The location to get the weather for"),
})
),
},
};
const modelWithTools = model.bindTools([weatherTool], {
strict: true,
tool_choice: "get_current_weather",
});
const result = await modelWithTools.invoke(
"Whats the result of 173827 times 287326 divided by 2?"
);
// Expect at least one tool call, allow multiple
expect(result.tool_calls?.length).toBeGreaterThanOrEqual(1);
expect(result.tool_calls?.[0].name).toBe("get_current_weather");
expect(result.tool_calls?.[0].args).toHaveProperty("location");
console.log(result.tool_calls?.[0].args);
});
describe("response_format: json_schema", () => {
const weatherSchema = z.object({
city: z.string().describe("The city to get the weather for"),
state: z.string().describe("The state to get the weather for"),
zipCode: z.string().describe("The zip code to get the weather for"),
unit: z
.enum(["fahrenheit", "celsius"])
.describe("The unit to get the weather in"),
});
it("can invoke", async () => {
const model = new ChatOpenAI({
model: "gpt-4o-2024-08-06",
}).bind({
response_format: {
type: "json_schema",
json_schema: {
name: "get_current_weather",
description: "Get the current weather in a location",
schema: zodToJsonSchema(weatherSchema),
strict: true,
},
},
});
const response = await model.invoke(
"What is the weather in San Francisco, 91626 CA?"
);
const parsed = JSON.parse(response.content as string);
expect(parsed).toHaveProperty("city");
expect(parsed).toHaveProperty("state");
expect(parsed).toHaveProperty("zipCode");
expect(parsed).toHaveProperty("unit");
});
it("can stream", async () => {
const model = new ChatOpenAI({
model: "gpt-4o-2024-08-06",
}).bind({
response_format: {
type: "json_schema",
json_schema: {
name: "get_current_weather",
description: "Get the current weather in a location",
schema: zodToJsonSchema(weatherSchema),
strict: true,
},
},
});
const stream = await model.stream(
"What is the weather in San Francisco, 91626 CA?"
);
let full: AIMessageChunk | undefined;
for await (const chunk of stream) {
full = !full ? chunk : concat(full, chunk);
}
expect(full).toBeDefined();
if (!full) return;
const parsed = JSON.parse(full.content as string);
expect(parsed).toHaveProperty("city");
expect(parsed).toHaveProperty("state");
expect(parsed).toHaveProperty("zipCode");
expect(parsed).toHaveProperty("unit");
});
it("can invoke with a zod schema passed in", async () => {
const model = new ChatOpenAI({
model: "gpt-4o-2024-08-06",
}).bind({
response_format: {
type: "json_schema",
json_schema: {
name: "get_current_weather",
description: "Get the current weather in a location",
schema: weatherSchema,
strict: true,
},
},
});
const response = await model.invoke(
"What is the weather in San Francisco, 91626 CA?"
);
const parsed = JSON.parse(response.content as string);
expect(parsed).toHaveProperty("city");
expect(parsed).toHaveProperty("state");
expect(parsed).toHaveProperty("zipCode");
expect(parsed).toHaveProperty("unit");
});
it("can stream with a zod schema passed in", async () => {
const model = new ChatOpenAI({
model: "gpt-4o-2024-08-06",
}).bind({
response_format: {
type: "json_schema",
json_schema: {
name: "get_current_weather",
description: "Get the current weather in a location",
schema: weatherSchema,
strict: true,
},
},
});
const stream = await model.stream(
"What is the weather in San Francisco, 91626 CA?"
);
let full: AIMessageChunk | undefined;
for await (const chunk of stream) {
full = !full ? chunk : concat(full, chunk);
}
expect(full).toBeDefined();
if (!full) return;
const parsed = JSON.parse(full.content as string);
expect(parsed).toHaveProperty("city");
expect(parsed).toHaveProperty("state");
expect(parsed).toHaveProperty("zipCode");
expect(parsed).toHaveProperty("unit");
});
it("can be invoked with WSO", async () => {
const model = new ChatOpenAI({
model: "gpt-4o-2024-08-06",
}).withStructuredOutput(weatherSchema, {
name: "get_current_weather",
method: "jsonSchema",
strict: true,
});
const response = await model.invoke(
"What is the weather in San Francisco, 91626 CA?"
);
expect(response).toHaveProperty("city");
expect(response).toHaveProperty("state");
expect(response).toHaveProperty("zipCode");
expect(response).toHaveProperty("unit");
});
// Flaky test
it.skip("can be streamed with WSO", async () => {
const model = new ChatOpenAI({
model: "gpt-4o-2024-08-06",
}).withStructuredOutput(weatherSchema, {
name: "get_current_weather",
method: "jsonSchema",
strict: true,
});
const stream = await model.stream(
"What is the weather in San Francisco, 91626 CA?"
);
// It should yield a single chunk
let full: z.infer<typeof weatherSchema> | undefined;
for await (const chunk of stream) {
full = chunk;
}
expect(full).toBeDefined();
if (!full) return;
expect(full).toHaveProperty("city");
expect(full).toHaveProperty("state");
expect(full).toHaveProperty("zipCode");
expect(full).toHaveProperty("unit");
});
});