@langchain/xai 0.0.1

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.
@@ -0,0 +1,387 @@
1
+ import { BaseChatModelCallOptions, BindToolsInput, LangSmithParams, type BaseChatModelParams } from "@langchain/core/language_models/chat_models";
2
+ import { Serialized } from "@langchain/core/load/serializable";
3
+ import { type OpenAICoreRequestOptions, type OpenAIClient, ChatOpenAI, OpenAIToolChoice } from "@langchain/openai";
4
+ type ChatXAIToolType = BindToolsInput | OpenAIClient.ChatCompletionTool;
5
+ export interface ChatXAICallOptions extends BaseChatModelCallOptions {
6
+ headers?: Record<string, string>;
7
+ tools?: ChatXAIToolType[];
8
+ tool_choice?: OpenAIToolChoice | string | "auto" | "any";
9
+ }
10
+ export interface ChatXAIInput extends BaseChatModelParams {
11
+ /**
12
+ * The xAI API key to use for requests.
13
+ * @default process.env.XAI_API_KEY
14
+ */
15
+ apiKey?: string;
16
+ /**
17
+ * The name of the model to use.
18
+ * @default "grok-beta"
19
+ */
20
+ model?: string;
21
+ /**
22
+ * Up to 4 sequences where the API will stop generating further tokens. The
23
+ * returned text will not contain the stop sequence.
24
+ * Alias for `stopSequences`
25
+ */
26
+ stop?: Array<string>;
27
+ /**
28
+ * Up to 4 sequences where the API will stop generating further tokens. The
29
+ * returned text will not contain the stop sequence.
30
+ */
31
+ stopSequences?: Array<string>;
32
+ /**
33
+ * Whether or not to stream responses.
34
+ */
35
+ streaming?: boolean;
36
+ /**
37
+ * The temperature to use for sampling.
38
+ * @default 0.7
39
+ */
40
+ temperature?: number;
41
+ /**
42
+ * The maximum number of tokens that the model can process in a single response.
43
+ * This limits ensures computational efficiency and resource management.
44
+ */
45
+ maxTokens?: number;
46
+ }
47
+ /**
48
+ * xAI chat model integration.
49
+ *
50
+ * The xAI API is compatible to the OpenAI API with some limitations.
51
+ *
52
+ * Setup:
53
+ * Install `@langchain/xai` and set an environment variable named `XAI_API_KEY`.
54
+ *
55
+ * ```bash
56
+ * npm install @langchain/xai
57
+ * export XAI_API_KEY="your-api-key"
58
+ * ```
59
+ *
60
+ * ## [Constructor args](https://api.js.langchain.com/classes/langchain_xai.ChatXAI.html#constructor)
61
+ *
62
+ * ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_xai.ChatXAICallOptions.html)
63
+ *
64
+ * Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.
65
+ * They can also be passed via `.bind`, or the second arg in `.bindTools`, like shown in the examples below:
66
+ *
67
+ * ```typescript
68
+ * // When calling `.bind`, call options should be passed via the first argument
69
+ * const llmWithArgsBound = llm.bind({
70
+ * stop: ["\n"],
71
+ * tools: [...],
72
+ * });
73
+ *
74
+ * // When calling `.bindTools`, call options should be passed via the second argument
75
+ * const llmWithTools = llm.bindTools(
76
+ * [...],
77
+ * {
78
+ * tool_choice: "auto",
79
+ * }
80
+ * );
81
+ * ```
82
+ *
83
+ * ## Examples
84
+ *
85
+ * <details open>
86
+ * <summary><strong>Instantiate</strong></summary>
87
+ *
88
+ * ```typescript
89
+ * import { ChatXAI } from '@langchain/xai';
90
+ *
91
+ * const llm = new ChatXAI({
92
+ * model: "grok-beta",
93
+ * temperature: 0,
94
+ * // other params...
95
+ * });
96
+ * ```
97
+ * </details>
98
+ *
99
+ * <br />
100
+ *
101
+ * <details>
102
+ * <summary><strong>Invoking</strong></summary>
103
+ *
104
+ * ```typescript
105
+ * const input = `Translate "I love programming" into French.`;
106
+ *
107
+ * // Models also accept a list of chat messages or a formatted prompt
108
+ * const result = await llm.invoke(input);
109
+ * console.log(result);
110
+ * ```
111
+ *
112
+ * ```txt
113
+ * AIMessage {
114
+ * "content": "The French translation of \"I love programming\" is \"J'aime programmer\". In this sentence, \"J'aime\" is the first person singular conjugation of the French verb \"aimer\" which means \"to love\", and \"programmer\" is the French infinitive for \"to program\". I hope this helps! Let me know if you have any other questions.",
115
+ * "additional_kwargs": {},
116
+ * "response_metadata": {
117
+ * "tokenUsage": {
118
+ * "completionTokens": 82,
119
+ * "promptTokens": 20,
120
+ * "totalTokens": 102
121
+ * },
122
+ * "finish_reason": "stop"
123
+ * },
124
+ * "tool_calls": [],
125
+ * "invalid_tool_calls": []
126
+ * }
127
+ * ```
128
+ * </details>
129
+ *
130
+ * <br />
131
+ *
132
+ * <details>
133
+ * <summary><strong>Streaming Chunks</strong></summary>
134
+ *
135
+ * ```typescript
136
+ * for await (const chunk of await llm.stream(input)) {
137
+ * console.log(chunk);
138
+ * }
139
+ * ```
140
+ *
141
+ * ```txt
142
+ * AIMessageChunk {
143
+ * "content": "",
144
+ * "additional_kwargs": {},
145
+ * "response_metadata": {
146
+ * "finishReason": null
147
+ * },
148
+ * "tool_calls": [],
149
+ * "tool_call_chunks": [],
150
+ * "invalid_tool_calls": []
151
+ * }
152
+ * AIMessageChunk {
153
+ * "content": "The",
154
+ * "additional_kwargs": {},
155
+ * "response_metadata": {
156
+ * "finishReason": null
157
+ * },
158
+ * "tool_calls": [],
159
+ * "tool_call_chunks": [],
160
+ * "invalid_tool_calls": []
161
+ * }
162
+ * AIMessageChunk {
163
+ * "content": " French",
164
+ * "additional_kwargs": {},
165
+ * "response_metadata": {
166
+ * "finishReason": null
167
+ * },
168
+ * "tool_calls": [],
169
+ * "tool_call_chunks": [],
170
+ * "invalid_tool_calls": []
171
+ * }
172
+ * AIMessageChunk {
173
+ * "content": " translation",
174
+ * "additional_kwargs": {},
175
+ * "response_metadata": {
176
+ * "finishReason": null
177
+ * },
178
+ * "tool_calls": [],
179
+ * "tool_call_chunks": [],
180
+ * "invalid_tool_calls": []
181
+ * }
182
+ * AIMessageChunk {
183
+ * "content": " of",
184
+ * "additional_kwargs": {},
185
+ * "response_metadata": {
186
+ * "finishReason": null
187
+ * },
188
+ * "tool_calls": [],
189
+ * "tool_call_chunks": [],
190
+ * "invalid_tool_calls": []
191
+ * }
192
+ * AIMessageChunk {
193
+ * "content": " \"",
194
+ * "additional_kwargs": {},
195
+ * "response_metadata": {
196
+ * "finishReason": null
197
+ * },
198
+ * "tool_calls": [],
199
+ * "tool_call_chunks": [],
200
+ * "invalid_tool_calls": []
201
+ * }
202
+ * AIMessageChunk {
203
+ * "content": "I",
204
+ * "additional_kwargs": {},
205
+ * "response_metadata": {
206
+ * "finishReason": null
207
+ * },
208
+ * "tool_calls": [],
209
+ * "tool_call_chunks": [],
210
+ * "invalid_tool_calls": []
211
+ * }
212
+ * AIMessageChunk {
213
+ * "content": " love",
214
+ * "additional_kwargs": {},
215
+ * "response_metadata": {
216
+ * "finishReason": null
217
+ * },
218
+ * "tool_calls": [],
219
+ * "tool_call_chunks": [],
220
+ * "invalid_tool_calls": []
221
+ * }
222
+ * ...
223
+ * AIMessageChunk {
224
+ * "content": ".",
225
+ * "additional_kwargs": {},
226
+ * "response_metadata": {
227
+ * "finishReason": null
228
+ * },
229
+ * "tool_calls": [],
230
+ * "tool_call_chunks": [],
231
+ * "invalid_tool_calls": []
232
+ * }
233
+ * AIMessageChunk {
234
+ * "content": "",
235
+ * "additional_kwargs": {},
236
+ * "response_metadata": {
237
+ * "finishReason": "stop"
238
+ * },
239
+ * "tool_calls": [],
240
+ * "tool_call_chunks": [],
241
+ * "invalid_tool_calls": []
242
+ * }
243
+ * ```
244
+ * </details>
245
+ *
246
+ * <br />
247
+ *
248
+ * <details>
249
+ * <summary><strong>Aggregate Streamed Chunks</strong></summary>
250
+ *
251
+ * ```typescript
252
+ * import { AIMessageChunk } from '@langchain/core/messages';
253
+ * import { concat } from '@langchain/core/utils/stream';
254
+ *
255
+ * const stream = await llm.stream(input);
256
+ * let full: AIMessageChunk | undefined;
257
+ * for await (const chunk of stream) {
258
+ * full = !full ? chunk : concat(full, chunk);
259
+ * }
260
+ * console.log(full);
261
+ * ```
262
+ *
263
+ * ```txt
264
+ * AIMessageChunk {
265
+ * "content": "The French translation of \"I love programming\" is \"J'aime programmer\". In this sentence, \"J'aime\" is the first person singular conjugation of the French verb \"aimer\" which means \"to love\", and \"programmer\" is the French infinitive for \"to program\". I hope this helps! Let me know if you have any other questions.",
266
+ * "additional_kwargs": {},
267
+ * "response_metadata": {
268
+ * "finishReason": "stop"
269
+ * },
270
+ * "tool_calls": [],
271
+ * "tool_call_chunks": [],
272
+ * "invalid_tool_calls": []
273
+ * }
274
+ * ```
275
+ * </details>
276
+ *
277
+ * <br />
278
+ *
279
+ * <details>
280
+ * <summary><strong>Bind tools</strong></summary>
281
+ *
282
+ * ```typescript
283
+ * import { z } from 'zod';
284
+ *
285
+ * const llmForToolCalling = new ChatXAI({
286
+ * model: "grok-beta",
287
+ * temperature: 0,
288
+ * // other params...
289
+ * });
290
+ *
291
+ * const GetWeather = {
292
+ * name: "GetWeather",
293
+ * description: "Get the current weather in a given location",
294
+ * schema: z.object({
295
+ * location: z.string().describe("The city and state, e.g. San Francisco, CA")
296
+ * }),
297
+ * }
298
+ *
299
+ * const GetPopulation = {
300
+ * name: "GetPopulation",
301
+ * description: "Get the current population in a given location",
302
+ * schema: z.object({
303
+ * location: z.string().describe("The city and state, e.g. San Francisco, CA")
304
+ * }),
305
+ * }
306
+ *
307
+ * const llmWithTools = llmForToolCalling.bindTools([GetWeather, GetPopulation]);
308
+ * const aiMsg = await llmWithTools.invoke(
309
+ * "Which city is hotter today and which is bigger: LA or NY?"
310
+ * );
311
+ * console.log(aiMsg.tool_calls);
312
+ * ```
313
+ *
314
+ * ```txt
315
+ * [
316
+ * {
317
+ * name: 'GetWeather',
318
+ * args: { location: 'Los Angeles, CA' },
319
+ * type: 'tool_call',
320
+ * id: 'call_cd34'
321
+ * },
322
+ * {
323
+ * name: 'GetWeather',
324
+ * args: { location: 'New York, NY' },
325
+ * type: 'tool_call',
326
+ * id: 'call_68rf'
327
+ * },
328
+ * {
329
+ * name: 'GetPopulation',
330
+ * args: { location: 'Los Angeles, CA' },
331
+ * type: 'tool_call',
332
+ * id: 'call_f81z'
333
+ * },
334
+ * {
335
+ * name: 'GetPopulation',
336
+ * args: { location: 'New York, NY' },
337
+ * type: 'tool_call',
338
+ * id: 'call_8byt'
339
+ * }
340
+ * ]
341
+ * ```
342
+ * </details>
343
+ *
344
+ * <br />
345
+ *
346
+ * <details>
347
+ * <summary><strong>Structured Output</strong></summary>
348
+ *
349
+ * ```typescript
350
+ * import { z } from 'zod';
351
+ *
352
+ * const Joke = z.object({
353
+ * setup: z.string().describe("The setup of the joke"),
354
+ * punchline: z.string().describe("The punchline to the joke"),
355
+ * rating: z.number().optional().describe("How funny the joke is, from 1 to 10")
356
+ * }).describe('Joke to tell user.');
357
+ *
358
+ * const structuredLlm = llmForToolCalling.withStructuredOutput(Joke, { name: "Joke" });
359
+ * const jokeResult = await structuredLlm.invoke("Tell me a joke about cats");
360
+ * console.log(jokeResult);
361
+ * ```
362
+ *
363
+ * ```txt
364
+ * {
365
+ * setup: "Why don't cats play poker in the wild?",
366
+ * punchline: 'Because there are too many cheetahs.'
367
+ * }
368
+ * ```
369
+ * </details>
370
+ *
371
+ * <br />
372
+ */
373
+ export declare class ChatXAI extends ChatOpenAI<ChatXAICallOptions> {
374
+ static lc_name(): string;
375
+ _llmType(): string;
376
+ get lc_secrets(): {
377
+ [key: string]: string;
378
+ } | undefined;
379
+ lc_serializable: boolean;
380
+ lc_namespace: string[];
381
+ constructor(fields?: Partial<ChatXAIInput>);
382
+ toJSON(): Serialized;
383
+ getLsParams(options: this["ParsedCallOptions"]): LangSmithParams;
384
+ completionWithRetry(request: OpenAIClient.Chat.ChatCompletionCreateParamsStreaming, options?: OpenAICoreRequestOptions): Promise<AsyncIterable<OpenAIClient.Chat.Completions.ChatCompletionChunk>>;
385
+ completionWithRetry(request: OpenAIClient.Chat.ChatCompletionCreateParamsNonStreaming, options?: OpenAICoreRequestOptions): Promise<OpenAIClient.Chat.Completions.ChatCompletion>;
386
+ }
387
+ export {};