fastv0
Version:
Fast File System Operations and AI Integration for Node.js - Like Cursor's token management
288 lines (280 loc) • 9.83 kB
JavaScript
/**
* AI Integration - Connect with AI models for file analysis
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AIIntegration = void 0;
const axios_1 = __importDefault(require("axios"));
class AIIntegration {
constructor(apiKeys = {}) {
this.apiKeys = apiKeys;
this.providers = {
openai: this.analyzeWithOpenAI.bind(this),
groq: this.analyzeWithGroq.bind(this),
anthropic: this.analyzeWithAnthropic.bind(this),
google: this.analyzeWithGoogle.bind(this)
};
}
async analyzeFileContent(content, fileType, provider = 'groq') {
try {
if (!this.providers[provider]) {
return { success: false, error: `Provider ${provider} not supported` };
}
const analysisFunc = this.providers[provider];
const result = await analysisFunc(content, fileType);
return {
success: true,
analysis: result,
provider: provider,
fileType: fileType,
analyzedAt: new Date().toISOString()
};
}
catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : String(error)
};
}
}
async generateFileSummary(content, fileType) {
try {
const prompt = `
Analyze this ${fileType} file and provide a comprehensive summary:
1. Purpose and functionality
2. Key components and structure
3. Dependencies and imports
4. Main functions or classes
5. Code quality assessment
6. Potential improvements
File content:
${content.substring(0, 2000)} // Limit content for token efficiency
`;
// Use Groq for fast analysis
const result = await this.analyzeWithGroq(prompt, 'summary');
return {
success: true,
analysis: result,
fileType: fileType,
analyzedAt: new Date().toISOString()
};
}
catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : String(error)
};
}
}
async suggestImprovements(content, fileType) {
try {
const prompt = `
Review this ${fileType} code and suggest specific improvements:
1. Code quality issues
2. Performance optimizations
3. Security concerns
4. Best practices violations
5. Refactoring opportunities
Provide specific, actionable suggestions with examples.
Code:
${content.substring(0, 2000)}
`;
const result = await this.analyzeWithGroq(prompt, 'improvements');
return {
success: true,
analysis: result,
fileType: fileType,
analyzedAt: new Date().toISOString()
};
}
catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : String(error)
};
}
}
async detectCodeIssues(content, fileType) {
try {
const prompt = `
Analyze this ${fileType} code for potential issues:
1. Syntax errors
2. Logic errors
3. Security vulnerabilities
4. Performance bottlenecks
5. Memory leaks
6. Unused variables/functions
Provide specific line numbers and explanations.
Code:
${content.substring(0, 2000)}
`;
const result = await this.analyzeWithGroq(prompt, 'issues');
return {
success: true,
analysis: result,
fileType: fileType,
analyzedAt: new Date().toISOString()
};
}
catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : String(error)
};
}
}
async batchAnalyzeFiles(files, provider = 'groq') {
try {
const results = [];
for (const fileInfo of files) {
const analysis = await this.analyzeFileContent(fileInfo.content, fileInfo.fileType, provider);
results.push({
filePath: fileInfo.filePath,
analysis: analysis
});
}
return {
success: true,
results: results,
totalFiles: files.length,
provider: provider,
analyzedAt: new Date().toISOString()
};
}
catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : String(error)
};
}
}
async analyzeWithGroq(content, analysisType) {
try {
const apiKey = this.apiKeys.groq;
if (!apiKey) {
return 'Groq API key not provided';
}
const response = await axios_1.default.post('https://api.groq.com/openai/v1/chat/completions', {
model: 'llama-3.1-8b-instant',
messages: [
{ role: 'system', content: `You are an expert code analyzer. Provide detailed ${analysisType}.` },
{ role: 'user', content: content }
],
max_tokens: 2000,
temperature: 0.3
}, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
return response.data.choices[0].message.content;
}
else {
return `Groq API error: ${response.status}`;
}
}
catch (error) {
return `Groq analysis error: ${error instanceof Error ? error.message : String(error)}`;
}
}
async analyzeWithOpenAI(content, analysisType) {
try {
const apiKey = this.apiKeys.openai;
if (!apiKey) {
return 'OpenAI API key not provided';
}
const response = await axios_1.default.post('https://api.openai.com/v1/chat/completions', {
model: 'gpt-4o-mini',
messages: [
{ role: 'system', content: `You are an expert code analyzer. Provide detailed ${analysisType}.` },
{ role: 'user', content: content }
],
max_tokens: 2000,
temperature: 0.3
}, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
return response.data.choices[0].message.content;
}
else {
return `OpenAI API error: ${response.status}`;
}
}
catch (error) {
return `OpenAI analysis error: ${error instanceof Error ? error.message : String(error)}`;
}
}
async analyzeWithAnthropic(content, analysisType) {
try {
const apiKey = this.apiKeys.anthropic;
if (!apiKey) {
return 'Anthropic API key not provided';
}
const response = await axios_1.default.post('https://api.anthropic.com/v1/messages', {
model: 'claude-3-5-sonnet-20241022',
max_tokens: 2000,
messages: [
{ role: 'user', content: `Analyze this code for ${analysisType}: ${content}` }
]
}, {
headers: {
'x-api-key': apiKey,
'Content-Type': 'application/json',
'anthropic-version': '2023-06-01'
}
});
if (response.status === 200) {
return response.data.content[0].text;
}
else {
return `Anthropic API error: ${response.status}`;
}
}
catch (error) {
return `Anthropic analysis error: ${error instanceof Error ? error.message : String(error)}`;
}
}
async analyzeWithGoogle(content, analysisType) {
try {
const apiKey = this.apiKeys.google;
if (!apiKey) {
return 'Google API key not provided';
}
const response = await axios_1.default.post(`https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro:generateContent?key=${apiKey}`, {
contents: [{
parts: [{
text: `Analyze this code for ${analysisType}: ${content}`
}]
}],
generationConfig: {
maxOutputTokens: 2000,
temperature: 0.3
}
}, {
headers: {
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
return response.data.candidates[0].content.parts[0].text;
}
else {
return `Google API error: ${response.status}`;
}
}
catch (error) {
return `Google analysis error: ${error instanceof Error ? error.message : String(error)}`;
}
}
}
exports.AIIntegration = AIIntegration;
//# sourceMappingURL=ai-integration.js.map
;