-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy pathchat_models.ts
2872 lines (2657 loc) Β· 84.8 KB
/
chat_models.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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { type ClientOptions, OpenAI as OpenAIClient } from "openai";
import { CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager";
import {
AIMessage,
AIMessageChunk,
type BaseMessage,
ChatMessage,
ChatMessageChunk,
FunctionMessageChunk,
HumanMessageChunk,
SystemMessageChunk,
ToolMessage,
ToolMessageChunk,
OpenAIToolCall,
isAIMessage,
type UsageMetadata,
type BaseMessageFields,
type MessageContent,
type InvalidToolCall,
type MessageContentImageUrl,
} from "@langchain/core/messages";
import {
ChatGenerationChunk,
type ChatGeneration,
type ChatResult,
} from "@langchain/core/outputs";
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import {
BaseChatModel,
type BindToolsInput,
type LangSmithParams,
type BaseChatModelParams,
} from "@langchain/core/language_models/chat_models";
import {
isOpenAITool,
type BaseFunctionCallOptions,
type BaseLanguageModelInput,
type FunctionDefinition,
type StructuredOutputMethodOptions,
type StructuredOutputMethodParams,
} from "@langchain/core/language_models/base";
import { NewTokenIndices } from "@langchain/core/callbacks/base";
import { z } from "zod";
import {
Runnable,
RunnableLambda,
RunnablePassthrough,
RunnableSequence,
} from "@langchain/core/runnables";
import {
JsonOutputParser,
StructuredOutputParser,
} from "@langchain/core/output_parsers";
import {
JsonOutputKeyToolsParser,
convertLangChainToolCallToOpenAI,
makeInvalidToolCall,
parseToolCall,
} from "@langchain/core/output_parsers/openai_tools";
import { zodToJsonSchema } from "zod-to-json-schema";
import type { ToolCall, ToolCallChunk } from "@langchain/core/messages/tool";
import { zodResponseFormat } from "openai/helpers/zod";
import type {
ResponseFormatText,
ResponseFormatJSONObject,
ResponseFormatJSONSchema,
} from "openai/resources/shared";
import type {
OpenAICallOptions,
OpenAIChatInput,
OpenAICoreRequestOptions,
ChatOpenAIResponseFormat,
} from "./types.js";
import { type OpenAIEndpointConfig, getEndpoint } from "./utils/azure.js";
import {
OpenAIToolChoice,
formatToOpenAIToolChoice,
wrapOpenAIClientError,
} from "./utils/openai.js";
import {
FunctionDef,
formatFunctionDefinitions,
} from "./utils/openai-format-fndef.js";
import { _convertToOpenAITool } from "./utils/tools.js";
export type { OpenAICallOptions, OpenAIChatInput };
interface TokenUsage {
completionTokens?: number;
promptTokens?: number;
totalTokens?: number;
}
interface OpenAILLMOutput {
tokenUsage: TokenUsage;
}
// TODO import from SDK when available
type OpenAIRoleEnum =
| "system"
| "developer"
| "assistant"
| "user"
| "function"
| "tool";
type OpenAICompletionParam =
OpenAIClient.Chat.Completions.ChatCompletionMessageParam;
type OpenAIFnDef = OpenAIClient.Chat.ChatCompletionCreateParams.Function;
type OpenAIFnCallOption = OpenAIClient.Chat.ChatCompletionFunctionCallOption;
function extractGenericMessageCustomRole(message: ChatMessage) {
if (
message.role !== "system" &&
message.role !== "developer" &&
message.role !== "assistant" &&
message.role !== "user" &&
message.role !== "function" &&
message.role !== "tool"
) {
console.warn(`Unknown message role: ${message.role}`);
}
return message.role as OpenAIRoleEnum;
}
export function messageToOpenAIRole(message: BaseMessage): OpenAIRoleEnum {
const type = message._getType();
switch (type) {
case "system":
return "system";
case "ai":
return "assistant";
case "human":
return "user";
case "function":
return "function";
case "tool":
return "tool";
case "generic": {
if (!ChatMessage.isInstance(message))
throw new Error("Invalid generic chat message");
return extractGenericMessageCustomRole(message);
}
default:
throw new Error(`Unknown message type: ${type}`);
}
}
// Used in LangSmith, export is important here
export function _convertMessagesToOpenAIParams(
messages: BaseMessage[],
model?: string
): OpenAICompletionParam[] {
// TODO: Function messages do not support array content, fix cast
return messages.flatMap((message) => {
let role = messageToOpenAIRole(message);
if (role === "system" && isReasoningModel(model)) {
role = "developer";
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const completionParam: Record<string, any> = {
role,
content: message.content,
};
if (message.name != null) {
completionParam.name = message.name;
}
if (message.additional_kwargs.function_call != null) {
completionParam.function_call = message.additional_kwargs.function_call;
completionParam.content = "";
}
if (isAIMessage(message) && !!message.tool_calls?.length) {
completionParam.tool_calls = message.tool_calls.map(
convertLangChainToolCallToOpenAI
);
completionParam.content = "";
} else {
if (message.additional_kwargs.tool_calls != null) {
completionParam.tool_calls = message.additional_kwargs.tool_calls;
}
if ((message as ToolMessage).tool_call_id != null) {
completionParam.tool_call_id = (message as ToolMessage).tool_call_id;
}
}
if (
message.additional_kwargs.audio &&
typeof message.additional_kwargs.audio === "object" &&
"id" in message.additional_kwargs.audio
) {
const audioMessage = {
role: "assistant",
audio: {
id: message.additional_kwargs.audio.id,
},
};
return [completionParam, audioMessage] as OpenAICompletionParam[];
}
return completionParam as OpenAICompletionParam;
});
}
const _FUNCTION_CALL_IDS_MAP_KEY = "__openai_function_call_ids__";
function _convertMessagesToOpenAIResponsesParams(
messages: BaseMessage[],
model?: string
): ResponsesInputItem[] {
return messages.flatMap(
(lcMsg): ResponsesInputItem | ResponsesInputItem[] => {
let role = messageToOpenAIRole(lcMsg);
if (role === "system" && isReasoningModel(model)) role = "developer";
if (role === "function") {
throw new Error("Function messages are not supported in Responses API");
}
if (role === "tool") {
const toolMessage = lcMsg as ToolMessage;
// Handle computer call output
if (toolMessage.additional_kwargs?.type === "computer_call_output") {
const output = (() => {
if (typeof toolMessage.content === "string") {
return {
type: "computer_screenshot" as const,
image_url: toolMessage.content,
};
}
if (Array.isArray(toolMessage.content)) {
const oaiScreenshot = toolMessage.content.find(
(i) => i.type === "computer_screenshot"
) as { type: "computer_screenshot"; image_url: string };
if (oaiScreenshot) return oaiScreenshot;
const lcImage = toolMessage.content.find(
(i) => i.type === "image_url"
) as MessageContentImageUrl;
if (lcImage) {
return {
type: "computer_screenshot" as const,
image_url:
typeof lcImage.image_url === "string"
? lcImage.image_url
: lcImage.image_url.url,
};
}
}
throw new Error("Invalid computer call output");
})();
return {
type: "computer_call_output",
output,
call_id: toolMessage.tool_call_id,
};
}
return {
type: "function_call_output",
call_id: toolMessage.tool_call_id,
id: toolMessage.id,
output:
typeof toolMessage.content !== "string"
? JSON.stringify(toolMessage.content)
: toolMessage.content,
};
}
if (role === "assistant") {
const input: ResponsesInputItem[] = [];
// reasoning items
if (lcMsg.additional_kwargs.reasoning != null) {
type FindType<T, TType extends string> = T extends { type: TType }
? T
: never;
type ReasoningItem = FindType<ResponsesInputItem, "reasoning">;
const isReasoningItem = (item: unknown): item is ReasoningItem =>
typeof item === "object" &&
item != null &&
"type" in item &&
item.type === "reasoning";
if (isReasoningItem(lcMsg.additional_kwargs.reasoning)) {
input.push(lcMsg.additional_kwargs.reasoning);
}
}
// ai content
let { content } = lcMsg;
if (lcMsg.additional_kwargs.refusal != null) {
if (typeof content === "string") {
content = [{ type: "output_text", text: content, annotations: [] }];
}
content = [
...content,
{ type: "refusal", refusal: lcMsg.additional_kwargs.refusal },
];
}
input.push({
type: "message",
role: "assistant",
content:
typeof content === "string"
? content
: content.flatMap((item) => {
if (item.type === "text") {
return {
type: "output_text",
text: item.text,
// @ts-expect-error TODO: add types for `annotations`
annotations: item.annotations ?? [],
};
}
if (item.type === "output_text" || item.type === "refusal") {
return item;
}
return [];
}),
});
// function tool calls and computer use tool calls
const functionCallIds =
// eslint-disable-next-line @typescript-eslint/no-use-before-define
lcMsg.additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] as
| Record<string, string>
| undefined;
if (isAIMessage(lcMsg) && !!lcMsg.tool_calls?.length) {
input.push(
...lcMsg.tool_calls.map(
(toolCall): ResponsesInputItem => ({
type: "function_call",
name: toolCall.name,
arguments: JSON.stringify(toolCall.args),
call_id: toolCall.id!,
// @ts-expect-error Might come from a non-Responses API message
id: functionCallIds?.[toolCall.id!],
})
)
);
} else if (lcMsg.additional_kwargs.tool_calls != null) {
input.push(
...lcMsg.additional_kwargs.tool_calls.map(
(toolCall): ResponsesInputItem => ({
type: "function_call",
name: toolCall.function.name,
call_id: toolCall.id,
// @ts-expect-error Might come from a non-Responses API message
id: functionCallIds?.[toolCall.id],
arguments: toolCall.function.arguments,
})
)
);
}
const toolOutputs = (
lcMsg.response_metadata.output as Array<ResponsesInputItem>
)?.length
? lcMsg.response_metadata.output
: lcMsg.additional_kwargs.tool_outputs;
if (toolOutputs != null) {
const castToolOutputs = toolOutputs as Array<ResponsesInputItem>;
const reasoningCalls = castToolOutputs?.filter(
(item) => item.type === "reasoning"
);
const computerCalls = castToolOutputs?.filter(
(item) => item.type === "computer_call"
);
// NOTE: Reasoning outputs must be passed to the model BEFORE computer calls.
if (reasoningCalls.length > 0 && computerCalls.length > 0) {
input.push(...reasoningCalls);
}
if (computerCalls.length > 0) input.push(...computerCalls);
}
return input;
}
const content =
typeof lcMsg.content === "string"
? lcMsg.content
: lcMsg.content.flatMap((item) => {
if (item.type === "text") {
return { type: "input_text", text: item.text };
}
if (item.type === "image_url") {
const image_url =
typeof item.image_url === "string"
? item.image_url
: item.image_url.url;
const detail =
typeof item.image_url === "string"
? "auto"
: item.image_url.detail;
return { type: "input_image", image_url, detail };
}
if (
item.type === "input_text" ||
item.type === "input_image" ||
item.type === "input_file"
) {
return item;
}
return [];
});
if (role === "user" || role === "system" || role === "developer") {
return { type: "message", role, content };
}
console.warn(
`Unsupported role found when converting to OpenAI Responses API: ${role}`
);
return [];
}
);
}
function _convertOpenAIResponsesMessageToBaseMessage(
response: ResponsesCreateInvoke | ResponsesParseInvoke
): BaseMessage {
if (response.error) {
// TODO: add support for `addLangChainErrorFields`
const error = new Error(response.error.message);
error.name = response.error.code;
throw error;
}
const content: MessageContent = [];
const tool_calls: ToolCall[] = [];
const invalid_tool_calls: InvalidToolCall[] = [];
const response_metadata: Record<string, unknown> = {
model: response.model,
created_at: response.created_at,
id: response.id,
incomplete_details: response.incomplete_details,
metadata: response.metadata,
object: response.object,
status: response.status,
user: response.user,
// for compatibility with chat completion calls.
model_name: response.model,
};
const additional_kwargs: {
[key: string]: unknown;
refusal?: string;
reasoning?: unknown;
tool_outputs?: unknown[];
parsed?: unknown;
[_FUNCTION_CALL_IDS_MAP_KEY]?: Record<string, string>;
} = {};
for (const item of response.output) {
if (item.type === "message") {
content.push(
...item.content.flatMap((part) => {
if (part.type === "output_text") {
if ("parsed" in part && part.parsed != null) {
additional_kwargs.parsed = part.parsed;
}
return {
type: "text",
text: part.text,
annotations: part.annotations,
};
}
if (part.type === "refusal") {
additional_kwargs.refusal = part.refusal;
return [];
}
return part;
})
);
} else if (item.type === "function_call") {
const fnAdapter = {
function: { name: item.name, arguments: item.arguments },
id: item.call_id,
};
try {
tool_calls.push(parseToolCall(fnAdapter, { returnId: true }));
} catch (e: unknown) {
let errMessage: string | undefined;
if (
typeof e === "object" &&
e != null &&
"message" in e &&
typeof e.message === "string"
) {
errMessage = e.message;
}
invalid_tool_calls.push(makeInvalidToolCall(fnAdapter, errMessage));
}
additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] ??= {};
additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY][item.call_id] = item.id;
} else if (item.type === "reasoning") {
additional_kwargs.reasoning = item;
} else {
additional_kwargs.tool_outputs ??= [];
additional_kwargs.tool_outputs.push(item);
}
}
return new AIMessage({
id: response.id,
content,
tool_calls,
invalid_tool_calls,
usage_metadata: response.usage,
additional_kwargs,
response_metadata,
});
}
function _convertOpenAIResponsesDeltaToBaseMessageChunk(
chunk: ResponseReturnStreamEvents
) {
const content: Record<string, unknown>[] = [];
let generationInfo: Record<string, unknown> = {};
let usage_metadata: UsageMetadata | undefined;
const tool_call_chunks: ToolCallChunk[] = [];
const response_metadata: Record<string, unknown> = {};
const additional_kwargs: Record<string, unknown> = {};
let id: string | undefined;
if (chunk.type === "response.output_text.delta") {
content.push({
type: "text",
text: chunk.delta,
index: chunk.content_index,
});
} else if (chunk.type === "response.output_text.annotation.added") {
content.push({
type: "text",
text: "",
annotations: [chunk.annotation],
index: chunk.content_index,
});
} else if (
chunk.type === "response.output_item.added" &&
chunk.item.type === "message"
) {
id = chunk.item.id;
} else if (
chunk.type === "response.output_item.added" &&
chunk.item.type === "function_call"
) {
tool_call_chunks.push({
type: "tool_call_chunk",
name: chunk.item.name,
args: chunk.item.arguments,
id: chunk.item.id,
index: chunk.output_index,
});
additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] = {
[chunk.item.call_id]: chunk.item.id,
};
} else if (
chunk.type === "response.output_item.done" &&
(chunk.item.type === "web_search_call" ||
chunk.item.type === "file_search_call" ||
chunk.item.type === "computer_call")
) {
additional_kwargs.tool_outputs = [chunk.item];
} else if (chunk.type === "response.created") {
response_metadata.id = chunk.response.id;
response_metadata.model_name = chunk.response.model;
response_metadata.model = chunk.response.model;
} else if (chunk.type === "response.completed") {
const msg = _convertOpenAIResponsesMessageToBaseMessage(chunk.response);
usage_metadata = chunk.response.usage;
if (chunk.response.text?.format?.type === "json_schema") {
additional_kwargs.parsed ??= JSON.parse(msg.text);
}
for (const [key, value] of Object.entries(chunk.response)) {
if (key !== "id") response_metadata[key] = value;
}
} else if (chunk.type === "response.function_call_arguments.delta") {
tool_call_chunks.push({
type: "tool_call_chunk",
args: chunk.delta,
index: chunk.output_index,
});
} else if (
chunk.type === "response.web_search_call.completed" ||
chunk.type === "response.file_search_call.completed"
) {
generationInfo = {
tool_outputs: {
id: chunk.item_id,
type: chunk.type.replace("response.", "").replace(".completed", ""),
status: "completed",
},
};
} else if (chunk.type === "response.refusal.done") {
additional_kwargs.refusal = chunk.refusal;
} else {
return null;
}
return new ChatGenerationChunk({
// Legacy reasons, `onLLMNewToken` should pulls this out
text: content.map((part) => part.text).join(""),
message: new AIMessageChunk({
id,
content,
tool_call_chunks,
usage_metadata,
additional_kwargs,
response_metadata,
}),
generationInfo,
});
}
// Utility types to get hidden OpenAI response types
type ExtractAsyncIterableType<T> = T extends AsyncIterable<infer U> ? U : never;
type ExcludeController<T> = T extends { controller: unknown } ? never : T;
type ExcludeNonController<T> = T extends { controller: unknown } ? T : never;
type ResponsesCreate = OpenAIClient.Responses["create"];
type ResponsesParse = OpenAIClient.Responses["parse"];
type ResponsesCreateParams = Parameters<OpenAIClient.Responses["create"]>[0];
type ResponsesTool = Exclude<ResponsesCreateParams["tools"], undefined>[number];
type ResponsesToolChoice = Exclude<
ResponsesCreateParams["tool_choice"],
undefined
>;
type ResponsesInputItem = Exclude<
ResponsesCreateParams["input"],
string | undefined
>[number];
type ResponsesCreateInvoke = ExcludeController<
Awaited<ReturnType<ResponsesCreate>>
>;
type ResponsesParseInvoke = ExcludeController<
Awaited<ReturnType<ResponsesParse>>
>;
type ResponsesCreateStream = ExcludeNonController<
Awaited<ReturnType<ResponsesCreate>>
>;
type ResponseInvocationParams = Omit<ResponsesCreateParams, "input">;
type ResponseReturnStreamEvents =
ExtractAsyncIterableType<ResponsesCreateStream>;
type ChatCompletionInvocationParams = Omit<
OpenAIClient.Chat.ChatCompletionCreateParams,
"messages"
>;
type ChatOpenAIToolType =
| BindToolsInput
| OpenAIClient.ChatCompletionTool
| ResponsesTool;
function isBuiltInTool(tool: ChatOpenAIToolType): tool is ResponsesTool {
return "type" in tool && tool.type !== "function";
}
function isBuiltInToolChoice(
tool_choice: OpenAIToolChoice | ResponsesToolChoice | undefined
): tool_choice is ResponsesToolChoice {
return (
tool_choice != null &&
typeof tool_choice === "object" &&
"type" in tool_choice &&
tool_choice.type !== "function"
);
}
function _convertChatOpenAIToolTypeToOpenAITool(
tool: ChatOpenAIToolType,
fields?: {
strict?: boolean;
}
): OpenAIClient.ChatCompletionTool {
if (isOpenAITool(tool)) {
if (fields?.strict !== undefined) {
return {
...tool,
function: {
...tool.function,
strict: fields.strict,
},
};
}
return tool;
}
return _convertToOpenAITool(tool, fields);
}
function isReasoningModel(model?: string) {
return model?.startsWith("o1") || model?.startsWith("o3");
}
// TODO: Use the base structured output options param in next breaking release.
export interface ChatOpenAIStructuredOutputMethodOptions<
IncludeRaw extends boolean
> extends StructuredOutputMethodOptions<IncludeRaw> {
/**
* strict: If `true` and `method` = "function_calling", model output is
* guaranteed to exactly match the schema. If `true`, the input schema
* will also be validated according to
* https://platform.openai.com/docs/guides/structured-outputs/supported-schemas.
* If `false`, input schema will not be validated and model output will not
* be validated.
* If `undefined`, `strict` argument will not be passed to the model.
*
* @version 0.2.6
* @note Planned breaking change in version `0.3.0`:
* `strict` will default to `true` when `method` is
* "function_calling" as of version `0.3.0`.
*/
strict?: boolean;
}
export interface ChatOpenAICallOptions
extends OpenAICallOptions,
BaseFunctionCallOptions {
tools?: ChatOpenAIToolType[];
tool_choice?: OpenAIToolChoice | ResponsesToolChoice;
promptIndex?: number;
response_format?: ChatOpenAIResponseFormat;
seed?: number;
/**
* Additional options to pass to streamed completions.
* If provided takes precedence over "streamUsage" set at initialization time.
*/
stream_options?: {
/**
* Whether or not to include token usage in the stream.
* If set to `true`, this will include an additional
* chunk at the end of the stream with the token usage.
*/
include_usage: boolean;
};
/**
* Whether or not to restrict the ability to
* call multiple tools in one response.
*/
parallel_tool_calls?: boolean;
/**
* If `true`, model output is guaranteed to exactly match the JSON Schema
* provided in the tool definition. If `true`, the input schema will also be
* validated according to
* https://platform.openai.com/docs/guides/structured-outputs/supported-schemas.
*
* If `false`, input schema will not be validated and model output will not
* be validated.
*
* If `undefined`, `strict` argument will not be passed to the model.
*
* @version 0.2.6
*/
strict?: boolean;
/**
* Output types that you would like the model to generate for this request. Most
* models are capable of generating text, which is the default:
*
* `["text"]`
*
* The `gpt-4o-audio-preview` model can also be used to
* [generate audio](https://platform.openai.com/docs/guides/audio). To request that
* this model generate both text and audio responses, you can use:
*
* `["text", "audio"]`
*/
modalities?: Array<OpenAIClient.Chat.ChatCompletionModality>;
/**
* Parameters for audio output. Required when audio output is requested with
* `modalities: ["audio"]`.
* [Learn more](https://platform.openai.com/docs/guides/audio).
*/
audio?: OpenAIClient.Chat.ChatCompletionAudioParam;
/**
* Static predicted output content, such as the content of a text file that is being regenerated.
* [Learn more](https://platform.openai.com/docs/guides/latency-optimization#use-predicted-outputs).
*/
prediction?: OpenAIClient.ChatCompletionPredictionContent;
/**
* Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high.
* Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response.
*/
reasoning_effort?: OpenAIClient.Chat.ChatCompletionReasoningEffort;
/**
* Configuration options for a text response from the model. Can be plain text or
* structured JSON data.
*/
text?: ResponsesCreateParams["text"];
/**
* The truncation strategy to use for the model response.
*/
truncation?: ResponsesCreateParams["truncation"];
/**
* Specify additional output data to include in the model response.
*/
include?: ResponsesCreateParams["include"];
/**
* The unique ID of the previous response to the model. Use this to create
* multi-turn conversations.
*/
previous_response_id?: ResponsesCreateParams["previous_response_id"];
}
export interface ChatOpenAIFields
extends Partial<OpenAIChatInput>,
BaseChatModelParams {
configuration?: ClientOptions;
useResponsesApi?: boolean;
}
/**
* OpenAI chat model integration.
*
* To use with Azure, import the `AzureChatOpenAI` class.
*
* Setup:
* Install `@langchain/openai` and set an environment variable named `OPENAI_API_KEY`.
*
* ```bash
* npm install @langchain/openai
* export OPENAI_API_KEY="your-api-key"
* ```
*
* ## [Constructor args](https://api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html#constructor)
*
* ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_openai.ChatOpenAICallOptions.html)
*
* Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.
* They can also be passed via `.bind`, or the second arg in `.bindTools`, like shown in the examples below:
*
* ```typescript
* // When calling `.bind`, call options should be passed via the first argument
* const llmWithArgsBound = llm.bind({
* stop: ["\n"],
* tools: [...],
* });
*
* // When calling `.bindTools`, call options should be passed via the second argument
* const llmWithTools = llm.bindTools(
* [...],
* {
* tool_choice: "auto",
* }
* );
* ```
*
* ## Examples
*
* <details open>
* <summary><strong>Instantiate</strong></summary>
*
* ```typescript
* import { ChatOpenAI } from '@langchain/openai';
*
* const llm = new ChatOpenAI({
* model: "gpt-4o",
* temperature: 0,
* maxTokens: undefined,
* timeout: undefined,
* maxRetries: 2,
* // apiKey: "...",
* // baseUrl: "...",
* // organization: "...",
* // other params...
* });
* ```
* </details>
*
* <br />
*
* <details>
* <summary><strong>Invoking</strong></summary>
*
* ```typescript
* const input = `Translate "I love programming" into French.`;
*
* // Models also accept a list of chat messages or a formatted prompt
* const result = await llm.invoke(input);
* console.log(result);
* ```
*
* ```txt
* AIMessage {
* "id": "chatcmpl-9u4Mpu44CbPjwYFkTbeoZgvzB00Tz",
* "content": "J'adore la programmation.",
* "response_metadata": {
* "tokenUsage": {
* "completionTokens": 5,
* "promptTokens": 28,
* "totalTokens": 33
* },
* "finish_reason": "stop",
* "system_fingerprint": "fp_3aa7262c27"
* },
* "usage_metadata": {
* "input_tokens": 28,
* "output_tokens": 5,
* "total_tokens": 33
* }
* }
* ```
* </details>
*
* <br />
*
* <details>
* <summary><strong>Streaming Chunks</strong></summary>
*
* ```typescript
* for await (const chunk of await llm.stream(input)) {
* console.log(chunk);
* }
* ```
*
* ```txt
* AIMessageChunk {
* "id": "chatcmpl-9u4NWB7yUeHCKdLr6jP3HpaOYHTqs",
* "content": ""
* }
* AIMessageChunk {
* "content": "J"
* }
* AIMessageChunk {
* "content": "'adore"
* }
* AIMessageChunk {
* "content": " la"
* }
* AIMessageChunk {
* "content": " programmation",,
* }
* AIMessageChunk {
* "content": ".",,
* }
* AIMessageChunk {
* "content": "",
* "response_metadata": {
* "finish_reason": "stop",
* "system_fingerprint": "fp_c9aa9c0491"
* },
* }
* AIMessageChunk {
* "content": "",
* "usage_metadata": {
* "input_tokens": 28,
* "output_tokens": 5,
* "total_tokens": 33
* }
* }
* ```
* </details>
*
* <br />
*
* <details>
* <summary><strong>Aggregate Streamed Chunks</strong></summary>
*