iobroker.assistant 1.2.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -0
- package/admin/custom/.vite/manifest.json +18 -18
- package/admin/custom/assets/Components-x2Dfv8qE.js +2 -0
- package/admin/custom/assets/{_virtual_mf-localSharedImportMap___mfe_internal__ConfigCustomAssistant__mf_owner__1-C5NPM0Of.js → _virtual_mf-localSharedImportMap___mfe_internal__ConfigCustomAssistant__mf_owner__1-B4YbqhBb.js} +1 -1
- package/admin/custom/assets/{_virtual_mf___mfe_internal__ConfigCustomAssistant__mf_owner__163539842885036__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-Cdyjt5KT.js → _virtual_mf___mfe_internal__ConfigCustomAssistant__mf_owner__163539842885036__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-o4EU_Ut5.js} +10 -10
- package/admin/custom/assets/{_virtual_mf___mfe_internal__ConfigCustomAssistant__mf_owner__163539842885036__loadShare__shared-Dsw5zWS8.js → _virtual_mf___mfe_internal__ConfigCustomAssistant__mf_owner__163539842885036__loadShare__shared--be2hWbV.js} +1 -1
- package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomAssistant__mf_owner__163539842885036__prebuild___mf_0_iobroker_mf_1_json_mf_2_config__prebuild__-BsTz_EWE.js +122 -0
- package/admin/custom/assets/{hostInit-jJe8bIfV.js → hostInit-Blh7a-Qe.js} +1 -1
- package/admin/custom/assets/{lib-CL8mXvI6.js → lib-DBbNtolG.js} +1 -1
- package/admin/custom/assets/{mf-entry-bootstrap-0-ab227aa6.js → mf-entry-bootstrap-0-7abd30d3.js} +2 -2
- package/admin/custom/assets/{pendingShares-wrGtfliQ.js → pendingShares-U0D1MYK4.js} +1 -1
- package/admin/custom/customComponents.js +2 -2
- package/admin/custom/i18n/de.json +16 -0
- package/admin/custom/i18n/en.json +16 -0
- package/admin/custom/i18n/es.json +16 -0
- package/admin/custom/i18n/fr.json +16 -0
- package/admin/custom/i18n/it.json +16 -0
- package/admin/custom/i18n/nl.json +16 -0
- package/admin/custom/i18n/pl.json +16 -0
- package/admin/custom/i18n/pt.json +16 -0
- package/admin/custom/i18n/ru.json +16 -0
- package/admin/custom/i18n/uk.json +16 -0
- package/admin/custom/i18n/zh-cn.json +16 -0
- package/admin/custom/index.html +2 -2
- package/admin/custom/mf-manifest.json +1 -1
- package/admin/custom/mf-stats.json +1 -1
- package/admin/i18n/de.json +25 -2
- package/admin/i18n/en.json +25 -2
- package/admin/i18n/es.json +25 -2
- package/admin/i18n/fr.json +25 -2
- package/admin/i18n/it.json +25 -2
- package/admin/i18n/nl.json +25 -2
- package/admin/i18n/pl.json +25 -2
- package/admin/i18n/pt.json +25 -2
- package/admin/i18n/ru.json +25 -2
- package/admin/i18n/uk.json +25 -2
- package/admin/i18n/zh-cn.json +25 -2
- package/admin/jsonConfig.json +197 -13
- package/build/lib/credentials.js +11 -5
- package/build/lib/credentials.js.map +1 -1
- package/build/lib/llm.js +17 -3
- package/build/lib/llm.js.map +1 -1
- package/build/lib/nlu.js +249 -9
- package/build/lib/nlu.js.map +1 -1
- package/build/lib/piAgent.js +89 -0
- package/build/lib/piAgent.js.map +1 -0
- package/build/lib/systemAi.js +124 -0
- package/build/lib/systemAi.js.map +1 -0
- package/build/lib/voice/engines.js +31 -3
- package/build/lib/voice/engines.js.map +1 -1
- package/build/lib/voice/openrouter.js +220 -0
- package/build/lib/voice/openrouter.js.map +1 -0
- package/build/main.js +573 -59
- package/build/main.js.map +1 -1
- package/io-package.json +27 -17
- package/package.json +1 -1
- package/admin/custom/assets/Components-BSewCBfS.js +0 -2
- package/admin/custom/assets/_virtual_mf___mfe_internal__ConfigCustomAssistant__mf_owner__163539842885036__prebuild___mf_0_iobroker_mf_1_json_mf_2_config__prebuild__-SgSagTOv.js +0 -122
package/build/lib/llm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file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I,CAAC,OAAO,EAAE;oBAClE,KAAK,EAAE,IAAI,CAAC,KAAK;oBACjB,KAAK,EAAE,IAAI,CAAC,KAAK;iBACpB;aACJ,CAAC,CAAC;YACH,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC;gBACnB,OAAO,IAAI,CAAC,OAAO;qBACd,MAAM,CAAC,CAAC,CAAM,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC;qBACrC,GAAG,CAAC,CAAC,CAAM,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;qBACvB,IAAI,CAAC,EAAE,CAAC;qBACR,IAAI,EAAE,CAAC;YAChB,CAAC;YAED,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC;YAC5D,KAAK,GAAG,QAAQ,CAAC,MAAM,CAAC;YACxB,MAAM,WAAW,GAAG,EAAE,CAAC;YACvB,KAAK,MAAM,EAAE,IAAI,QAAQ,EAAE,CAAC;gBACxB,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,CAAC;gBACrD,WAAW,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,aAAa,EAAE,WAAW,EAAE,EAAE,CAAC,EAAE,EAAE,OAAO,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;YACnG,CAAC;YACD,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,CAAC,CAAC;QAC1D,CAAC;QACD,OAAO,IAAI,CAAC,aAAa,EAAE,CAAC;IAChC,CAAC;CACJ;AA9fD,4BA8fC","sourcesContent":["import OpenAI from 'openai';\nimport Anthropic from '@anthropic-ai/sdk';\nimport type { Tool } from './tools';\nimport { errorInfo, type JournalTokens, type TraceFn } from './journal';\n\n/** All selectable LLM providers. gemini/deepseek/custom all use the OpenAI-compatible SDK path. */\nexport type Provider = 'openai' | 'anthropic' | 'gemini' | 'deepseek' | 'custom';\n\ninterface ProviderPreset {\n /** Which vendor SDK to use. */\n sdk: 'openai' | 'anthropic';\n /** Fixed API base URL ('' = SDK default; for 'custom' the user's baseUrl is used instead). */\n baseUrl: string;\n /** Default model when none is configured. */\n defaultModel: string;\n}\n\n/** Per-provider SDK, endpoint and default model. Gemini/DeepSeek expose OpenAI-compatible endpoints. */\nexport const PROVIDER_PRESETS: Record<Provider, ProviderPreset> = {\n openai: { sdk: 'openai', baseUrl: '', defaultModel: 'gpt-4o-mini' },\n anthropic: { sdk: 'anthropic', baseUrl: '', defaultModel: 'claude-sonnet-4-6' },\n gemini: {\n sdk: 'openai',\n baseUrl: 'https://generativelanguage.googleapis.com/v1beta/openai/',\n defaultModel: 'gemini-2.0-flash',\n },\n deepseek: { sdk: 'openai', baseUrl: 'https://api.deepseek.com', defaultModel: 'deepseek-chat' },\n custom: { sdk: 'openai', baseUrl: '', defaultModel: '' },\n};\n\n/** Resolve the effective SDK, base URL and default model for a provider (custom uses `configBaseUrl`). */\nexport function resolveProvider(\n provider: string | undefined,\n configBaseUrl?: string,\n): { sdk: 'openai' | 'anthropic'; baseUrl: string; defaultModel: string } {\n const preset = PROVIDER_PRESETS[(provider as Provider) || 'openai'] || PROVIDER_PRESETS.openai;\n return {\n sdk: preset.sdk,\n baseUrl: provider === 'custom' ? configBaseUrl || '' : preset.baseUrl,\n defaultModel: preset.defaultModel,\n };\n}\n\n/**\n * API key to use for `provider`: a local OpenAI-compatible server (the `custom` provider) usually has no\n * key at all, but the OpenAI SDK refuses to start without one — a placeholder goes into the\n * `Authorization` header, which such servers ignore. Empty for every other provider without a key.\n */\nexport function effectiveApiKey(provider: string | undefined, apiKey: string): string {\n return apiKey || (provider === 'custom' ? 'no-key' : '');\n}\n\nexport interface LlmAgentOptions {\n provider: Provider;\n apiKey: string;\n model: string;\n baseUrl?: string;\n systemPrompt?: string;\n maxTokens?: number;\n tools: Tool[];\n log: ioBroker.Logger;\n /** Records the prompt and every round of {@link LlmAgent.ask} (the request journal's debug view). */\n trace?: TraceFn;\n}\n\n/** Normalised token counts of an OpenAI-compatible or Anthropic `usage` block. */\nfunction tokensOf(usage: any): JournalTokens | undefined {\n if (!usage || typeof usage !== 'object') {\n return undefined;\n }\n if (usage.input_tokens !== undefined) {\n return {\n input: Number(usage.input_tokens) || 0,\n output: Number(usage.output_tokens) || 0,\n cacheRead: Number(usage.cache_read_input_tokens) || undefined,\n cacheWrite: Number(usage.cache_creation_input_tokens) || undefined,\n };\n }\n return {\n input: Number(usage.prompt_tokens) || 0,\n output: Number(usage.completion_tokens) || 0,\n cacheRead: Number(usage.prompt_tokens_details?.cached_tokens) || undefined,\n };\n}\n\n/** \"Round 2 → get_states, set_state\" or \"Round 3 → answer\" — the title of a round in the trace. */\nfunction roundTitle(round: number, toolNames: string[]): string {\n return `Round ${round + 1} → ${toolNames.length ? toolNames.join(', ') : 'answer'}`;\n}\n\n/**\n * Provider-agnostic LLM agent with tool-calling.\n *\n * `ask(question)` runs the model, executes any tool calls it requests, feeds the\n * results back, and repeats until the model returns a final text answer.\n *\n * The request/response plumbing of the vendor SDKs is intentionally loosely typed\n * (`any`) so the code stays robust across minor SDK type changes; the public API\n * (options, `ask`, tools) is fully typed.\n */\nexport class LlmAgent {\n public readonly provider: 'openai' | 'anthropic';\n /** Configured model; empty means \"ask the server\" (see {@link ensureModel}). */\n private configuredModel: string;\n private modelLookup: Promise<string> | null = null;\n\n private readonly systemPrompt: string;\n private readonly maxTokens: number;\n private readonly tools: Tool[];\n private readonly toolMap: Record<string, Tool>;\n private readonly log: ioBroker.Logger;\n private readonly maxRounds = 6; // safety cap against tool-call loops\n /** Configured provider (gemini, deepseek, custom … — {@link provider} is only the SDK). */\n private readonly providerName: string;\n private readonly baseUrl: string;\n private readonly trace?: TraceFn;\n\n private readonly openai?: OpenAI;\n private readonly anthropic?: Anthropic;\n\n constructor(opts: LlmAgentOptions) {\n this.provider = opts.provider === 'anthropic' ? 'anthropic' : 'openai';\n this.providerName = opts.provider || this.provider;\n this.baseUrl = opts.baseUrl || '';\n this.trace = opts.trace;\n this.configuredModel = (opts.model || '').trim();\n this.systemPrompt = opts.systemPrompt || '';\n this.maxTokens = opts.maxTokens || 1024;\n this.tools = opts.tools || [];\n this.log = opts.log;\n this.toolMap = Object.fromEntries(this.tools.map(t => [t.name, t]));\n\n if (this.provider === 'anthropic') {\n this.anthropic = new Anthropic({ apiKey: opts.apiKey, baseURL: opts.baseUrl || undefined });\n } else {\n this.openai = new OpenAI({ apiKey: opts.apiKey, baseURL: opts.baseUrl || undefined });\n }\n }\n\n /** The model requests go to — empty until {@link ensureModel} has looked it up, if none was configured. */\n public get model(): string {\n return this.configuredModel;\n }\n\n /**\n * Make sure there is a model to send. A local OpenAI-compatible server (Ollama, LM Studio, llama.cpp\n * server, …) is usually set up with the `custom` provider and no model typed in — and sending\n * `\"model\": \"\"` gets a 400 from the server (\"unknown provider for model\" and the like) that says\n * nothing about the real cause. So an empty model is looked up once from the server's `/models` list\n * (with one model loaded, that is the one), and a server that lists nothing gets a clear error.\n */\n private async ensureModel(): Promise<string> {\n if (this.configuredModel) {\n return this.configuredModel;\n }\n this.modelLookup ||= this.listModels()\n .then(models => {\n if (!models.length) {\n throw new Error('no model configured and the server lists none');\n }\n this.configuredModel = models[0];\n this.log.info(\n `No model configured — using \"${models[0]}\" from the server${\n models.length > 1 ? ` (available: ${models.join(', ')})` : ''\n }. Select a model in the adapter settings to choose another.`,\n );\n return models[0];\n })\n .catch(e => {\n this.modelLookup = null; // let the next request try again (server may still be starting)\n throw new Error(\n `No model configured — select one in the adapter settings (lookup failed: ${(e as Error).message})`,\n );\n });\n return this.modelLookup;\n }\n\n /**\n * `systemPrompt` overrides the configured one for this call (e.g. to inject a device list).\n * `history` are prior turns (user/assistant) prepended so the model can resolve follow-ups.\n */\n public async ask(\n question: string,\n systemPrompt?: string,\n history: { role: 'user' | 'assistant'; content: string }[] = [],\n ): Promise<string> {\n await this.ensureModel();\n this.log.debug(`llm ask [${this.provider}/${this.model}] (${history.length} history): ${question}`);\n const started = Date.now();\n const sys = systemPrompt ?? this.systemPrompt;\n this.trace?.({\n stage: 'cloud',\n title: `${this.providerName} · ${this.model}: ${this.tools.length} tools, ${history.length} earlier turn(s)`,\n data: {\n provider: this.providerName,\n sdk: this.provider,\n model: this.model,\n baseUrl: this.baseUrl || undefined,\n maxTokens: this.maxTokens,\n maxRounds: this.maxRounds,\n system: sys,\n tools: this.tools.map(t => t.name),\n },\n });\n const answer =\n this.provider === 'anthropic'\n ? await this.askAnthropic(question, sys, history)\n : await this.askOpenAI(question, sys, history);\n this.log.debug(`llm answer (${Date.now() - started} ms): ${answer}`);\n return answer;\n }\n\n /** Compact, truncated JSON for debug logging of LLM requests/responses. */\n private dump(label: string, payload: unknown): void {\n if (this.log.level !== 'silly' && this.log.level !== 'debug') {\n return; // avoid stringifying large payloads when debug logging is off\n }\n const max = this.log.level === 'silly' ? 8000 : 1500;\n let text: string;\n try {\n text = JSON.stringify(payload);\n } catch {\n text = String(payload);\n }\n this.log.debug(`${label}: ${text.length > max ? `${text.slice(0, max)}…[${text.length}]` : text}`);\n }\n\n /**\n * One prompt in, one line out — no tools, no history, no system prompt. The small side jobs\n * (translate/rephrase/classify) all run through here.\n */\n private async complete(prompt: string, maxTokens: number): Promise<string> {\n await this.ensureModel();\n if (this.provider === 'anthropic') {\n const client = this.anthropic as Anthropic;\n const resp: any = await client.messages.create({\n model: this.model,\n max_tokens: maxTokens,\n messages: [{ role: 'user', content: prompt }],\n });\n return resp.content\n .filter((b: any) => b.type === 'text')\n .map((b: any) => b.text)\n .join('')\n .trim();\n }\n const client = this.openai as OpenAI;\n const resp: any = await client.chat.completions.create({\n model: this.model,\n max_tokens: maxTokens,\n messages: [{ role: 'user', content: prompt }],\n });\n return String(resp.choices[0].message.content || '').trim();\n }\n\n /** Translate a short device/room name into `targetLanguage` (single completion, no tools). */\n public async translate(text: string, targetLanguage: string): Promise<string> {\n const trimmed = (text || '').trim();\n if (!trimmed) {\n return '';\n }\n return this.complete(\n `Translate the following smart-home device or room name into ${targetLanguage}. ` +\n `Reply with ONLY the translation — no quotes, no punctuation, no explanation.\\n\\nName: ${trimmed}`,\n 64,\n );\n }\n\n /**\n * Reword a canned sentence (a trigger's announcement or question) so it sounds spoken rather than\n * templated, keeping every concrete detail. `persona` is the adapter's system prompt, so the reworded\n * line still sounds like the same assistant. Returns the input unchanged on any problem — a trigger\n * must still fire when the model is unavailable.\n */\n public async rephrase(text: string, language: string, persona = ''): Promise<string> {\n const trimmed = (text || '').trim();\n if (!trimmed) {\n return '';\n }\n try {\n const result = await this.complete(\n `${persona ? `${persona.trim()}\\n\\n` : ''}Reword the following sentence so it sounds natural and ` +\n `spoken${language ? `, in ${language}` : ''}. Keep every concrete detail (names, numbers, ` +\n `versions, times) and keep it one short sentence. If it is a question, keep it a question. ` +\n `Reply with ONLY the sentence.\\n\\nSentence: ${trimmed}`,\n 200,\n );\n return result || trimmed;\n } catch (e) {\n this.log.warn(`rephrase failed, using the original text: ${(e as Error).message}`);\n return trimmed;\n }\n }\n\n /**\n * Reword an ioBroker system notification into one spoken sentence, in the given `tone` (see\n * `notifications.toneFor`). Separate from {@link rephrase} because of the hints below: they are\n * specific to how ioBroker words its notifications, and each one comes from a real text that was\n * read out wrongly — version numbers mistaken for dates, origin prefixes spelled out letter by\n * letter, an empty `{}` announced as a problem. Returns the input unchanged on any failure.\n */\n public async rewordNotification(text: string, tone: string, language: string, persona = ''): Promise<string> {\n const trimmed = (text || '').trim();\n if (!trimmed) {\n return '';\n }\n try {\n const result = await this.complete(\n `${persona ? `${persona.trim()}\\n\\n` : ''}Reword the following system notification into one ` +\n `short, natural, spoken sentence${language ? `, in ${language}` : ''}. ` +\n `Keep every concrete detail such as adapter names and version numbers. ` +\n `Dates like M/D/YYYY or M/D/YYYY, H:MM:SS AM/PM are timestamps — say them as a date or ` +\n `a time, never as a version number. Technical prefixes such as ` +\n `\"system.host.XYZ: adapter.0:\" only say where it came from and need not be repeated. ` +\n `Empty values such as \"onedrive: {}\" mean there is nothing wrong there — only mention ` +\n `them if it matters. ${tone} Reply with ONLY the sentence.\\n\\nNotification: ${trimmed}`,\n 300,\n );\n return result || trimmed;\n } catch (e) {\n this.log.warn(`notification rewording failed, speaking the original: ${(e as Error).message}`);\n return trimmed;\n }\n }\n\n /**\n * Does `answer` express `category` (\"agreement\", \"Zustimmung\", \"refusal\", …)? This is the classifier\n * behind a trigger's response rules, where a spoken \"ja, mach das\" has to map onto one rule. Decided\n * by the model because the wording is open-ended; a failure answers `false`, so an unclassifiable\n * reply falls through to the trigger's fallback rule instead of acting on a guess.\n */\n public async classify(answer: string, category: string): Promise<boolean> {\n const text = (answer || '').trim();\n const want = (category || '').trim();\n if (!text || !want) {\n return false;\n }\n try {\n const verdict = await this.complete(\n `Does the following reply express \"${want}\"? Consider the meaning, in any language, ` +\n `including short or indirect phrasings. Answer with exactly YES or NO.\\n\\nReply: ${text}`,\n 8,\n );\n return /^\\s*(yes|ja|да)\\b/i.test(verdict);\n } catch (e) {\n this.log.warn(`classify failed ('${want}'): ${(e as Error).message}`);\n return false;\n }\n }\n\n /** Lightweight validation of the provider credentials (used by the settings Test button). */\n public async testConnection(): Promise<{ ok: boolean; error?: string }> {\n try {\n if (this.provider === 'anthropic') {\n const client = this.anthropic as Anthropic;\n await client.messages.create({\n model: await this.ensureModel(),\n max_tokens: 1,\n messages: [{ role: 'user', content: 'ping' }],\n });\n } else {\n const client = this.openai as OpenAI;\n await client.models.list();\n }\n return { ok: true };\n } catch (e) {\n return { ok: false, error: (e as Error).message };\n }\n }\n\n /** List the provider's available model ids (for the settings autocomplete). */\n public async listModels(): Promise<string[]> {\n if (this.provider === 'anthropic') {\n const client = this.anthropic as Anthropic;\n const res = (await client.models.list()) as unknown as { data?: { id: string }[] };\n return (res.data || []).map(m => m.id);\n }\n const client = this.openai as OpenAI;\n const res = (await client.models.list()) as unknown as { data?: { id: string }[] };\n // OpenAI lists many non-chat models (embeddings, tts, whisper, …) — filter to chat-capable-ish.\n const EXCLUDE =\n /embedding|whisper|tts|audio|dall-e|moderation|image|realtime|transcribe|search|davinci|babbage|codex/i;\n return (res.data || [])\n .map(m => String(m.id))\n .filter(id => !EXCLUDE.test(id))\n .sort();\n }\n\n /**\n * One model request of the tool loop, timed. A failure goes into the trace together with what was sent\n * (status, API error body, stack) before it is rethrown.\n */\n private async timedRound(\n round: number,\n sent: unknown[],\n call: () => Promise<any>,\n ): Promise<{ resp: any; ms: number }> {\n const start = Date.now();\n try {\n return { resp: await call(), ms: Date.now() - start };\n } catch (e) {\n this.trace?.({\n stage: 'cloud',\n level: 'error',\n title: `Round ${round + 1} failed: ${(e as Error).message}`,\n ms: Date.now() - start,\n data: { sent, error: errorInfo(e) },\n });\n throw e;\n }\n }\n\n private tooManyRounds(): string {\n this.trace?.({ stage: 'cloud', level: 'warn', title: `Gave up after ${this.maxRounds} rounds of tool calls` });\n return 'Ich konnte die Anfrage nicht abschließen (zu viele Tool-Schritte).';\n }\n\n private async runTool(name: string, args: Record<string, unknown>): Promise<unknown> {\n const tool = this.toolMap[name];\n if (!tool) {\n return { error: `unknown tool: ${name}` };\n }\n try {\n const result = await tool.run(args || {});\n this.log.info(`tool ${name}(${JSON.stringify(args)}) → ${JSON.stringify(result).slice(0, 200)}`);\n return result;\n } catch (e) {\n this.log.warn(`tool ${name} failed: ${(e as Error).message}`);\n return { error: (e as Error).message };\n }\n }\n\n // ── OpenAI (Chat Completions + function tools) ──────────────────────────\n private async askOpenAI(\n question: string,\n systemPrompt: string,\n history: { role: 'user' | 'assistant'; content: string }[] = [],\n ): Promise<string> {\n const client = this.openai as OpenAI;\n const tools = this.tools.map(t => ({\n type: 'function' as const,\n function: { name: t.name, description: t.description, parameters: t.parameters },\n }));\n\n const messages: any[] = [];\n if (systemPrompt) {\n messages.push({ role: 'system', content: systemPrompt });\n }\n for (const t of history) {\n messages.push({ role: t.role, content: t.content });\n }\n messages.push({ role: 'user', content: question });\n // Messages the trace has shown already: the system prompt is part of the opening step.\n let shown = systemPrompt ? 1 : 0;\n\n for (let round = 0; round < this.maxRounds; round++) {\n const request = {\n model: this.model,\n messages,\n tools: tools.length ? tools : undefined,\n max_tokens: this.maxTokens,\n };\n this.dump(`llm → openai round ${round}`, request);\n const sent = messages.slice(shown);\n const { resp, ms } = await this.timedRound(round, sent, () => client.chat.completions.create(request));\n const msg = resp.choices[0].message;\n this.dump(`llm ← openai round ${round}`, { message: msg, usage: resp.usage });\n messages.push(msg);\n shown = messages.length;\n this.trace?.({\n stage: 'cloud',\n title: roundTitle(\n round,\n (msg.tool_calls || []).map((tc: any) => String(tc.function?.name)),\n ),\n ms,\n tokens: tokensOf(resp.usage),\n data: {\n sent,\n response: { finish_reason: resp.choices[0].finish_reason, message: msg },\n model: resp.model,\n usage: resp.usage,\n },\n });\n\n if (!msg.tool_calls || !msg.tool_calls.length) {\n return String(msg.content || '').trim();\n }\n\n for (const tc of msg.tool_calls) {\n let args: Record<string, unknown> = {};\n try {\n args = JSON.parse(tc.function.arguments || '{}');\n } catch {\n /* leave empty */\n }\n const result = await this.runTool(tc.function.name, args);\n messages.push({ role: 'tool', tool_call_id: tc.id, content: JSON.stringify(result) });\n }\n }\n return this.tooManyRounds();\n }\n\n /**\n * Keep a single cache breakpoint on the last content block of the last message (Anthropic allows\n * ≤4 total; we also mark system + last tool). Strips prior message breakpoints so we never exceed it.\n */\n private markLastMessageForCache(messages: any[]): void {\n for (const m of messages) {\n if (Array.isArray(m.content)) {\n for (const b of m.content) {\n if (b && typeof b === 'object') {\n delete b.cache_control;\n }\n }\n }\n }\n const last = messages[messages.length - 1];\n if (!last) {\n return;\n }\n if (typeof last.content === 'string') {\n last.content = [{ type: 'text', text: last.content, cache_control: { type: 'ephemeral' } }];\n } else if (Array.isArray(last.content) && last.content.length) {\n const b = last.content[last.content.length - 1];\n if (b && typeof b === 'object') {\n b.cache_control = { type: 'ephemeral' };\n }\n }\n }\n\n // ── Anthropic (Messages API + tool_use) ─────────────────────────────────\n private async askAnthropic(\n question: string,\n systemPrompt: string,\n history: { role: 'user' | 'assistant'; content: string }[] = [],\n ): Promise<string> {\n const client = this.anthropic as Anthropic;\n const tools: any[] = this.tools.map(t => ({\n name: t.name,\n description: t.description,\n input_schema: t.parameters as Anthropic.Tool.InputSchema,\n }));\n // Prompt caching: mark the last tool → the static prefix (system + all tools) is cached and\n // read back on every later round/request (5-min TTL), cutting latency & cost on the big context.\n if (tools.length) {\n tools[tools.length - 1] = { ...tools[tools.length - 1], cache_control: { type: 'ephemeral' } };\n }\n const system: any = systemPrompt\n ? [{ type: 'text', text: systemPrompt, cache_control: { type: 'ephemeral' } }]\n : undefined;\n\n const messages: any[] = [\n ...history.map(t => ({ role: t.role, content: t.content })),\n { role: 'user', content: question },\n ];\n // Messages the trace has shown already (the system prompt is part of the opening step).\n let shown = 0;\n\n for (let round = 0; round < this.maxRounds; round++) {\n // Cache the growing conversation prefix too (e.g. the large list_devices result): move a\n // single cache breakpoint to the last content block of the last message each round.\n this.markLastMessageForCache(messages);\n const request = {\n model: this.model,\n max_tokens: this.maxTokens,\n system,\n tools: tools.length ? tools : undefined,\n messages,\n };\n this.dump(`llm → anthropic round ${round}`, request);\n const sent = messages.slice(shown);\n const { resp, ms } = await this.timedRound(round, sent, () => client.messages.create(request));\n this.dump(`llm ← anthropic round ${round}`, { content: resp.content, usage: resp.usage });\n\n const toolUses = resp.content.filter((b: any) => b.type === 'tool_use');\n this.trace?.({\n stage: 'cloud',\n title: roundTitle(\n round,\n toolUses.map((b: any) => String(b.name)),\n ),\n ms,\n tokens: tokensOf(resp.usage),\n data: {\n sent,\n response: { stop_reason: resp.stop_reason, content: resp.content },\n model: resp.model,\n usage: resp.usage,\n },\n });\n if (!toolUses.length) {\n return resp.content\n .filter((b: any) => b.type === 'text')\n .map((b: any) => b.text)\n .join('')\n .trim();\n }\n\n messages.push({ role: 'assistant', content: resp.content });\n shown = messages.length;\n const toolResults = [];\n for (const tu of toolUses) {\n const result = await this.runTool(tu.name, tu.input);\n toolResults.push({ type: 'tool_result', tool_use_id: tu.id, content: JSON.stringify(result) });\n }\n messages.push({ role: 'user', content: toolResults });\n }\n return this.tooManyRounds();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"llm.js","sourceRoot":"","sources":["../../src/lib/llm.ts"],"names":[],"mappings":";;;;;;AAoCA,0CAUC;AAOD,0CAEC;AAvDD,oDAA4B;AAC5B,4DAA0C;AAE1C,uCAAwE;AAcxE,wGAAwG;AAC3F,QAAA,gBAAgB,GAAqC;IAC9D,MAAM,EAAE,EAAE,GAAG,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE,EAAE,YAAY,EAAE,aAAa,EAAE;IACnE,SAAS,EAAE,EAAE,GAAG,EAAE,WAAW,EAAE,OAAO,EAAE,EAAE,EAAE,YAAY,EAAE,mBAAmB,EAAE;IAC/E,MAAM,EAAE;QACJ,GAAG,EAAE,QAAQ;QACb,OAAO,EAAE,0DAA0D;QACnE,YAAY,EAAE,kBAAkB;KACnC;IACD,QAAQ,EAAE,EAAE,GAAG,EAAE,QAAQ,EAAE,OAAO,EAAE,0BAA0B,EAAE,YAAY,EAAE,eAAe,EAAE;IAC/F,oDAAoD;IACpD,UAAU,EAAE,EAAE,GAAG,EAAE,QAAQ,EAAE,OAAO,EAAE,8BAA8B,EAAE,YAAY,EAAE,oBAAoB,EAAE;IAC1G,MAAM,EAAE,EAAE,GAAG,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE,EAAE,YAAY,EAAE,EAAE,EAAE;CAC3D,CAAC;AAEF,mGAAmG;AACtF,QAAA,kBAAkB,GAAG,EAAE,cAAc,EAAE,0BAA0B,EAAE,SAAS,EAAE,UAAU,EAAE,CAAC;AAExG,0GAA0G;AAC1G,SAAgB,eAAe,CAC3B,QAA4B,EAC5B,aAAsB;IAEtB,MAAM,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I,CAAC,OAAO,EAAE,CAAC,CAAC;YAC5D,KAAK,GAAG,QAAQ,CAAC,MAAM,CAAC;YACxB,MAAM,WAAW,GAAG,EAAE,CAAC;YACvB,KAAK,MAAM,EAAE,IAAI,QAAQ,EAAE,CAAC;gBACxB,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,CAAC;gBACrD,WAAW,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,aAAa,EAAE,WAAW,EAAE,EAAE,CAAC,EAAE,EAAE,OAAO,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;YACnG,CAAC;YACD,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,CAAC,CAAC;QAC1D,CAAC;QACD,OAAO,IAAI,CAAC,aAAa,EAAE,CAAC;IAChC,CAAC;CACJ;AAvgBD,4BAugBC","sourcesContent":["import OpenAI from 'openai';\nimport Anthropic from '@anthropic-ai/sdk';\nimport type { Tool } from './tools';\nimport { errorInfo, type JournalTokens, type TraceFn } from './journal';\n\n/** All selectable LLM providers. gemini/deepseek/openrouter/custom all use the OpenAI-compatible SDK path. */\nexport type Provider = 'openai' | 'anthropic' | 'gemini' | 'deepseek' | 'openrouter' | 'custom';\n\ninterface ProviderPreset {\n /** Which vendor SDK to use. */\n sdk: 'openai' | 'anthropic';\n /** Fixed API base URL ('' = SDK default; for 'custom' the user's baseUrl is used instead). */\n baseUrl: string;\n /** Default model when none is configured. */\n defaultModel: string;\n}\n\n/** Per-provider SDK, endpoint and default model. Gemini/DeepSeek expose OpenAI-compatible endpoints. */\nexport const PROVIDER_PRESETS: Record<Provider, ProviderPreset> = {\n openai: { sdk: 'openai', baseUrl: '', defaultModel: 'gpt-4o-mini' },\n anthropic: { sdk: 'anthropic', baseUrl: '', defaultModel: 'claude-sonnet-4-6' },\n gemini: {\n sdk: 'openai',\n baseUrl: 'https://generativelanguage.googleapis.com/v1beta/openai/',\n defaultModel: 'gemini-2.0-flash',\n },\n deepseek: { sdk: 'openai', baseUrl: 'https://api.deepseek.com', defaultModel: 'deepseek-chat' },\n // OpenRouter names a model with its vendor in front\n openrouter: { sdk: 'openai', baseUrl: 'https://openrouter.ai/api/v1', defaultModel: 'openai/gpt-4o-mini' },\n custom: { sdk: 'openai', baseUrl: '', defaultModel: '' },\n};\n\n/** OpenRouter shows the calling app in its statistics (same attribution as `@iobroker/ai-core`) */\nexport const OPENROUTER_HEADERS = { 'HTTP-Referer': 'https://www.iobroker.net', 'X-Title': 'ioBroker' };\n\n/** Resolve the effective SDK, base URL and default model for a provider (custom uses `configBaseUrl`). */\nexport function resolveProvider(\n provider: string | undefined,\n configBaseUrl?: string,\n): { sdk: 'openai' | 'anthropic'; baseUrl: string; defaultModel: string } {\n const preset = PROVIDER_PRESETS[(provider as Provider) || 'openai'] || PROVIDER_PRESETS.openai;\n return {\n sdk: preset.sdk,\n baseUrl: provider === 'custom' ? configBaseUrl || '' : preset.baseUrl,\n defaultModel: preset.defaultModel,\n };\n}\n\n/**\n * API key to use for `provider`: a local OpenAI-compatible server (the `custom` provider) usually has no\n * key at all, but the OpenAI SDK refuses to start without one — a placeholder goes into the\n * `Authorization` header, which such servers ignore. Empty for every other provider without a key.\n */\nexport function effectiveApiKey(provider: string | undefined, apiKey: string): string {\n return apiKey || (provider === 'custom' ? 'no-key' : '');\n}\n\nexport interface LlmAgentOptions {\n provider: Provider;\n apiKey: string;\n model: string;\n baseUrl?: string;\n systemPrompt?: string;\n maxTokens?: number;\n tools: Tool[];\n log: ioBroker.Logger;\n /** Records the prompt and every round of {@link LlmAgent.ask} (the request journal's debug view). */\n trace?: TraceFn;\n}\n\n/** Normalised token counts of an OpenAI-compatible or Anthropic `usage` block. */\nfunction tokensOf(usage: any): JournalTokens | undefined {\n if (!usage || typeof usage !== 'object') {\n return undefined;\n }\n if (usage.input_tokens !== undefined) {\n return {\n input: Number(usage.input_tokens) || 0,\n output: Number(usage.output_tokens) || 0,\n cacheRead: Number(usage.cache_read_input_tokens) || undefined,\n cacheWrite: Number(usage.cache_creation_input_tokens) || undefined,\n };\n }\n return {\n input: Number(usage.prompt_tokens) || 0,\n output: Number(usage.completion_tokens) || 0,\n cacheRead: Number(usage.prompt_tokens_details?.cached_tokens) || undefined,\n };\n}\n\n/** \"Round 2 → get_states, set_state\" or \"Round 3 → answer\" — the title of a round in the trace. */\nfunction roundTitle(round: number, toolNames: string[]): string {\n return `Round ${round + 1} → ${toolNames.length ? toolNames.join(', ') : 'answer'}`;\n}\n\n/**\n * Provider-agnostic LLM agent with tool-calling.\n *\n * `ask(question)` runs the model, executes any tool calls it requests, feeds the\n * results back, and repeats until the model returns a final text answer.\n *\n * The request/response plumbing of the vendor SDKs is intentionally loosely typed\n * (`any`) so the code stays robust across minor SDK type changes; the public API\n * (options, `ask`, tools) is fully typed.\n */\nexport class LlmAgent {\n public readonly provider: 'openai' | 'anthropic';\n /** Configured model; empty means \"ask the server\" (see {@link ensureModel}). */\n private configuredModel: string;\n private modelLookup: Promise<string> | null = null;\n\n private readonly systemPrompt: string;\n private readonly maxTokens: number;\n private readonly tools: Tool[];\n private readonly toolMap: Record<string, Tool>;\n private readonly log: ioBroker.Logger;\n private readonly maxRounds = 6; // safety cap against tool-call loops\n /** Configured provider (gemini, deepseek, custom … — {@link provider} is only the SDK). */\n private readonly providerName: string;\n private readonly baseUrl: string;\n private readonly trace?: TraceFn;\n\n private readonly openai?: OpenAI;\n private readonly anthropic?: Anthropic;\n\n constructor(opts: LlmAgentOptions) {\n this.provider = opts.provider === 'anthropic' ? 'anthropic' : 'openai';\n this.providerName = opts.provider || this.provider;\n this.baseUrl = opts.baseUrl || '';\n this.trace = opts.trace;\n this.configuredModel = (opts.model || '').trim();\n this.systemPrompt = opts.systemPrompt || '';\n this.maxTokens = opts.maxTokens || 1024;\n this.tools = opts.tools || [];\n this.log = opts.log;\n this.toolMap = Object.fromEntries(this.tools.map(t => [t.name, t]));\n\n if (this.provider === 'anthropic') {\n this.anthropic = new Anthropic({ apiKey: opts.apiKey, baseURL: opts.baseUrl || undefined });\n } else {\n this.openai = new OpenAI({\n apiKey: opts.apiKey,\n baseURL: opts.baseUrl || undefined,\n defaultHeaders: opts.provider === 'openrouter' ? OPENROUTER_HEADERS : undefined,\n });\n }\n }\n\n /** The model requests go to — empty until {@link ensureModel} has looked it up, if none was configured. */\n public get model(): string {\n return this.configuredModel;\n }\n\n /**\n * Make sure there is a model to send. A local OpenAI-compatible server (Ollama, LM Studio, llama.cpp\n * server, …) is usually set up with the `custom` provider and no model typed in — and sending\n * `\"model\": \"\"` gets a 400 from the server (\"unknown provider for model\" and the like) that says\n * nothing about the real cause. So an empty model is looked up once from the server's `/models` list\n * (with one model loaded, that is the one), and a server that lists nothing gets a clear error.\n */\n private async ensureModel(): Promise<string> {\n if (this.configuredModel) {\n return this.configuredModel;\n }\n this.modelLookup ||= this.listModels()\n .then(models => {\n if (!models.length) {\n throw new Error('no model configured and the server lists none');\n }\n this.configuredModel = models[0];\n this.log.info(\n `No model configured — using \"${models[0]}\" from the server${\n models.length > 1 ? ` (available: ${models.join(', ')})` : ''\n }. Select a model in the adapter settings to choose another.`,\n );\n return models[0];\n })\n .catch(e => {\n this.modelLookup = null; // let the next request try again (server may still be starting)\n throw new Error(\n `No model configured — select one in the adapter settings (lookup failed: ${(e as Error).message})`,\n );\n });\n return this.modelLookup;\n }\n\n /**\n * `systemPrompt` overrides the configured one for this call (e.g. to inject a device list).\n * `history` are prior turns (user/assistant) prepended so the model can resolve follow-ups.\n */\n public async ask(\n question: string,\n systemPrompt?: string,\n history: { role: 'user' | 'assistant'; content: string }[] = [],\n ): Promise<string> {\n await this.ensureModel();\n this.log.debug(`llm ask [${this.provider}/${this.model}] (${history.length} history): ${question}`);\n const started = Date.now();\n const sys = systemPrompt ?? this.systemPrompt;\n this.trace?.({\n stage: 'cloud',\n title: `${this.providerName} · ${this.model}: ${this.tools.length} tools, ${history.length} earlier turn(s)`,\n data: {\n provider: this.providerName,\n sdk: this.provider,\n model: this.model,\n baseUrl: this.baseUrl || undefined,\n maxTokens: this.maxTokens,\n maxRounds: this.maxRounds,\n system: sys,\n tools: this.tools.map(t => t.name),\n },\n });\n const answer =\n this.provider === 'anthropic'\n ? await this.askAnthropic(question, sys, history)\n : await this.askOpenAI(question, sys, history);\n this.log.debug(`llm answer (${Date.now() - started} ms): ${answer}`);\n return answer;\n }\n\n /** Compact, truncated JSON for debug logging of LLM requests/responses. */\n private dump(label: string, payload: unknown): void {\n if (this.log.level !== 'silly' && this.log.level !== 'debug') {\n return; // avoid stringifying large payloads when debug logging is off\n }\n const max = this.log.level === 'silly' ? 8000 : 1500;\n let text: string;\n try {\n text = JSON.stringify(payload);\n } catch {\n text = String(payload);\n }\n this.log.debug(`${label}: ${text.length > max ? `${text.slice(0, max)}…[${text.length}]` : text}`);\n }\n\n /**\n * One prompt in, one line out — no tools, no history, no system prompt. The small side jobs\n * (translate/rephrase/classify) all run through here.\n */\n private async complete(prompt: string, maxTokens: number): Promise<string> {\n await this.ensureModel();\n if (this.provider === 'anthropic') {\n const client = this.anthropic as Anthropic;\n const resp: any = await client.messages.create({\n model: this.model,\n max_tokens: maxTokens,\n messages: [{ role: 'user', content: prompt }],\n });\n return resp.content\n .filter((b: any) => b.type === 'text')\n .map((b: any) => b.text)\n .join('')\n .trim();\n }\n const client = this.openai as OpenAI;\n const resp: any = await client.chat.completions.create({\n model: this.model,\n max_tokens: maxTokens,\n messages: [{ role: 'user', content: prompt }],\n });\n return String(resp.choices[0].message.content || '').trim();\n }\n\n /** Translate a short device/room name into `targetLanguage` (single completion, no tools). */\n public async translate(text: string, targetLanguage: string): Promise<string> {\n const trimmed = (text || '').trim();\n if (!trimmed) {\n return '';\n }\n return this.complete(\n `Translate the following smart-home device or room name into ${targetLanguage}. ` +\n `Reply with ONLY the translation — no quotes, no punctuation, no explanation.\\n\\nName: ${trimmed}`,\n 64,\n );\n }\n\n /**\n * Reword a canned sentence (a trigger's announcement or question) so it sounds spoken rather than\n * templated, keeping every concrete detail. `persona` is the adapter's system prompt, so the reworded\n * line still sounds like the same assistant. Returns the input unchanged on any problem — a trigger\n * must still fire when the model is unavailable.\n */\n public async rephrase(text: string, language: string, persona = ''): Promise<string> {\n const trimmed = (text || '').trim();\n if (!trimmed) {\n return '';\n }\n try {\n const result = await this.complete(\n `${persona ? `${persona.trim()}\\n\\n` : ''}Reword the following sentence so it sounds natural and ` +\n `spoken${language ? `, in ${language}` : ''}. Keep every concrete detail (names, numbers, ` +\n `versions, times) and keep it one short sentence. If it is a question, keep it a question. ` +\n `Reply with ONLY the sentence.\\n\\nSentence: ${trimmed}`,\n 200,\n );\n return result || trimmed;\n } catch (e) {\n this.log.warn(`rephrase failed, using the original text: ${(e as Error).message}`);\n return trimmed;\n }\n }\n\n /**\n * Reword an ioBroker system notification into one spoken sentence, in the given `tone` (see\n * `notifications.toneFor`). Separate from {@link rephrase} because of the hints below: they are\n * specific to how ioBroker words its notifications, and each one comes from a real text that was\n * read out wrongly — version numbers mistaken for dates, origin prefixes spelled out letter by\n * letter, an empty `{}` announced as a problem. Returns the input unchanged on any failure.\n */\n public async rewordNotification(text: string, tone: string, language: string, persona = ''): Promise<string> {\n const trimmed = (text || '').trim();\n if (!trimmed) {\n return '';\n }\n try {\n const result = await this.complete(\n `${persona ? `${persona.trim()}\\n\\n` : ''}Reword the following system notification into one ` +\n `short, natural, spoken sentence${language ? `, in ${language}` : ''}. ` +\n `Keep every concrete detail such as adapter names and version numbers. ` +\n `Dates like M/D/YYYY or M/D/YYYY, H:MM:SS AM/PM are timestamps — say them as a date or ` +\n `a time, never as a version number. Technical prefixes such as ` +\n `\"system.host.XYZ: adapter.0:\" only say where it came from and need not be repeated. ` +\n `Empty values such as \"onedrive: {}\" mean there is nothing wrong there — only mention ` +\n `them if it matters. ${tone} Reply with ONLY the sentence.\\n\\nNotification: ${trimmed}`,\n 300,\n );\n return result || trimmed;\n } catch (e) {\n this.log.warn(`notification rewording failed, speaking the original: ${(e as Error).message}`);\n return trimmed;\n }\n }\n\n /**\n * Does `answer` express `category` (\"agreement\", \"Zustimmung\", \"refusal\", …)? This is the classifier\n * behind a trigger's response rules, where a spoken \"ja, mach das\" has to map onto one rule. Decided\n * by the model because the wording is open-ended; a failure answers `false`, so an unclassifiable\n * reply falls through to the trigger's fallback rule instead of acting on a guess.\n */\n public async classify(answer: string, category: string): Promise<boolean> {\n const text = (answer || '').trim();\n const want = (category || '').trim();\n if (!text || !want) {\n return false;\n }\n try {\n const verdict = await this.complete(\n `Does the following reply express \"${want}\"? Consider the meaning, in any language, ` +\n `including short or indirect phrasings. Answer with exactly YES or NO.\\n\\nReply: ${text}`,\n 8,\n );\n return /^\\s*(yes|ja|да)\\b/i.test(verdict);\n } catch (e) {\n this.log.warn(`classify failed ('${want}'): ${(e as Error).message}`);\n return false;\n }\n }\n\n /** Lightweight validation of the provider credentials (used by the settings Test button). */\n public async testConnection(): Promise<{ ok: boolean; error?: string }> {\n try {\n if (this.provider === 'anthropic') {\n const client = this.anthropic as Anthropic;\n await client.messages.create({\n model: await this.ensureModel(),\n max_tokens: 1,\n messages: [{ role: 'user', content: 'ping' }],\n });\n } else {\n const client = this.openai as OpenAI;\n if (this.providerName === 'openrouter') {\n // its model list is public and accepts any key; /key needs a valid one\n await client.get('/key');\n } else {\n await client.models.list();\n }\n }\n return { ok: true };\n } catch (e) {\n return { ok: false, error: (e as Error).message };\n }\n }\n\n /** List the provider's available model ids (for the settings autocomplete). */\n public async listModels(): Promise<string[]> {\n if (this.provider === 'anthropic') {\n const client = this.anthropic as Anthropic;\n const res = (await client.models.list()) as unknown as { data?: { id: string }[] };\n return (res.data || []).map(m => m.id);\n }\n const client = this.openai as OpenAI;\n const res = (await client.models.list()) as unknown as { data?: { id: string }[] };\n // OpenAI lists many non-chat models (embeddings, tts, whisper, …) — filter to chat-capable-ish.\n const EXCLUDE =\n /embedding|whisper|tts|audio|dall-e|moderation|image|realtime|transcribe|search|davinci|babbage|codex/i;\n return (res.data || [])\n .map(m => String(m.id))\n .filter(id => !EXCLUDE.test(id))\n .sort();\n }\n\n /**\n * One model request of the tool loop, timed. A failure goes into the trace together with what was sent\n * (status, API error body, stack) before it is rethrown.\n */\n private async timedRound(\n round: number,\n sent: unknown[],\n call: () => Promise<any>,\n ): Promise<{ resp: any; ms: number }> {\n const start = Date.now();\n try {\n return { resp: await call(), ms: Date.now() - start };\n } catch (e) {\n this.trace?.({\n stage: 'cloud',\n level: 'error',\n title: `Round ${round + 1} failed: ${(e as Error).message}`,\n ms: Date.now() - start,\n data: { sent, error: errorInfo(e) },\n });\n throw e;\n }\n }\n\n private tooManyRounds(): string {\n this.trace?.({ stage: 'cloud', level: 'warn', title: `Gave up after ${this.maxRounds} rounds of tool calls` });\n return 'Ich konnte die Anfrage nicht abschließen (zu viele Tool-Schritte).';\n }\n\n private async runTool(name: string, args: Record<string, unknown>): Promise<unknown> {\n const tool = this.toolMap[name];\n if (!tool) {\n return { error: `unknown tool: ${name}` };\n }\n try {\n const result = await tool.run(args || {});\n this.log.info(`tool ${name}(${JSON.stringify(args)}) → ${JSON.stringify(result).slice(0, 200)}`);\n return result;\n } catch (e) {\n this.log.warn(`tool ${name} failed: ${(e as Error).message}`);\n return { error: (e as Error).message };\n }\n }\n\n // ── OpenAI (Chat Completions + function tools) ──────────────────────────\n private async askOpenAI(\n question: string,\n systemPrompt: string,\n history: { role: 'user' | 'assistant'; content: string }[] = [],\n ): Promise<string> {\n const client = this.openai as OpenAI;\n const tools = this.tools.map(t => ({\n type: 'function' as const,\n function: { name: t.name, description: t.description, parameters: t.parameters },\n }));\n\n const messages: any[] = [];\n if (systemPrompt) {\n messages.push({ role: 'system', content: systemPrompt });\n }\n for (const t of history) {\n messages.push({ role: t.role, content: t.content });\n }\n messages.push({ role: 'user', content: question });\n // Messages the trace has shown already: the system prompt is part of the opening step.\n let shown = systemPrompt ? 1 : 0;\n\n for (let round = 0; round < this.maxRounds; round++) {\n const request = {\n model: this.model,\n messages,\n tools: tools.length ? tools : undefined,\n max_tokens: this.maxTokens,\n };\n this.dump(`llm → openai round ${round}`, request);\n const sent = messages.slice(shown);\n const { resp, ms } = await this.timedRound(round, sent, () => client.chat.completions.create(request));\n const msg = resp.choices[0].message;\n this.dump(`llm ← openai round ${round}`, { message: msg, usage: resp.usage });\n messages.push(msg);\n shown = messages.length;\n this.trace?.({\n stage: 'cloud',\n title: roundTitle(\n round,\n (msg.tool_calls || []).map((tc: any) => String(tc.function?.name)),\n ),\n ms,\n tokens: tokensOf(resp.usage),\n data: {\n sent,\n response: { finish_reason: resp.choices[0].finish_reason, message: msg },\n model: resp.model,\n usage: resp.usage,\n },\n });\n\n if (!msg.tool_calls || !msg.tool_calls.length) {\n return String(msg.content || '').trim();\n }\n\n for (const tc of msg.tool_calls) {\n let args: Record<string, unknown> = {};\n try {\n args = JSON.parse(tc.function.arguments || '{}');\n } catch {\n /* leave empty */\n }\n const result = await this.runTool(tc.function.name, args);\n messages.push({ role: 'tool', tool_call_id: tc.id, content: JSON.stringify(result) });\n }\n }\n return this.tooManyRounds();\n }\n\n /**\n * Keep a single cache breakpoint on the last content block of the last message (Anthropic allows\n * ≤4 total; we also mark system + last tool). Strips prior message breakpoints so we never exceed it.\n */\n private markLastMessageForCache(messages: any[]): void {\n for (const m of messages) {\n if (Array.isArray(m.content)) {\n for (const b of m.content) {\n if (b && typeof b === 'object') {\n delete b.cache_control;\n }\n }\n }\n }\n const last = messages[messages.length - 1];\n if (!last) {\n return;\n }\n if (typeof last.content === 'string') {\n last.content = [{ type: 'text', text: last.content, cache_control: { type: 'ephemeral' } }];\n } else if (Array.isArray(last.content) && last.content.length) {\n const b = last.content[last.content.length - 1];\n if (b && typeof b === 'object') {\n b.cache_control = { type: 'ephemeral' };\n }\n }\n }\n\n // ── Anthropic (Messages API + tool_use) ─────────────────────────────────\n private async askAnthropic(\n question: string,\n systemPrompt: string,\n history: { role: 'user' | 'assistant'; content: string }[] = [],\n ): Promise<string> {\n const client = this.anthropic as Anthropic;\n const tools: any[] = this.tools.map(t => ({\n name: t.name,\n description: t.description,\n input_schema: t.parameters as Anthropic.Tool.InputSchema,\n }));\n // Prompt caching: mark the last tool → the static prefix (system + all tools) is cached and\n // read back on every later round/request (5-min TTL), cutting latency & cost on the big context.\n if (tools.length) {\n tools[tools.length - 1] = { ...tools[tools.length - 1], cache_control: { type: 'ephemeral' } };\n }\n const system: any = systemPrompt\n ? [{ type: 'text', text: systemPrompt, cache_control: { type: 'ephemeral' } }]\n : undefined;\n\n const messages: any[] = [\n ...history.map(t => ({ role: t.role, content: t.content })),\n { role: 'user', content: question },\n ];\n // Messages the trace has shown already (the system prompt is part of the opening step).\n let shown = 0;\n\n for (let round = 0; round < this.maxRounds; round++) {\n // Cache the growing conversation prefix too (e.g. the large list_devices result): move a\n // single cache breakpoint to the last content block of the last message each round.\n this.markLastMessageForCache(messages);\n const request = {\n model: this.model,\n max_tokens: this.maxTokens,\n system,\n tools: tools.length ? tools : undefined,\n messages,\n };\n this.dump(`llm → anthropic round ${round}`, request);\n const sent = messages.slice(shown);\n const { resp, ms } = await this.timedRound(round, sent, () => client.messages.create(request));\n this.dump(`llm ← anthropic round ${round}`, { content: resp.content, usage: resp.usage });\n\n const toolUses = resp.content.filter((b: any) => b.type === 'tool_use');\n this.trace?.({\n stage: 'cloud',\n title: roundTitle(\n round,\n toolUses.map((b: any) => String(b.name)),\n ),\n ms,\n tokens: tokensOf(resp.usage),\n data: {\n sent,\n response: { stop_reason: resp.stop_reason, content: resp.content },\n model: resp.model,\n usage: resp.usage,\n },\n });\n if (!toolUses.length) {\n return resp.content\n .filter((b: any) => b.type === 'text')\n .map((b: any) => b.text)\n .join('')\n .trim();\n }\n\n messages.push({ role: 'assistant', content: resp.content });\n shown = messages.length;\n const toolResults = [];\n for (const tu of toolUses) {\n const result = await this.runTool(tu.name, tu.input);\n toolResults.push({ type: 'tool_result', tool_use_id: tu.id, content: JSON.stringify(result) });\n }\n messages.push({ role: 'user', content: toolResults });\n }\n return this.tooManyRounds();\n }\n}\n"]}
|
package/build/lib/nlu.js
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
*/
|
|
12
12
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
13
13
|
exports.Nlu = void 0;
|
|
14
|
+
exports.spelledNumbersToDigits = spelledNumbersToDigits;
|
|
14
15
|
exports.parseClockTime = parseClockTime;
|
|
15
16
|
exports.parseWeekdays = parseWeekdays;
|
|
16
17
|
exports.parseDurationSeconds = parseDurationSeconds;
|
|
@@ -303,6 +304,158 @@ const NUMBER_WORDS = {
|
|
|
303
304
|
девять: '9',
|
|
304
305
|
десять: '10',
|
|
305
306
|
};
|
|
307
|
+
/** Units 1–9 (normalized), de/en/ru — the parts of a spelled-out number above twelve */
|
|
308
|
+
const UNIT_WORDS = {
|
|
309
|
+
eins: 1,
|
|
310
|
+
zwei: 2,
|
|
311
|
+
drei: 3,
|
|
312
|
+
vier: 4,
|
|
313
|
+
fuenf: 5,
|
|
314
|
+
sechs: 6,
|
|
315
|
+
sieben: 7,
|
|
316
|
+
acht: 8,
|
|
317
|
+
neun: 9,
|
|
318
|
+
one: 1,
|
|
319
|
+
two: 2,
|
|
320
|
+
three: 3,
|
|
321
|
+
four: 4,
|
|
322
|
+
five: 5,
|
|
323
|
+
six: 6,
|
|
324
|
+
seven: 7,
|
|
325
|
+
eight: 8,
|
|
326
|
+
nine: 9,
|
|
327
|
+
один: 1,
|
|
328
|
+
одна: 1,
|
|
329
|
+
одно: 1,
|
|
330
|
+
два: 2,
|
|
331
|
+
две: 2,
|
|
332
|
+
три: 3,
|
|
333
|
+
четыре: 4,
|
|
334
|
+
пять: 5,
|
|
335
|
+
шесть: 6,
|
|
336
|
+
семь: 7,
|
|
337
|
+
восемь: 8,
|
|
338
|
+
девять: 9,
|
|
339
|
+
};
|
|
340
|
+
/** 10–19, de/en/ru */
|
|
341
|
+
const TEEN_WORDS = {
|
|
342
|
+
zehn: 10,
|
|
343
|
+
elf: 11,
|
|
344
|
+
zwoelf: 12,
|
|
345
|
+
dreizehn: 13,
|
|
346
|
+
vierzehn: 14,
|
|
347
|
+
fuenfzehn: 15,
|
|
348
|
+
sechzehn: 16,
|
|
349
|
+
siebzehn: 17,
|
|
350
|
+
achtzehn: 18,
|
|
351
|
+
neunzehn: 19,
|
|
352
|
+
ten: 10,
|
|
353
|
+
eleven: 11,
|
|
354
|
+
twelve: 12,
|
|
355
|
+
thirteen: 13,
|
|
356
|
+
fourteen: 14,
|
|
357
|
+
fifteen: 15,
|
|
358
|
+
sixteen: 16,
|
|
359
|
+
seventeen: 17,
|
|
360
|
+
eighteen: 18,
|
|
361
|
+
nineteen: 19,
|
|
362
|
+
десять: 10,
|
|
363
|
+
одиннадцать: 11,
|
|
364
|
+
двенадцать: 12,
|
|
365
|
+
тринадцать: 13,
|
|
366
|
+
четырнадцать: 14,
|
|
367
|
+
пятнадцать: 15,
|
|
368
|
+
шестнадцать: 16,
|
|
369
|
+
семнадцать: 17,
|
|
370
|
+
восемнадцать: 18,
|
|
371
|
+
девятнадцать: 19,
|
|
372
|
+
};
|
|
373
|
+
/** Tens 20–90, de/en/ru */
|
|
374
|
+
const TEN_WORDS = {
|
|
375
|
+
zwanzig: 20,
|
|
376
|
+
dreissig: 30,
|
|
377
|
+
vierzig: 40,
|
|
378
|
+
fuenfzig: 50,
|
|
379
|
+
sechzig: 60,
|
|
380
|
+
siebzig: 70,
|
|
381
|
+
achtzig: 80,
|
|
382
|
+
neunzig: 90,
|
|
383
|
+
twenty: 20,
|
|
384
|
+
thirty: 30,
|
|
385
|
+
forty: 40,
|
|
386
|
+
fifty: 50,
|
|
387
|
+
sixty: 60,
|
|
388
|
+
seventy: 70,
|
|
389
|
+
eighty: 80,
|
|
390
|
+
ninety: 90,
|
|
391
|
+
двадцать: 20,
|
|
392
|
+
тридцать: 30,
|
|
393
|
+
сорок: 40,
|
|
394
|
+
пятьдесят: 50,
|
|
395
|
+
шестьдесят: 60,
|
|
396
|
+
семьдесят: 70,
|
|
397
|
+
восемьдесят: 80,
|
|
398
|
+
девяносто: 90,
|
|
399
|
+
};
|
|
400
|
+
const HUNDRED_WORDS = new Set(['hundert', 'einhundert', 'hundred', 'сто']);
|
|
401
|
+
/** Value of one spelled-out number word ("fuenfundzwanzig", "twenty-five", "fünfzig"), or null */
|
|
402
|
+
function numberWordValue(word) {
|
|
403
|
+
if (HUNDRED_WORDS.has(word)) {
|
|
404
|
+
return 100;
|
|
405
|
+
}
|
|
406
|
+
const direct = TEN_WORDS[word] ?? TEEN_WORDS[word] ?? UNIT_WORDS[word];
|
|
407
|
+
if (direct !== undefined) {
|
|
408
|
+
return direct;
|
|
409
|
+
}
|
|
410
|
+
// de "fünfundzwanzig" (unit first, "ein" as in "einundzwanzig"), en "twenty-five"
|
|
411
|
+
const de = /^(\p{L}+?)und(\p{L}+)$/u.exec(word);
|
|
412
|
+
if (de && TEN_WORDS[de[2]] !== undefined && (de[1] === 'ein' || UNIT_WORDS[de[1]] !== undefined)) {
|
|
413
|
+
return TEN_WORDS[de[2]] + (UNIT_WORDS[de[1]] ?? 1);
|
|
414
|
+
}
|
|
415
|
+
const en = /^(\p{L}+)-(\p{L}+)$/u.exec(word);
|
|
416
|
+
if (en && TEN_WORDS[en[1]] !== undefined && UNIT_WORDS[en[2]] !== undefined) {
|
|
417
|
+
return TEN_WORDS[en[1]] + UNIT_WORDS[en[2]];
|
|
418
|
+
}
|
|
419
|
+
return null;
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Spelled-out whole numbers up to 100 → digits in normalized text (de/en/ru): "fuenfzig prozent" → "50 prozent",
|
|
423
|
+
* "twenty five" → "25", "двадцать пять" → "25", "one hundred" → "100". Speech recognition writes numbers as words
|
|
424
|
+
* often enough that a level command would otherwise miss. Articles ("ein", "a") stay words.
|
|
425
|
+
*
|
|
426
|
+
* @param text normalized text
|
|
427
|
+
*/
|
|
428
|
+
function spelledNumbersToDigits(text) {
|
|
429
|
+
const words = text.split(/\s+/).filter(Boolean);
|
|
430
|
+
const out = [];
|
|
431
|
+
for (let i = 0; i < words.length; i++) {
|
|
432
|
+
const [, word, tail] = /^(.*?)([.,!?;:]*)$/u.exec(words[i]);
|
|
433
|
+
let value = numberWordValue(word);
|
|
434
|
+
if (value === null) {
|
|
435
|
+
// "one hundred", "a hundred", "ein hundert"
|
|
436
|
+
const next = words[i + 1]?.replace(/[.,!?;:]+$/u, '');
|
|
437
|
+
if (['one', 'a', 'ein'].includes(word) && next && HUNDRED_WORDS.has(next)) {
|
|
438
|
+
out.push(`100${/[.,!?;:]+$/u.exec(words[i + 1])?.[0] || ''}`);
|
|
439
|
+
i++;
|
|
440
|
+
continue;
|
|
441
|
+
}
|
|
442
|
+
out.push(words[i]);
|
|
443
|
+
continue;
|
|
444
|
+
}
|
|
445
|
+
let end = tail;
|
|
446
|
+
// en "twenty five", ru "двадцать пять": a ten followed by a unit
|
|
447
|
+
if (TEN_WORDS[word] !== undefined && !tail && i + 1 < words.length) {
|
|
448
|
+
const [, nextWord, nextTail] = /^(.*?)([.,!?;:]*)$/u.exec(words[i + 1]);
|
|
449
|
+
if (UNIT_WORDS[nextWord] !== undefined) {
|
|
450
|
+
value += UNIT_WORDS[nextWord];
|
|
451
|
+
end = nextTail;
|
|
452
|
+
i++;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
out.push(`${value}${end}`);
|
|
456
|
+
}
|
|
457
|
+
return out.join(' ');
|
|
458
|
+
}
|
|
306
459
|
/** Fixed phrases replaced up front so their fractions don't collide with the general number-word pass. */
|
|
307
460
|
const DURATION_PHRASES = [
|
|
308
461
|
[/(?<![\p{L}])dreiviertelstunde(?![\p{L}])/iu, '45 minuten'],
|
|
@@ -315,6 +468,26 @@ const DURATION_PHRASES = [
|
|
|
315
468
|
[/quarter hour/iu, '15 minutes'],
|
|
316
469
|
[/(?<![\p{L}])полтора часа(?![\p{L}])/iu, '90 минут'],
|
|
317
470
|
[/(?<![\p{L}])полчаса(?![\p{L}])/iu, '30 минут'],
|
|
471
|
+
// a unit without a number: "in einer Stunde", "in an hour", "через час", "через минуту"
|
|
472
|
+
[/(?<![\p{L}])einer halben stunde(?![\p{L}])/iu, '30 minuten'],
|
|
473
|
+
[/(?<![\p{L}])einer? (stunde|minute)(?![\p{L}])/iu, '1 $1'],
|
|
474
|
+
[/(?<![\p{L}])an? (hour|minute)(?![\p{L}])/iu, '1 $1'],
|
|
475
|
+
[/(?<![\p{L}])через (час|минуту)(?![\p{L}])/iu, 'через 1 $1'],
|
|
476
|
+
];
|
|
477
|
+
/** Prepositions of a delay: "in 2 Stunden", "nach 10 Minuten", "через 2 часа", "after 5 minutes" */
|
|
478
|
+
const DELAY_PREPOSITION_RE = /(?<![\p{L}])(?:in|nach|через|after)\s+/gu;
|
|
479
|
+
/**
|
|
480
|
+
* A clock time that cannot be anything else: "22:30", "7 Uhr", "7 o'clock", "7 pm", "в 7 часов", "в 10 вечера",
|
|
481
|
+
* "halb acht" — unlike a bare "um 3", which is as often "um 3 lauter" or "um 20 Prozent".
|
|
482
|
+
*/
|
|
483
|
+
const CLOCK_RE = /\d{1,2}:\d{2}|\d\s*(?:uhr|o.?clock|[ap]m)(?![\p{L}])|(?<![\p{L}])(?:в|во)\s+\d{1,2}\s*(?:час\p{L}*|утра|вечера|ночи|дня)(?![\p{L}])|(?<![\p{L}])(?:halb|viertel|dreiviertel|quarter|half past)\s/u;
|
|
484
|
+
/** Percent values, removed before looking for a clock time ("um 20 Prozent" is no time) */
|
|
485
|
+
const PERCENT_RE = /\d+(?:[.,]\d+)?\s*(?:%|prozent|percent|процент\p{L}*)/giu;
|
|
486
|
+
/** Day words for a clock time, the longer first ("übermorgen" before "morgen") */
|
|
487
|
+
const DAY_WORDS = [
|
|
488
|
+
[/(?<![\p{L}])(?:uebermorgen|day after tomorrow|послезавтра)(?![\p{L}])/u, 2],
|
|
489
|
+
[/(?<![\p{L}])(?:morgen|tomorrow|завтра)(?![\p{L}])/u, 1],
|
|
490
|
+
[/(?<![\p{L}])(?:heute|today|сегодня)(?![\p{L}])/u, 0],
|
|
318
491
|
];
|
|
319
492
|
const HOUR_RE = /(\d+(?:[.,]\d+)?)\s*(?:stunden?|hours?|hrs?|h|час(?:а|ов)?)(?![\p{L}])/giu;
|
|
320
493
|
const MIN_RE = /(\d+(?:[.,]\d+)?)\s*(?:minuten?|mins?|minutes?|минут[уы]?)(?![\p{L}])/giu;
|
|
@@ -702,6 +875,12 @@ class Nlu {
|
|
|
702
875
|
if (combined.length > 1) {
|
|
703
876
|
return combined;
|
|
704
877
|
}
|
|
878
|
+
// Several commands, one of them for later, and not every part understood: the time must not be applied to
|
|
879
|
+
// the whole sentence ("Licht an und Rollo in 10 Minuten zu" would switch the light on in 10 minutes).
|
|
880
|
+
const whole = this.prepare(text);
|
|
881
|
+
if (whole && splitCommands(text).length > 1 && this.parseWhen(whole)) {
|
|
882
|
+
return [];
|
|
883
|
+
}
|
|
705
884
|
const single = this.parse(text);
|
|
706
885
|
return single ? [single] : [];
|
|
707
886
|
}
|
|
@@ -725,15 +904,18 @@ class Nlu {
|
|
|
725
904
|
const intents = [];
|
|
726
905
|
for (let i = 0; i < parts.length; i++) {
|
|
727
906
|
// A segment stating no action borrows the nearest sibling's — looking ahead first, because the
|
|
728
|
-
// verb usually comes last in this shape ("schalte A | und B **an**").
|
|
729
|
-
|
|
907
|
+
// verb usually comes last in this shape ("schalte A | und B **an**"). The time comes with it: in
|
|
908
|
+
// "schalte A und B in 10 Minuten aus" both wait.
|
|
909
|
+
let from = -1;
|
|
730
910
|
if (isBare(features[i])) {
|
|
731
|
-
|
|
732
|
-
for (let j = i - 1;
|
|
733
|
-
|
|
911
|
+
from = features.findIndex((f, j) => j > i && !isBare(f));
|
|
912
|
+
for (let j = i - 1; from < 0 && j >= 0; j--) {
|
|
913
|
+
from = isBare(features[j]) ? -1 : j;
|
|
734
914
|
}
|
|
735
915
|
}
|
|
736
|
-
const
|
|
916
|
+
const inherited = from >= 0 ? features[from] : null;
|
|
917
|
+
const inheritedTime = from >= 0 ? this.parseWhen(parts[from]) : null;
|
|
918
|
+
const intent = this.parsePrepared(parts[i], inherited, inheritedTime && inheritedTime !== 'unclear' ? inheritedTime : null);
|
|
737
919
|
if (intent) {
|
|
738
920
|
intents.push(intent);
|
|
739
921
|
}
|
|
@@ -754,13 +936,27 @@ class Nlu {
|
|
|
754
936
|
* first and never inherit anything; `inherited` supplies the action for a segment that names only a
|
|
755
937
|
* device (see {@link parseCombined}).
|
|
756
938
|
*/
|
|
757
|
-
parsePrepared(p, inherited) {
|
|
939
|
+
parsePrepared(p, inherited, inheritedTime = null) {
|
|
758
940
|
// Timer / alarm intents ("timer 5 minuten", "weck mich um 7 Uhr", "wie lange noch") — before
|
|
759
941
|
// window/device matching, and device-independent.
|
|
760
942
|
const schedule = this.parseSchedule(p.raw, p.norm, p.joined);
|
|
761
943
|
if (schedule) {
|
|
762
944
|
return schedule;
|
|
763
945
|
}
|
|
946
|
+
// A command for later ("Licht in 2 Stunden aus", "выключи свет через 2 часа") must never run now: it
|
|
947
|
+
// becomes a deferred device intent, or goes to the LLM. Before the time query — "через 2 часа" has "час".
|
|
948
|
+
const time = this.parseWhen(p);
|
|
949
|
+
if (time) {
|
|
950
|
+
const roomName = this.findRoom(p.joined);
|
|
951
|
+
const device = this.findDevice(p.joined, roomName);
|
|
952
|
+
if (time !== 'unclear') {
|
|
953
|
+
return device ? this.deferred(p, device, roomName, time) : null;
|
|
954
|
+
}
|
|
955
|
+
if (device) {
|
|
956
|
+
return null; // "Licht um 7 aus" — maybe 7 o'clock, maybe not: the LLM asks or knows
|
|
957
|
+
}
|
|
958
|
+
// no device: "um 3 lauter" is a volume step, go on
|
|
959
|
+
}
|
|
764
960
|
// Time / date query ("what time is it", "which day is today") — device-independent, answered from
|
|
765
961
|
// the host clock. After the schedule parse so a clock phrase with a timer/alarm keyword still wins.
|
|
766
962
|
const timeQuery = this.parseTimeQuery(p.joined);
|
|
@@ -784,9 +980,52 @@ class Nlu {
|
|
|
784
980
|
let features = this.extractFeatures(p);
|
|
785
981
|
if (inherited && this.namesOnly(p, device, roomName)) {
|
|
786
982
|
features = inherited;
|
|
983
|
+
if (inheritedTime) {
|
|
984
|
+
return this.deferred(p, device, roomName, inheritedTime, inherited);
|
|
985
|
+
}
|
|
787
986
|
}
|
|
788
987
|
return this.buildDeviceIntent(device, roomName, features);
|
|
789
988
|
}
|
|
989
|
+
/**
|
|
990
|
+
* When a command is meant to run: after a delay ("in 2 Stunden", "через полчаса", "in 10 minutes") or at a clock
|
|
991
|
+
* time ("um 22 Uhr", "morgen um 7:30", "в 10 вечера", "at 10 pm"). `unclear`: a time that could be meant
|
|
992
|
+
* otherwise ("um 7", a weekday, "jeden Tag") — a device command with it is left to the LLM. Null: no time.
|
|
993
|
+
*/
|
|
994
|
+
parseWhen(p) {
|
|
995
|
+
const norm = spelledNumbersToDigits(p.norm);
|
|
996
|
+
DELAY_PREPOSITION_RE.lastIndex = 0;
|
|
997
|
+
let m;
|
|
998
|
+
while ((m = DELAY_PREPOSITION_RE.exec(norm))) {
|
|
999
|
+
// the duration right after the preposition: "in der Küche" is no delay, "in 2 Stunden" is
|
|
1000
|
+
const words = norm.substring(m.index).split(/\s+/).slice(0, 5).join(' ');
|
|
1001
|
+
const seconds = parseDurationSeconds(words, false);
|
|
1002
|
+
if (seconds) {
|
|
1003
|
+
return { delaySec: seconds };
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
const raw = p.raw.replace(PERCENT_RE, ' ');
|
|
1007
|
+
const clock = parseClockTime(raw);
|
|
1008
|
+
if (!clock) {
|
|
1009
|
+
return null;
|
|
1010
|
+
}
|
|
1011
|
+
if (!CLOCK_RE.test(spelledNumbersToDigits(normalize(raw))) || parseWeekdays(p.norm).length) {
|
|
1012
|
+
return 'unclear';
|
|
1013
|
+
}
|
|
1014
|
+
const day = DAY_WORDS.find(([re]) => re.test(p.norm))?.[1];
|
|
1015
|
+
return { at: day === undefined ? { ...clock } : { ...clock, day } };
|
|
1016
|
+
}
|
|
1017
|
+
/** A device command for later: only switching and setting (a question about later is the LLM's) */
|
|
1018
|
+
deferred(p, device, roomName, time, features = this.extractFeatures(p)) {
|
|
1019
|
+
// "Licht an und in 2 Stunden wieder aus": two actions with one time — which one is meant for later?
|
|
1020
|
+
if (p.tokens.some(t => TURN_ON.has(t)) && p.tokens.some(t => TURN_OFF.has(t))) {
|
|
1021
|
+
return null;
|
|
1022
|
+
}
|
|
1023
|
+
const intent = this.buildDeviceIntent(device, roomName, features);
|
|
1024
|
+
if (!intent || !['on', 'off', 'level', 'color'].includes(intent.action)) {
|
|
1025
|
+
return null;
|
|
1026
|
+
}
|
|
1027
|
+
return { ...intent, ...time };
|
|
1028
|
+
}
|
|
790
1029
|
/** The action half of a command: on/off, level, color, and whether it is a question. */
|
|
791
1030
|
extractFeatures(p) {
|
|
792
1031
|
return {
|
|
@@ -1076,7 +1315,8 @@ class Nlu {
|
|
|
1076
1315
|
}
|
|
1077
1316
|
const percent = /(?:prozent|percent|процент\p{L}*|%)/u.test(p.norm);
|
|
1078
1317
|
// "ein bisschen lauter" is no step count — only digits and the number words from two upwards count.
|
|
1079
|
-
const num = p.tokens
|
|
1318
|
+
const num = spelledNumbersToDigits(p.tokens.join(' '))
|
|
1319
|
+
.split(' ')
|
|
1080
1320
|
.map(w => (/^\d+$/.test(w) ? w : ['ein', 'eine', 'einen'].includes(w) ? '' : NUMBER_WORDS[w] || ''))
|
|
1081
1321
|
.find(w => /^\d+$/.test(w));
|
|
1082
1322
|
const n = num === undefined ? null : parseInt(num, 10);
|
|
@@ -1182,7 +1422,7 @@ class Nlu {
|
|
|
1182
1422
|
return null;
|
|
1183
1423
|
}
|
|
1184
1424
|
findLevel(text) {
|
|
1185
|
-
const m = text.match(/(\d+(?:[.,]\d+)?)\s*(?:prozent|percent|процент\w*|%)/u);
|
|
1425
|
+
const m = spelledNumbersToDigits(text).match(/(\d+(?:[.,]\d+)?)\s*(?:prozent|percent|процент\w*|%)/u);
|
|
1186
1426
|
return m ? parseFloat(m[1].replace(',', '.')) : null;
|
|
1187
1427
|
}
|
|
1188
1428
|
findColor(text) {
|