@langchain/openai 0.2.6 → 0.2.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/azure/chat_models.cjs +412 -0
- package/dist/azure/chat_models.d.ts +412 -0
- package/dist/azure/chat_models.js +412 -0
- package/dist/chat_models.cjs +541 -37
- package/dist/chat_models.d.ts +462 -29
- package/dist/chat_models.js +541 -37
- package/dist/types.d.ts +12 -0
- package/dist/utils/tools.cjs +54 -0
- package/dist/utils/tools.d.ts +20 -0
- package/dist/utils/tools.js +50 -0
- package/package.json +4 -4
package/dist/chat_models.js
CHANGED
|
@@ -4,14 +4,15 @@ import { ChatGenerationChunk, } from "@langchain/core/outputs";
|
|
|
4
4
|
import { getEnvironmentVariable } from "@langchain/core/utils/env";
|
|
5
5
|
import { BaseChatModel, } from "@langchain/core/language_models/chat_models";
|
|
6
6
|
import { isOpenAITool, } from "@langchain/core/language_models/base";
|
|
7
|
-
import { convertToOpenAITool } from "@langchain/core/utils/function_calling";
|
|
8
7
|
import { RunnablePassthrough, RunnableSequence, } from "@langchain/core/runnables";
|
|
9
8
|
import { JsonOutputParser, StructuredOutputParser, } from "@langchain/core/output_parsers";
|
|
10
9
|
import { JsonOutputKeyToolsParser, convertLangChainToolCallToOpenAI, makeInvalidToolCall, parseToolCall, } from "@langchain/core/output_parsers/openai_tools";
|
|
11
10
|
import { zodToJsonSchema } from "zod-to-json-schema";
|
|
11
|
+
import { zodResponseFormat } from "openai/helpers/zod";
|
|
12
12
|
import { getEndpoint } from "./utils/azure.js";
|
|
13
13
|
import { formatToOpenAIToolChoice, wrapOpenAIClientError, } from "./utils/openai.js";
|
|
14
14
|
import { formatFunctionDefinitions, } from "./utils/openai-format-fndef.js";
|
|
15
|
+
import { _convertToOpenAITool } from "./utils/tools.js";
|
|
15
16
|
function extractGenericMessageCustomRole(message) {
|
|
16
17
|
if (message.role !== "system" &&
|
|
17
18
|
message.role !== "assistant" &&
|
|
@@ -194,40 +195,466 @@ function _convertChatOpenAIToolTypeToOpenAITool(tool, fields) {
|
|
|
194
195
|
}
|
|
195
196
|
return tool;
|
|
196
197
|
}
|
|
197
|
-
return
|
|
198
|
+
return _convertToOpenAITool(tool, fields);
|
|
198
199
|
}
|
|
199
200
|
/**
|
|
200
|
-
*
|
|
201
|
-
*
|
|
202
|
-
*
|
|
203
|
-
*
|
|
204
|
-
*
|
|
205
|
-
*
|
|
206
|
-
*
|
|
207
|
-
*
|
|
208
|
-
*
|
|
209
|
-
*
|
|
210
|
-
*
|
|
211
|
-
*
|
|
212
|
-
*
|
|
213
|
-
*
|
|
214
|
-
*
|
|
215
|
-
*
|
|
216
|
-
*
|
|
201
|
+
* OpenAI chat model integration.
|
|
202
|
+
*
|
|
203
|
+
* Setup:
|
|
204
|
+
* Install `@langchain/openai` and set an environment variable named `OPENAI_API_KEY`.
|
|
205
|
+
*
|
|
206
|
+
* ```bash
|
|
207
|
+
* npm install @langchain/openai
|
|
208
|
+
* export OPENAI_API_KEY="your-api-key"
|
|
209
|
+
* ```
|
|
210
|
+
*
|
|
211
|
+
* ## [Constructor args](https://api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html#constructor)
|
|
212
|
+
*
|
|
213
|
+
* ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_openai.ChatOpenAICallOptions.html)
|
|
214
|
+
*
|
|
215
|
+
* Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.
|
|
216
|
+
* They can also be passed via `.bind`, or the second arg in `.bindTools`, like shown in the examples below:
|
|
217
|
+
*
|
|
218
|
+
* ```typescript
|
|
219
|
+
* // When calling `.bind`, call options should be passed via the first argument
|
|
220
|
+
* const llmWithArgsBound = llm.bind({
|
|
221
|
+
* stop: ["\n"],
|
|
222
|
+
* tools: [...],
|
|
223
|
+
* });
|
|
224
|
+
*
|
|
225
|
+
* // When calling `.bindTools`, call options should be passed via the second argument
|
|
226
|
+
* const llmWithTools = llm.bindTools(
|
|
227
|
+
* [...],
|
|
228
|
+
* {
|
|
229
|
+
* tool_choice: "auto",
|
|
230
|
+
* }
|
|
231
|
+
* );
|
|
232
|
+
* ```
|
|
233
|
+
*
|
|
234
|
+
* ## Examples
|
|
235
|
+
*
|
|
236
|
+
* <details open>
|
|
237
|
+
* <summary><strong>Instantiate</strong></summary>
|
|
238
|
+
*
|
|
217
239
|
* ```typescript
|
|
218
|
-
*
|
|
219
|
-
*
|
|
220
|
-
*
|
|
221
|
-
* model: "
|
|
240
|
+
* import { ChatOpenAI } from '@langchain/openai';
|
|
241
|
+
*
|
|
242
|
+
* const llm = new ChatOpenAI({
|
|
243
|
+
* model: "gpt-4o",
|
|
244
|
+
* temperature: 0,
|
|
245
|
+
* maxTokens: undefined,
|
|
246
|
+
* timeout: undefined,
|
|
247
|
+
* maxRetries: 2,
|
|
248
|
+
* // apiKey: "...",
|
|
249
|
+
* // baseUrl: "...",
|
|
250
|
+
* // organization: "...",
|
|
251
|
+
* // other params...
|
|
222
252
|
* });
|
|
253
|
+
* ```
|
|
254
|
+
* </details>
|
|
255
|
+
*
|
|
256
|
+
* <br />
|
|
257
|
+
*
|
|
258
|
+
* <details>
|
|
259
|
+
* <summary><strong>Invoking</strong></summary>
|
|
260
|
+
*
|
|
261
|
+
* ```typescript
|
|
262
|
+
* const input = `Translate "I love programming" into French.`;
|
|
263
|
+
*
|
|
264
|
+
* // Models also accept a list of chat messages or a formatted prompt
|
|
265
|
+
* const result = await llm.invoke(input);
|
|
266
|
+
* console.log(result);
|
|
267
|
+
* ```
|
|
268
|
+
*
|
|
269
|
+
* ```txt
|
|
270
|
+
* AIMessage {
|
|
271
|
+
* "id": "chatcmpl-9u4Mpu44CbPjwYFkTbeoZgvzB00Tz",
|
|
272
|
+
* "content": "J'adore la programmation.",
|
|
273
|
+
* "response_metadata": {
|
|
274
|
+
* "tokenUsage": {
|
|
275
|
+
* "completionTokens": 5,
|
|
276
|
+
* "promptTokens": 28,
|
|
277
|
+
* "totalTokens": 33
|
|
278
|
+
* },
|
|
279
|
+
* "finish_reason": "stop",
|
|
280
|
+
* "system_fingerprint": "fp_3aa7262c27"
|
|
281
|
+
* },
|
|
282
|
+
* "usage_metadata": {
|
|
283
|
+
* "input_tokens": 28,
|
|
284
|
+
* "output_tokens": 5,
|
|
285
|
+
* "total_tokens": 33
|
|
286
|
+
* }
|
|
287
|
+
* }
|
|
288
|
+
* ```
|
|
289
|
+
* </details>
|
|
290
|
+
*
|
|
291
|
+
* <br />
|
|
292
|
+
*
|
|
293
|
+
* <details>
|
|
294
|
+
* <summary><strong>Streaming Chunks</strong></summary>
|
|
295
|
+
*
|
|
296
|
+
* ```typescript
|
|
297
|
+
* for await (const chunk of await llm.stream(input)) {
|
|
298
|
+
* console.log(chunk);
|
|
299
|
+
* }
|
|
300
|
+
* ```
|
|
301
|
+
*
|
|
302
|
+
* ```txt
|
|
303
|
+
* AIMessageChunk {
|
|
304
|
+
* "id": "chatcmpl-9u4NWB7yUeHCKdLr6jP3HpaOYHTqs",
|
|
305
|
+
* "content": ""
|
|
306
|
+
* }
|
|
307
|
+
* AIMessageChunk {
|
|
308
|
+
* "content": "J"
|
|
309
|
+
* }
|
|
310
|
+
* AIMessageChunk {
|
|
311
|
+
* "content": "'adore"
|
|
312
|
+
* }
|
|
313
|
+
* AIMessageChunk {
|
|
314
|
+
* "content": " la"
|
|
315
|
+
* }
|
|
316
|
+
* AIMessageChunk {
|
|
317
|
+
* "content": " programmation",,
|
|
318
|
+
* }
|
|
319
|
+
* AIMessageChunk {
|
|
320
|
+
* "content": ".",,
|
|
321
|
+
* }
|
|
322
|
+
* AIMessageChunk {
|
|
323
|
+
* "content": "",
|
|
324
|
+
* "response_metadata": {
|
|
325
|
+
* "finish_reason": "stop",
|
|
326
|
+
* "system_fingerprint": "fp_c9aa9c0491"
|
|
327
|
+
* },
|
|
328
|
+
* }
|
|
329
|
+
* AIMessageChunk {
|
|
330
|
+
* "content": "",
|
|
331
|
+
* "usage_metadata": {
|
|
332
|
+
* "input_tokens": 28,
|
|
333
|
+
* "output_tokens": 5,
|
|
334
|
+
* "total_tokens": 33
|
|
335
|
+
* }
|
|
336
|
+
* }
|
|
337
|
+
* ```
|
|
338
|
+
* </details>
|
|
339
|
+
*
|
|
340
|
+
* <br />
|
|
341
|
+
*
|
|
342
|
+
* <details>
|
|
343
|
+
* <summary><strong>Aggregate Streamed Chunks</strong></summary>
|
|
344
|
+
*
|
|
345
|
+
* ```typescript
|
|
346
|
+
* import { AIMessageChunk } from '@langchain/core/messages';
|
|
347
|
+
* import { concat } from '@langchain/core/utils/stream';
|
|
223
348
|
*
|
|
224
|
-
*
|
|
225
|
-
*
|
|
349
|
+
* const stream = await llm.stream(input);
|
|
350
|
+
* let full: AIMessageChunk | undefined;
|
|
351
|
+
* for await (const chunk of stream) {
|
|
352
|
+
* full = !full ? chunk : concat(full, chunk);
|
|
353
|
+
* }
|
|
354
|
+
* console.log(full);
|
|
355
|
+
* ```
|
|
356
|
+
*
|
|
357
|
+
* ```txt
|
|
358
|
+
* AIMessageChunk {
|
|
359
|
+
* "id": "chatcmpl-9u4PnX6Fy7OmK46DASy0bH6cxn5Xu",
|
|
360
|
+
* "content": "J'adore la programmation.",
|
|
361
|
+
* "response_metadata": {
|
|
362
|
+
* "prompt": 0,
|
|
363
|
+
* "completion": 0,
|
|
364
|
+
* "finish_reason": "stop",
|
|
365
|
+
* },
|
|
366
|
+
* "usage_metadata": {
|
|
367
|
+
* "input_tokens": 28,
|
|
368
|
+
* "output_tokens": 5,
|
|
369
|
+
* "total_tokens": 33
|
|
370
|
+
* }
|
|
371
|
+
* }
|
|
372
|
+
* ```
|
|
373
|
+
* </details>
|
|
374
|
+
*
|
|
375
|
+
* <br />
|
|
376
|
+
*
|
|
377
|
+
* <details>
|
|
378
|
+
* <summary><strong>Bind tools</strong></summary>
|
|
379
|
+
*
|
|
380
|
+
* ```typescript
|
|
381
|
+
* import { z } from 'zod';
|
|
382
|
+
*
|
|
383
|
+
* const GetWeather = {
|
|
384
|
+
* name: "GetWeather",
|
|
385
|
+
* description: "Get the current weather in a given location",
|
|
386
|
+
* schema: z.object({
|
|
387
|
+
* location: z.string().describe("The city and state, e.g. San Francisco, CA")
|
|
388
|
+
* }),
|
|
389
|
+
* }
|
|
390
|
+
*
|
|
391
|
+
* const GetPopulation = {
|
|
392
|
+
* name: "GetPopulation",
|
|
393
|
+
* description: "Get the current population in a given location",
|
|
394
|
+
* schema: z.object({
|
|
395
|
+
* location: z.string().describe("The city and state, e.g. San Francisco, CA")
|
|
396
|
+
* }),
|
|
397
|
+
* }
|
|
398
|
+
*
|
|
399
|
+
* const llmWithTools = llm.bindTools(
|
|
400
|
+
* [GetWeather, GetPopulation],
|
|
401
|
+
* {
|
|
402
|
+
* // strict: true // enforce tool args schema is respected
|
|
403
|
+
* }
|
|
404
|
+
* );
|
|
405
|
+
* const aiMsg = await llmWithTools.invoke(
|
|
406
|
+
* "Which city is hotter today and which is bigger: LA or NY?"
|
|
407
|
+
* );
|
|
408
|
+
* console.log(aiMsg.tool_calls);
|
|
409
|
+
* ```
|
|
410
|
+
*
|
|
411
|
+
* ```txt
|
|
412
|
+
* [
|
|
413
|
+
* {
|
|
414
|
+
* name: 'GetWeather',
|
|
415
|
+
* args: { location: 'Los Angeles, CA' },
|
|
416
|
+
* type: 'tool_call',
|
|
417
|
+
* id: 'call_uPU4FiFzoKAtMxfmPnfQL6UK'
|
|
418
|
+
* },
|
|
419
|
+
* {
|
|
420
|
+
* name: 'GetWeather',
|
|
421
|
+
* args: { location: 'New York, NY' },
|
|
422
|
+
* type: 'tool_call',
|
|
423
|
+
* id: 'call_UNkEwuQsHrGYqgDQuH9nPAtX'
|
|
424
|
+
* },
|
|
425
|
+
* {
|
|
426
|
+
* name: 'GetPopulation',
|
|
427
|
+
* args: { location: 'Los Angeles, CA' },
|
|
428
|
+
* type: 'tool_call',
|
|
429
|
+
* id: 'call_kL3OXxaq9OjIKqRTpvjaCH14'
|
|
430
|
+
* },
|
|
431
|
+
* {
|
|
432
|
+
* name: 'GetPopulation',
|
|
433
|
+
* args: { location: 'New York, NY' },
|
|
434
|
+
* type: 'tool_call',
|
|
435
|
+
* id: 'call_s9KQB1UWj45LLGaEnjz0179q'
|
|
436
|
+
* }
|
|
437
|
+
* ]
|
|
438
|
+
* ```
|
|
439
|
+
* </details>
|
|
440
|
+
*
|
|
441
|
+
* <br />
|
|
442
|
+
*
|
|
443
|
+
* <details>
|
|
444
|
+
* <summary><strong>Structured Output</strong></summary>
|
|
445
|
+
*
|
|
446
|
+
* ```typescript
|
|
447
|
+
* import { z } from 'zod';
|
|
448
|
+
*
|
|
449
|
+
* const Joke = z.object({
|
|
450
|
+
* setup: z.string().describe("The setup of the joke"),
|
|
451
|
+
* punchline: z.string().describe("The punchline to the joke"),
|
|
452
|
+
* rating: z.number().optional().describe("How funny the joke is, from 1 to 10")
|
|
453
|
+
* }).describe('Joke to tell user.');
|
|
226
454
|
*
|
|
227
|
-
*
|
|
228
|
-
*
|
|
455
|
+
* const structuredLlm = llm.withStructuredOutput(Joke, { name: "Joke" });
|
|
456
|
+
* const jokeResult = await structuredLlm.invoke("Tell me a joke about cats");
|
|
457
|
+
* console.log(jokeResult);
|
|
458
|
+
* ```
|
|
459
|
+
*
|
|
460
|
+
* ```txt
|
|
461
|
+
* {
|
|
462
|
+
* setup: 'Why was the cat sitting on the computer?',
|
|
463
|
+
* punchline: 'Because it wanted to keep an eye on the mouse!',
|
|
464
|
+
* rating: 7
|
|
465
|
+
* }
|
|
466
|
+
* ```
|
|
467
|
+
* </details>
|
|
468
|
+
*
|
|
469
|
+
* <br />
|
|
470
|
+
*
|
|
471
|
+
* <details>
|
|
472
|
+
* <summary><strong>JSON Object Response Format</strong></summary>
|
|
473
|
+
*
|
|
474
|
+
* ```typescript
|
|
475
|
+
* const jsonLlm = llm.bind({ response_format: { type: "json_object" } });
|
|
476
|
+
* const jsonLlmAiMsg = await jsonLlm.invoke(
|
|
477
|
+
* "Return a JSON object with key 'randomInts' and a value of 10 random ints in [0-99]"
|
|
478
|
+
* );
|
|
479
|
+
* console.log(jsonLlmAiMsg.content);
|
|
480
|
+
* ```
|
|
481
|
+
*
|
|
482
|
+
* ```txt
|
|
483
|
+
* {
|
|
484
|
+
* "randomInts": [23, 87, 45, 12, 78, 34, 56, 90, 11, 67]
|
|
485
|
+
* }
|
|
486
|
+
* ```
|
|
487
|
+
* </details>
|
|
488
|
+
*
|
|
489
|
+
* <br />
|
|
490
|
+
*
|
|
491
|
+
* <details>
|
|
492
|
+
* <summary><strong>Multimodal</strong></summary>
|
|
493
|
+
*
|
|
494
|
+
* ```typescript
|
|
495
|
+
* import { HumanMessage } from '@langchain/core/messages';
|
|
496
|
+
*
|
|
497
|
+
* const imageUrl = "https://example.com/image.jpg";
|
|
498
|
+
* const imageData = await fetch(imageUrl).then(res => res.arrayBuffer());
|
|
499
|
+
* const base64Image = Buffer.from(imageData).toString('base64');
|
|
500
|
+
*
|
|
501
|
+
* const message = new HumanMessage({
|
|
502
|
+
* content: [
|
|
503
|
+
* { type: "text", text: "describe the weather in this image" },
|
|
504
|
+
* {
|
|
505
|
+
* type: "image_url",
|
|
506
|
+
* image_url: { url: `data:image/jpeg;base64,${base64Image}` },
|
|
507
|
+
* },
|
|
508
|
+
* ]
|
|
509
|
+
* });
|
|
229
510
|
*
|
|
511
|
+
* const imageDescriptionAiMsg = await llm.invoke([message]);
|
|
512
|
+
* console.log(imageDescriptionAiMsg.content);
|
|
230
513
|
* ```
|
|
514
|
+
*
|
|
515
|
+
* ```txt
|
|
516
|
+
* The weather in the image appears to be clear and sunny. The sky is mostly blue with a few scattered white clouds, indicating fair weather. The bright sunlight is casting shadows on the green, grassy hill, suggesting it is a pleasant day with good visibility. There are no signs of rain or stormy conditions.
|
|
517
|
+
* ```
|
|
518
|
+
* </details>
|
|
519
|
+
*
|
|
520
|
+
* <br />
|
|
521
|
+
*
|
|
522
|
+
* <details>
|
|
523
|
+
* <summary><strong>Usage Metadata</strong></summary>
|
|
524
|
+
*
|
|
525
|
+
* ```typescript
|
|
526
|
+
* const aiMsgForMetadata = await llm.invoke(input);
|
|
527
|
+
* console.log(aiMsgForMetadata.usage_metadata);
|
|
528
|
+
* ```
|
|
529
|
+
*
|
|
530
|
+
* ```txt
|
|
531
|
+
* { input_tokens: 28, output_tokens: 5, total_tokens: 33 }
|
|
532
|
+
* ```
|
|
533
|
+
* </details>
|
|
534
|
+
*
|
|
535
|
+
* <br />
|
|
536
|
+
*
|
|
537
|
+
* <details>
|
|
538
|
+
* <summary><strong>Logprobs</strong></summary>
|
|
539
|
+
*
|
|
540
|
+
* ```typescript
|
|
541
|
+
* const logprobsLlm = new ChatOpenAI({ logprobs: true });
|
|
542
|
+
* const aiMsgForLogprobs = await logprobsLlm.invoke(input);
|
|
543
|
+
* console.log(aiMsgForLogprobs.response_metadata.logprobs);
|
|
544
|
+
* ```
|
|
545
|
+
*
|
|
546
|
+
* ```txt
|
|
547
|
+
* {
|
|
548
|
+
* content: [
|
|
549
|
+
* {
|
|
550
|
+
* token: 'J',
|
|
551
|
+
* logprob: -0.000050616763,
|
|
552
|
+
* bytes: [Array],
|
|
553
|
+
* top_logprobs: []
|
|
554
|
+
* },
|
|
555
|
+
* {
|
|
556
|
+
* token: "'",
|
|
557
|
+
* logprob: -0.01868736,
|
|
558
|
+
* bytes: [Array],
|
|
559
|
+
* top_logprobs: []
|
|
560
|
+
* },
|
|
561
|
+
* {
|
|
562
|
+
* token: 'ad',
|
|
563
|
+
* logprob: -0.0000030545007,
|
|
564
|
+
* bytes: [Array],
|
|
565
|
+
* top_logprobs: []
|
|
566
|
+
* },
|
|
567
|
+
* { token: 'ore', logprob: 0, bytes: [Array], top_logprobs: [] },
|
|
568
|
+
* {
|
|
569
|
+
* token: ' la',
|
|
570
|
+
* logprob: -0.515404,
|
|
571
|
+
* bytes: [Array],
|
|
572
|
+
* top_logprobs: []
|
|
573
|
+
* },
|
|
574
|
+
* {
|
|
575
|
+
* token: ' programm',
|
|
576
|
+
* logprob: -0.0000118755715,
|
|
577
|
+
* bytes: [Array],
|
|
578
|
+
* top_logprobs: []
|
|
579
|
+
* },
|
|
580
|
+
* { token: 'ation', logprob: 0, bytes: [Array], top_logprobs: [] },
|
|
581
|
+
* {
|
|
582
|
+
* token: '.',
|
|
583
|
+
* logprob: -0.0000037697225,
|
|
584
|
+
* bytes: [Array],
|
|
585
|
+
* top_logprobs: []
|
|
586
|
+
* }
|
|
587
|
+
* ],
|
|
588
|
+
* refusal: null
|
|
589
|
+
* }
|
|
590
|
+
* ```
|
|
591
|
+
* </details>
|
|
592
|
+
*
|
|
593
|
+
* <br />
|
|
594
|
+
*
|
|
595
|
+
* <details>
|
|
596
|
+
* <summary><strong>Response Metadata</strong></summary>
|
|
597
|
+
*
|
|
598
|
+
* ```typescript
|
|
599
|
+
* const aiMsgForResponseMetadata = await llm.invoke(input);
|
|
600
|
+
* console.log(aiMsgForResponseMetadata.response_metadata);
|
|
601
|
+
* ```
|
|
602
|
+
*
|
|
603
|
+
* ```txt
|
|
604
|
+
* {
|
|
605
|
+
* tokenUsage: { completionTokens: 5, promptTokens: 28, totalTokens: 33 },
|
|
606
|
+
* finish_reason: 'stop',
|
|
607
|
+
* system_fingerprint: 'fp_3aa7262c27'
|
|
608
|
+
* }
|
|
609
|
+
* ```
|
|
610
|
+
* </details>
|
|
611
|
+
*
|
|
612
|
+
* <br />
|
|
613
|
+
*
|
|
614
|
+
* <details>
|
|
615
|
+
* <summary><strong>JSON Schema Structured Output</strong></summary>
|
|
616
|
+
*
|
|
617
|
+
* ```typescript
|
|
618
|
+
* const llmForJsonSchema = new ChatOpenAI({
|
|
619
|
+
* model: "gpt-4o-2024-08-06",
|
|
620
|
+
* }).withStructuredOutput(
|
|
621
|
+
* z.object({
|
|
622
|
+
* command: z.string().describe("The command to execute"),
|
|
623
|
+
* expectedOutput: z.string().describe("The expected output of the command"),
|
|
624
|
+
* options: z
|
|
625
|
+
* .array(z.string())
|
|
626
|
+
* .describe("The options you can pass to the command"),
|
|
627
|
+
* }),
|
|
628
|
+
* {
|
|
629
|
+
* method: "jsonSchema",
|
|
630
|
+
* strict: true, // Optional when using the `jsonSchema` method
|
|
631
|
+
* }
|
|
632
|
+
* );
|
|
633
|
+
*
|
|
634
|
+
* const jsonSchemaRes = await llmForJsonSchema.invoke(
|
|
635
|
+
* "What is the command to list files in a directory?"
|
|
636
|
+
* );
|
|
637
|
+
* console.log(jsonSchemaRes);
|
|
638
|
+
* ```
|
|
639
|
+
*
|
|
640
|
+
* ```txt
|
|
641
|
+
* {
|
|
642
|
+
* command: 'ls',
|
|
643
|
+
* expectedOutput: 'A list of files and subdirectories within the specified directory.',
|
|
644
|
+
* options: [
|
|
645
|
+
* '-a: include directory entries whose names begin with a dot (.).',
|
|
646
|
+
* '-l: use a long listing format.',
|
|
647
|
+
* '-h: with -l, print sizes in human readable format (e.g., 1K, 234M, 2G).',
|
|
648
|
+
* '-t: sort by time, newest first.',
|
|
649
|
+
* '-r: reverse order while sorting.',
|
|
650
|
+
* '-S: sort by file size, largest first.',
|
|
651
|
+
* '-R: list subdirectories recursively.'
|
|
652
|
+
* ]
|
|
653
|
+
* }
|
|
654
|
+
* ```
|
|
655
|
+
* </details>
|
|
656
|
+
*
|
|
657
|
+
* <br />
|
|
231
658
|
*/
|
|
232
659
|
export class ChatOpenAI extends BaseChatModel {
|
|
233
660
|
static lc_name() {
|
|
@@ -567,6 +994,17 @@ export class ChatOpenAI extends BaseChatModel {
|
|
|
567
994
|
...kwargs,
|
|
568
995
|
});
|
|
569
996
|
}
|
|
997
|
+
createResponseFormat(resFormat) {
|
|
998
|
+
if (resFormat &&
|
|
999
|
+
resFormat.type === "json_schema" &&
|
|
1000
|
+
resFormat.json_schema.schema &&
|
|
1001
|
+
isZodSchema(resFormat.json_schema.schema)) {
|
|
1002
|
+
return zodResponseFormat(resFormat.json_schema.schema, resFormat.json_schema.name, {
|
|
1003
|
+
description: resFormat.json_schema.description,
|
|
1004
|
+
});
|
|
1005
|
+
}
|
|
1006
|
+
return resFormat;
|
|
1007
|
+
}
|
|
570
1008
|
/**
|
|
571
1009
|
* Get the parameters used to invoke the model
|
|
572
1010
|
*/
|
|
@@ -606,7 +1044,7 @@ export class ChatOpenAI extends BaseChatModel {
|
|
|
606
1044
|
? options.tools.map((tool) => _convertChatOpenAIToolTypeToOpenAITool(tool, { strict }))
|
|
607
1045
|
: undefined,
|
|
608
1046
|
tool_choice: formatToOpenAIToolChoice(options?.tool_choice),
|
|
609
|
-
response_format: options?.response_format,
|
|
1047
|
+
response_format: this.createResponseFormat(options?.response_format),
|
|
610
1048
|
seed: options?.seed,
|
|
611
1049
|
...streamOptionsConfig,
|
|
612
1050
|
parallel_tool_calls: options?.parallel_tool_calls,
|
|
@@ -632,6 +1070,20 @@ export class ChatOpenAI extends BaseChatModel {
|
|
|
632
1070
|
stream: true,
|
|
633
1071
|
};
|
|
634
1072
|
let defaultRole;
|
|
1073
|
+
if (params.response_format &&
|
|
1074
|
+
params.response_format.type === "json_schema") {
|
|
1075
|
+
console.warn(`OpenAI does not yet support streaming with "response_format" set to "json_schema". Falling back to non-streaming mode.`);
|
|
1076
|
+
const res = await this._generate(messages, options, runManager);
|
|
1077
|
+
const chunk = new ChatGenerationChunk({
|
|
1078
|
+
message: new AIMessageChunk({
|
|
1079
|
+
...res.generations[0].message,
|
|
1080
|
+
}),
|
|
1081
|
+
text: res.generations[0].text,
|
|
1082
|
+
generationInfo: res.generations[0].generationInfo,
|
|
1083
|
+
});
|
|
1084
|
+
yield chunk;
|
|
1085
|
+
return runManager?.handleLLMNewToken(res.generations[0].text ?? "", undefined, undefined, undefined, undefined, { chunk });
|
|
1086
|
+
}
|
|
635
1087
|
const streamIterable = await this.completionWithRetry(params, options);
|
|
636
1088
|
let usage;
|
|
637
1089
|
for await (const data of streamIterable) {
|
|
@@ -658,7 +1110,7 @@ export class ChatOpenAI extends BaseChatModel {
|
|
|
658
1110
|
}
|
|
659
1111
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
660
1112
|
const generationInfo = { ...newTokenIndices };
|
|
661
|
-
if (choice.finish_reason
|
|
1113
|
+
if (choice.finish_reason != null) {
|
|
662
1114
|
generationInfo.finish_reason = choice.finish_reason;
|
|
663
1115
|
// Only include system fingerprint in the last chunk for now
|
|
664
1116
|
// to avoid concatenation issues
|
|
@@ -735,14 +1187,28 @@ export class ChatOpenAI extends BaseChatModel {
|
|
|
735
1187
|
return { generations, llmOutput: { estimatedTokenUsage: tokenUsage } };
|
|
736
1188
|
}
|
|
737
1189
|
else {
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
1190
|
+
let data;
|
|
1191
|
+
if (options.response_format &&
|
|
1192
|
+
options.response_format.type === "json_schema") {
|
|
1193
|
+
data = await this.betaParsedCompletionWithRetry({
|
|
1194
|
+
...params,
|
|
1195
|
+
stream: false,
|
|
1196
|
+
messages: messagesMapped,
|
|
1197
|
+
}, {
|
|
1198
|
+
signal: options?.signal,
|
|
1199
|
+
...options?.options,
|
|
1200
|
+
});
|
|
1201
|
+
}
|
|
1202
|
+
else {
|
|
1203
|
+
data = await this.completionWithRetry({
|
|
1204
|
+
...params,
|
|
1205
|
+
stream: false,
|
|
1206
|
+
messages: messagesMapped,
|
|
1207
|
+
}, {
|
|
1208
|
+
signal: options?.signal,
|
|
1209
|
+
...options?.options,
|
|
1210
|
+
});
|
|
1211
|
+
}
|
|
746
1212
|
const { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens, } = data?.usage ?? {};
|
|
747
1213
|
if (completionTokens) {
|
|
748
1214
|
tokenUsage.completionTokens =
|
|
@@ -887,6 +1353,25 @@ export class ChatOpenAI extends BaseChatModel {
|
|
|
887
1353
|
}
|
|
888
1354
|
});
|
|
889
1355
|
}
|
|
1356
|
+
/**
|
|
1357
|
+
* Call the beta chat completions parse endpoint. This should only be called if
|
|
1358
|
+
* response_format is set to "json_object".
|
|
1359
|
+
* @param {OpenAIClient.Chat.ChatCompletionCreateParamsNonStreaming} request
|
|
1360
|
+
* @param {OpenAICoreRequestOptions | undefined} options
|
|
1361
|
+
*/
|
|
1362
|
+
async betaParsedCompletionWithRetry(request, options) {
|
|
1363
|
+
const requestOptions = this._getClientOptions(options);
|
|
1364
|
+
return this.caller.call(async () => {
|
|
1365
|
+
try {
|
|
1366
|
+
const res = await this.client.beta.chat.completions.parse(request, requestOptions);
|
|
1367
|
+
return res;
|
|
1368
|
+
}
|
|
1369
|
+
catch (e) {
|
|
1370
|
+
const error = wrapOpenAIClientError(e);
|
|
1371
|
+
throw error;
|
|
1372
|
+
}
|
|
1373
|
+
});
|
|
1374
|
+
}
|
|
890
1375
|
_getClientOptions(options) {
|
|
891
1376
|
if (!this.client) {
|
|
892
1377
|
const openAIEndpointConfig = {
|
|
@@ -979,6 +1464,25 @@ export class ChatOpenAI extends BaseChatModel {
|
|
|
979
1464
|
outputParser = new JsonOutputParser();
|
|
980
1465
|
}
|
|
981
1466
|
}
|
|
1467
|
+
else if (method === "jsonSchema") {
|
|
1468
|
+
llm = this.bind({
|
|
1469
|
+
response_format: {
|
|
1470
|
+
type: "json_schema",
|
|
1471
|
+
json_schema: {
|
|
1472
|
+
name: name ?? "extract",
|
|
1473
|
+
description: schema.description,
|
|
1474
|
+
schema,
|
|
1475
|
+
strict: config?.strict,
|
|
1476
|
+
},
|
|
1477
|
+
},
|
|
1478
|
+
});
|
|
1479
|
+
if (isZodSchema(schema)) {
|
|
1480
|
+
outputParser = StructuredOutputParser.fromZodSchema(schema);
|
|
1481
|
+
}
|
|
1482
|
+
else {
|
|
1483
|
+
outputParser = new JsonOutputParser();
|
|
1484
|
+
}
|
|
1485
|
+
}
|
|
982
1486
|
else {
|
|
983
1487
|
let functionName = name ?? "extract";
|
|
984
1488
|
// Is function calling
|
package/dist/types.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { OpenAI as OpenAIClient } from "openai";
|
|
2
|
+
import type { ResponseFormatText, ResponseFormatJSONObject, ResponseFormatJSONSchema } from "openai/resources/shared";
|
|
2
3
|
import { TiktokenModel } from "js-tiktoken/lite";
|
|
3
4
|
import type { BaseLanguageModelCallOptions } from "@langchain/core/language_models/base";
|
|
5
|
+
import type { z } from "zod";
|
|
4
6
|
export type { TiktokenModel };
|
|
5
7
|
export declare interface OpenAIBaseInput {
|
|
6
8
|
/** Sampling temperature to use */
|
|
@@ -179,3 +181,13 @@ export declare interface AzureOpenAIInput {
|
|
|
179
181
|
*/
|
|
180
182
|
azureADTokenProvider?: () => Promise<string>;
|
|
181
183
|
}
|
|
184
|
+
type ChatOpenAIResponseFormatJSONSchema = Omit<ResponseFormatJSONSchema, "json_schema"> & {
|
|
185
|
+
json_schema: Omit<ResponseFormatJSONSchema["json_schema"], "schema"> & {
|
|
186
|
+
/**
|
|
187
|
+
* The schema for the response format, described as a JSON Schema object
|
|
188
|
+
* or a Zod object.
|
|
189
|
+
*/
|
|
190
|
+
schema: Record<string, any> | z.ZodObject<any, any, any, any>;
|
|
191
|
+
};
|
|
192
|
+
};
|
|
193
|
+
export type ChatOpenAIResponseFormat = ResponseFormatText | ResponseFormatJSONObject | ChatOpenAIResponseFormatJSONSchema;
|