-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathai-analysis.ts
More file actions
131 lines (110 loc) · 4.15 KB
/
Copy pathai-analysis.ts
File metadata and controls
131 lines (110 loc) · 4.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
import * as fs from 'fs';
export interface AIAnalysisResult {
analysis: string;
provider: string;
model: string;
}
function detectProvider(model: string): 'anthropic' | 'openai' {
return model.toLowerCase().startsWith('claude') ? 'anthropic' : 'openai';
}
async function callAnthropicAPI(prompt: string, token: string, model: string): Promise<string> {
const response = await fetch('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': token,
'anthropic-version': '2023-06-01',
},
body: JSON.stringify({
model,
max_tokens: 2048,
messages: [{ role: 'user', content: prompt }],
}),
});
if (!response.ok) {
const error = await response.text();
throw new Error(`Anthropic API error ${response.status}: ${error}`);
}
const data = await response.json() as any;
return data.content[0].text as string;
}
async function callOpenAIAPI(prompt: string, token: string, model: string): Promise<string> {
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
},
body: JSON.stringify({
model,
max_tokens: 2048,
messages: [{ role: 'user', content: prompt }],
}),
});
if (!response.ok) {
const error = await response.text();
throw new Error(`OpenAI API error ${response.status}: ${error}`);
}
const data = await response.json() as any;
return data.choices[0].message.content as string;
}
function buildPrompt(diffData: unknown): string {
// Truncate large diff data to avoid token limits (~50k chars)
const MAX_CHARS = 50000;
let diffStr = JSON.stringify(diffData, null, 2);
if (diffStr.length > MAX_CHARS) {
diffStr = diffStr.substring(0, MAX_CHARS) + '\n... (truncated due to size)';
}
return `You are a frontend performance expert analyzing a JavaScript bundle size diff report generated by Rsdoctor (a Webpack/Rspack bundle analyzer).
Please analyze the following bundle diff JSON data and provide a concise report covering:
1. **Size Regression Summary**: Which assets/chunks increased significantly in size
2. **Root Cause Analysis**: Likely causes of size increases based on the diff data
3. **Risk Assessment**: Overall severity — Low / Medium / High — with a brief justification
4. **Optimization Recommendations**: Specific, actionable steps to reduce the regressions
Focus especially on:
- Assets or chunks with >5% or >10 KB size increase
- Newly added large assets or modules
- Changes to initial/entry chunks (highest priority)
- Potential duplicate dependencies
Bundle diff data:
\`\`\`json
${diffStr}
\`\`\`
Respond in concise GitHub-flavored Markdown suitable for a PR comment. If there are no regressions, say so clearly.`;
}
/**
* Run AI degradation analysis on a bundle-diff JSON file.
*
* @param diffJsonPath Path to the JSON file produced by `rsdoctor bundle-diff --json`
* @param token AI API key (Anthropic or OpenAI)
* @param model Model name — auto-detects provider from prefix (default: claude-3-5-haiku-latest)
*/
export async function analyzeWithAI(
diffJsonPath: string,
token: string,
model = 'claude-3-5-haiku-latest',
): Promise<AIAnalysisResult | null> {
if (!token) {
console.log('ℹ️ No AI token provided, skipping AI analysis');
return null;
}
if (!fs.existsSync(diffJsonPath)) {
console.log(`⚠️ Bundle diff JSON not found at ${diffJsonPath}, skipping AI analysis`);
return null;
}
try {
const diffData: unknown = JSON.parse(fs.readFileSync(diffJsonPath, 'utf8'));
const prompt = buildPrompt(diffData);
const provider = detectProvider(model);
console.log(`🤖 Running AI analysis with ${provider} (${model})...`);
const analysis =
provider === 'anthropic'
? await callAnthropicAPI(prompt, token, model)
: await callOpenAIAPI(prompt, token, model);
console.log('✅ AI analysis completed');
return { analysis, provider, model };
} catch (error) {
console.warn(`⚠️ AI analysis failed: ${error}`);
return null;
}
}