Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
82 lines (72 loc) · 2.51 KB
/
Copy pathbackground.js
File metadata and controls
82 lines (72 loc) · 2.51 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
async function loadSystemPrompt() {
const res = await fetch(chrome.runtime.getURL('prompts/skill_builder.txt'));
return res.text();
}
function buildUserPrompt(title, transcript) {
return `Video Title: "${title}"\n\nTranscript:\n${transcript}`;
}
function extractSkillName(skillMd) {
const match = skillMd.match(/^name:\s*(.+)$/m);
return match ? match[1].trim() : 'my-skill';
}
async function generateSkill({ transcript, videoTitle, apiKey, apiBaseUrl, model }) {
try {
const systemPrompt = await loadSystemPrompt();
const userPrompt = buildUserPrompt(videoTitle, transcript);
const baseUrl = (apiBaseUrl || '').replace(/\/+$/, '');
const endpoint = `${baseUrl}/chat/completions`;
console.log('[YTSkill] LLM request →', endpoint, '| model:', model,
'| transcript chars:', transcript?.length || 0, '| key set:', !!apiKey);
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model,
stream: true,
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userPrompt }
]
})
});
if (!response.ok) {
const errText = await response.text().catch(() => 'Unknown error');
chrome.runtime.sendMessage({ type: 'SKILL_ERROR', message: `API error ${response.status}: ${errText}` });
return;
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) {
chrome.runtime.sendMessage({ type: 'SKILL_DONE' });
break;
}
const chunk = decoder.decode(value);
const lines = chunk.split('\n').filter(l => l.startsWith('data: '));
for (const line of lines) {
const data = line.slice(6);
if (data === '[DONE]') continue;
try {
const parsed = JSON.parse(data);
const token = parsed.choices?.[0]?.delta?.content || '';
if (token) {
chrome.runtime.sendMessage({ type: 'SKILL_CHUNK', token });
}
} catch {}
}
}
} catch (err) {
console.error('[YTSkill] generateSkill failed:', err);
chrome.runtime.sendMessage({ type: 'SKILL_ERROR', message: err.message });
}
}
chrome.runtime.onMessage.addListener((req, sender, sendResponse) => {
if (req.type === 'GENERATE_SKILL') {
generateSkill(req.payload);
return true;
}
});