From bcb877ac07e730f7cf7816a3f9374c1c14608301 Mon Sep 17 00:00:00 2001 From: hemanth5055 Date: Fri, 17 Oct 2025 20:53:52 +0530 Subject: [PATCH] modify Gemini to return translation and source language in structured format using XML-like tags --- backend/src/index.ts | 43 ++++++++++++++++++++++++++++--------------- 1 file changed, 28 insertions(+), 15 deletions(-) diff --git a/backend/src/index.ts b/backend/src/index.ts index 0dce003..53ee713 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -68,19 +68,32 @@ async function handleTranslate(request: Request, model: ReturnType +...translated code... + + +...detected language... + + +Do not include any markdown, comments, or extra text. Original Code: ${code}`; const result = await model.generateContent(prompt); - const translatedCode = result.response.text(); + const text = result.response.text(); + + const translatedMatch = text.match(/([\s\S]*?)<\/TranslatedLanguage>/); + const sourceMatch = text.match(/([\s\S]*?)<\/SourceLanguage>/); + + const translation = translatedMatch ? translatedMatch[1].trim() : ""; + const sourceLanguage = sourceMatch ? sourceMatch[1].trim() : ""; + await updateAnalytics(sourceLanguage, targetLanguage, env); - return new Response(JSON.stringify({ translation: translatedCode}), { + + return new Response(JSON.stringify({ translation, sourceLanguage }), { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' }, }); @@ -176,13 +189,13 @@ export default { }, }; -async function detectLanguage(code: string, model: ReturnType) { - const prompt = `Identify the programming language of the following code. -Only respond with the exact language name (e.g., "python", "javascript", "c++", "java", etc.) without any extra text or punctuation. +// async function detectLanguage(code: string, model: ReturnType) { +// const prompt = `Identify the programming language of the following code. +// Only respond with the exact language name (e.g., "python", "javascript", "c++", "java", etc.) without any extra text or punctuation. -Code: -${code}`; +// Code: +// ${code}`; - const result = await model.generateContent(prompt); - return result.response.text().trim().toLowerCase(); -} +// const result = await model.generateContent(prompt); +// return result.response.text().trim().toLowerCase(); +// }