Spaces:
Sleeping
Sleeping
File size: 6,469 Bytes
de36cdc 64682dd de36cdc |
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 |
import { env } from "$env/dynamic/private";
import type {
Endpoint,
EndpointMessage,
TextGenerationStreamOutputWithToolsAndWebSources,
} from "../endpoints";
import { z } from "zod";
import {
createImageProcessorOptionsValidator,
makeImageProcessor,
type ImageProcessor,
} from "../images";
import { LlamaChatSession, LlamaContextSequence, resolveModelFile } from "node-llama-cpp";
import { findRepoRoot } from "$lib/server/findRepoRoot";
import { fileURLToPath } from "url";
import { dirname, join } from "path";
import { logger } from "$lib/server/logger";
import { llama } from "./utilsLocal";
export const endpointLocalParametersSchema = z.object({
weight: z.number().int().positive().default(1),
model: z.any(),
modelPath: z.string().optional(),
type: z.literal("local"),
multimodal: z
.object({
// Assumes IDEFICS
image: createImageProcessorOptionsValidator({
supportedMimeTypes: ["image/jpeg", "image/webp"],
preferredMimeType: "image/webp",
maxSizeInMB: 5,
maxWidth: 378,
maxHeight: 980,
}),
})
.default({}),
});
export async function endpointLocal(
input: z.input<typeof endpointLocalParametersSchema>
): Promise<Endpoint> {
// Parse and validate input
const {
modelPath: modelPathInput,
multimodal,
model,
} = endpointLocalParametersSchema.parse(input);
// Setup model path and folder
const path = modelPathInput ?? `hf:${model.id ?? model.name}`;
const modelFolder =
env.MODELS_STORAGE_PATH ||
join(findRepoRoot(dirname(fileURLToPath(import.meta.url))), "models");
// Initialize Llama model
const modelPath = await resolveModelFile(path, modelFolder);
if (!llama) {
throw new Error("Failed to initialize llama.cpp build.");
}
const modelLoaded = await llama.loadModel({
modelPath,
});
// Create context and image processor
const context = await modelLoaded.createContext({ sequences: 1 });
const imageProcessor = makeImageProcessor(multimodal.image);
return async function ({
messages,
preprompt,
continueMessage,
generateSettings,
// tools,
// toolResults,
isMultimodal,
}) {
// Process messages and build prompt
const processedMessages = await Promise.all(
messages.map((msg) => prepareMessage(Boolean(isMultimodal), msg, imageProcessor))
);
let sequence: LlamaContextSequence;
try {
sequence = context.getSequence();
} catch (error) {
logger.error(error, `Error getting sequence`);
throw error;
}
const chatSession = new LlamaChatSession({
contextSequence: sequence,
systemPrompt: preprompt,
});
chatSession.setChatHistory(
messages.slice(0, -1).map((message) => {
switch (message.from) {
case "user":
return {
type: "user",
text: message.content,
};
case "assistant":
return {
type: "model",
response: [message.content],
};
case "system":
return {
type: "system",
text: message.content,
};
}
})
);
async function* generateTokens(): AsyncGenerator<TextGenerationStreamOutputWithToolsAndWebSources> {
let tokenId = 0;
let fullText = "";
// A simple queue for tokens that have been produced
const queue: TextGenerationStreamOutputWithToolsAndWebSources[] = [];
let waitingResolve:
| ((value: TextGenerationStreamOutputWithToolsAndWebSources | null) => void)
| null = null;
let generationCompleted = false;
// Helper function to push tokens to the queue
function pushOutput(output: TextGenerationStreamOutputWithToolsAndWebSources) {
if (waitingResolve) {
waitingResolve(output);
waitingResolve = null;
} else {
queue.push(output);
}
}
const options = {
maxTokens: generateSettings?.max_new_tokens,
temperature: generateSettings?.temperature ?? 0.2,
topP: generateSettings?.top_p ?? 0.9,
topK: generateSettings?.top_k ?? 40,
onTextChunk: (text: string) => {
fullText += text;
const output: TextGenerationStreamOutputWithToolsAndWebSources = {
token: {
id: tokenId++,
text,
logprob: 0,
special: false,
},
generated_text: null,
details: null,
};
// Instead of returning the token, push it into our queue.
pushOutput(output);
},
};
let generationPromise;
if (!continueMessage)
// Start the token generation process
generationPromise = chatSession.prompt(
processedMessages[processedMessages.length - 1].content,
options
);
else {
generationPromise = chatSession.completePrompt(
processedMessages[processedMessages.length - 1].content,
options
);
}
try {
// Yield tokens as they become available
while (!generationCompleted || queue.length > 0) {
if (queue.length === 0) {
const output =
await new Promise<TextGenerationStreamOutputWithToolsAndWebSources | null>(
(resolve) => (waitingResolve = resolve)
);
// When output is null, it indicates generation completion.
if (output === null || !output.token.text) break;
if (model.parameters.stop_sequences?.includes(output.token.text)) {
break;
}
yield output;
} else {
const output = queue.shift();
if (output) yield output;
}
}
// Wait for the generation process to complete (and catch errors if any)
await generationPromise.finally(() => {
generationCompleted = true;
// Resolve any pending waiters so the loop can end.
if (waitingResolve) {
waitingResolve(null);
waitingResolve = null;
}
});
// Yield a final token that contains the full generated text.
yield {
token: {
id: tokenId,
text: "",
logprob: 0,
special: true,
},
generated_text: fullText,
details: null,
};
} catch (error) {
logger.error(error, `Generation error`);
// Ensure we clean up the LlamaManager in case of errors
throw error;
}
}
return generateTokens();
};
}
async function prepareMessage(
isMultimodal: boolean,
message: EndpointMessage,
imageProcessor: ImageProcessor
): Promise<EndpointMessage> {
if (!isMultimodal) return message;
const files = await Promise.all(message.files?.map(imageProcessor) ?? []);
const markdowns = files.map(
(file) => `})`
);
const content = message.content + "\n" + markdowns.join("\n ");
return { ...message, content };
}
|