@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,411 @@
1
+ import { getEnvironmentVariable } from "@langchain/core/utils/env";
2
+ import { ChatOpenAI, } from "@langchain/openai";
3
+ /**
4
+ * xAI chat model integration.
5
+ *
6
+ * The xAI API is compatible to the OpenAI API with some limitations.
7
+ *
8
+ * Setup:
9
+ * Install `@langchain/xai` and set an environment variable named `XAI_API_KEY`.
10
+ *
11
+ * ```bash
12
+ * npm install @langchain/xai
13
+ * export XAI_API_KEY="your-api-key"
14
+ * ```
15
+ *
16
+ * ## [Constructor args](https://api.js.langchain.com/classes/langchain_xai.ChatXAI.html#constructor)
17
+ *
18
+ * ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_xai.ChatXAICallOptions.html)
19
+ *
20
+ * Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.
21
+ * They can also be passed via `.bind`, or the second arg in `.bindTools`, like shown in the examples below:
22
+ *
23
+ * ```typescript
24
+ * // When calling `.bind`, call options should be passed via the first argument
25
+ * const llmWithArgsBound = llm.bind({
26
+ * stop: ["\n"],
27
+ * tools: [...],
28
+ * });
29
+ *
30
+ * // When calling `.bindTools`, call options should be passed via the second argument
31
+ * const llmWithTools = llm.bindTools(
32
+ * [...],
33
+ * {
34
+ * tool_choice: "auto",
35
+ * }
36
+ * );
37
+ * ```
38
+ *
39
+ * ## Examples
40
+ *
41
+ * <details open>
42
+ * <summary><strong>Instantiate</strong></summary>
43
+ *
44
+ * ```typescript
45
+ * import { ChatXAI } from '@langchain/xai';
46
+ *
47
+ * const llm = new ChatXAI({
48
+ * model: "grok-beta",
49
+ * temperature: 0,
50
+ * // other params...
51
+ * });
52
+ * ```
53
+ * </details>
54
+ *
55
+ * <br />
56
+ *
57
+ * <details>
58
+ * <summary><strong>Invoking</strong></summary>
59
+ *
60
+ * ```typescript
61
+ * const input = `Translate "I love programming" into French.`;
62
+ *
63
+ * // Models also accept a list of chat messages or a formatted prompt
64
+ * const result = await llm.invoke(input);
65
+ * console.log(result);
66
+ * ```
67
+ *
68
+ * ```txt
69
+ * AIMessage {
70
+ * "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.",
71
+ * "additional_kwargs": {},
72
+ * "response_metadata": {
73
+ * "tokenUsage": {
74
+ * "completionTokens": 82,
75
+ * "promptTokens": 20,
76
+ * "totalTokens": 102
77
+ * },
78
+ * "finish_reason": "stop"
79
+ * },
80
+ * "tool_calls": [],
81
+ * "invalid_tool_calls": []
82
+ * }
83
+ * ```
84
+ * </details>
85
+ *
86
+ * <br />
87
+ *
88
+ * <details>
89
+ * <summary><strong>Streaming Chunks</strong></summary>
90
+ *
91
+ * ```typescript
92
+ * for await (const chunk of await llm.stream(input)) {
93
+ * console.log(chunk);
94
+ * }
95
+ * ```
96
+ *
97
+ * ```txt
98
+ * AIMessageChunk {
99
+ * "content": "",
100
+ * "additional_kwargs": {},
101
+ * "response_metadata": {
102
+ * "finishReason": null
103
+ * },
104
+ * "tool_calls": [],
105
+ * "tool_call_chunks": [],
106
+ * "invalid_tool_calls": []
107
+ * }
108
+ * AIMessageChunk {
109
+ * "content": "The",
110
+ * "additional_kwargs": {},
111
+ * "response_metadata": {
112
+ * "finishReason": null
113
+ * },
114
+ * "tool_calls": [],
115
+ * "tool_call_chunks": [],
116
+ * "invalid_tool_calls": []
117
+ * }
118
+ * AIMessageChunk {
119
+ * "content": " French",
120
+ * "additional_kwargs": {},
121
+ * "response_metadata": {
122
+ * "finishReason": null
123
+ * },
124
+ * "tool_calls": [],
125
+ * "tool_call_chunks": [],
126
+ * "invalid_tool_calls": []
127
+ * }
128
+ * AIMessageChunk {
129
+ * "content": " translation",
130
+ * "additional_kwargs": {},
131
+ * "response_metadata": {
132
+ * "finishReason": null
133
+ * },
134
+ * "tool_calls": [],
135
+ * "tool_call_chunks": [],
136
+ * "invalid_tool_calls": []
137
+ * }
138
+ * AIMessageChunk {
139
+ * "content": " of",
140
+ * "additional_kwargs": {},
141
+ * "response_metadata": {
142
+ * "finishReason": null
143
+ * },
144
+ * "tool_calls": [],
145
+ * "tool_call_chunks": [],
146
+ * "invalid_tool_calls": []
147
+ * }
148
+ * AIMessageChunk {
149
+ * "content": " \"",
150
+ * "additional_kwargs": {},
151
+ * "response_metadata": {
152
+ * "finishReason": null
153
+ * },
154
+ * "tool_calls": [],
155
+ * "tool_call_chunks": [],
156
+ * "invalid_tool_calls": []
157
+ * }
158
+ * AIMessageChunk {
159
+ * "content": "I",
160
+ * "additional_kwargs": {},
161
+ * "response_metadata": {
162
+ * "finishReason": null
163
+ * },
164
+ * "tool_calls": [],
165
+ * "tool_call_chunks": [],
166
+ * "invalid_tool_calls": []
167
+ * }
168
+ * AIMessageChunk {
169
+ * "content": " love",
170
+ * "additional_kwargs": {},
171
+ * "response_metadata": {
172
+ * "finishReason": null
173
+ * },
174
+ * "tool_calls": [],
175
+ * "tool_call_chunks": [],
176
+ * "invalid_tool_calls": []
177
+ * }
178
+ * ...
179
+ * AIMessageChunk {
180
+ * "content": ".",
181
+ * "additional_kwargs": {},
182
+ * "response_metadata": {
183
+ * "finishReason": null
184
+ * },
185
+ * "tool_calls": [],
186
+ * "tool_call_chunks": [],
187
+ * "invalid_tool_calls": []
188
+ * }
189
+ * AIMessageChunk {
190
+ * "content": "",
191
+ * "additional_kwargs": {},
192
+ * "response_metadata": {
193
+ * "finishReason": "stop"
194
+ * },
195
+ * "tool_calls": [],
196
+ * "tool_call_chunks": [],
197
+ * "invalid_tool_calls": []
198
+ * }
199
+ * ```
200
+ * </details>
201
+ *
202
+ * <br />
203
+ *
204
+ * <details>
205
+ * <summary><strong>Aggregate Streamed Chunks</strong></summary>
206
+ *
207
+ * ```typescript
208
+ * import { AIMessageChunk } from '@langchain/core/messages';
209
+ * import { concat } from '@langchain/core/utils/stream';
210
+ *
211
+ * const stream = await llm.stream(input);
212
+ * let full: AIMessageChunk | undefined;
213
+ * for await (const chunk of stream) {
214
+ * full = !full ? chunk : concat(full, chunk);
215
+ * }
216
+ * console.log(full);
217
+ * ```
218
+ *
219
+ * ```txt
220
+ * AIMessageChunk {
221
+ * "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.",
222
+ * "additional_kwargs": {},
223
+ * "response_metadata": {
224
+ * "finishReason": "stop"
225
+ * },
226
+ * "tool_calls": [],
227
+ * "tool_call_chunks": [],
228
+ * "invalid_tool_calls": []
229
+ * }
230
+ * ```
231
+ * </details>
232
+ *
233
+ * <br />
234
+ *
235
+ * <details>
236
+ * <summary><strong>Bind tools</strong></summary>
237
+ *
238
+ * ```typescript
239
+ * import { z } from 'zod';
240
+ *
241
+ * const llmForToolCalling = new ChatXAI({
242
+ * model: "grok-beta",
243
+ * temperature: 0,
244
+ * // other params...
245
+ * });
246
+ *
247
+ * const GetWeather = {
248
+ * name: "GetWeather",
249
+ * description: "Get the current weather in a given location",
250
+ * schema: z.object({
251
+ * location: z.string().describe("The city and state, e.g. San Francisco, CA")
252
+ * }),
253
+ * }
254
+ *
255
+ * const GetPopulation = {
256
+ * name: "GetPopulation",
257
+ * description: "Get the current population in a given location",
258
+ * schema: z.object({
259
+ * location: z.string().describe("The city and state, e.g. San Francisco, CA")
260
+ * }),
261
+ * }
262
+ *
263
+ * const llmWithTools = llmForToolCalling.bindTools([GetWeather, GetPopulation]);
264
+ * const aiMsg = await llmWithTools.invoke(
265
+ * "Which city is hotter today and which is bigger: LA or NY?"
266
+ * );
267
+ * console.log(aiMsg.tool_calls);
268
+ * ```
269
+ *
270
+ * ```txt
271
+ * [
272
+ * {
273
+ * name: 'GetWeather',
274
+ * args: { location: 'Los Angeles, CA' },
275
+ * type: 'tool_call',
276
+ * id: 'call_cd34'
277
+ * },
278
+ * {
279
+ * name: 'GetWeather',
280
+ * args: { location: 'New York, NY' },
281
+ * type: 'tool_call',
282
+ * id: 'call_68rf'
283
+ * },
284
+ * {
285
+ * name: 'GetPopulation',
286
+ * args: { location: 'Los Angeles, CA' },
287
+ * type: 'tool_call',
288
+ * id: 'call_f81z'
289
+ * },
290
+ * {
291
+ * name: 'GetPopulation',
292
+ * args: { location: 'New York, NY' },
293
+ * type: 'tool_call',
294
+ * id: 'call_8byt'
295
+ * }
296
+ * ]
297
+ * ```
298
+ * </details>
299
+ *
300
+ * <br />
301
+ *
302
+ * <details>
303
+ * <summary><strong>Structured Output</strong></summary>
304
+ *
305
+ * ```typescript
306
+ * import { z } from 'zod';
307
+ *
308
+ * const Joke = z.object({
309
+ * setup: z.string().describe("The setup of the joke"),
310
+ * punchline: z.string().describe("The punchline to the joke"),
311
+ * rating: z.number().optional().describe("How funny the joke is, from 1 to 10")
312
+ * }).describe('Joke to tell user.');
313
+ *
314
+ * const structuredLlm = llmForToolCalling.withStructuredOutput(Joke, { name: "Joke" });
315
+ * const jokeResult = await structuredLlm.invoke("Tell me a joke about cats");
316
+ * console.log(jokeResult);
317
+ * ```
318
+ *
319
+ * ```txt
320
+ * {
321
+ * setup: "Why don't cats play poker in the wild?",
322
+ * punchline: 'Because there are too many cheetahs.'
323
+ * }
324
+ * ```
325
+ * </details>
326
+ *
327
+ * <br />
328
+ */
329
+ export class ChatXAI extends ChatOpenAI {
330
+ static lc_name() {
331
+ return "ChatXAI";
332
+ }
333
+ _llmType() {
334
+ return "xAI";
335
+ }
336
+ get lc_secrets() {
337
+ return {
338
+ apiKey: "XAI_API_KEY",
339
+ };
340
+ }
341
+ constructor(fields) {
342
+ const apiKey = fields?.apiKey || getEnvironmentVariable("XAI_API_KEY");
343
+ if (!apiKey) {
344
+ throw new Error(`xAI API key not found. Please set the XAI_API_KEY environment variable or provide the key into "apiKey" field.`);
345
+ }
346
+ super({
347
+ ...fields,
348
+ model: fields?.model || "grok-beta",
349
+ apiKey,
350
+ configuration: {
351
+ baseURL: "https://api.x.ai/v1",
352
+ },
353
+ });
354
+ Object.defineProperty(this, "lc_serializable", {
355
+ enumerable: true,
356
+ configurable: true,
357
+ writable: true,
358
+ value: true
359
+ });
360
+ Object.defineProperty(this, "lc_namespace", {
361
+ enumerable: true,
362
+ configurable: true,
363
+ writable: true,
364
+ value: ["langchain", "chat_models", "xai"]
365
+ });
366
+ }
367
+ toJSON() {
368
+ const result = super.toJSON();
369
+ if ("kwargs" in result &&
370
+ typeof result.kwargs === "object" &&
371
+ result.kwargs != null) {
372
+ delete result.kwargs.openai_api_key;
373
+ delete result.kwargs.configuration;
374
+ }
375
+ return result;
376
+ }
377
+ getLsParams(options) {
378
+ const params = super.getLsParams(options);
379
+ params.ls_provider = "xai";
380
+ return params;
381
+ }
382
+ /**
383
+ * Calls the xAI API with retry logic in case of failures.
384
+ * @param request The request to send to the xAI API.
385
+ * @param options Optional configuration for the API call.
386
+ * @returns The response from the xAI API.
387
+ */
388
+ async completionWithRetry(request, options) {
389
+ delete request.frequency_penalty;
390
+ delete request.presence_penalty;
391
+ delete request.logit_bias;
392
+ delete request.functions;
393
+ const newRequestMessages = request.messages.map((msg) => {
394
+ if (!msg.content) {
395
+ return {
396
+ ...msg,
397
+ content: "",
398
+ };
399
+ }
400
+ return msg;
401
+ });
402
+ const newRequest = {
403
+ ...request,
404
+ messages: newRequestMessages,
405
+ };
406
+ if (newRequest.stream === true) {
407
+ return super.completionWithRetry(newRequest, options);
408
+ }
409
+ return super.completionWithRetry(newRequest, options);
410
+ }
411
+ }
package/dist/index.cjs ADDED
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./chat_models.cjs"), exports);
@@ -0,0 +1 @@
1
+ export * from "./chat_models.js";
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export * from "./chat_models.js";
package/index.cjs ADDED
@@ -0,0 +1 @@
1
+ module.exports = require('./dist/index.cjs');
package/index.d.cts ADDED
@@ -0,0 +1 @@
1
+ export * from './dist/index.js'
package/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './dist/index.js'
package/index.js ADDED
@@ -0,0 +1 @@
1
+ export * from './dist/index.js'
package/package.json ADDED
@@ -0,0 +1,94 @@
1
+ {
2
+ "name": "@langchain/xai",
3
+ "version": "0.0.1",
4
+ "description": "xAI integration for LangChain.js",
5
+ "type": "module",
6
+ "engines": {
7
+ "node": ">=18"
8
+ },
9
+ "main": "./index.js",
10
+ "types": "./index.d.ts",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git@github.com:langchain-ai/langchainjs.git"
14
+ },
15
+ "homepage": "https://github.com/langchain-ai/langchainjs/tree/main/libs/langchain-xai/",
16
+ "scripts": {
17
+ "build": "yarn turbo:command build:internal --filter=@langchain/xai",
18
+ "build:internal": "yarn lc_build --create-entrypoints --pre --tree-shaking",
19
+ "lint:eslint": "NODE_OPTIONS=--max-old-space-size=4096 eslint --cache --ext .ts,.js src/",
20
+ "lint:dpdm": "dpdm --exit-code circular:1 --no-warning --no-tree src/*.ts src/**/*.ts",
21
+ "lint": "yarn lint:eslint && yarn lint:dpdm",
22
+ "lint:fix": "yarn lint:eslint --fix && yarn lint:dpdm",
23
+ "clean": "rm -rf .turbo dist/",
24
+ "prepack": "yarn build",
25
+ "test": "NODE_OPTIONS=--experimental-vm-modules jest --testPathIgnorePatterns=\\.int\\.test.ts --testTimeout 30000 --maxWorkers=50%",
26
+ "test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch --testPathIgnorePatterns=\\.int\\.test.ts",
27
+ "test:single": "NODE_OPTIONS=--experimental-vm-modules yarn run jest --config jest.config.cjs --testTimeout 100000",
28
+ "test:int": "NODE_OPTIONS=--experimental-vm-modules jest --testPathPattern=\\.int\\.test.ts --testTimeout 100000 --maxWorkers=50%",
29
+ "test:standard:unit": "NODE_OPTIONS=--experimental-vm-modules jest --testPathPattern=\\.standard\\.test.ts --testTimeout 100000 --maxWorkers=50%",
30
+ "test:standard:int": "NODE_OPTIONS=--experimental-vm-modules jest --testPathPattern=\\.standard\\.int\\.test.ts --testTimeout 100000 --maxWorkers=50%",
31
+ "test:standard": "yarn test:standard:unit && yarn test:standard:int",
32
+ "format": "prettier --config .prettierrc --write \"src\"",
33
+ "format:check": "prettier --config .prettierrc --check \"src\""
34
+ },
35
+ "author": "LangChain",
36
+ "license": "MIT",
37
+ "dependencies": {
38
+ "@langchain/openai": "~0.3.0"
39
+ },
40
+ "peerDependencies": {
41
+ "@langchain/core": ">=0.2.21 <0.4.0"
42
+ },
43
+ "devDependencies": {
44
+ "@jest/globals": "^29.5.0",
45
+ "@langchain/core": "workspace:*",
46
+ "@langchain/openai": "workspace:^",
47
+ "@langchain/scripts": ">=0.1.0 <0.2.0",
48
+ "@langchain/standard-tests": "0.0.0",
49
+ "@swc/core": "^1.3.90",
50
+ "@swc/jest": "^0.2.29",
51
+ "@tsconfig/recommended": "^1.0.3",
52
+ "@types/uuid": "^9",
53
+ "@typescript-eslint/eslint-plugin": "^6.12.0",
54
+ "@typescript-eslint/parser": "^6.12.0",
55
+ "dotenv": "^16.3.1",
56
+ "dpdm": "^3.12.0",
57
+ "eslint": "^8.33.0",
58
+ "eslint-config-airbnb-base": "^15.0.0",
59
+ "eslint-config-prettier": "^8.6.0",
60
+ "eslint-plugin-import": "^2.27.5",
61
+ "eslint-plugin-no-instanceof": "^1.0.1",
62
+ "eslint-plugin-prettier": "^4.2.1",
63
+ "jest": "^29.5.0",
64
+ "jest-environment-node": "^29.6.4",
65
+ "prettier": "^2.8.3",
66
+ "release-it": "^17.6.0",
67
+ "rollup": "^4.5.2",
68
+ "ts-jest": "^29.1.0",
69
+ "typescript": "<5.2.0",
70
+ "zod": "^3.22.4"
71
+ },
72
+ "publishConfig": {
73
+ "access": "public"
74
+ },
75
+ "exports": {
76
+ ".": {
77
+ "types": {
78
+ "import": "./index.d.ts",
79
+ "require": "./index.d.cts",
80
+ "default": "./index.d.ts"
81
+ },
82
+ "import": "./index.js",
83
+ "require": "./index.cjs"
84
+ },
85
+ "./package.json": "./package.json"
86
+ },
87
+ "files": [
88
+ "dist/",
89
+ "index.cjs",
90
+ "index.js",
91
+ "index.d.ts",
92
+ "index.d.cts"
93
+ ]
94
+ }