UNPKG

editcodewithai

Version:
57 lines (56 loc) 2.32 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.performAiEdit = performAiEdit; const llm_code_format_1 = require("llm-code-format"); const prompt_1 = require("./prompt"); const metadata_1 = require("./metadata"); const fileUtils_1 = require("./fileUtils"); const debug = false; /** * Core AI logic for: * - Building the prompt (including context) * - Calling the provided LLM function * - Parsing and merging file changes * - Retrieving cost metadata */ async function performAiEdit({ prompt, files, llmFunction, apiKey, }) { // 1. Format the existing files into the "markdown code block" format const preparedFiles = (0, fileUtils_1.prepareFilesForPrompt)(files); const filesContext = (0, llm_code_format_1.formatMarkdownFiles)(preparedFiles); // 2. Assemble the final prompt const fullPrompt = (0, prompt_1.assembleFullPrompt)({ filesContext, prompt }); debug && console.log("[performAiEdit] fullPrompt:", fullPrompt); // 3. Invoke the model via the provided LLM function const result = await llmFunction(fullPrompt); // 4. We parse the output to figure out which files changed const resultString = result.content; const parsed = (0, llm_code_format_1.parseMarkdownFiles)(resultString, "bold"); // 5. Merge the changes into a new `Files` object const changedFiles = (0, fileUtils_1.mergeFileChanges)(files, parsed.files); // 6. Retrieve cost metadata for charging the user const openRouterGenerationId = result.generationId || ""; let upstreamCostCents = 0; let provider = ""; let inputTokens = 0; let outputTokens = 0; if (openRouterGenerationId && apiKey) { const costData = await (0, metadata_1.getGenerationMetadata)({ apiKey, generationId: openRouterGenerationId, }); upstreamCostCents = costData.upstreamCostCents; provider = costData.provider; inputTokens = costData.inputTokens; outputTokens = costData.outputTokens; } return { changedFiles, openRouterGenerationId, upstreamCostCents, provider, inputTokens, outputTokens, promptTemplateVersion: prompt_1.PROMPT_TEMPLATE_VERSION, rawResponse: resultString, // Include the raw response }; }