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,165 @@
1
+ import { CallbackManagerForLLMRun } from "../../callbacks/manager.js";
2
+ import { BaseMessage, ChatResult } from "../../schema/index.js";
3
+ import { IterableReadableStream } from "../../util/stream.js";
4
+ import { BaseChatModel, BaseChatModelParams } from "../base.js";
5
+ import { BaseWebSocketStream, WebSocketStreamOptions } from "../../util/iflytek_websocket_stream.js";
6
+ /**
7
+ * Type representing the role of a message in the Xinghuo chat model.
8
+ */
9
+ export type XinghuoMessageRole = "assistant" | "user";
10
+ /**
11
+ * Interface representing a message in the Xinghuo chat model.
12
+ */
13
+ interface XinghuoMessage {
14
+ role: XinghuoMessageRole;
15
+ content: string;
16
+ }
17
+ /**
18
+ * Interface representing a request for a chat completion.
19
+ */
20
+ interface ChatCompletionRequest {
21
+ messages: XinghuoMessage[];
22
+ temperature?: number;
23
+ max_tokens?: number;
24
+ top_k?: number;
25
+ chat_id?: string;
26
+ }
27
+ export interface ChatCompletionChunk {
28
+ header: {
29
+ code: number;
30
+ message: string;
31
+ sid: string;
32
+ status: number;
33
+ };
34
+ payload: {
35
+ choices: {
36
+ status: number;
37
+ seq: number;
38
+ text: {
39
+ content: string;
40
+ role: XinghuoMessageRole;
41
+ index: number;
42
+ }[];
43
+ };
44
+ usage?: {
45
+ text: {
46
+ question_tokens: number;
47
+ prompt_tokens: number;
48
+ completion_tokens: number;
49
+ total_tokens: number;
50
+ };
51
+ };
52
+ };
53
+ }
54
+ /**
55
+ * Interface representing a response from a chat completion.
56
+ */
57
+ interface ChatCompletionResponse {
58
+ result: string;
59
+ usage?: {
60
+ completion_tokens: number;
61
+ prompt_tokens: number;
62
+ total_tokens: number;
63
+ };
64
+ }
65
+ declare interface IflytekXinghuoChatInput {
66
+ /** Model version to use. Available options are: v1.1, v2.1, v3.1
67
+ * @default "v2.1"
68
+ */
69
+ version: string;
70
+ /**
71
+ * ID of the end-user who made requests.
72
+ */
73
+ userId?: string;
74
+ /**
75
+ * APPID to use when making requests. Defaults to the value of
76
+ * `IFLYTEK_APPID` environment variable.
77
+ */
78
+ iflytekAppid?: string;
79
+ /**
80
+ * API key to use when making requests. Defaults to the value of
81
+ * `IFLYTEK_API_KEY` environment variable.
82
+ */
83
+ iflytekApiKey?: string;
84
+ /**
85
+ * API Secret to use when making requests. Defaults to the value of
86
+ * `IFLYTEK_API_SECRET` environment variable.
87
+ */
88
+ iflytekApiSecret?: string;
89
+ /** Amount of randomness injected into the response. Ranges
90
+ * from 0 to 1 (0 is not included). Use temp closer to 0 for analytical /
91
+ * multiple choice, and temp closer to 1 for creative
92
+ * and generative tasks. Defaults to 0.5.
93
+ */
94
+ temperature?: number;
95
+ max_tokens?: number;
96
+ top_k?: number;
97
+ streaming?: boolean;
98
+ }
99
+ /**
100
+ * Wrapper around IflytekXingHuo large language models that use the Chat endpoint.
101
+ *
102
+ * To use you should have the `IFLYTEK_API_KEY` and `IFLYTEK_API_SECRET` and `IFLYTEK_APPID`
103
+ * environment variable set.
104
+ *
105
+ * @augments BaseChatModel
106
+ * @augments IflytekXinghuoChatInput
107
+ */
108
+ export declare abstract class BaseChatIflytekXinghuo extends BaseChatModel implements IflytekXinghuoChatInput {
109
+ static lc_name(): string;
110
+ get callKeys(): string[];
111
+ get lc_secrets(): {
112
+ [key: string]: string;
113
+ } | undefined;
114
+ get lc_aliases(): {
115
+ [key: string]: string;
116
+ } | undefined;
117
+ lc_serializable: boolean;
118
+ version: string;
119
+ iflytekAppid: string;
120
+ iflytekApiKey: string;
121
+ iflytekApiSecret: string;
122
+ userId?: string;
123
+ apiUrl: string;
124
+ domain: string;
125
+ temperature: number;
126
+ max_tokens: number;
127
+ top_k: number;
128
+ streaming: boolean;
129
+ constructor(fields?: Partial<IflytekXinghuoChatInput> & BaseChatModelParams);
130
+ /**
131
+ * Get the identifying parameters for the model
132
+ */
133
+ identifyingParams(): {
134
+ max_tokens?: number | undefined;
135
+ temperature?: number | undefined;
136
+ top_k?: number | undefined;
137
+ chat_id?: string | undefined;
138
+ streaming: boolean;
139
+ version: string;
140
+ };
141
+ /**
142
+ * Get the parameters used to invoke the model
143
+ */
144
+ invocationParams(): Omit<ChatCompletionRequest, "messages"> & {
145
+ streaming: boolean;
146
+ };
147
+ /**
148
+ * Method that retrieves the auth websocketStream for making requests to the Iflytek Xinghuo API.
149
+ * @returns The auth websocketStream for making requests to the Iflytek Xinghuo API.
150
+ */
151
+ abstract openWebSocketStream<T extends BaseWebSocketStream<string>>(options: WebSocketStreamOptions): Promise<T>;
152
+ /**
153
+ * Calls the Xinghuo API completion.
154
+ * @param request The request to send to the Xinghuo API.
155
+ * @param signal The signal for the API call.
156
+ * @returns The response from the Xinghuo API.
157
+ */
158
+ completion(request: ChatCompletionRequest, stream: true, signal?: AbortSignal): Promise<IterableReadableStream<string>>;
159
+ completion(request: ChatCompletionRequest, stream: false, signal?: AbortSignal): Promise<ChatCompletionResponse>;
160
+ _generate(messages: BaseMessage[], options: this["ParsedCallOptions"], runManager?: CallbackManagerForLLMRun | undefined): Promise<ChatResult>;
161
+ /** @ignore */
162
+ _combineLLMOutput(): Record<string, any> | undefined;
163
+ _llmType(): string;
164
+ }
165
+ export {};
@@ -0,0 +1,331 @@
1
+ import { AIMessage, ChatMessage, } from "../../schema/index.js";
2
+ import { getEnvironmentVariable } from "../../util/env.js";
3
+ import { IterableReadableStream } from "../../util/stream.js";
4
+ import { BaseChatModel } from "../base.js";
5
+ /**
6
+ * Function that extracts the custom role of a generic chat message.
7
+ * @param message Chat message from which to extract the custom role.
8
+ * @returns The custom role of the chat message.
9
+ */
10
+ function extractGenericMessageCustomRole(message) {
11
+ if (message.role !== "assistant" && message.role !== "user") {
12
+ console.warn(`Unknown message role: ${message.role}`);
13
+ }
14
+ return message.role;
15
+ }
16
+ /**
17
+ * Function that converts a base message to a Xinghuo message role.
18
+ * @param message Base message to convert.
19
+ * @returns The Xinghuo message role.
20
+ */
21
+ function messageToXinghuoRole(message) {
22
+ const type = message._getType();
23
+ switch (type) {
24
+ case "ai":
25
+ return "assistant";
26
+ case "human":
27
+ return "user";
28
+ case "system":
29
+ throw new Error("System messages should not be here");
30
+ case "function":
31
+ throw new Error("Function messages not supported");
32
+ case "generic": {
33
+ if (!ChatMessage.isInstance(message))
34
+ throw new Error("Invalid generic chat message");
35
+ return extractGenericMessageCustomRole(message);
36
+ }
37
+ default:
38
+ throw new Error(`Unknown message type: ${type}`);
39
+ }
40
+ }
41
+ /**
42
+ * Wrapper around IflytekXingHuo large language models that use the Chat endpoint.
43
+ *
44
+ * To use you should have the `IFLYTEK_API_KEY` and `IFLYTEK_API_SECRET` and `IFLYTEK_APPID`
45
+ * environment variable set.
46
+ *
47
+ * @augments BaseChatModel
48
+ * @augments IflytekXinghuoChatInput
49
+ */
50
+ export class BaseChatIflytekXinghuo extends BaseChatModel {
51
+ static lc_name() {
52
+ return "ChatIflytekXinghuo";
53
+ }
54
+ get callKeys() {
55
+ return ["stop", "signal", "options"];
56
+ }
57
+ get lc_secrets() {
58
+ return {
59
+ iflytekApiKey: "IFLYTEK_API_KEY",
60
+ iflytekApiSecret: "IFLYTEK_API_SECRET",
61
+ };
62
+ }
63
+ get lc_aliases() {
64
+ return undefined;
65
+ }
66
+ constructor(fields) {
67
+ super(fields ?? {});
68
+ Object.defineProperty(this, "lc_serializable", {
69
+ enumerable: true,
70
+ configurable: true,
71
+ writable: true,
72
+ value: true
73
+ });
74
+ Object.defineProperty(this, "version", {
75
+ enumerable: true,
76
+ configurable: true,
77
+ writable: true,
78
+ value: "v2.1"
79
+ });
80
+ Object.defineProperty(this, "iflytekAppid", {
81
+ enumerable: true,
82
+ configurable: true,
83
+ writable: true,
84
+ value: void 0
85
+ });
86
+ Object.defineProperty(this, "iflytekApiKey", {
87
+ enumerable: true,
88
+ configurable: true,
89
+ writable: true,
90
+ value: void 0
91
+ });
92
+ Object.defineProperty(this, "iflytekApiSecret", {
93
+ enumerable: true,
94
+ configurable: true,
95
+ writable: true,
96
+ value: void 0
97
+ });
98
+ Object.defineProperty(this, "userId", {
99
+ enumerable: true,
100
+ configurable: true,
101
+ writable: true,
102
+ value: void 0
103
+ });
104
+ Object.defineProperty(this, "apiUrl", {
105
+ enumerable: true,
106
+ configurable: true,
107
+ writable: true,
108
+ value: void 0
109
+ });
110
+ Object.defineProperty(this, "domain", {
111
+ enumerable: true,
112
+ configurable: true,
113
+ writable: true,
114
+ value: void 0
115
+ });
116
+ Object.defineProperty(this, "temperature", {
117
+ enumerable: true,
118
+ configurable: true,
119
+ writable: true,
120
+ value: 0.5
121
+ });
122
+ Object.defineProperty(this, "max_tokens", {
123
+ enumerable: true,
124
+ configurable: true,
125
+ writable: true,
126
+ value: 2048
127
+ });
128
+ Object.defineProperty(this, "top_k", {
129
+ enumerable: true,
130
+ configurable: true,
131
+ writable: true,
132
+ value: 4
133
+ });
134
+ Object.defineProperty(this, "streaming", {
135
+ enumerable: true,
136
+ configurable: true,
137
+ writable: true,
138
+ value: false
139
+ });
140
+ const iflytekAppid = fields?.iflytekAppid ?? getEnvironmentVariable("IFLYTEK_APPID");
141
+ if (!iflytekAppid) {
142
+ throw new Error("Iflytek APPID not found");
143
+ }
144
+ else {
145
+ this.iflytekAppid = iflytekAppid;
146
+ }
147
+ const iflytekApiKey = fields?.iflytekApiKey ?? getEnvironmentVariable("IFLYTEK_API_KEY");
148
+ if (!iflytekApiKey) {
149
+ throw new Error("Iflytek API key not found");
150
+ }
151
+ else {
152
+ this.iflytekApiKey = iflytekApiKey;
153
+ }
154
+ const iflytekApiSecret = fields?.iflytekApiSecret ?? getEnvironmentVariable("IFLYTEK_API_SECRET");
155
+ if (!iflytekApiSecret) {
156
+ throw new Error("Iflytek API secret not found");
157
+ }
158
+ else {
159
+ this.iflytekApiSecret = iflytekApiSecret;
160
+ }
161
+ this.userId = fields?.userId ?? this.userId;
162
+ this.streaming = fields?.streaming ?? this.streaming;
163
+ this.temperature = fields?.temperature ?? this.temperature;
164
+ this.max_tokens = fields?.max_tokens ?? this.max_tokens;
165
+ this.top_k = fields?.top_k ?? this.top_k;
166
+ this.version = fields?.version ?? this.version;
167
+ if (["v1.1", "v2.1", "v3.1"].includes(this.version)) {
168
+ switch (this.version) {
169
+ case "v1.1":
170
+ this.domain = "general";
171
+ break;
172
+ case "v2.1":
173
+ this.domain = "generalv2";
174
+ break;
175
+ case "v3.1":
176
+ this.domain = "generalv3";
177
+ break;
178
+ default:
179
+ this.domain = "generalv2";
180
+ }
181
+ this.apiUrl = `wss://spark-api.xf-yun.com/${this.version}/chat`;
182
+ }
183
+ else {
184
+ throw new Error(`Invalid model version: ${this.version}`);
185
+ }
186
+ }
187
+ /**
188
+ * Get the identifying parameters for the model
189
+ */
190
+ identifyingParams() {
191
+ return {
192
+ version: this.version,
193
+ ...this.invocationParams(),
194
+ };
195
+ }
196
+ /**
197
+ * Get the parameters used to invoke the model
198
+ */
199
+ invocationParams() {
200
+ return {
201
+ streaming: this.streaming,
202
+ temperature: this.temperature,
203
+ top_k: this.top_k,
204
+ };
205
+ }
206
+ async completion(request, stream, signal) {
207
+ const webSocketStream = await this.openWebSocketStream({
208
+ signal,
209
+ });
210
+ const connection = await webSocketStream.connection;
211
+ const header = {
212
+ app_id: this.iflytekAppid,
213
+ uid: this.userId,
214
+ };
215
+ const parameter = {
216
+ chat: {
217
+ domain: this.domain,
218
+ temperature: request.temperature ?? this.temperature,
219
+ max_tokens: request.max_tokens ?? this.max_tokens,
220
+ top_k: request.top_k ?? this.top_k,
221
+ },
222
+ };
223
+ const payload = {
224
+ message: {
225
+ text: request.messages,
226
+ },
227
+ };
228
+ const message = JSON.stringify({
229
+ header,
230
+ parameter,
231
+ payload,
232
+ });
233
+ const { writable, readable } = connection;
234
+ const writer = writable.getWriter();
235
+ await writer.write(message);
236
+ const streams = IterableReadableStream.fromReadableStream(readable);
237
+ if (stream) {
238
+ return streams;
239
+ }
240
+ else {
241
+ let response = { result: "" };
242
+ for await (const chunk of streams) {
243
+ const data = JSON.parse(chunk);
244
+ const { header, payload } = data;
245
+ if (header.code === 0) {
246
+ if (header.status === 0) {
247
+ response.result = payload.choices?.text[0]?.content ?? "";
248
+ }
249
+ else if (header.status === 1) {
250
+ response.result += payload.choices?.text[0]?.content ?? "";
251
+ }
252
+ else if (header.status === 2) {
253
+ response = { ...response, usage: payload.usage?.text };
254
+ break;
255
+ }
256
+ }
257
+ else {
258
+ break;
259
+ }
260
+ }
261
+ void streams.cancel();
262
+ void webSocketStream.close();
263
+ return response;
264
+ }
265
+ }
266
+ async _generate(messages, options, runManager) {
267
+ const tokenUsage = {};
268
+ const params = this.invocationParams();
269
+ const messagesMapped = messages.map((message) => ({
270
+ role: messageToXinghuoRole(message),
271
+ content: message.content,
272
+ }));
273
+ const data = params.streaming
274
+ ? await (async () => {
275
+ const streams = await this.completion({ messages: messagesMapped, ...params }, true, options.signal);
276
+ let response = { result: "" };
277
+ for await (const chunk of streams) {
278
+ const data = JSON.parse(chunk);
279
+ const { header, payload } = data;
280
+ if (header.code === 0) {
281
+ if (header.status === 0) {
282
+ response.result = payload.choices?.text[0]?.content ?? "";
283
+ }
284
+ else if (header.status === 1) {
285
+ response.result += payload.choices?.text[0]?.content ?? "";
286
+ }
287
+ else if (header.status === 2) {
288
+ response = { ...response, usage: payload.usage?.text };
289
+ break;
290
+ }
291
+ void runManager?.handleLLMNewToken(payload.choices?.text[0]?.content);
292
+ }
293
+ else {
294
+ break;
295
+ }
296
+ }
297
+ void streams.cancel();
298
+ return response;
299
+ })()
300
+ : await this.completion({ messages: messagesMapped, ...params }, false, options.signal);
301
+ const { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens, } = data.usage ?? {};
302
+ if (completionTokens) {
303
+ tokenUsage.completionTokens =
304
+ (tokenUsage.completionTokens ?? 0) + completionTokens;
305
+ }
306
+ if (promptTokens) {
307
+ tokenUsage.promptTokens = (tokenUsage.promptTokens ?? 0) + promptTokens;
308
+ }
309
+ if (totalTokens) {
310
+ tokenUsage.totalTokens = (tokenUsage.totalTokens ?? 0) + totalTokens;
311
+ }
312
+ const generations = [];
313
+ const text = data.result ?? "";
314
+ generations.push({
315
+ text,
316
+ message: new AIMessage(text),
317
+ });
318
+ return {
319
+ generations,
320
+ llmOutput: { tokenUsage },
321
+ };
322
+ }
323
+ /** @ignore */
324
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
325
+ _combineLLMOutput() {
326
+ return [];
327
+ }
328
+ _llmType() {
329
+ return "iflytek_xinghuo";
330
+ }
331
+ }
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ChatIflytekXinghuo = void 0;
7
+ const ws_1 = __importDefault(require("ws"));
8
+ const common_js_1 = require("./common.cjs");
9
+ const iflytek_websocket_stream_js_1 = require("../../util/iflytek_websocket_stream.cjs");
10
+ class WebSocketStream extends iflytek_websocket_stream_js_1.BaseWebSocketStream {
11
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
12
+ // @ts-ignore
13
+ openWebSocket(url, options) {
14
+ return new ws_1.default(url, options.protocols ?? []);
15
+ }
16
+ }
17
+ class ChatIflytekXinghuo extends common_js_1.BaseChatIflytekXinghuo {
18
+ async openWebSocketStream(options) {
19
+ const host = "spark-api.xf-yun.com";
20
+ const date = new Date().toUTCString();
21
+ const url = `GET /${this.version}/chat HTTP/1.1`;
22
+ const { createHmac } = await import("crypto");
23
+ const hash = createHmac("sha256", this.iflytekApiSecret)
24
+ .update(`host: ${host}\ndate: ${date}\n${url}`)
25
+ .digest("base64");
26
+ const authorization_origin = `api_key="${this.iflytekApiKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${hash}"`;
27
+ const authorization = Buffer.from(authorization_origin).toString("base64");
28
+ let authWebSocketUrl = this.apiUrl;
29
+ authWebSocketUrl += `?authorization=${authorization}`;
30
+ authWebSocketUrl += `&host=${encodeURIComponent(host)}`;
31
+ authWebSocketUrl += `&date=${encodeURIComponent(date)}`;
32
+ return new WebSocketStream(authWebSocketUrl, options);
33
+ }
34
+ }
35
+ exports.ChatIflytekXinghuo = ChatIflytekXinghuo;
@@ -0,0 +1,5 @@
1
+ import { BaseChatIflytekXinghuo } from "./common.js";
2
+ import { WebSocketStreamOptions } from "../../util/iflytek_websocket_stream.js";
3
+ export declare class ChatIflytekXinghuo extends BaseChatIflytekXinghuo {
4
+ openWebSocketStream<WebSocketStream>(options: WebSocketStreamOptions): Promise<WebSocketStream>;
5
+ }
@@ -0,0 +1,28 @@
1
+ import WebSocket from "ws";
2
+ import { BaseChatIflytekXinghuo } from "./common.js";
3
+ import { BaseWebSocketStream, } from "../../util/iflytek_websocket_stream.js";
4
+ class WebSocketStream extends BaseWebSocketStream {
5
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
6
+ // @ts-ignore
7
+ openWebSocket(url, options) {
8
+ return new WebSocket(url, options.protocols ?? []);
9
+ }
10
+ }
11
+ export class ChatIflytekXinghuo extends BaseChatIflytekXinghuo {
12
+ async openWebSocketStream(options) {
13
+ const host = "spark-api.xf-yun.com";
14
+ const date = new Date().toUTCString();
15
+ const url = `GET /${this.version}/chat HTTP/1.1`;
16
+ const { createHmac } = await import("crypto");
17
+ const hash = createHmac("sha256", this.iflytekApiSecret)
18
+ .update(`host: ${host}\ndate: ${date}\n${url}`)
19
+ .digest("base64");
20
+ const authorization_origin = `api_key="${this.iflytekApiKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${hash}"`;
21
+ const authorization = Buffer.from(authorization_origin).toString("base64");
22
+ let authWebSocketUrl = this.apiUrl;
23
+ authWebSocketUrl += `?authorization=${authorization}`;
24
+ authWebSocketUrl += `&host=${encodeURIComponent(host)}`;
25
+ authWebSocketUrl += `&date=${encodeURIComponent(date)}`;
26
+ return new WebSocketStream(authWebSocketUrl, options);
27
+ }
28
+ }
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ChatIflytekXinghuo = void 0;
4
+ const common_js_1 = require("./common.cjs");
5
+ const iflytek_websocket_stream_js_1 = require("../../util/iflytek_websocket_stream.cjs");
6
+ class WebSocketStream extends iflytek_websocket_stream_js_1.BaseWebSocketStream {
7
+ openWebSocket(url, options) {
8
+ return new WebSocket(url, options.protocols ?? []);
9
+ }
10
+ }
11
+ class ChatIflytekXinghuo extends common_js_1.BaseChatIflytekXinghuo {
12
+ async openWebSocketStream(options) {
13
+ const host = "spark-api.xf-yun.com";
14
+ const date = new Date().toUTCString();
15
+ const url = `GET /${this.version}/chat HTTP/1.1`;
16
+ const keyBuffer = new TextEncoder().encode(this.iflytekApiSecret);
17
+ const dataBuffer = new TextEncoder().encode(`host: ${host}\ndate: ${date}\n${url}`);
18
+ const cryptoKey = await crypto.subtle.importKey("raw", keyBuffer, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
19
+ const signature = await crypto.subtle.sign("HMAC", cryptoKey, dataBuffer);
20
+ const hash = window.btoa(String.fromCharCode(...new Uint8Array(signature)));
21
+ const authorization_origin = `api_key="${this.iflytekApiKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${hash}"`;
22
+ const authorization = window.btoa(authorization_origin);
23
+ let authWebSocketUrl = this.apiUrl;
24
+ authWebSocketUrl += `?authorization=${authorization}`;
25
+ authWebSocketUrl += `&host=${encodeURIComponent(host)}`;
26
+ authWebSocketUrl += `&date=${encodeURIComponent(date)}`;
27
+ return new WebSocketStream(authWebSocketUrl, options);
28
+ }
29
+ }
30
+ exports.ChatIflytekXinghuo = ChatIflytekXinghuo;
@@ -0,0 +1,5 @@
1
+ import { BaseChatIflytekXinghuo } from "./common.js";
2
+ import { WebSocketStreamOptions } from "../../util/iflytek_websocket_stream.js";
3
+ export declare class ChatIflytekXinghuo extends BaseChatIflytekXinghuo {
4
+ openWebSocketStream<WebSocketStream>(options: WebSocketStreamOptions): Promise<WebSocketStream>;
5
+ }
@@ -0,0 +1,26 @@
1
+ import { BaseChatIflytekXinghuo } from "./common.js";
2
+ import { BaseWebSocketStream, } from "../../util/iflytek_websocket_stream.js";
3
+ class WebSocketStream extends BaseWebSocketStream {
4
+ openWebSocket(url, options) {
5
+ return new WebSocket(url, options.protocols ?? []);
6
+ }
7
+ }
8
+ export class ChatIflytekXinghuo extends BaseChatIflytekXinghuo {
9
+ async openWebSocketStream(options) {
10
+ const host = "spark-api.xf-yun.com";
11
+ const date = new Date().toUTCString();
12
+ const url = `GET /${this.version}/chat HTTP/1.1`;
13
+ const keyBuffer = new TextEncoder().encode(this.iflytekApiSecret);
14
+ const dataBuffer = new TextEncoder().encode(`host: ${host}\ndate: ${date}\n${url}`);
15
+ const cryptoKey = await crypto.subtle.importKey("raw", keyBuffer, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
16
+ const signature = await crypto.subtle.sign("HMAC", cryptoKey, dataBuffer);
17
+ const hash = window.btoa(String.fromCharCode(...new Uint8Array(signature)));
18
+ const authorization_origin = `api_key="${this.iflytekApiKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${hash}"`;
19
+ const authorization = window.btoa(authorization_origin);
20
+ let authWebSocketUrl = this.apiUrl;
21
+ authWebSocketUrl += `?authorization=${authorization}`;
22
+ authWebSocketUrl += `&host=${encodeURIComponent(host)}`;
23
+ authWebSocketUrl += `&date=${encodeURIComponent(date)}`;
24
+ return new WebSocketStream(authWebSocketUrl, options);
25
+ }
26
+ }