-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Copy pathwebllm.ts
156 lines (140 loc) Β· 4.39 KB
/
webllm.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
import {
SimpleChatModel,
type BaseChatModelParams,
} from "@langchain/core/language_models/chat_models";
import type { BaseLanguageModelCallOptions } from "@langchain/core/language_models/base";
import { CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager";
import { BaseMessage, AIMessageChunk } from "@langchain/core/messages";
import { ChatGenerationChunk } from "@langchain/core/outputs";
import * as webllm from "@mlc-ai/web-llm";
import { ChatCompletionMessageParam } from "@mlc-ai/web-llm/lib/openai_api_protocols";
export interface WebLLMInputs extends BaseChatModelParams {
appConfig?: webllm.AppConfig;
chatOptions?: webllm.ChatOptions;
temperature?: number;
model: string;
}
export interface WebLLMCallOptions extends BaseLanguageModelCallOptions {}
/**
* To use this model you need to have the `@mlc-ai/web-llm` module installed.
* This can be installed using `npm install -S @mlc-ai/web-llm`.
*
* You can see a list of available model records here:
* https://github.com/mlc-ai/web-llm/blob/main/src/config.ts
* @example
* ```typescript
* // Initialize the ChatWebLLM model with the model record.
* const model = new ChatWebLLM({
* model: "Phi-3-mini-4k-instruct-q4f16_1-MLC",
* chatOptions: {
* temperature: 0.5,
* },
* });
*
* // Call the model with a message and await the response.
* const response = await model.invoke([
* new HumanMessage({ content: "My name is John." }),
* ]);
* ```
*/
export class ChatWebLLM extends SimpleChatModel<WebLLMCallOptions> {
static inputs: WebLLMInputs;
protected engine: webllm.MLCEngine;
appConfig?: webllm.AppConfig;
chatOptions?: webllm.ChatOptions;
temperature?: number;
model: string;
static lc_name() {
return "ChatWebLLM";
}
constructor(inputs: WebLLMInputs) {
super(inputs);
this.appConfig = inputs.appConfig;
this.chatOptions = inputs.chatOptions;
this.model = inputs.model;
this.temperature = inputs.temperature;
this.engine = new webllm.MLCEngine({
appConfig: this.appConfig,
});
}
_llmType() {
return "web-llm";
}
async initialize(progressCallback?: webllm.InitProgressCallback) {
if (progressCallback !== undefined) {
this.engine.setInitProgressCallback(progressCallback);
}
await this.reload(this.model, this.chatOptions);
}
async reload(modelId: string, newChatOpts?: webllm.ChatOptions) {
await this.engine.reload(modelId, newChatOpts);
}
async *_streamResponseChunks(
messages: BaseMessage[],
options: this["ParsedCallOptions"],
runManager?: CallbackManagerForLLMRun
): AsyncGenerator<ChatGenerationChunk> {
const messagesInput: ChatCompletionMessageParam[] = messages.map(
(message) => {
if (typeof message.content !== "string") {
throw new Error(
"ChatWebLLM does not support non-string message content in sessions."
);
}
const langChainType = message._getType();
let role;
if (langChainType === "ai") {
role = "assistant" as const;
} else if (langChainType === "human") {
role = "user" as const;
} else if (langChainType === "system") {
role = "system" as const;
} else {
throw new Error(
"Function, tool, and generic messages are not supported."
);
}
return {
role,
content: message.content,
};
}
);
const stream = await this.engine.chat.completions.create({
stream: true,
messages: messagesInput,
stop: options.stop,
logprobs: true,
});
for await (const chunk of stream) {
// Last chunk has undefined content
const text = chunk.choices[0].delta.content ?? "";
yield new ChatGenerationChunk({
text,
message: new AIMessageChunk({
content: text,
additional_kwargs: {
logprobs: chunk.choices[0].logprobs,
finish_reason: chunk.choices[0].finish_reason,
},
}),
});
await runManager?.handleLLMNewToken(text);
}
}
async _call(
messages: BaseMessage[],
options: this["ParsedCallOptions"],
runManager?: CallbackManagerForLLMRun
): Promise<string> {
const chunks = [];
for await (const chunk of this._streamResponseChunks(
messages,
options,
runManager
)) {
chunks.push(chunk.text);
}
return chunks.join("");
}
}