|
| 1 | +import { ChatOpenAI } from "@langchain/openai"; |
| 2 | +import dotenv from "dotenv"; |
| 3 | +import { Configuration } from "../Configuration.js"; |
| 4 | +import { TypeScriptParser } from "../TypeScriptParser.js"; |
| 5 | +import { CodeFormatter } from "./utils/CodeFormatter.js"; |
| 6 | +import { DocumentOrganizer } from "./utils/DocumentOrganizer.js"; |
| 7 | + |
| 8 | +dotenv.config(); |
| 9 | + |
| 10 | +/** |
| 11 | + * Service for interacting with OpenAI chat API. |
| 12 | + */ |
| 13 | +export class AIService { |
| 14 | + private chatModel: ChatOpenAI; |
| 15 | + private typeScriptParser: TypeScriptParser; |
| 16 | + private codeFormatter: CodeFormatter; |
| 17 | + private documentOrganizer: DocumentOrganizer; |
| 18 | + |
| 19 | + /** |
| 20 | + * Constructor for initializing the ChatOpenAI instance. |
| 21 | + * |
| 22 | + * @param {Configuration} configuration - The configuration instance to be used |
| 23 | + * @throws {Error} If OPENAI_API_KEY environment variable is not set |
| 24 | + */ |
| 25 | + constructor(private configuration: Configuration) { |
| 26 | + if (!process.env.OPENAI_API_KEY) { |
| 27 | + throw new Error("OPENAI_API_KEY is not set"); |
| 28 | + } |
| 29 | + this.chatModel = new ChatOpenAI({ apiKey: process.env.OPENAI_API_KEY }); |
| 30 | + this.typeScriptParser = new TypeScriptParser(); |
| 31 | + this.codeFormatter = new CodeFormatter(); |
| 32 | + this.documentOrganizer = new DocumentOrganizer(); |
| 33 | + } |
| 34 | + |
| 35 | + /** |
| 36 | + * Generates a comment based on the specified prompt by invoking the chat model. |
| 37 | + * @param {string} prompt - The prompt for which to generate a comment |
| 38 | + * @returns {Promise<string>} The generated comment |
| 39 | + */ |
| 40 | + public async generateComment(prompt: string): Promise<string> { |
| 41 | + try { |
| 42 | + // First try with generous limit |
| 43 | + let finalPrompt = this.codeFormatter.truncateCodeBlock(prompt, 8000); |
| 44 | + |
| 45 | + // Only append language instruction if not English |
| 46 | + const normalizedLanguage = this.configuration.language |
| 47 | + .toLowerCase() |
| 48 | + .trim(); |
| 49 | + if (normalizedLanguage !== "english") { |
| 50 | + finalPrompt += `\n\nEverything except the JSDoc conventions and code should be in ${this.configuration.language}`; |
| 51 | + } |
| 52 | + |
| 53 | + console.log( |
| 54 | + `Generating comment for prompt of length: ${finalPrompt.length}` |
| 55 | + ); |
| 56 | + |
| 57 | + try { |
| 58 | + const response = await this.chatModel.invoke(finalPrompt); |
| 59 | + return response.content as string; |
| 60 | + } catch (error) { |
| 61 | + if ( |
| 62 | + error instanceof Error && |
| 63 | + error.message.includes("maximum context length") |
| 64 | + ) { |
| 65 | + console.warn( |
| 66 | + "Token limit exceeded, attempting with further truncation..." |
| 67 | + ); |
| 68 | + // Try with more aggressive truncation |
| 69 | + finalPrompt = this.codeFormatter.truncateCodeBlock(prompt, 4000); |
| 70 | + try { |
| 71 | + const response = |
| 72 | + await this.chatModel.invoke(finalPrompt); |
| 73 | + return response.content as string; |
| 74 | + } catch (retryError) { |
| 75 | + if ( |
| 76 | + retryError instanceof Error && |
| 77 | + retryError.message.includes( |
| 78 | + "maximum context length" |
| 79 | + ) |
| 80 | + ) { |
| 81 | + console.warn( |
| 82 | + "Still exceeding token limit, using minimal context..." |
| 83 | + ); |
| 84 | + // Final attempt with minimal context |
| 85 | + finalPrompt = this.codeFormatter.truncateCodeBlock(prompt, 2000); |
| 86 | + const response = |
| 87 | + await this.chatModel.invoke(finalPrompt); |
| 88 | + return response.content as string; |
| 89 | + } |
| 90 | + throw retryError; |
| 91 | + } |
| 92 | + } |
| 93 | + throw error; |
| 94 | + } |
| 95 | + } catch (error) { |
| 96 | + this.handleAPIError(error as Error); |
| 97 | + return ""; |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + /** |
| 102 | + * Handle API errors by logging the error message and throwing the error. |
| 103 | + * |
| 104 | + * |
| 105 | + * @param {Error} error The error object to handle |
| 106 | + * @returns {void} |
| 107 | + */ |
| 108 | + public handleAPIError(error: Error): void { |
| 109 | + console.error("API Error:", error.message); |
| 110 | + throw error; |
| 111 | + } |
| 112 | +} |
0 commit comments