Datasets:
File size: 4,594 Bytes
8d88d9b |
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 |
import { GoogleGenerativeAI, HarmBlockThreshold, HarmCategory } from "@google/generative-ai";
import type { Content, Part, SafetySetting, TextPart } from "@google/generative-ai";
import { z } from "zod";
import type { Message, MessageFile } from "$lib/types/Message";
import type { TextGenerationStreamOutput } from "@huggingface/inference";
import type { Endpoint } from "../endpoints";
import { createImageProcessorOptionsValidator, makeImageProcessor } from "../images";
import type { ImageProcessorOptions } from "../images";
import { env } from "$env/dynamic/private";
export const endpointGenAIParametersSchema = z.object({
weight: z.number().int().positive().default(1),
model: z.any(),
type: z.literal("genai"),
apiKey: z.string().default(env.GOOGLE_GENAI_API_KEY),
safetyThreshold: z
.enum([
HarmBlockThreshold.HARM_BLOCK_THRESHOLD_UNSPECIFIED,
HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
HarmBlockThreshold.BLOCK_NONE,
HarmBlockThreshold.BLOCK_ONLY_HIGH,
])
.optional(),
multimodal: z
.object({
image: createImageProcessorOptionsValidator({
supportedMimeTypes: ["image/png", "image/jpeg", "image/webp"],
preferredMimeType: "image/webp",
// The 4 / 3 compensates for the 33% increase in size when converting to base64
maxSizeInMB: (5 / 4) * 3,
maxWidth: 4096,
maxHeight: 4096,
}),
})
.default({}),
});
export function endpointGenAI(input: z.input<typeof endpointGenAIParametersSchema>): Endpoint {
const { model, apiKey, safetyThreshold, multimodal } = endpointGenAIParametersSchema.parse(input);
const genAI = new GoogleGenerativeAI(apiKey);
const safetySettings = safetyThreshold
? Object.keys(HarmCategory)
.filter((cat) => cat !== HarmCategory.HARM_CATEGORY_UNSPECIFIED)
.reduce((acc, val) => {
acc.push({
category: val as HarmCategory,
threshold: safetyThreshold,
});
return acc;
}, [] as SafetySetting[])
: undefined;
return async ({ messages, preprompt, generateSettings }) => {
const parameters = { ...model.parameters, ...generateSettings };
const generativeModel = genAI.getGenerativeModel({
model: model.id ?? model.name,
safetySettings,
generationConfig: {
maxOutputTokens: parameters?.max_new_tokens ?? 4096,
stopSequences: parameters?.stop,
temperature: parameters?.temperature ?? 1,
},
});
let systemMessage = preprompt;
if (messages[0].from === "system") {
systemMessage = messages[0].content;
messages.shift();
}
const genAIMessages = await Promise.all(
messages.map(async ({ from, content, files }: Omit<Message, "id">): Promise<Content> => {
return {
role: from === "user" ? "user" : "model",
parts: [
...(await Promise.all(
(files ?? []).map((file) => fileToImageBlock(file, multimodal.image))
)),
{ text: content },
],
};
})
);
const result = await generativeModel.generateContentStream({
contents: genAIMessages,
systemInstruction:
systemMessage && systemMessage.trim() !== ""
? {
role: "system",
parts: [{ text: systemMessage }],
}
: undefined,
});
let tokenId = 0;
return (async function* () {
let generatedText = "";
for await (const data of result.stream) {
if (!data?.candidates?.length) break; // Handle case where no candidates are present
const candidate = data.candidates[0];
if (!candidate.content?.parts?.length) continue; // Skip if no parts are present
const firstPart = candidate.content.parts.find((part) => "text" in part) as
| TextPart
| undefined;
if (!firstPart) continue; // Skip if no text part is found
const content = firstPart.text;
generatedText += content;
const output: TextGenerationStreamOutput = {
token: {
id: tokenId++,
text: content,
logprob: 0,
special: false,
},
generated_text: null,
details: null,
};
yield output;
}
const output: TextGenerationStreamOutput = {
token: {
id: tokenId++,
text: "",
logprob: 0,
special: true,
},
generated_text: generatedText,
details: null,
};
yield output;
})();
};
}
async function fileToImageBlock(
file: MessageFile,
opts: ImageProcessorOptions<"image/png" | "image/jpeg" | "image/webp">
): Promise<Part> {
const processor = makeImageProcessor(opts);
const { image, mime } = await processor(file);
return {
inlineData: {
mimeType: mime,
data: image.toString("base64"),
},
};
}
export default endpointGenAI;
|