-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Copy pathchat_models.ts
1434 lines (1346 loc) Β· 40.6 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 { v4 as uuidv4 } from "uuid";
import { Mistral as MistralClient } from "@mistralai/mistralai";
import {
ChatCompletionRequest as MistralAIChatCompletionRequest,
ChatCompletionRequestToolChoice as MistralAIToolChoice,
Messages as MistralAIMessage,
} from "@mistralai/mistralai/models/components/chatcompletionrequest.js";
import { ContentChunk as MistralAIContentChunk } from "@mistralai/mistralai/models/components/contentchunk.js";
import { Tool as MistralAITool } from "@mistralai/mistralai/models/components/tool.js";
import { ToolCall as MistralAIToolCall } from "@mistralai/mistralai/models/components/toolcall.js";
import { ChatCompletionStreamRequest as MistralAIChatCompletionStreamRequest } from "@mistralai/mistralai/models/components/chatcompletionstreamrequest.js";
import { UsageInfo as MistralAITokenUsage } from "@mistralai/mistralai/models/components/usageinfo.js";
import { CompletionEvent as MistralAIChatCompletionEvent } from "@mistralai/mistralai/models/components/completionevent.js";
import { ChatCompletionResponse as MistralAIChatCompletionResponse } from "@mistralai/mistralai/models/components/chatcompletionresponse.js";
import {
type BeforeRequestHook,
type RequestErrorHook,
type ResponseHook,
HTTPClient as MistralAIHTTPClient,
} from "@mistralai/mistralai/lib/http.js";
import {
BaseMessage,
MessageType,
MessageContent,
MessageContentComplex,
AIMessage,
HumanMessage,
HumanMessageChunk,
AIMessageChunk,
ToolMessageChunk,
ChatMessageChunk,
FunctionMessageChunk,
isAIMessage,
} from "@langchain/core/messages";
import type {
BaseLanguageModelInput,
BaseLanguageModelCallOptions,
StructuredOutputMethodOptions,
FunctionDefinition,
} from "@langchain/core/language_models/base";
import { CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager";
import {
type BaseChatModelParams,
BaseChatModel,
BindToolsInput,
LangSmithParams,
} from "@langchain/core/language_models/chat_models";
import {
ChatGeneration,
ChatGenerationChunk,
ChatResult,
} from "@langchain/core/outputs";
import { AsyncCaller } from "@langchain/core/utils/async_caller";
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { NewTokenIndices } from "@langchain/core/callbacks/base";
import { z } from "zod";
import {
type BaseLLMOutputParser,
JsonOutputParser,
StructuredOutputParser,
} from "@langchain/core/output_parsers";
import {
JsonOutputKeyToolsParser,
convertLangChainToolCallToOpenAI,
makeInvalidToolCall,
parseToolCall,
} from "@langchain/core/output_parsers/openai_tools";
import {
Runnable,
RunnablePassthrough,
RunnableSequence,
} from "@langchain/core/runnables";
import { zodToJsonSchema } from "zod-to-json-schema";
import { ToolCallChunk } from "@langchain/core/messages/tool";
import {
_convertToolCallIdToMistralCompatible,
_mistralContentChunkToMessageContentComplex,
} from "./utils.js";
interface TokenUsage {
completionTokens?: number;
promptTokens?: number;
totalTokens?: number;
}
type ChatMistralAIToolType = MistralAIToolCall | MistralAITool | BindToolsInput;
export interface ChatMistralAICallOptions
extends Omit<BaseLanguageModelCallOptions, "stop"> {
response_format?: {
type: "text" | "json_object";
};
tools?: ChatMistralAIToolType[];
tool_choice?: MistralAIToolChoice;
/**
* Whether or not to include token usage in the stream.
* @default {true}
*/
streamUsage?: boolean;
}
/**
* Input to chat model class.
*/
export interface ChatMistralAIInput
extends BaseChatModelParams,
Pick<ChatMistralAICallOptions, "streamUsage"> {
/**
* The API key to use.
* @default {process.env.MISTRAL_API_KEY}
*/
apiKey?: string;
/**
* The name of the model to use.
* Alias for `model`
* @deprecated Use `model` instead.
* @default {"mistral-small-latest"}
*/
modelName?: string;
/**
* The name of the model to use.
* @default {"mistral-small-latest"}
*/
model?: string;
/**
* Override the default server URL used by the Mistral SDK.
* @deprecated use serverURL instead
*/
endpoint?: string;
/**
* Override the default server URL used by the Mistral SDK.
*/
serverURL?: string;
/**
* What sampling temperature to use, between 0.0 and 2.0.
* Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.
* @default {0.7}
*/
temperature?: number;
/**
* Nucleus sampling, where the model considers the results of the tokens with `top_p` probability mass.
* So 0.1 means only the tokens comprising the top 10% probability mass are considered.
* Should be between 0 and 1.
* @default {1}
*/
topP?: number;
/**
* The maximum number of tokens to generate in the completion.
* The token count of your prompt plus max_tokens cannot exceed the model's context length.
*/
maxTokens?: number;
/**
* Whether or not to stream the response.
* @default {false}
*/
streaming?: boolean;
/**
* Whether to inject a safety prompt before all conversations.
* @default {false}
* @deprecated use safePrompt instead
*/
safeMode?: boolean;
/**
* Whether to inject a safety prompt before all conversations.
* @default {false}
*/
safePrompt?: boolean;
/**
* The seed to use for random sampling. If set, different calls will generate deterministic results.
* Alias for `seed`
*/
randomSeed?: number;
/**
* The seed to use for random sampling. If set, different calls will generate deterministic results.
*/
seed?: number;
/**
* A list of custom hooks that must follow (req: Request) => Awaitable<Request | void>
* They are automatically added when a ChatMistralAI instance is created.
*/
beforeRequestHooks?: BeforeRequestHook[];
/**
* A list of custom hooks that must follow (err: unknown, req: Request) => Awaitable<void>.
* They are automatically added when a ChatMistralAI instance is created.
*/
requestErrorHooks?: RequestErrorHook[];
/**
* A list of custom hooks that must follow (res: Response, req: Request) => Awaitable<void>.
* They are automatically added when a ChatMistralAI instance is created.
*/
responseHooks?: ResponseHook[];
/**
* Custom HTTP client to manage API requests.
* Allows users to add custom fetch implementations, hooks, as well as error and response processing.
*/
httpClient?: MistralAIHTTPClient;
/**
* Determines how much the model penalizes the repetition of words or phrases. A higher presence
* penalty encourages the model to use a wider variety of words and phrases, making the output
* more diverse and creative.
*/
presencePenalty?: number;
/**
* Penalizes the repetition of words based on their frequency in the generated text. A higher
* frequency penalty discourages the model from repeating words that have already appeared frequently
* in the output, promoting diversity and reducing repetition.
*/
frequencyPenalty?: number;
/**
* Number of completions to return for each request, input tokens are only billed once.
*/
numCompletions?: number;
}
function convertMessagesToMistralMessages(
messages: Array<BaseMessage>
): Array<MistralAIMessage> {
const getRole = (role: MessageType) => {
switch (role) {
case "human":
return "user";
case "ai":
return "assistant";
case "system":
return "system";
case "tool":
return "tool";
case "function":
return "assistant";
default:
throw new Error(`Unknown message type: ${role}`);
}
};
const getContent = (
content: MessageContent,
type: MessageType
): string | MistralAIContentChunk[] => {
const _generateContentChunk = (
complex: MessageContentComplex,
role: string
): MistralAIContentChunk => {
if (
complex.type === "image_url" &&
(role === "user" || role === "assistant")
) {
return {
type: complex.type,
imageUrl: complex?.image_url,
};
}
if (complex.type === "text") {
return {
type: complex.type,
text: complex?.text,
};
}
throw new Error(
`ChatMistralAI only supports messages of "image_url" for roles "user" and "assistant", and "text" for all others.\n\nReceived: ${JSON.stringify(
content,
null,
2
)}`
);
};
if (typeof content === "string") {
return content;
}
if (Array.isArray(content)) {
const mistralRole = getRole(type);
// Mistral "assistant" and "user" roles can support Mistral ContentChunks
// Mistral "system" role can support Mistral TextChunks
const newContent: MistralAIContentChunk[] = [];
content.forEach((messageContentComplex) => {
// Mistral content chunks only support type "text" and "image_url"
if (
messageContentComplex.type === "text" ||
messageContentComplex.type === "image_url"
) {
newContent.push(
_generateContentChunk(messageContentComplex, mistralRole)
);
} else {
throw new Error(
`Mistral only supports types "text" or "image_url" for complex message types.`
);
}
});
return newContent;
}
throw new Error(
`Message content must be a string or an array.\n\nReceived: ${JSON.stringify(
content,
null,
2
)}`
);
};
const getTools = (message: BaseMessage): MistralAIToolCall[] | undefined => {
if (isAIMessage(message) && !!message.tool_calls?.length) {
return message.tool_calls
.map((toolCall) => ({
...toolCall,
id: _convertToolCallIdToMistralCompatible(toolCall.id ?? ""),
}))
.map(convertLangChainToolCallToOpenAI) as MistralAIToolCall[];
}
return undefined;
};
return messages.map((message) => {
const toolCalls = getTools(message);
const content = getContent(message.content, message.getType());
if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
return {
role: getRole(message.getType()),
content,
name: message.name,
toolCallId: _convertToolCallIdToMistralCompatible(message.tool_call_id),
};
// Mistral "assistant" role can only support either content or tool calls but not both
} else if (isAIMessage(message)) {
if (toolCalls === undefined) {
return {
role: getRole(message.getType()),
content,
};
} else {
return {
role: getRole(message.getType()),
toolCalls,
};
}
}
return {
role: getRole(message.getType()),
content,
};
}) as MistralAIMessage[];
}
function mistralAIResponseToChatMessage(
choice: NonNullable<MistralAIChatCompletionResponse["choices"]>[0],
usage?: MistralAITokenUsage
): BaseMessage {
const { message } = choice;
if (message === undefined) {
throw new Error("No message found in response");
}
// MistralAI SDK does not include toolCalls in the non
// streaming return type, so we need to extract it like this
// to satisfy typescript.
let rawToolCalls: MistralAIToolCall[] = [];
if ("toolCalls" in message && Array.isArray(message.toolCalls)) {
rawToolCalls = message.toolCalls;
}
const content = _mistralContentChunkToMessageContentComplex(message.content);
switch (message.role) {
case "assistant": {
const toolCalls = [];
const invalidToolCalls = [];
for (const rawToolCall of rawToolCalls) {
try {
const parsed = parseToolCall(rawToolCall, { returnId: true });
toolCalls.push({
...parsed,
id: parsed.id ?? uuidv4().replace(/-/g, ""),
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
invalidToolCalls.push(makeInvalidToolCall(rawToolCall, e.message));
}
}
return new AIMessage({
content,
tool_calls: toolCalls,
invalid_tool_calls: invalidToolCalls,
additional_kwargs: {},
usage_metadata: usage
? {
input_tokens: usage.promptTokens,
output_tokens: usage.completionTokens,
total_tokens: usage.totalTokens,
}
: undefined,
});
}
default:
return new HumanMessage({ content });
}
}
function _convertDeltaToMessageChunk(
delta: {
role?: string | null | undefined;
content?: string | MistralAIContentChunk[] | null | undefined;
toolCalls?: MistralAIToolCall[] | null | undefined;
},
usage?: MistralAITokenUsage | null
) {
if (!delta.content && !delta.toolCalls) {
if (usage) {
return new AIMessageChunk({
content: "",
usage_metadata: usage
? {
input_tokens: usage.promptTokens,
output_tokens: usage.completionTokens,
total_tokens: usage.totalTokens,
}
: undefined,
});
}
return null;
}
// Our merge additional kwargs util function will throw unless there
// is an index key in each tool object (as seen in OpenAI's) so we
// need to insert it here.
const rawToolCallChunksWithIndex = delta.toolCalls?.length
? delta.toolCalls?.map(
(toolCall, index): MistralAIToolCall & { index: number } => ({
...toolCall,
index,
id: toolCall.id ?? uuidv4().replace(/-/g, ""),
type: "function",
})
)
: undefined;
let role = "assistant";
if (delta.role) {
role = delta.role;
}
const content = _mistralContentChunkToMessageContentComplex(delta.content);
let additional_kwargs;
const toolCallChunks: ToolCallChunk[] = [];
if (rawToolCallChunksWithIndex !== undefined) {
for (const rawToolCallChunk of rawToolCallChunksWithIndex) {
const rawArgs = rawToolCallChunk.function?.arguments;
const args =
rawArgs === undefined || typeof rawArgs === "string"
? rawArgs
: JSON.stringify(rawArgs);
toolCallChunks.push({
name: rawToolCallChunk.function?.name,
args,
id: rawToolCallChunk.id,
index: rawToolCallChunk.index,
type: "tool_call_chunk",
});
}
} else {
additional_kwargs = {};
}
if (role === "user") {
return new HumanMessageChunk({ content });
} else if (role === "assistant") {
return new AIMessageChunk({
content,
tool_call_chunks: toolCallChunks,
additional_kwargs,
usage_metadata: usage
? {
input_tokens: usage.promptTokens,
output_tokens: usage.completionTokens,
total_tokens: usage.totalTokens,
}
: undefined,
});
} else if (role === "tool") {
return new ToolMessageChunk({
content,
additional_kwargs,
tool_call_id: rawToolCallChunksWithIndex?.[0].id ?? "",
});
} else if (role === "function") {
return new FunctionMessageChunk({
content,
additional_kwargs,
});
} else {
return new ChatMessageChunk({ content, role });
}
}
function _convertToolToMistralTool(
tools: ChatMistralAIToolType[]
): MistralAITool[] {
return tools.map((tool) => {
if ("function" in tool) {
return tool as MistralAITool;
}
const description = tool.description ?? `Tool: ${tool.name}`;
return {
type: "function",
function: {
name: tool.name,
description,
parameters: zodToJsonSchema(tool.schema),
},
};
});
}
/**
* Mistral AI chat model integration.
*
* Setup:
* Install `@langchain/mistralai` and set an environment variable named `MISTRAL_API_KEY`.
*
* ```bash
* npm install @langchain/mistralai
* export MISTRAL_API_KEY="your-api-key"
* ```
*
* ## [Constructor args](https://api.js.langchain.com/classes/_langchain_mistralai.ChatMistralAI.html#constructor)
*
* ## [Runtime args](https://api.js.langchain.com/interfaces/_langchain_mistralai.ChatMistralAICallOptions.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 { ChatMistralAI } from '@langchain/mistralai';
*
* const llm = new ChatMistralAI({
* model: "mistral-large-2402",
* temperature: 0,
* // 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 {
* "content": "The translation of \"I love programming\" into French is \"J'aime la programmation\". Here's the breakdown:\n\n- \"I\" translates to \"Je\"\n- \"love\" translates to \"aime\"\n- \"programming\" translates to \"la programmation\"\n\nSo, \"J'aime la programmation\" means \"I love programming\" in French.",
* "additional_kwargs": {},
* "response_metadata": {
* "tokenUsage": {
* "completionTokens": 89,
* "promptTokens": 13,
* "totalTokens": 102
* },
* "finish_reason": "stop"
* },
* "tool_calls": [],
* "invalid_tool_calls": [],
* "usage_metadata": {
* "input_tokens": 13,
* "output_tokens": 89,
* "total_tokens": 102
* }
* }
* ```
* </details>
*
* <br />
*
* <details>
* <summary><strong>Streaming Chunks</strong></summary>
*
* ```typescript
* for await (const chunk of await llm.stream(input)) {
* console.log(chunk);
* }
* ```
*
* ```txt
* AIMessageChunk {
* "content": "The",
* "additional_kwargs": {},
* "response_metadata": {
* "prompt": 0,
* "completion": 0
* },
* "tool_calls": [],
* "tool_call_chunks": [],
* "invalid_tool_calls": []
* }
* AIMessageChunk {
* "content": " translation",
* "additional_kwargs": {},
* "response_metadata": {
* "prompt": 0,
* "completion": 0
* },
* "tool_calls": [],
* "tool_call_chunks": [],
* "invalid_tool_calls": []
* }
* AIMessageChunk {
* "content": " of",
* "additional_kwargs": {},
* "response_metadata": {
* "prompt": 0,
* "completion": 0
* },
* "tool_calls": [],
* "tool_call_chunks": [],
* "invalid_tool_calls": []
* }
* AIMessageChunk {
* "content": " \"",
* "additional_kwargs": {},
* "response_metadata": {
* "prompt": 0,
* "completion": 0
* },
* "tool_calls": [],
* "tool_call_chunks": [],
* "invalid_tool_calls": []
* }
* AIMessageChunk {
* "content": "I",
* "additional_kwargs": {},
* "response_metadata": {
* "prompt": 0,
* "completion": 0
* },
* "tool_calls": [],
* "tool_call_chunks": [],
* "invalid_tool_calls": []
* }
* AIMessageChunk {
* "content": ".",
* "additional_kwargs": {},
* "response_metadata": {
* "prompt": 0,
* "completion": 0
* },
* "tool_calls": [],
* "tool_call_chunks": [],
* "invalid_tool_calls": []
*}
*AIMessageChunk {
* "content": "",
* "additional_kwargs": {},
* "response_metadata": {
* "prompt": 0,
* "completion": 0
* },
* "tool_calls": [],
* "tool_call_chunks": [],
* "invalid_tool_calls": [],
* "usage_metadata": {
* "input_tokens": 13,
* "output_tokens": 89,
* "total_tokens": 102
* }
*}
* ```
* </details>
*
* <br />
*
* <details>
* <summary><strong>Aggregate Streamed Chunks</strong></summary>
*
* ```typescript
* import { AIMessageChunk } from '@langchain/core/messages';
* import { concat } from '@langchain/core/utils/stream';
*
* const stream = await llm.stream(input);
* let full: AIMessageChunk | undefined;
* for await (const chunk of stream) {
* full = !full ? chunk : concat(full, chunk);
* }
* console.log(full);
* ```
*
* ```txt
* AIMessageChunk {
* "content": "The translation of \"I love programming\" into French is \"J'aime la programmation\". Here's the breakdown:\n\n- \"I\" translates to \"Je\"\n- \"love\" translates to \"aime\"\n- \"programming\" translates to \"la programmation\"\n\nSo, \"J'aime la programmation\" means \"I love programming\" in French.",
* "additional_kwargs": {},
* "response_metadata": {
* "prompt": 0,
* "completion": 0
* },
* "tool_calls": [],
* "tool_call_chunks": [],
* "invalid_tool_calls": [],
* "usage_metadata": {
* "input_tokens": 13,
* "output_tokens": 89,
* "total_tokens": 102
* }
* }
* ```
* </details>
*
* <br />
*
* <details>
* <summary><strong>Bind tools</strong></summary>
*
* ```typescript
* import { z } from 'zod';
*
* const GetWeather = {
* name: "GetWeather",
* description: "Get the current weather in a given location",
* schema: z.object({
* location: z.string().describe("The city and state, e.g. San Francisco, CA")
* }),
* }
*
* const GetPopulation = {
* name: "GetPopulation",
* description: "Get the current population in a given location",
* schema: z.object({
* location: z.string().describe("The city and state, e.g. San Francisco, CA")
* }),
* }
*
* const llmWithTools = llm.bindTools([GetWeather, GetPopulation]);
* const aiMsg = await llmWithTools.invoke(
* "Which city is hotter today and which is bigger: LA or NY?"
* );
* console.log(aiMsg.tool_calls);
* ```
*
* ```txt
* [
* {
* name: 'GetWeather',
* args: { location: 'Los Angeles, CA' },
* type: 'tool_call',
* id: '47i216yko'
* },
* {
* name: 'GetWeather',
* args: { location: 'New York, NY' },
* type: 'tool_call',
* id: 'nb3v8Fpcn'
* },
* {
* name: 'GetPopulation',
* args: { location: 'Los Angeles, CA' },
* type: 'tool_call',
* id: 'EedWzByIB'
* },
* {
* name: 'GetPopulation',
* args: { location: 'New York, NY' },
* type: 'tool_call',
* id: 'jLdLia7zC'
* }
* ]
* ```
* </details>
*
* <br />
*
* <details>
* <summary><strong>Structured Output</strong></summary>
*
* ```typescript
* import { z } from 'zod';
*
* const Joke = z.object({
* setup: z.string().describe("The setup of the joke"),
* punchline: z.string().describe("The punchline to the joke"),
* rating: z.number().optional().describe("How funny the joke is, from 1 to 10")
* }).describe('Joke to tell user.');
*
* const structuredLlm = llm.withStructuredOutput(Joke, { name: "Joke" });
* const jokeResult = await structuredLlm.invoke("Tell me a joke about cats");
* console.log(jokeResult);
* ```
*
* ```txt
* {
* setup: "Why don't cats play poker in the jungle?",
* punchline: 'Too many cheetahs!',
* rating: 7
* }
* ```
* </details>
*
* <br />
*
* <details>
* <summary><strong>Usage Metadata</strong></summary>
*
* ```typescript
* const aiMsgForMetadata = await llm.invoke(input);
* console.log(aiMsgForMetadata.usage_metadata);
* ```
*
* ```txt
* { input_tokens: 13, output_tokens: 89, total_tokens: 102 }
* ```
* </details>
*
* <br />
*/
export class ChatMistralAI<
CallOptions extends ChatMistralAICallOptions = ChatMistralAICallOptions
>
extends BaseChatModel<CallOptions, AIMessageChunk>
implements ChatMistralAIInput
{
// Used for tracing, replace with the same name as your class
static lc_name() {
return "ChatMistralAI";
}
lc_namespace = ["langchain", "chat_models", "mistralai"];
model = "mistral-small-latest";
apiKey: string;
/**
* @deprecated use serverURL instead
*/
endpoint: string;
serverURL?: string;
temperature = 0.7;
streaming = false;
topP = 1;
maxTokens: number;
/**
* @deprecated use safePrompt instead
*/
safeMode = false;
safePrompt = false;
randomSeed?: number;
seed?: number;
maxRetries?: number;
lc_serializable = true;
streamUsage = true;
beforeRequestHooks?: Array<BeforeRequestHook>;
requestErrorHooks?: Array<RequestErrorHook>;
responseHooks?: Array<ResponseHook>;
httpClient?: MistralAIHTTPClient;
presencePenalty?: number;
frequencyPenalty?: number;
numCompletions?: number;
constructor(fields?: ChatMistralAIInput) {
super(fields ?? {});
const apiKey = fields?.apiKey ?? getEnvironmentVariable("MISTRAL_API_KEY");
if (!apiKey) {
throw new Error(
"API key MISTRAL_API_KEY is missing for MistralAI, but it is required."
);
}
this.apiKey = apiKey;
this.streaming = fields?.streaming ?? this.streaming;
this.serverURL = fields?.serverURL ?? this.serverURL;
this.temperature = fields?.temperature ?? this.temperature;
this.topP = fields?.topP ?? this.topP;
this.maxTokens = fields?.maxTokens ?? this.maxTokens;
this.safePrompt = fields?.safePrompt ?? this.safePrompt;
this.randomSeed = fields?.seed ?? fields?.randomSeed ?? this.seed;
this.seed = this.randomSeed;
this.maxRetries = fields?.maxRetries;
this.httpClient = fields?.httpClient;
this.model = fields?.model ?? fields?.modelName ?? this.model;
this.streamUsage = fields?.streamUsage ?? this.streamUsage;
this.beforeRequestHooks =
fields?.beforeRequestHooks ?? this.beforeRequestHooks;
this.requestErrorHooks =
fields?.requestErrorHooks ?? this.requestErrorHooks;
this.responseHooks = fields?.responseHooks ?? this.responseHooks;
this.presencePenalty = fields?.presencePenalty ?? this.presencePenalty;
this.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty;
this.numCompletions = fields?.numCompletions ?? this.numCompletions;
this.addAllHooksToHttpClient();
}
get lc_secrets(): { [key: string]: string } | undefined {
return {
apiKey: "MISTRAL_API_KEY",
};
}
get lc_aliases(): { [key: string]: string } | undefined {
return {
apiKey: "mistral_api_key",
};
}
getLsParams(options: this["ParsedCallOptions"]): LangSmithParams {
const params = this.invocationParams(options);
return {
ls_provider: "mistral",
ls_model_name: this.model,
ls_model_type: "chat",
ls_temperature: params.temperature ?? undefined,
ls_max_tokens: params.maxTokens ?? undefined,
};
}
_llmType() {
return "mistral_ai";
}
/**
* Get the parameters used to invoke the model
*/
invocationParams(
options?: this["ParsedCallOptions"]
): Omit<
MistralAIChatCompletionRequest | MistralAIChatCompletionStreamRequest,
"messages"
> {
const { response_format, tools, tool_choice } = options ?? {};
const mistralAITools: Array<MistralAITool> | undefined = tools?.length
? _convertToolToMistralTool(tools)
: undefined;
const params: Omit<MistralAIChatCompletionRequest, "messages"> = {
model: this.model,
tools: mistralAITools,
temperature: this.temperature,
maxTokens: this.maxTokens,
topP: this.topP,
randomSeed: this.seed,
safePrompt: this.safePrompt,
toolChoice: tool_choice,
responseFormat: response_format,
presencePenalty: this.presencePenalty,
frequencyPenalty: this.frequencyPenalty,
n: this.numCompletions,
};
return params;
}
override bindTools(
tools: ChatMistralAIToolType[],
kwargs?: Partial<CallOptions>
): Runnable<BaseLanguageModelInput, AIMessageChunk, CallOptions> {
return this.bind({
tools: _convertToolToMistralTool(tools),
...kwargs,