Files
Quick-Ling/server/api/translate.ts
T

174 lines
4.5 KiB
TypeScript

import { defineEventHandler, readBody, createError } from "h3";
const config = useRuntimeConfig();
const requestQueue = new Map<string, { count: number; windowStart: number }>();
const RATE_LIMIT_WINDOW = 10000;
const MAX_REQUESTS_PER_WINDOW = 5;
interface TranslateRequestBody {
text: string;
source: string;
target: string;
model?: string;
}
interface OllamaRequest {
model: string;
prompt: string;
stream: boolean;
}
interface OllamaResponse {
model: string;
response: string;
done: boolean;
}
export default defineEventHandler(async (event) => {
const body = await readBody<TranslateRequestBody>(event);
if (!body.text || !body.source || !body.target) {
throw createError({
statusCode: 400,
statusMessage: "Missing required fields: text, source, target",
});
}
if (!body.text.trim()) {
throw createError({
statusCode: 400,
statusMessage: "Text cannot be empty",
});
}
const clientIP = getRequestHeader(event, "x-forwarded-for") || "anonymous";
const now = Date.now();
const clientData = requestQueue.get(clientIP);
if (clientData && now - clientData.windowStart < RATE_LIMIT_WINDOW) {
if (clientData.count >= MAX_REQUESTS_PER_WINDOW) {
throw createError({
statusCode: 429,
statusMessage: `Rate limit exceeded. Maximum ${MAX_REQUESTS_PER_WINDOW} requests per ${RATE_LIMIT_WINDOW / 1000} seconds.`,
});
}
clientData.count++;
} else {
requestQueue.set(clientIP, { count: 1, windowStart: now });
}
const ollamaUrl = config.ollamahost;
const ALLOWED_MODELS = [
"translategemma:1b",
"translategemma:2b",
"translategemma:4b",
];
const model =
body.model && ALLOWED_MODELS.includes(body.model)
? body.model
: config.ollamamodel;
const prompt = `Translate the following text from ${body.source} to ${body.target}. Only output the translation, nothing else.
Text to translate: ${body.text}`;
const ollamaRequest: OllamaRequest = {
model,
prompt,
stream: false,
};
try {
const tagsResponse = await fetch(`${ollamaUrl}/api/tags`, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
if (tagsResponse.ok) {
const tagsData = await tagsResponse.json();
const models = tagsData.models || [];
const modelExists = models.some(
(m: { name: string }) => m.name.startsWith(model) || m.name === model,
);
if (!modelExists) {
throw createError({
statusCode: 404,
statusMessage: `Model "${model}" not found. Install it by running: ollama pull ${model}`,
});
}
}
} catch {}
try {
const response = await fetch(`${ollamaUrl}/api/generate`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(ollamaRequest),
});
if (!response.ok) {
const errorBody = await response.json().catch(() => ({}));
const errorMsg = errorBody.error || "Ollama request failed";
if (
errorMsg.includes("model not found") ||
errorMsg.includes("does not exist")
) {
throw createError({
statusCode: 404,
statusMessage: `Model "${model}" not found. Install it by running: ollama pull ${model}`,
});
}
throw createError({
statusCode: response.status,
statusMessage: errorMsg,
});
}
const ollamaResponse: OllamaResponse = await response.json();
return {
translatedText: ollamaResponse.response.trim(),
source: body.source,
target: body.target,
originalText: body.text,
};
} catch (error) {
if (error instanceof Error) {
if (
error.message.includes("ECONNREFUSED") ||
error.message.includes("fetch failed")
) {
throw createError({
statusCode: 503,
statusMessage:
"Ollama service is not available. Please ensure Ollama is running on " +
ollamaUrl,
});
}
if (
error.cause instanceof Error &&
error.cause.message.includes("model not found")
) {
throw createError({
statusCode: 404,
statusMessage: `Model "${model}" not found. Install it by running: ollama pull ${model}`,
});
}
throw createError({
statusCode: 500,
statusMessage: error.message,
});
}
throw createError({
statusCode: 500,
statusMessage: "Unknown error occurred during translation",
});
}
});