-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathchat_models.ts
3295 lines (3039 loc) Β· 97.4 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 type {
ChatCompletionContentPartText,
ChatCompletionContentPartImage,
ChatCompletionContentPartInputAudio,
ChatCompletionContentPart,
} from "openai/resources/chat/completions";
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,
StandardContentBlockConverter,
parseBase64DataUrl,
parseMimeType,
convertToProviderContentBlock,
isDataContentBlock,
} 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,
type OpenAIChatInput,
type OpenAICoreRequestOptions,
type ChatOpenAIResponseFormat,
ChatOpenAIReasoningSummary,
} 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}`);
}
}
const completionsApiContentBlockConverter: StandardContentBlockConverter<{
text: ChatCompletionContentPartText;
image: ChatCompletionContentPartImage;
audio: ChatCompletionContentPartInputAudio;
file: ChatCompletionContentPart.File;
}> = {
providerName: "ChatOpenAI",
fromStandardTextBlock(block): ChatCompletionContentPartText {
return { type: "text", text: block.text };
},
fromStandardImageBlock(block): ChatCompletionContentPartImage {
if (block.source_type === "url") {
return {
type: "image_url",
image_url: {
url: block.url,
...(block.metadata?.detail
? { detail: block.metadata.detail as "auto" | "low" | "high" }
: {}),
},
};
}
if (block.source_type === "base64") {
const url = `data:${block.mime_type ?? ""};base64,${block.data}`;
return {
type: "image_url",
image_url: {
url,
...(block.metadata?.detail
? { detail: block.metadata.detail as "auto" | "low" | "high" }
: {}),
},
};
}
throw new Error(
`Image content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`
);
},
fromStandardAudioBlock(block): ChatCompletionContentPartInputAudio {
if (block.source_type === "url") {
const data = parseBase64DataUrl({ dataUrl: block.url });
if (!data) {
throw new Error(
`URL audio blocks with source_type ${block.source_type} must be formatted as a data URL for ChatOpenAI`
);
}
const rawMimeType = data.mime_type || block.mime_type || "";
let mimeType: { type: string; subtype: string };
try {
mimeType = parseMimeType(rawMimeType);
} catch {
throw new Error(
`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`
);
}
if (
mimeType.type !== "audio" ||
(mimeType.subtype !== "wav" && mimeType.subtype !== "mp3")
) {
throw new Error(
`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`
);
}
return {
type: "input_audio",
input_audio: {
format: mimeType.subtype,
data: data.data,
},
};
}
if (block.source_type === "base64") {
let mimeType: { type: string; subtype: string };
try {
mimeType = parseMimeType(block.mime_type ?? "");
} catch {
throw new Error(
`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`
);
}
if (
mimeType.type !== "audio" ||
(mimeType.subtype !== "wav" && mimeType.subtype !== "mp3")
) {
throw new Error(
`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`
);
}
return {
type: "input_audio",
input_audio: {
format: mimeType.subtype,
data: block.data,
},
};
}
throw new Error(
`Audio content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`
);
},
fromStandardFileBlock(block): ChatCompletionContentPart.File {
if (block.source_type === "url") {
const data = parseBase64DataUrl({ dataUrl: block.url });
if (!data) {
throw new Error(
`URL file blocks with source_type ${block.source_type} must be formatted as a data URL for ChatOpenAI`
);
}
return {
type: "file",
file: {
file_data: block.url, // formatted as base64 data URL
...(block.metadata?.filename || block.metadata?.name
? {
filename: (block.metadata?.filename ||
block.metadata?.name) as string,
}
: {}),
},
};
}
if (block.source_type === "base64") {
return {
type: "file",
file: {
file_data: `data:${block.mime_type ?? ""};base64,${block.data}`,
...(block.metadata?.filename ||
block.metadata?.name ||
block.metadata?.title
? {
filename: (block.metadata?.filename ||
block.metadata?.name ||
block.metadata?.title) as string,
}
: {}),
},
};
}
if (block.source_type === "id") {
return {
type: "file",
file: {
file_id: block.id,
},
};
}
throw new Error(
`File content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`
);
},
};
// 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";
}
const content =
typeof message.content === "string"
? message.content
: message.content.map((m) => {
if (isDataContentBlock(m)) {
return convertToProviderContentBlock(
m,
completionsApiContentBlockConverter
);
}
return m;
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const completionParam: Record<string, any> = {
role,
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 _convertReasoningSummaryToOpenAIResponsesParams(
reasoning: ChatOpenAIReasoningSummary
): OpenAIClient.Responses.ResponseReasoningItem {
// combine summary parts that have the the same index and then remove the indexes
const summary = (
reasoning.summary.length > 1
? reasoning.summary.reduce(
(acc, curr) => {
const last = acc.at(-1);
if (last!.index === curr.index) {
last!.text += curr.text;
} else {
acc.push(curr);
}
return acc;
},
[{ ...reasoning.summary[0] }]
)
: reasoning.summary
).map((s) =>
Object.fromEntries(Object.entries(s).filter(([k]) => k !== "index"))
) as OpenAIClient.Responses.ResponseReasoningItem.Summary[];
return {
...reasoning,
summary,
} as OpenAIClient.Responses.ResponseReasoningItem;
}
function _convertMessagesToOpenAIResponsesParams(
messages: BaseMessage[],
model?: string,
zdrEnabled?: boolean
): ResponsesInputItem[] {
const lastAIMessage = messages.filter((m) => isAIMessage(m)).pop();
const lastAIMessageId = lastAIMessage?.response_metadata?.id;
const newMessages =
lastAIMessageId && lastAIMessageId.startsWith("resp_") && !zdrEnabled
? messages.slice(messages.indexOf(lastAIMessage) + 1)
: messages;
return newMessages.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") {
// if we have the original response items, just reuse them
if (
!zdrEnabled &&
lcMsg.response_metadata.output != null &&
Array.isArray(lcMsg.response_metadata.output) &&
lcMsg.response_metadata.output.length > 0 &&
lcMsg.response_metadata.output.every((item) => "type" in item)
) {
return lcMsg.response_metadata.output;
}
// otherwise, try to reconstruct the response from what we have
const input: ResponsesInputItem[] = [];
// reasoning items
if (!zdrEnabled && 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)) {
const reasoningItem =
_convertReasoningSummaryToOpenAIResponsesParams(
lcMsg.additional_kwargs.reasoning
);
input.push(reasoningItem);
}
}
// 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",
...(lcMsg.id && !zdrEnabled ? { id: lcMsg.id } : {}),
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!,
...(zdrEnabled ? { 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,
...(zdrEnabled ? { 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;
let computerCalls: Array<ResponsesInputItem> = [];
if (toolOutputs != null) {
const castToolOutputs = toolOutputs as Array<ResponsesInputItem>;
computerCalls = castToolOutputs?.filter(
(item) => item.type === "computer_call"
);
if (computerCalls.length > 0) input.push(...computerCalls);
}
return input;
}
const content =
typeof lcMsg.content === "string"
? lcMsg.content
: lcMsg.content.flatMap((item) => {
if (isDataContentBlock(item)) {
return convertToProviderContentBlock(
item,
completionsApiContentBlockConverter
);
}
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?: OpenAIClient.Responses.ResponseReasoningItem;
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] ??= {};
if (item.id) {
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: {
[key: string]: unknown;
reasoning?: Partial<ChatOpenAIReasoningSummary>;
} = {};
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 if (
chunk.type === "response.output_item.added" &&
"item" in chunk &&
chunk.item.type === "reasoning"
) {
const summary: ChatOpenAIReasoningSummary["summary"] | undefined = chunk
.item.summary
? chunk.item.summary.map((s, index) => ({
...s,
index,
}))
: undefined;
additional_kwargs.reasoning = {
// We only capture ID in the first chunk or else the concatenated result of all chunks will
// have an ID field that is repeated once per chunk. There is special handling for the `type`
// field that prevents this, however.
id: chunk.item.id,
type: chunk.item.type,
...(summary ? { summary } : {}),
};
} else if (chunk.type === "response.reasoning_summary_part.added") {
additional_kwargs.reasoning = {
type: "reasoning",
summary: [{ ...chunk.part, index: chunk.summary_index }],
};
} else if (chunk.type === "response.reasoning_summary_text.delta") {
additional_kwargs.reasoning = {
type: "reasoning",
summary: [
{ text: chunk.delta, type: "summary_text", index: chunk.summary_index },
],
};
} 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 = OpenAIClient.Responses.ResponseInputItem;
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: {