Skip to main content

Recent Posts

/**
 * Analyzes code using the Ollama API and returns a description and suggestions.
 * If the analysis is valid JSON, it is inserted into the AiDescriptions table.
 * @param code The code snippet to analyze.
 * @param language The programming language of the code.
 * @param postId (optional) The ID of the post being analyzed.
 * @returns An object containing description and suggestions.
 */
async function analyzeCodeWithOllama(
  code: string,
  language: string,
  postId?: string
): Promise<CodeAnalysisResponse> {
  if (!code || !language) {
    throw new Error('Code and language are required');
  }
  try {
    const prompt = createPrompt(code, language);
    const response: AxiosResponse = await axios.post(OLLAMA_API_URL, {
      model: MODEL_NAME,
      prompt,
      stream: false,
      think: false,
    });
    console.log('Raw Ollama response:', JSON.stringify(response.data, null, 2));
    let analysis: CodeAnalysisResponse;
    try {
      const responseText = typeof response.data === 'string' ? response.data : response.data.response || JSON.stringify(response.data);
      const jsonMatch = responseText.match(/{[\s\S]*}/);
      if (jsonMatch) {
        analysis = JSON.parse(jsonMatch[0]);
        // If valid JSON and postId is provided, insert into DB
        if (postId && analysis.description) {
          try {
            await insertAiDescription(postId, analysis.description, analysis.suggestions, new Date().toISOString());
          } catch (dbErr: any) {
            console.error(`Failed to insert AI description for post ${postId}:`, dbErr.message);
          }
        }
      } else {
        throw new Error('No valid JSON found in response');
      }
    } catch (parseError) {
      console.error('Error parsing Ollama response:', parseError, 'Response:', response.data);
      throw new Error('Failed to parse model response');
    }
    if (!analysis.description || !Array.isArray(analysis.suggestions)) {
      console.error('Invalid response format:', analysis);
      throw new Error('Invalid response format from model');
    }
    return analysis;
  } catch (error: any) {
    console.error('Error communicating with Ollama:', error.message);
    throw new Error('Failed to analyze code: ' + error.message);
  }
}

Post Statistics