Spaces:
Running
Running
File size: 4,536 Bytes
009fd18 | 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 | import type {
ConversationTurn,
LLMAdapter,
LLMGenerateOptions,
RuntimeWarmupOptions,
} from "../app/types";
import { SYSTEM_PROMPT } from "../prompts/system";
type ChatMessage = {
role: "system" | "user" | "assistant";
content: string;
};
type WebLLMModule = typeof import("@mlc-ai/web-llm");
type EngineType = Awaited<ReturnType<WebLLMModule["CreateMLCEngine"]>>;
type InitProgress = {
progress?: number;
text?: string;
timeElapsed?: number;
};
const MODEL_PREFERENCES = [
"Qwen2.5-0.5B-Instruct-q4f16_1-MLC",
"SmolLM2-360M-Instruct-q4f16_1-MLC",
"Llama-3.2-1B-Instruct-q4f16_1-MLC",
"Qwen2.5-1.5B-Instruct-q4f16_1-MLC",
];
const formatProgress = (progress: InitProgress): string => {
const percentage =
typeof progress.progress === "number"
? `${Math.round(progress.progress * 100)}%`
: null;
if (progress.text && percentage) {
return `${progress.text} (${percentage})`;
}
if (progress.text) {
return progress.text;
}
if (percentage) {
return `Loading language model (${percentage})`;
}
return "Loading language model...";
};
export class WebLLMChatAdapter implements LLMAdapter {
#engine: EngineType | null = null;
#modelId: string | null = null;
constructor(private readonly preferredModelId?: string) {}
async initialize(options: RuntimeWarmupOptions = {}): Promise<void> {
if (this.#engine) {
options.onProgress?.(
`Language ready (${this.#modelId ?? this.preferredModelId ?? "model loaded"}).`,
);
return;
}
const webllm = await import("@mlc-ai/web-llm");
const modelId =
this.preferredModelId ?? WebLLMChatAdapter.#resolveModelId(webllm);
options.onProgress?.(`Preparing ${modelId}...`);
this.#engine = await webllm.CreateMLCEngine(modelId, {
initProgressCallback: (progress: InitProgress) => {
options.onProgress?.(formatProgress(progress));
},
});
this.#modelId = modelId;
options.onProgress?.(`Language ready (${modelId}).`);
}
async generate(options: LLMGenerateOptions): Promise<string> {
await this.initialize();
if (!this.#engine) {
throw new Error("LLM engine failed to initialize.");
}
const messages = WebLLMChatAdapter.#toMessages(options.turns);
const stream = await this.#engine.chat.completions.create({
messages,
temperature: 0.7,
stream: true,
});
let finalText = "";
for await (const chunk of stream) {
if (options.signal?.aborted) {
break;
}
const delta = chunk.choices[0]?.delta?.content ?? "";
if (!delta) {
continue;
}
finalText += delta;
options.onChunk(delta);
}
return finalText.trim();
}
async warmup(options: RuntimeWarmupOptions = {}): Promise<void> {
await this.initialize(options);
if (!this.#engine) {
throw new Error("LLM engine failed to initialize.");
}
options.onProgress?.("Compiling first language response...");
await this.#engine.chat.completions.create({
messages: [
{
role: "system",
content: SYSTEM_PROMPT,
},
{
role: "user",
content: "Reply with one short word.",
},
],
temperature: 0,
max_tokens: 1,
});
options.onProgress?.("Language runtime warmed.");
}
static #toMessages(turns: ConversationTurn[]): ChatMessage[] {
const messages: ChatMessage[] = [
{
role: "system",
content: SYSTEM_PROMPT,
},
];
for (const turn of turns) {
if (turn.role === "system" || !turn.transcript.trim()) {
continue;
}
messages.push({
role: turn.role,
content: turn.transcript,
});
}
return messages;
}
static #resolveModelId(webllm: WebLLMModule): string {
const candidates = webllm.prebuiltAppConfig?.model_list ?? [];
const normalized = candidates
.map((candidate) => {
const modelId = "model_id" in candidate ? candidate.model_id : "";
return { candidate, modelId };
})
.filter((entry) => Boolean(entry.modelId));
for (const preference of MODEL_PREFERENCES) {
const match = normalized.find((entry) =>
entry.modelId.includes(preference),
);
if (match) {
return match.modelId;
}
}
const fallback = normalized.at(0)?.modelId;
if (!fallback) {
throw new Error("WebLLM did not expose any prebuilt models.");
}
return fallback;
}
}
|