langchain 0.0.177 → 0.0.178

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.
Files changed (35) hide show
  1. package/chat_models/iflytek_xinghuo/web.cjs +1 -0
  2. package/chat_models/iflytek_xinghuo/web.d.ts +1 -0
  3. package/chat_models/iflytek_xinghuo/web.js +1 -0
  4. package/chat_models/iflytek_xinghuo.cjs +1 -0
  5. package/chat_models/iflytek_xinghuo.d.ts +1 -0
  6. package/chat_models/iflytek_xinghuo.js +1 -0
  7. package/dist/chat_models/cloudflare_workersai.cjs +70 -24
  8. package/dist/chat_models/cloudflare_workersai.d.ts +6 -2
  9. package/dist/chat_models/cloudflare_workersai.js +71 -25
  10. package/dist/chat_models/iflytek_xinghuo/common.cjs +335 -0
  11. package/dist/chat_models/iflytek_xinghuo/common.d.ts +165 -0
  12. package/dist/chat_models/iflytek_xinghuo/common.js +331 -0
  13. package/dist/chat_models/iflytek_xinghuo/index.cjs +35 -0
  14. package/dist/chat_models/iflytek_xinghuo/index.d.ts +5 -0
  15. package/dist/chat_models/iflytek_xinghuo/index.js +28 -0
  16. package/dist/chat_models/iflytek_xinghuo/web.cjs +30 -0
  17. package/dist/chat_models/iflytek_xinghuo/web.d.ts +5 -0
  18. package/dist/chat_models/iflytek_xinghuo/web.js +26 -0
  19. package/dist/graphs/neo4j_graph.cjs +36 -5
  20. package/dist/graphs/neo4j_graph.js +14 -3
  21. package/dist/llms/cloudflare_workersai.cjs +59 -13
  22. package/dist/llms/cloudflare_workersai.d.ts +9 -3
  23. package/dist/llms/cloudflare_workersai.js +59 -13
  24. package/dist/load/import_constants.cjs +2 -0
  25. package/dist/load/import_constants.js +2 -0
  26. package/dist/prompts/chat.cjs +8 -0
  27. package/dist/prompts/chat.d.ts +5 -0
  28. package/dist/prompts/chat.js +8 -0
  29. package/dist/util/event-source-parse.cjs +20 -1
  30. package/dist/util/event-source-parse.d.ts +2 -0
  31. package/dist/util/event-source-parse.js +18 -0
  32. package/dist/util/iflytek_websocket_stream.cjs +81 -0
  33. package/dist/util/iflytek_websocket_stream.d.ts +27 -0
  34. package/dist/util/iflytek_websocket_stream.js +77 -0
  35. package/package.json +22 -1
@@ -0,0 +1 @@
1
+ module.exports = require('../../dist/chat_models/iflytek_xinghuo/web.cjs');
@@ -0,0 +1 @@
1
+ export * from '../../dist/chat_models/iflytek_xinghuo/web.js'
@@ -0,0 +1 @@
1
+ export * from '../../dist/chat_models/iflytek_xinghuo/web.js'
@@ -0,0 +1 @@
1
+ module.exports = require('../dist/chat_models/iflytek_xinghuo/index.cjs');
@@ -0,0 +1 @@
1
+ export * from '../dist/chat_models/iflytek_xinghuo/index.js'
@@ -0,0 +1 @@
1
+ export * from '../dist/chat_models/iflytek_xinghuo/index.js'
@@ -4,6 +4,7 @@ exports.ChatCloudflareWorkersAI = void 0;
4
4
  const base_js_1 = require("./base.cjs");
5
5
  const index_js_1 = require("../schema/index.cjs");
6
6
  const env_js_1 = require("../util/env.cjs");
7
+ const event_source_parse_js_1 = require("../util/event-source-parse.cjs");
7
8
  /**
8
9
  * A class that enables calls to the Cloudflare Workers AI API to access large language
9
10
  * models in a chat-like fashion. It extends the SimpleChatModel class and
@@ -45,7 +46,14 @@ class ChatCloudflareWorkersAI extends base_js_1.SimpleChatModel {
45
46
  writable: true,
46
47
  value: void 0
47
48
  });
49
+ Object.defineProperty(this, "streaming", {
50
+ enumerable: true,
51
+ configurable: true,
52
+ writable: true,
53
+ value: false
54
+ });
48
55
  this.model = fields?.model ?? this.model;
56
+ this.streaming = fields?.streaming ?? this.streaming;
49
57
  this.cloudflareAccountId =
50
58
  fields?.cloudflareAccountId ??
51
59
  (0, env_js_1.getEnvironmentVariable)("CLOUDFLARE_ACCOUNT_ID");
@@ -88,6 +96,50 @@ class ChatCloudflareWorkersAI extends base_js_1.SimpleChatModel {
88
96
  throw new Error(`No Cloudflare API key found. Please provide it when instantiating the CloudflareWorkersAI class, or set it as "CLOUDFLARE_API_KEY" in your environment variables.`);
89
97
  }
90
98
  }
99
+ async _request(messages, options, stream) {
100
+ this.validateEnvironment();
101
+ const url = `${this.baseUrl}/${this.model}`;
102
+ const headers = {
103
+ Authorization: `Bearer ${this.cloudflareApiToken}`,
104
+ "Content-Type": "application/json",
105
+ };
106
+ const formattedMessages = this._formatMessages(messages);
107
+ const data = { messages: formattedMessages, stream };
108
+ return this.caller.call(async () => {
109
+ const response = await fetch(url, {
110
+ method: "POST",
111
+ headers,
112
+ body: JSON.stringify(data),
113
+ signal: options.signal,
114
+ });
115
+ if (!response.ok) {
116
+ const error = new Error(`Cloudflare LLM call failed with status code ${response.status}`);
117
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
118
+ error.response = response;
119
+ throw error;
120
+ }
121
+ return response;
122
+ });
123
+ }
124
+ async *_streamResponseChunks(messages, options, runManager) {
125
+ const response = await this._request(messages, options, true);
126
+ if (!response.body) {
127
+ throw new Error("Empty response from Cloudflare. Please try again.");
128
+ }
129
+ const stream = (0, event_source_parse_js_1.convertEventStreamToIterableReadableDataStream)(response.body);
130
+ for await (const chunk of stream) {
131
+ if (chunk !== "[DONE]") {
132
+ const parsedChunk = JSON.parse(chunk);
133
+ const generationChunk = new index_js_1.ChatGenerationChunk({
134
+ message: new index_js_1.AIMessageChunk({ content: parsedChunk.response }),
135
+ text: parsedChunk.response,
136
+ });
137
+ yield generationChunk;
138
+ // eslint-disable-next-line no-void
139
+ void runManager?.handleLLMNewToken(generationChunk.text ?? "");
140
+ }
141
+ }
142
+ }
91
143
  _formatMessages(messages) {
92
144
  const formattedMessages = messages.map((message) => {
93
145
  let role;
@@ -115,31 +167,25 @@ class ChatCloudflareWorkersAI extends base_js_1.SimpleChatModel {
115
167
  return formattedMessages;
116
168
  }
117
169
  /** @ignore */
118
- async _call(messages, options) {
119
- this.validateEnvironment();
120
- const url = `${this.baseUrl}/${this.model}`;
121
- const headers = {
122
- Authorization: `Bearer ${this.cloudflareApiToken}`,
123
- "Content-Type": "application/json",
124
- };
125
- const formattedMessages = this._formatMessages(messages);
126
- const data = { messages: formattedMessages };
127
- const responseData = await this.caller.call(async () => {
128
- const response = await fetch(url, {
129
- method: "POST",
130
- headers,
131
- body: JSON.stringify(data),
132
- signal: options.signal,
133
- });
134
- if (!response.ok) {
135
- const error = new Error(`Cloudflare LLM call failed with status code ${response.status}`);
136
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
137
- error.response = response;
138
- throw error;
170
+ async _call(messages, options, runManager) {
171
+ if (!this.streaming) {
172
+ const response = await this._request(messages, options);
173
+ const responseData = await response.json();
174
+ return responseData.result.response;
175
+ }
176
+ else {
177
+ const stream = this._streamResponseChunks(messages, options, runManager);
178
+ let finalResult;
179
+ for await (const chunk of stream) {
180
+ if (finalResult === undefined) {
181
+ finalResult = chunk;
182
+ }
183
+ else {
184
+ finalResult = finalResult.concat(chunk);
185
+ }
139
186
  }
140
- return response.json();
141
- });
142
- return responseData.result.response;
187
+ return finalResult?.message?.content ?? "";
188
+ }
143
189
  }
144
190
  }
145
191
  exports.ChatCloudflareWorkersAI = ChatCloudflareWorkersAI;
@@ -1,7 +1,8 @@
1
1
  import { SimpleChatModel, BaseChatModelParams } from "./base.js";
2
2
  import { BaseLanguageModelCallOptions } from "../base_language/index.js";
3
- import { BaseMessage } from "../schema/index.js";
3
+ import { BaseMessage, ChatGenerationChunk } from "../schema/index.js";
4
4
  import { CloudflareWorkersAIInput } from "../llms/cloudflare_workersai.js";
5
+ import { CallbackManagerForLLMRun } from "../callbacks/manager.js";
5
6
  /**
6
7
  * An interface defining the options for a Cloudflare Workers AI call. It extends
7
8
  * the BaseLanguageModelCallOptions interface.
@@ -20,6 +21,7 @@ export declare class ChatCloudflareWorkersAI extends SimpleChatModel implements
20
21
  cloudflareAccountId?: string;
21
22
  cloudflareApiToken?: string;
22
23
  baseUrl: string;
24
+ streaming: boolean;
23
25
  constructor(fields?: CloudflareWorkersAIInput & BaseChatModelParams);
24
26
  _llmType(): string;
25
27
  /** Get the identifying parameters for this LLM. */
@@ -37,10 +39,12 @@ export declare class ChatCloudflareWorkersAI extends SimpleChatModel implements
37
39
  * Method to validate the environment.
38
40
  */
39
41
  validateEnvironment(): void;
42
+ _request(messages: BaseMessage[], options: this["ParsedCallOptions"], stream?: boolean): Promise<Response>;
43
+ _streamResponseChunks(messages: BaseMessage[], options: this["ParsedCallOptions"], runManager?: CallbackManagerForLLMRun): AsyncGenerator<ChatGenerationChunk>;
40
44
  protected _formatMessages(messages: BaseMessage[]): {
41
45
  role: string;
42
46
  content: string;
43
47
  }[];
44
48
  /** @ignore */
45
- _call(messages: BaseMessage[], options: this["ParsedCallOptions"]): Promise<string>;
49
+ _call(messages: BaseMessage[], options: this["ParsedCallOptions"], runManager?: CallbackManagerForLLMRun): Promise<string>;
46
50
  }
@@ -1,6 +1,7 @@
1
1
  import { SimpleChatModel } from "./base.js";
2
- import { ChatMessage } from "../schema/index.js";
2
+ import { AIMessageChunk, ChatGenerationChunk, ChatMessage, } from "../schema/index.js";
3
3
  import { getEnvironmentVariable } from "../util/env.js";
4
+ import { convertEventStreamToIterableReadableDataStream } from "../util/event-source-parse.js";
4
5
  /**
5
6
  * A class that enables calls to the Cloudflare Workers AI API to access large language
6
7
  * models in a chat-like fashion. It extends the SimpleChatModel class and
@@ -42,7 +43,14 @@ export class ChatCloudflareWorkersAI extends SimpleChatModel {
42
43
  writable: true,
43
44
  value: void 0
44
45
  });
46
+ Object.defineProperty(this, "streaming", {
47
+ enumerable: true,
48
+ configurable: true,
49
+ writable: true,
50
+ value: false
51
+ });
45
52
  this.model = fields?.model ?? this.model;
53
+ this.streaming = fields?.streaming ?? this.streaming;
46
54
  this.cloudflareAccountId =
47
55
  fields?.cloudflareAccountId ??
48
56
  getEnvironmentVariable("CLOUDFLARE_ACCOUNT_ID");
@@ -85,6 +93,50 @@ export class ChatCloudflareWorkersAI extends SimpleChatModel {
85
93
  throw new Error(`No Cloudflare API key found. Please provide it when instantiating the CloudflareWorkersAI class, or set it as "CLOUDFLARE_API_KEY" in your environment variables.`);
86
94
  }
87
95
  }
96
+ async _request(messages, options, stream) {
97
+ this.validateEnvironment();
98
+ const url = `${this.baseUrl}/${this.model}`;
99
+ const headers = {
100
+ Authorization: `Bearer ${this.cloudflareApiToken}`,
101
+ "Content-Type": "application/json",
102
+ };
103
+ const formattedMessages = this._formatMessages(messages);
104
+ const data = { messages: formattedMessages, stream };
105
+ return this.caller.call(async () => {
106
+ const response = await fetch(url, {
107
+ method: "POST",
108
+ headers,
109
+ body: JSON.stringify(data),
110
+ signal: options.signal,
111
+ });
112
+ if (!response.ok) {
113
+ const error = new Error(`Cloudflare LLM call failed with status code ${response.status}`);
114
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
115
+ error.response = response;
116
+ throw error;
117
+ }
118
+ return response;
119
+ });
120
+ }
121
+ async *_streamResponseChunks(messages, options, runManager) {
122
+ const response = await this._request(messages, options, true);
123
+ if (!response.body) {
124
+ throw new Error("Empty response from Cloudflare. Please try again.");
125
+ }
126
+ const stream = convertEventStreamToIterableReadableDataStream(response.body);
127
+ for await (const chunk of stream) {
128
+ if (chunk !== "[DONE]") {
129
+ const parsedChunk = JSON.parse(chunk);
130
+ const generationChunk = new ChatGenerationChunk({
131
+ message: new AIMessageChunk({ content: parsedChunk.response }),
132
+ text: parsedChunk.response,
133
+ });
134
+ yield generationChunk;
135
+ // eslint-disable-next-line no-void
136
+ void runManager?.handleLLMNewToken(generationChunk.text ?? "");
137
+ }
138
+ }
139
+ }
88
140
  _formatMessages(messages) {
89
141
  const formattedMessages = messages.map((message) => {
90
142
  let role;
@@ -112,30 +164,24 @@ export class ChatCloudflareWorkersAI extends SimpleChatModel {
112
164
  return formattedMessages;
113
165
  }
114
166
  /** @ignore */
115
- async _call(messages, options) {
116
- this.validateEnvironment();
117
- const url = `${this.baseUrl}/${this.model}`;
118
- const headers = {
119
- Authorization: `Bearer ${this.cloudflareApiToken}`,
120
- "Content-Type": "application/json",
121
- };
122
- const formattedMessages = this._formatMessages(messages);
123
- const data = { messages: formattedMessages };
124
- const responseData = await this.caller.call(async () => {
125
- const response = await fetch(url, {
126
- method: "POST",
127
- headers,
128
- body: JSON.stringify(data),
129
- signal: options.signal,
130
- });
131
- if (!response.ok) {
132
- const error = new Error(`Cloudflare LLM call failed with status code ${response.status}`);
133
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
134
- error.response = response;
135
- throw error;
167
+ async _call(messages, options, runManager) {
168
+ if (!this.streaming) {
169
+ const response = await this._request(messages, options);
170
+ const responseData = await response.json();
171
+ return responseData.result.response;
172
+ }
173
+ else {
174
+ const stream = this._streamResponseChunks(messages, options, runManager);
175
+ let finalResult;
176
+ for await (const chunk of stream) {
177
+ if (finalResult === undefined) {
178
+ finalResult = chunk;
179
+ }
180
+ else {
181
+ finalResult = finalResult.concat(chunk);
182
+ }
136
183
  }
137
- return response.json();
138
- });
139
- return responseData.result.response;
184
+ return finalResult?.message?.content ?? "";
185
+ }
140
186
  }
141
187
  }
@@ -0,0 +1,335 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BaseChatIflytekXinghuo = void 0;
4
+ const index_js_1 = require("../../schema/index.cjs");
5
+ const env_js_1 = require("../../util/env.cjs");
6
+ const stream_js_1 = require("../../util/stream.cjs");
7
+ const base_js_1 = require("../base.cjs");
8
+ /**
9
+ * Function that extracts the custom role of a generic chat message.
10
+ * @param message Chat message from which to extract the custom role.
11
+ * @returns The custom role of the chat message.
12
+ */
13
+ function extractGenericMessageCustomRole(message) {
14
+ if (message.role !== "assistant" && message.role !== "user") {
15
+ console.warn(`Unknown message role: ${message.role}`);
16
+ }
17
+ return message.role;
18
+ }
19
+ /**
20
+ * Function that converts a base message to a Xinghuo message role.
21
+ * @param message Base message to convert.
22
+ * @returns The Xinghuo message role.
23
+ */
24
+ function messageToXinghuoRole(message) {
25
+ const type = message._getType();
26
+ switch (type) {
27
+ case "ai":
28
+ return "assistant";
29
+ case "human":
30
+ return "user";
31
+ case "system":
32
+ throw new Error("System messages should not be here");
33
+ case "function":
34
+ throw new Error("Function messages not supported");
35
+ case "generic": {
36
+ if (!index_js_1.ChatMessage.isInstance(message))
37
+ throw new Error("Invalid generic chat message");
38
+ return extractGenericMessageCustomRole(message);
39
+ }
40
+ default:
41
+ throw new Error(`Unknown message type: ${type}`);
42
+ }
43
+ }
44
+ /**
45
+ * Wrapper around IflytekXingHuo large language models that use the Chat endpoint.
46
+ *
47
+ * To use you should have the `IFLYTEK_API_KEY` and `IFLYTEK_API_SECRET` and `IFLYTEK_APPID`
48
+ * environment variable set.
49
+ *
50
+ * @augments BaseChatModel
51
+ * @augments IflytekXinghuoChatInput
52
+ */
53
+ class BaseChatIflytekXinghuo extends base_js_1.BaseChatModel {
54
+ static lc_name() {
55
+ return "ChatIflytekXinghuo";
56
+ }
57
+ get callKeys() {
58
+ return ["stop", "signal", "options"];
59
+ }
60
+ get lc_secrets() {
61
+ return {
62
+ iflytekApiKey: "IFLYTEK_API_KEY",
63
+ iflytekApiSecret: "IFLYTEK_API_SECRET",
64
+ };
65
+ }
66
+ get lc_aliases() {
67
+ return undefined;
68
+ }
69
+ constructor(fields) {
70
+ super(fields ?? {});
71
+ Object.defineProperty(this, "lc_serializable", {
72
+ enumerable: true,
73
+ configurable: true,
74
+ writable: true,
75
+ value: true
76
+ });
77
+ Object.defineProperty(this, "version", {
78
+ enumerable: true,
79
+ configurable: true,
80
+ writable: true,
81
+ value: "v2.1"
82
+ });
83
+ Object.defineProperty(this, "iflytekAppid", {
84
+ enumerable: true,
85
+ configurable: true,
86
+ writable: true,
87
+ value: void 0
88
+ });
89
+ Object.defineProperty(this, "iflytekApiKey", {
90
+ enumerable: true,
91
+ configurable: true,
92
+ writable: true,
93
+ value: void 0
94
+ });
95
+ Object.defineProperty(this, "iflytekApiSecret", {
96
+ enumerable: true,
97
+ configurable: true,
98
+ writable: true,
99
+ value: void 0
100
+ });
101
+ Object.defineProperty(this, "userId", {
102
+ enumerable: true,
103
+ configurable: true,
104
+ writable: true,
105
+ value: void 0
106
+ });
107
+ Object.defineProperty(this, "apiUrl", {
108
+ enumerable: true,
109
+ configurable: true,
110
+ writable: true,
111
+ value: void 0
112
+ });
113
+ Object.defineProperty(this, "domain", {
114
+ enumerable: true,
115
+ configurable: true,
116
+ writable: true,
117
+ value: void 0
118
+ });
119
+ Object.defineProperty(this, "temperature", {
120
+ enumerable: true,
121
+ configurable: true,
122
+ writable: true,
123
+ value: 0.5
124
+ });
125
+ Object.defineProperty(this, "max_tokens", {
126
+ enumerable: true,
127
+ configurable: true,
128
+ writable: true,
129
+ value: 2048
130
+ });
131
+ Object.defineProperty(this, "top_k", {
132
+ enumerable: true,
133
+ configurable: true,
134
+ writable: true,
135
+ value: 4
136
+ });
137
+ Object.defineProperty(this, "streaming", {
138
+ enumerable: true,
139
+ configurable: true,
140
+ writable: true,
141
+ value: false
142
+ });
143
+ const iflytekAppid = fields?.iflytekAppid ?? (0, env_js_1.getEnvironmentVariable)("IFLYTEK_APPID");
144
+ if (!iflytekAppid) {
145
+ throw new Error("Iflytek APPID not found");
146
+ }
147
+ else {
148
+ this.iflytekAppid = iflytekAppid;
149
+ }
150
+ const iflytekApiKey = fields?.iflytekApiKey ?? (0, env_js_1.getEnvironmentVariable)("IFLYTEK_API_KEY");
151
+ if (!iflytekApiKey) {
152
+ throw new Error("Iflytek API key not found");
153
+ }
154
+ else {
155
+ this.iflytekApiKey = iflytekApiKey;
156
+ }
157
+ const iflytekApiSecret = fields?.iflytekApiSecret ?? (0, env_js_1.getEnvironmentVariable)("IFLYTEK_API_SECRET");
158
+ if (!iflytekApiSecret) {
159
+ throw new Error("Iflytek API secret not found");
160
+ }
161
+ else {
162
+ this.iflytekApiSecret = iflytekApiSecret;
163
+ }
164
+ this.userId = fields?.userId ?? this.userId;
165
+ this.streaming = fields?.streaming ?? this.streaming;
166
+ this.temperature = fields?.temperature ?? this.temperature;
167
+ this.max_tokens = fields?.max_tokens ?? this.max_tokens;
168
+ this.top_k = fields?.top_k ?? this.top_k;
169
+ this.version = fields?.version ?? this.version;
170
+ if (["v1.1", "v2.1", "v3.1"].includes(this.version)) {
171
+ switch (this.version) {
172
+ case "v1.1":
173
+ this.domain = "general";
174
+ break;
175
+ case "v2.1":
176
+ this.domain = "generalv2";
177
+ break;
178
+ case "v3.1":
179
+ this.domain = "generalv3";
180
+ break;
181
+ default:
182
+ this.domain = "generalv2";
183
+ }
184
+ this.apiUrl = `wss://spark-api.xf-yun.com/${this.version}/chat`;
185
+ }
186
+ else {
187
+ throw new Error(`Invalid model version: ${this.version}`);
188
+ }
189
+ }
190
+ /**
191
+ * Get the identifying parameters for the model
192
+ */
193
+ identifyingParams() {
194
+ return {
195
+ version: this.version,
196
+ ...this.invocationParams(),
197
+ };
198
+ }
199
+ /**
200
+ * Get the parameters used to invoke the model
201
+ */
202
+ invocationParams() {
203
+ return {
204
+ streaming: this.streaming,
205
+ temperature: this.temperature,
206
+ top_k: this.top_k,
207
+ };
208
+ }
209
+ async completion(request, stream, signal) {
210
+ const webSocketStream = await this.openWebSocketStream({
211
+ signal,
212
+ });
213
+ const connection = await webSocketStream.connection;
214
+ const header = {
215
+ app_id: this.iflytekAppid,
216
+ uid: this.userId,
217
+ };
218
+ const parameter = {
219
+ chat: {
220
+ domain: this.domain,
221
+ temperature: request.temperature ?? this.temperature,
222
+ max_tokens: request.max_tokens ?? this.max_tokens,
223
+ top_k: request.top_k ?? this.top_k,
224
+ },
225
+ };
226
+ const payload = {
227
+ message: {
228
+ text: request.messages,
229
+ },
230
+ };
231
+ const message = JSON.stringify({
232
+ header,
233
+ parameter,
234
+ payload,
235
+ });
236
+ const { writable, readable } = connection;
237
+ const writer = writable.getWriter();
238
+ await writer.write(message);
239
+ const streams = stream_js_1.IterableReadableStream.fromReadableStream(readable);
240
+ if (stream) {
241
+ return streams;
242
+ }
243
+ else {
244
+ let response = { result: "" };
245
+ for await (const chunk of streams) {
246
+ const data = JSON.parse(chunk);
247
+ const { header, payload } = data;
248
+ if (header.code === 0) {
249
+ if (header.status === 0) {
250
+ response.result = payload.choices?.text[0]?.content ?? "";
251
+ }
252
+ else if (header.status === 1) {
253
+ response.result += payload.choices?.text[0]?.content ?? "";
254
+ }
255
+ else if (header.status === 2) {
256
+ response = { ...response, usage: payload.usage?.text };
257
+ break;
258
+ }
259
+ }
260
+ else {
261
+ break;
262
+ }
263
+ }
264
+ void streams.cancel();
265
+ void webSocketStream.close();
266
+ return response;
267
+ }
268
+ }
269
+ async _generate(messages, options, runManager) {
270
+ const tokenUsage = {};
271
+ const params = this.invocationParams();
272
+ const messagesMapped = messages.map((message) => ({
273
+ role: messageToXinghuoRole(message),
274
+ content: message.content,
275
+ }));
276
+ const data = params.streaming
277
+ ? await (async () => {
278
+ const streams = await this.completion({ messages: messagesMapped, ...params }, true, options.signal);
279
+ let response = { result: "" };
280
+ for await (const chunk of streams) {
281
+ const data = JSON.parse(chunk);
282
+ const { header, payload } = data;
283
+ if (header.code === 0) {
284
+ if (header.status === 0) {
285
+ response.result = payload.choices?.text[0]?.content ?? "";
286
+ }
287
+ else if (header.status === 1) {
288
+ response.result += payload.choices?.text[0]?.content ?? "";
289
+ }
290
+ else if (header.status === 2) {
291
+ response = { ...response, usage: payload.usage?.text };
292
+ break;
293
+ }
294
+ void runManager?.handleLLMNewToken(payload.choices?.text[0]?.content);
295
+ }
296
+ else {
297
+ break;
298
+ }
299
+ }
300
+ void streams.cancel();
301
+ return response;
302
+ })()
303
+ : await this.completion({ messages: messagesMapped, ...params }, false, options.signal);
304
+ const { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens, } = data.usage ?? {};
305
+ if (completionTokens) {
306
+ tokenUsage.completionTokens =
307
+ (tokenUsage.completionTokens ?? 0) + completionTokens;
308
+ }
309
+ if (promptTokens) {
310
+ tokenUsage.promptTokens = (tokenUsage.promptTokens ?? 0) + promptTokens;
311
+ }
312
+ if (totalTokens) {
313
+ tokenUsage.totalTokens = (tokenUsage.totalTokens ?? 0) + totalTokens;
314
+ }
315
+ const generations = [];
316
+ const text = data.result ?? "";
317
+ generations.push({
318
+ text,
319
+ message: new index_js_1.AIMessage(text),
320
+ });
321
+ return {
322
+ generations,
323
+ llmOutput: { tokenUsage },
324
+ };
325
+ }
326
+ /** @ignore */
327
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
328
+ _combineLLMOutput() {
329
+ return [];
330
+ }
331
+ _llmType() {
332
+ return "iflytek_xinghuo";
333
+ }
334
+ }
335
+ exports.BaseChatIflytekXinghuo = BaseChatIflytekXinghuo;