Improve voice turns, local commands and Spotify controls

This commit is contained in:
2026-11-11 13:34:30 +03:00
parent 095bc51521
commit 0e921617dd
28 changed files with 906 additions and 126 deletions
+56 -22
View File
@@ -68,15 +68,32 @@ export async function openTts(settings, signal, onAudio) {
return { ws, done, text(text) { if (ws.readyState !== WebSocket.OPEN) throw new Error('tts_closed'); ws.send(JSON.stringify(flash ? { text } : { inputs: [{ text, voice_id: settings.voiceId }] })); }, finish() { if (ws.readyState !== WebSocket.OPEN) throw new Error('tts_closed'); ws.send(JSON.stringify(flash ? { text: '' } : { close_socket: true })); } };
}
const sentenceSegments = new Intl.Segmenter('ru', { granularity: 'sentence' });
function shortReply(text) {
const compact = Array.from(sentenceSegments.segment(text.trim()), part => part.segment).slice(0, 2).join('').trim();
if (compact.length <= 300) return compact;
const end = compact.lastIndexOf(' ', 297);
return compact.slice(0, end > 170 ? end : 297).trimEnd() + '…';
}
export async function streamAnswer(settings, history, userText, signal, onText, executeDeviceTool) {
if (env.LLM_MODE === 'echo') { onText(userText); return userText; }
const question = userText.toLowerCase().replace(/[?!.…]+$/u, '').trim();
if (/^(?:какая (?:это|у тебя) модель|на какой модели ты работаешь|какая у тебя языковая модель)$/u.test(question)) {
const model = settings.llmModel === 'anthropic/claude-haiku-5.5' ? 'Claude Haiku 5.5' : settings.llmModel;
const answer = `Я работаю на ${model}.`;
onText(answer);
return answer;
}
if (!env.OPENROUTER_API_KEY) throw new Error('llm_config');
const moscowDate = new Intl.DateTimeFormat('ru-RU', { timeZone: 'Europe/Moscow', dateStyle: 'long' }).format(new Date());
const systemPrompt = `${settings.systemPrompt}\nСегодня ${moscowDate} (Москва). Используй веб-поиск для актуальных сведений и когда требуется проверить сомнительные факты. Вызывай инструменты без вступительных фраз. Подтверждай воспроизведение музыки только после успешного результата инструмента. Отвечай для озвучивания без Markdown и ссылок, если их не попросили.`;
const systemPrompt = `${settings.systemPrompt}\nСегодня ${moscowDate} (Москва). Используй веб-поиск для актуальных сведений и когда требуется проверить сомнительные факты. Твоя языковая модель: ${settings.llmModel}. Обычно отвечай одной короткой фразой, максимум двумя предложениями. Подробности давай по просьбе. На простой вопрос отвечай сразу, без служебных оговорок, и не возвращайся к предыдущим темам без просьбы. При неясности задай один короткий уточняющий вопрос. Вызывай инструменты без вступительных фраз. Сообщай результат команды один раз. Упоминай громкость, только если её спросили или попросили изменить. Подтверждай трек, только если инструмент вернул актуальный трек. Отвечай для озвучивания без Markdown и ссылок, если их не попросили.`;
const messages = [{ role: 'system', content: systemPrompt }, ...history.slice(-10).flatMap(t => [{ role: 'user', content: t.user }, { role: 'assistant', content: t.assistant }]), { role: 'user', content: userText }];
let answer = '', totalCalls = 0;
const detailed = /подробн|развернут|пошагов|детальн/iu.test(userText);
let totalCalls = 0;
for (let round = 0; round < 4; round++) {
const response = await fetch(llmUrl, { method: 'POST', signal, headers: { Authorization: `Bearer ${env.OPENROUTER_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ model: settings.llmModel, messages, tools, stream: true, max_tokens: 1200, ...(settings.llmModel === 'anthropic/claude-haiku-5.5' ? { reasoning: { enabled: false, effort: 'low' } } : {}) }) });
const response = await fetch(llmUrl, { method: 'POST', signal, headers: { Authorization: `Bearer ${env.OPENROUTER_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ model: settings.llmModel, messages, tools, stream: true, max_tokens: detailed ? 800 : 220, ...(settings.llmModel === 'anthropic/claude-haiku-5.5' ? { reasoning: { enabled: false, effort: 'low' } } : {}) }) });
if (!response.ok || !response.body) throw new Error('llm_error');
let buffer = '', content = '', done = false, finishReason;
const calls = new Map();
@@ -92,10 +109,8 @@ export async function streamAnswer(settings, history, userText, signal, onText,
if (choice.finish_reason) finishReason = choice.finish_reason;
const delta = choice.delta || {};
if (typeof delta.content === 'string' && delta.content) {
const prefix = !content && answer && !/\s$/.test(answer) && !/^\s/.test(delta.content) ? ' ' : '';
content += delta.content; answer += prefix + delta.content;
if (answer.length > 12000) throw new Error('llm_limit');
onText(prefix + delta.content);
content += delta.content;
if (content.length > 12000) throw new Error('llm_limit');
}
for (const part of delta.tool_calls || []) {
if (!Number.isInteger(part.index) || part.index < 0 || part.index >= 4) throw new Error('llm_limit');
@@ -118,28 +133,47 @@ export async function streamAnswer(settings, history, userText, signal, onText,
if (buffer.trim()) consume(buffer);
if (!done || !finishReason) throw new Error('llm_incomplete');
if (!calls.size) {
if (finishReason !== 'stop' || !answer.trim()) throw new Error('llm_incomplete');
if (!['stop', 'length'].includes(finishReason) || !content.trim()) throw new Error('llm_incomplete');
const answer = detailed ? content.trim() : shortReply(content);
onText(answer);
return answer;
}
if (finishReason !== 'tool_calls') throw new Error('llm_incomplete');
const ordered = [...calls.entries()].sort((a, b) => a[0] - b[0]).map(([, call]) => call);
if ((totalCalls += ordered.length) > 4 || round === 3 || ordered.some(c => !c.id || !c.function.name)) throw new Error('llm_limit');
messages.push({ role: 'assistant', content: content || null, tool_calls: ordered });
for (const call of ordered) {
if (signal.aborted) throw new Error('aborted');
let result;
try {
const args = validateTool(call.function.name, JSON.parse(call.function.arguments));
if (typeof executeDeviceTool !== 'function') throw new Error('device_unavailable');
result = await executeDeviceTool(call.function.name, args);
if (signal.aborted) throw new Error('aborted');
result = JSON.stringify(result ?? { ok: true });
if (result.length > 8192) result = JSON.stringify({ error: 'result_too_large' });
} catch (error) {
if (signal.aborted) throw error;
result = JSON.stringify({ error: 'tool_failed' });
const results = new Map();
const groups = [
ordered.filter(call => call.function.name === 'station_volume'),
ordered.filter(call => call.function.name !== 'station_volume'),
];
await Promise.all(groups.map(async group => {
for (const call of group) {
signal.throwIfAborted();
let result;
try {
const args = validateTool(call.function.name, JSON.parse(call.function.arguments));
if (typeof executeDeviceTool !== 'function') throw new Error('device_unavailable');
result = await executeDeviceTool(call.function.name, args);
signal.throwIfAborted();
if (JSON.stringify(result ?? {}).length > 8192) result = { error: 'result_too_large' };
} catch (error) {
if (signal.aborted) throw error;
result = { error: 'tool_failed' };
}
results.set(call.id, result ?? { ok: true });
}
messages.push({ role: 'tool', tool_call_id: call.id, content: result });
}));
if (ordered.length === 1 && ordered[0].function.name === 'spotify_play') {
const result = results.get(ordered[0].id);
const title = result.selection?.name?.trim().slice(0, 110);
let answer;
if (result.accepted === true) answer = title ? `Включаю «${title}».` : 'Включаю музыку.';
if (result.error === 'spotify_not_found') answer = 'В Spotify ничего не нашла.';
if (answer) { onText(answer); return answer; }
}
for (const call of ordered) {
messages.push({ role: 'tool', tool_call_id: call.id, content: JSON.stringify(results.get(call.id)) });
}
}
throw new Error('llm_limit');