-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
zhipuai.ts
459 lines (402 loc) Β· 11.6 KB
/
zhipuai.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
import {
BaseChatModel,
type BaseChatModelParams,
} from "@langchain/core/language_models/chat_models";
import {
AIMessage,
type BaseMessage,
ChatMessage,
} from "@langchain/core/messages";
import { type ChatResult } from "@langchain/core/outputs";
import { type CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager";
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { encodeApiKey } from "../utils/zhipuai.js";
export type ZhipuMessageRole = "system" | "assistant" | "user";
interface ZhipuMessage {
role: ZhipuMessageRole;
content: string;
}
/**
* Interface representing a request for a chat completion.
*
* See https://open.bigmodel.cn/dev/howuse/model
*/
type ModelName =
| (string & NonNullable<unknown>)
// will be deprecated models
| "chatglm_pro" // deprecated in 2024-12-31T23:59:59+0800οΌpoint to glm-4
| "chatglm_std" // deprecated in 2024-12-31T23:59:59+0800οΌpoint to glm-3-turbo
| "chatglm_lite" // deprecated in 2024-12-31T23:59:59+0800οΌpoint to glm-3-turbo
// GLM-4 more powerful on Q/A and text generation, suitable for complex dialog interactions and deep content creation design.
| "glm-4" // context size: 128k
| "glm-4v" // context size: 2k
// ChatGLM-Turbo
| "glm-3-turbo" // context size: 128k
| "chatglm_turbo"; // context size: 32k
interface ChatCompletionRequest {
model: ModelName;
messages?: ZhipuMessage[];
do_sample?: boolean;
stream?: boolean;
request_id?: string;
max_tokens?: number | null;
top_p?: number | null;
top_k?: number | null;
temperature?: number | null;
stop?: string[];
}
interface BaseResponse {
code?: string;
message?: string;
}
interface ChoiceMessage {
role: string;
content: string;
}
interface ResponseChoice {
index: number;
finish_reason: "stop" | "length" | "null" | null;
delta: ChoiceMessage;
message: ChoiceMessage;
}
/**
* Interface representing a response from a chat completion.
*/
interface ChatCompletionResponse extends BaseResponse {
choices: ResponseChoice[];
created: number;
id: string;
model: string;
request_id: string;
usage: {
completion_tokens: number;
prompt_tokens: number;
total_tokens: number;
};
output: {
text: string;
finish_reason: "stop" | "length" | "null" | null;
};
}
/**
* Interface defining the input to the ZhipuAIChatInput class.
*/
export interface ChatZhipuAIParams {
/**
* @default "glm-3-turbo"
* Alias for `model`
*/
modelName: ModelName;
/**
* @default "glm-3-turbo"
*/
model: ModelName;
/** Whether to stream the results or not. Defaults to false. */
streaming?: boolean;
/** Messages to pass as a prefix to the prompt */
messages?: ZhipuMessage[];
/**
* API key to use when making requests. Defaults to the value of
* `ZHIPUAI_API_KEY` environment variable.
* Alias for `apiKey`
*/
zhipuAIApiKey?: string;
/**
* API key to use when making requests. Defaults to the value of
* `ZHIPUAI_API_KEY` environment variable.
*/
apiKey?: string;
/** Amount of randomness injected into the response. Ranges
* from 0 to 1 (0 is not included). Use temp closer to 0 for analytical /
* multiple choice, and temp closer to 1 for creative
* and generative tasks. Defaults to 0.95
*/
temperature?: number;
/** Total probability mass of tokens to consider at each step. Range
* from 0 to 1 Defaults to 0.7
*/
topP?: number;
/**
* Unique identifier for the request. Defaults to a random UUID.
*/
requestId?: string;
/**
* turn on sampling strategy when do_sample is true,
* do_sample is false, temperatureγtop_p will not take effect
*/
doSample?: boolean;
/**
* max value is 8192οΌdefaults to 1024
*/
maxTokens?: number;
stop?: string[];
}
function messageToRole(message: BaseMessage): ZhipuMessageRole {
const type = message._getType();
switch (type) {
case "ai":
return "assistant";
case "human":
return "user";
case "system":
return "system";
case "function":
throw new Error("Function messages not supported yet");
case "generic": {
if (!ChatMessage.isInstance(message)) {
throw new Error("Invalid generic chat message");
}
if (["system", "assistant", "user"].includes(message.role)) {
return message.role as ZhipuMessageRole;
}
throw new Error(`Unknown message type: ${type}`);
}
default:
throw new Error(`Unknown message type: ${type}`);
}
}
export class ChatZhipuAI extends BaseChatModel implements ChatZhipuAIParams {
static lc_name() {
return "ChatZhipuAI";
}
get callKeys() {
return ["stop", "signal", "options"];
}
get lc_secrets() {
return {
zhipuAIApiKey: "ZHIPUAI_API_KEY",
apiKey: "ZHIPUAI_API_KEY",
};
}
get lc_aliases() {
return undefined;
}
zhipuAIApiKey?: string;
apiKey?: string;
streaming: boolean;
doSample?: boolean;
messages?: ZhipuMessage[];
requestId?: string;
modelName: ChatCompletionRequest["model"];
model: ChatCompletionRequest["model"];
apiUrl: string;
maxTokens?: number | undefined;
temperature?: number | undefined;
topP?: number | undefined;
stop?: string[];
constructor(fields: Partial<ChatZhipuAIParams> & BaseChatModelParams = {}) {
super(fields);
this.zhipuAIApiKey =
fields?.apiKey ??
fields?.zhipuAIApiKey ??
getEnvironmentVariable("ZHIPUAI_API_KEY");
if (!this.zhipuAIApiKey) {
throw new Error("ZhipuAI API key not found");
}
this.apiUrl = "https://open.bigmodel.cn/api/paas/v4/chat/completions";
this.streaming = fields.streaming ?? false;
this.messages = fields.messages ?? [];
this.temperature = fields.temperature ?? 0.95;
this.topP = fields.topP ?? 0.7;
this.stop = fields.stop;
this.maxTokens = fields.maxTokens;
this.modelName = fields?.model ?? fields.modelName ?? "glm-3-turbo";
this.model = this.modelName;
this.doSample = fields.doSample;
}
/**
* Get the parameters used to invoke the model
*/
invocationParams(): Omit<ChatCompletionRequest, "messages"> {
return {
model: this.model,
request_id: this.requestId,
do_sample: this.doSample,
stream: this.streaming,
temperature: this.temperature,
top_p: this.topP,
max_tokens: this.maxTokens,
stop: this.stop,
};
}
/**
* Get the identifying parameters for the model
*/
identifyingParams(): Omit<ChatCompletionRequest, "messages"> {
return this.invocationParams();
}
/** @ignore */
async _generate(
messages: BaseMessage[],
options?: this["ParsedCallOptions"],
runManager?: CallbackManagerForLLMRun
): Promise<ChatResult> {
const parameters = this.invocationParams();
const messagesMapped: ZhipuMessage[] = messages.map((message) => ({
role: messageToRole(message),
content: message.content as string,
}));
const data = parameters.stream
? await new Promise<ChatCompletionResponse>((resolve, reject) => {
let response: ChatCompletionResponse;
let rejected = false;
let resolved = false;
this.completionWithRetry(
{
...parameters,
messages: messagesMapped,
},
true,
options?.signal,
(event) => {
const data: ChatCompletionResponse = JSON.parse(event.data);
if (data?.code) {
if (rejected) {
return;
}
rejected = true;
reject(new Error(data?.message));
return;
}
const { delta, finish_reason } = data.choices[0];
const text = delta.content;
if (!response) {
response = {
...data,
output: { text, finish_reason },
};
} else {
response.output.text += text;
response.output.finish_reason = finish_reason;
response.usage = data.usage;
}
void runManager?.handleLLMNewToken(text ?? "");
if (finish_reason && finish_reason !== "null") {
if (resolved || rejected) return;
resolved = true;
resolve(response);
}
}
).catch((error) => {
if (!rejected) {
rejected = true;
reject(error);
}
});
})
: await this.completionWithRetry(
{
...parameters,
messages: messagesMapped,
},
false,
options?.signal
).then<ChatCompletionResponse>((data) => {
if (data?.code) {
throw new Error(data?.message);
}
const { finish_reason, message } = data.choices[0];
const text = message.content;
return {
...data,
output: { text, finish_reason },
};
});
const {
prompt_tokens = 0,
completion_tokens = 0,
total_tokens = 0,
} = data.usage;
const { text } = data.output;
return {
generations: [
{
text,
message: new AIMessage(text),
},
],
llmOutput: {
tokenUsage: {
promptTokens: prompt_tokens,
completionTokens: completion_tokens,
totalTokens: total_tokens,
},
},
};
}
/** @ignore */
async completionWithRetry(
request: ChatCompletionRequest,
stream: boolean,
signal?: AbortSignal,
onmessage?: (event: MessageEvent) => void
) {
const makeCompletionRequest = async () => {
const response = await fetch(this.apiUrl, {
method: "POST",
headers: {
...(stream ? { Accept: "text/event-stream" } : {}),
Authorization: `Bearer ${encodeApiKey(this.zhipuAIApiKey)}`,
"Content-Type": "application/json",
},
body: JSON.stringify(request),
signal,
});
if (!stream) {
return response.json();
}
if (response.body) {
// response will not be a stream if an error occurred
if (
!response.headers.get("content-type")?.startsWith("text/event-stream")
) {
onmessage?.(
new MessageEvent("message", {
data: await response.text(),
})
);
return;
}
const reader = response.body.getReader();
const decoder = new TextDecoder("utf-8");
let data = "";
let continueReading = true;
while (continueReading) {
const { done, value } = await reader.read();
if (done) {
continueReading = false;
break;
}
data += decoder.decode(value);
let continueProcessing = true;
while (continueProcessing) {
const newlineIndex = data.indexOf("\n");
if (newlineIndex === -1) {
continueProcessing = false;
break;
}
const line = data.slice(0, newlineIndex);
data = data.slice(newlineIndex + 1);
if (line.startsWith("data:")) {
const value = line.slice("data:".length).trim();
if (value === "[DONE]") {
continueReading = false;
break;
}
const event = new MessageEvent("message", { data: value });
onmessage?.(event);
}
}
}
}
};
return this.caller.call(makeCompletionRequest);
}
_llmType(): string {
return "zhipuai";
}
/** @ignore */
_combineLLMOutput() {
return [];
}
}