alkawthar alhaqq
import { GoogleGenAI, Type } from "@google/genai"; import type { SystemDesign, GroundingChunk, ResearchOutputData } from '../types'; if (!process.env.API_KEY) { throw new Error("API_KEY environment variable not set"); } const ai = new GoogleGenAI({ apiKey: process.env.API_KEY }); const MAX_RETRIES = 3; const INITIAL_BACKOFF_MS = 1000; const fetchWithRetry = async <T>(apiCall: () => Promise<T>): Promise<T> => { let lastError: Error | null = null; for (let i = 0; i < MAX_RETRIES; i++) { try { return await apiCall(); } catch (error) { lastError = error instanceof Error ? error : new Error('An unknown error occurred'); if (i < MAX_RETRIES - 1) { const backoffTime = INITIAL_BACKOFF_MS * Math.pow(2, i); console.warn(`API call failed. Retrying in ${backoffTime}ms... (Attempt ${i + 1}/${MAX_RETRIES})`); await new Promise(resolve => setTimeout(resolve, backoffTime)); } } } console.error("API call failed after multiple retries.", lastError); throw new Error(`API operation failed after ${MAX_RETRIES} attempts: ${lastError?.message}`); }; const reviewSystemInstruction = `You are an expert software engineer and world-class code reviewer. Your purpose is to provide constructive, insightful, and actionable feedback on code submissions. Analyze the code for correctness, performance, security vulnerabilities, adherence to best practices, and code style. Structure your feedback clearly using Markdown. Start with a brief, high-level summary (1-2 sentences). Then, provide a bulleted list of specific points using '*' for each point. For each point, if applicable, you MUST provide a corrected code snippet using markdown code fences (\`\`\`). Be encouraging and professional. Do not include a greeting or sign-off. `; export const reviewCode = async (code: string, language: string): Promise<string> => { return fetchWithRetry(async () => { const response = await ai.models.generateContent({ model: "gemini-2.5-flash", contents: `Please review this ${language} code:\n\n\`\`\`\n${code}\n\`\`\``, config: { systemInstruction: reviewSystemInstruction, temperature: 0.2, topP: 0.9, topK: 40 } }); return response.text; }); }; const generationSystemInstruction = `You are a world-class software engineer who specializes in writing code. Based on the user's request, write a complete, production-ready code snippet in the specified language. IMPORTANT: Only output the raw code for the requested language. Do NOT include any explanations, comments about the code, or markdown formatting like \`\`\`. Your output should be only the code itself, ready to be copied and pasted into a file.`; export const generateCode = async (prompt: string, language: string): Promise<string> => { return fetchWithRetry(async () => { const response = await ai.models.generateContent({ model: "gemini-2.5-flash", contents: `Generate a code snippet in ${language} for the following prompt:\n\n${prompt}`, config: { systemInstruction: generationSystemInstruction, temperature: 0.3, topP: 0.95, topK: 40 } }); return response.text.trim(); }); }; const designSystemInstruction = `You are a senior Python software architect. Your task is to design a complete, runnable Python application based on the user's prompt. You must generate a list of all the necessary files, including their full paths and complete source code. For example, for a simple Flask app, you might generate 'app.py', 'requirements.txt', and a '.gitignore' file. The output MUST be a valid JSON object that adheres to the provided schema. Do not include any text outside of the JSON object.`; const designSystemSchema = { type: Type.OBJECT, properties: { file_structure: { type: Type.ARRAY, description: "An array of files representing the application structure.", items: { type: Type.OBJECT, properties: { name: { type: Type.STRING, description: "The full path of the file (e.g., 'app/main.py', 'requirements.txt')." }, content: { type: Type.STRING, description: "The complete source code or content for the file." } }, required: ["name", "content"] } } }, required: ["file_structure"] }; export const designSystem = async (prompt: string): Promise<SystemDesign> => { return fetchWithRetry(async () => { const response = await ai.models.generateContent({ model: "gemini-2.5-flash", contents: `Design a Python application based on this prompt: ${prompt}`, config: { systemInstruction: designSystemInstruction, responseMimeType: "application/json", responseSchema: designSystemSchema, temperature: 0.4, topP: 0.95, topK: 40 } }); const jsonText = response.text.trim(); return JSON.parse(jsonText); }); }; const fixCodeSystemInstruction = `You are an expert software developer. Your task is to fix the user's code. Analyze the provided code snippet for bugs, performance issues, or style violations. Rewrite the code to be correct, efficient, and clean. IMPORTANT: Only output the raw, corrected code for the specified language. Do NOT include any explanations, comments about the code, or markdown formatting like \`\`\`. Your output should be only the corrected code itself, ready to be copied and pasted into a file.`; export const fixCode = async (code: string, language: string): Promise<string> => { return fetchWithRetry(async () => { const response = await ai.models.generateContent({ model: "gemini-2.5-flash", contents: `Please fix this ${language} code:\n\n\`\`\`\n${code}\n\`\`\``, config: { systemInstruction: fixCodeSystemInstruction, temperature: 0.3, topP: 0.95, topK: 40, }, }); return response.text.trim(); }); }; const testGenerationSystemInstruction = `You are an expert QA engineer. Your task is to write comprehensive unit tests for the given code snippet. Use a popular testing framework for the specified language (e.g., pytest for Python, Jest for JavaScript/TypeScript, JUnit for Java). Cover positive cases, negative cases, and edge cases. IMPORTANT: Only output the raw test code. Do not include explanations or markdown formatting.`; export const generateTests = async (code: string, language: string): Promise<string> => { return fetchWithRetry(async () => { const response = await ai.models.generateContent({ model: "gemini-2.5-flash", contents: `Generate unit tests for this ${language} code:\n\n\`\`\`\n${code}\n\`\`\``, config: { systemInstruction: testGenerationSystemInstruction, temperature: 0.4, }, }); return response.text.trim(); }); }; const devopsSystemInstruction = `You are an expert DevOps engineer. Your task is to generate a configuration file based on the user's request. This could be a Dockerfile, a docker-compose.yml, a GitHub Actions workflow, a Kubernetes manifest, a Terraform script, etc. Ensure the generated file follows best practices for security and efficiency. IMPORTANT: Only output the raw code/configuration. Do not include explanations or markdown formatting.`; export const generateDevopsConfig = async (prompt: string): Promise<string> => { return fetchWithRetry(async () => { const response = await ai.models.generateContent({ model: "gemini-2.5-flash", contents: `Generate a DevOps configuration file for the following request: ${prompt}`, config: { systemInstruction: devopsSystemInstruction, temperature: 0.3, }, }); return response.text.trim(); }); }; const dataScienceSystemInstruction = `You are an expert data scientist. Your task is to generate a code snippet for data analysis, manipulation, or querying based on the user's request. Use popular libraries for the specified language (e.g., pandas, NumPy, scikit-learn for Python; dplyr, ggplot2 for R). For SQL, write an efficient and correct query. IMPORTANT: Only output the raw code. Do not include explanations or markdown formatting.`; export const generateDataScript = async (prompt: string, language: string): Promise<string> => { return fetchWithRetry(async () => { const response = await ai.models.generateContent({ model: "gemini-2.5-flash", contents: `Language: ${language}. Request: ${prompt}`, config: { systemInstruction: dataScienceSystemInstruction, temperature: 0.3, }, }); return response.text.trim(); }); }; const critiqueSystemInstruction = `You are a principal software architect and a ruthless quality assurance engineer. Your task is to critique a provided system design. The user will provide a JSON object representing a file structure and code. Analyze the design for potential issues: security vulnerabilities (e.g., hardcoded secrets, injection risks), scalability bottlenecks, maintainability problems, lack of error handling, missing documentation, or deviation from best practices. Be harsh, specific, and thorough. Provide a concise, bulleted list of critiques in Markdown format. For each point, explain *why* it's an issue.`; export const critiqueSystemDesign = async (design: SystemDesign): Promise<string> => { return fetchWithRetry(async () => { const response = await ai.models.generateContent({ model: "gemini-2.5-flash", contents: `Critique the following system design:\n\n\`\`\`json\n${JSON.stringify(design, null, 2)}\n\`\`\``, config: { systemInstruction: critiqueSystemInstruction, temperature: 0.5, }, }); return response.text; }); }; const refineSystemInstruction = `You are a senior software architect tasked with refining a system design based on a critique. The user will provide the original goal, the flawed system design, and a list of critiques. Your job is to generate a new, improved system design that meticulously addresses every single point in the critique. The new design must be more robust, secure, scalable, and maintainable. You MUST output a valid JSON object adhering to the provided schema, representing the complete, corrected file structure and code. Do not output any other text.`; export const refineSystemDesign = async (originalGoal: string, originalDesign: SystemDesign, critique: string): Promise<SystemDesign> => { return fetchWithRetry(async () => { const response = await ai.models.generateContent({ model: "gemini-2.5-flash", contents: `Original Goal: ${originalGoal}\n\nCritique:\n${critique}\n\nOriginal Flawed Design:\n\`\`\`json\n${JSON.stringify(originalDesign, null, 2)}\n\`\`\`\n\nPlease provide the refined system design that fixes these issues.`, config: { systemInstruction: refineSystemInstruction, responseMimeType: "application/json", responseSchema: designSystemSchema, temperature: 0.4, } }); const jsonText = response.text.trim(); return JSON.parse(jsonText); }); }; const researchSystemInstruction = `You are a helpful AI research assistant. Your goal is to answer the user's question based on up-to-date information from Google Search. Provide a clear, comprehensive answer. If the user asks for a comparison, provide a balanced view. After the answer, you MUST list the web sources you used.`; export const researchTopic = async (prompt: string): Promise<ResearchOutputData> => { return fetchWithRetry(async () => { const response = await ai.models.generateContent({ model: "gemini-2.5-flash", contents: prompt, config: { systemInstruction: researchSystemInstruction, tools: [{ googleSearch: {} }], temperature: 0.5, }, }); const answer = response.text; const sources = (response.candidates?.[0]?.groundingMetadata?.groundingChunks ?? []) as GroundingChunk[]; return { answer, sources }; }); }; const securityScanSystemInstruction = `You are an expert cybersecurity analyst. Your primary function is to conduct a thorough security audit of the provided code. Identify vulnerabilities, such as those listed in the OWASP Top 10 (e.g., SQL injection, XSS, insecure deserialization), hardcoded secrets, use of weak cryptographic algorithms, and insecure dependencies. Structure your report using Markdown. Start with a 1-2 sentence summary of the security posture. Then, provide a bulleted list of findings. For each finding, you must include: - A title for the vulnerability. - A severity level (Critical, High, Medium, Low, Informational). - A detailed explanation of the vulnerability and the potential impact. - A specific, corrected code snippet showing how to remediate the issue. If no issues are found, state that clearly. Be professional and direct.`; export const scanCodeForSecurity = async (code: string, language: string): Promise<string> => { return fetchWithRetry(async () => { const response = await ai.models.generateContent({ model: "gemini-2.5-flash", contents: `Perform a security audit on this ${language} code:\n\n\`\`\`\n${code}\n\`\`\``, config: { systemInstruction: securityScanSystemInstruction, temperature: 0.2, }, }); return response.text; }); }; const docsGenerationSystemInstruction = `You are an expert technical writer. Your task is to generate clear, concise, and professional documentation for the provided code snippet. The output must be in Markdown format. The documentation should include: - A brief, one-sentence summary of the function or class. - A more detailed description of its purpose and functionality. - A section for parameters, describing each parameter's type and purpose. - A section for the return value, describing what is returned. - A complete, runnable usage example in a code block. Do not output anything other than the Markdown documentation. Do not include a title like "Documentation".`; export const generateDocumentation = async (code: string, language: string): Promise<string> => { return fetchWithRetry(async () => { const response = await ai.models.generateContent({ model: "gemini-2.5-flash", contents: `Generate Markdown documentation for this ${language} code:\n\n\`\`\`\n${code}\n\`\`\``, config: { systemInstruction: docsGenerationSystemInstruction, temperature: 0.3, }, }); return response.text.trim(); }); }; - Follow Up Deployment
3b6e0e6 verified