react-voice-action-router 1.0.1 → 1.0.2
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/LICENSE +20 -20
- package/README.md +20 -20
- package/dist/adapters/index.d.mts +1 -14
- package/dist/adapters/index.d.ts +1 -14
- package/dist/adapters/index.js.map +1 -1
- package/dist/adapters/index.mjs.map +1 -1
- package/dist/{index-B9ulrUXF.d.mts → index-DyZ8YKh9.d.mts} +12 -1
- package/dist/{index-B9ulrUXF.d.ts → index-DyZ8YKh9.d.ts} +12 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +61 -0
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +61 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
package/LICENSE
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2026 Nouman Ejaz
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Nouman Ejaz
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
21
|
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
# react-voice-action-router 🎙️
|
|
2
|
-
|
|
3
|
-
> **Don't build a chatbot. Build a hands-free interface.**
|
|
4
|
-
|
|
5
|
-
[](https://www.npmjs.com/package/react-voice-action-router)
|
|
6
|
-
[](https://opensource.org/licenses/MIT)
|
|
7
|
-
|
|
8
|
-
A headless, latency-first voice intent router for React applications. It bridges natural language speech to your existing React functions using an **LLM-Agnostic Adapter Pattern**.
|
|
9
|
-
|
|
10
|
-
* **Headless & Zero UI:** We provide the logic hooks; you build the interface (or keep it invisible).
|
|
11
|
-
* **Context-Aware:** The AI only knows about commands on the *current* screen, reducing costs and hallucinations.
|
|
12
|
-
* **Universal Adapter:** Works with OpenAI, Anthropic, local Llama models (Ollama), or your own secure backend.
|
|
13
|
-
* **Latency-First:** Supports instant execution for exact phrases, falling back to AI for fuzzy intents.
|
|
14
|
-
|
|
15
|
-
---
|
|
16
|
-
|
|
17
|
-
## Installation
|
|
18
|
-
|
|
19
|
-
```bash
|
|
20
|
-
npm install react-voice-action-router
|
|
1
|
+
# react-voice-action-router 🎙️
|
|
2
|
+
|
|
3
|
+
> **Don't build a chatbot. Build a hands-free interface.**
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/react-voice-action-router)
|
|
6
|
+
[](https://opensource.org/licenses/MIT)
|
|
7
|
+
|
|
8
|
+
A headless, latency-first voice intent router for React applications. It bridges natural language speech to your existing React functions using an **LLM-Agnostic Adapter Pattern**.
|
|
9
|
+
|
|
10
|
+
* **Headless & Zero UI:** We provide the logic hooks; you build the interface (or keep it invisible).
|
|
11
|
+
* **Context-Aware:** The AI only knows about commands on the *current* screen, reducing costs and hallucinations.
|
|
12
|
+
* **Universal Adapter:** Works with OpenAI, Anthropic, local Llama models (Ollama), or your own secure backend.
|
|
13
|
+
* **Latency-First:** Supports instant execution for exact phrases, falling back to AI for fuzzy intents.
|
|
14
|
+
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
## Installation
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
npm install react-voice-action-router
|
|
21
21
|
# Note: React 16.8+ is required for Hooks support.
|
|
@@ -1,14 +1 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
interface OpenAIConfig {
|
|
4
|
-
apiKey: string;
|
|
5
|
-
/** @default "gpt-4o-mini" */
|
|
6
|
-
model?: string;
|
|
7
|
-
}
|
|
8
|
-
/**
|
|
9
|
-
* A Factory that creates an Adapter for OpenAI.
|
|
10
|
-
* Users call this: createOpenAIAdapter({ apiKey: '...' })
|
|
11
|
-
*/
|
|
12
|
-
declare const createOpenAIAdapter: (config: OpenAIConfig) => LLMAdapter;
|
|
13
|
-
|
|
14
|
-
export { createOpenAIAdapter };
|
|
1
|
+
export { c as createOpenAIAdapter } from '../index-DyZ8YKh9.mjs';
|
package/dist/adapters/index.d.ts
CHANGED
|
@@ -1,14 +1 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
interface OpenAIConfig {
|
|
4
|
-
apiKey: string;
|
|
5
|
-
/** @default "gpt-4o-mini" */
|
|
6
|
-
model?: string;
|
|
7
|
-
}
|
|
8
|
-
/**
|
|
9
|
-
* A Factory that creates an Adapter for OpenAI.
|
|
10
|
-
* Users call this: createOpenAIAdapter({ apiKey: '...' })
|
|
11
|
-
*/
|
|
12
|
-
declare const createOpenAIAdapter: (config: OpenAIConfig) => LLMAdapter;
|
|
13
|
-
|
|
14
|
-
export { createOpenAIAdapter };
|
|
1
|
+
export { c as createOpenAIAdapter } from '../index-DyZ8YKh9.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/core/prompt.ts","../../src/adapters/openai.ts"],"names":[],"mappings":";;;AAMO,IAAM,kBAAA,GAAqB,CAAC,QAAA,KAA6C;AAE5E,EAAA,MAAM,cAAc,QAAA,CAAS,GAAA;AAAA,IAAI,SAC7B,CAAA,OAAA,EAAU,GAAA,CAAI,EAAE,CAAA,kBAAA,EAAqB,IAAI,WAAW,CAAA,CAAA;AAAA,GACxD,CAAE,KAAK,IAAI,CAAA;AAEX,EAAA,OAAO;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA,EAYT,WAAW;;AAAA;AAAA;AAAA,CAAA;AAKb,CAAA;;;AChB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EAAE,WAAW,IAAA,EAAK;AAAA,IAC7B;AAAA,EACJ,CAAA;AACJ","file":"index.js","sourcesContent":["import { VoiceCommand } from '../types';\
|
|
1
|
+
{"version":3,"sources":["../../src/core/prompt.ts","../../src/adapters/openai.ts"],"names":[],"mappings":";;;AAMO,IAAM,kBAAA,GAAqB,CAAC,QAAA,KAA6C;AAE5E,EAAA,MAAM,cAAc,QAAA,CAAS,GAAA;AAAA,IAAI,SAC7B,CAAA,OAAA,EAAU,GAAA,CAAI,EAAE,CAAA,kBAAA,EAAqB,IAAI,WAAW,CAAA,CAAA;AAAA,GACxD,CAAE,KAAK,IAAI,CAAA;AAEX,EAAA,OAAO;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA,EAYT,WAAW;;AAAA;AAAA;AAAA,CAAA;AAKb,CAAA;;;AChBO,IAAM,mBAAA,GAAsB,CAAC,MAAA,KAAqC;AACrE,EAAA,OAAO,OAAO,YAAY,QAAA,KAAa;AAGnC,IAAA,MAAM,YAAA,GAAe,mBAAmB,QAAQ,CAAA;AAGhD,IAAA,MAAM,QAAA,GAAW,MAAM,KAAA,CAAM,4CAAA,EAA8C;AAAA,MACvE,MAAA,EAAQ,MAAA;AAAA,MACR,OAAA,EAAS;AAAA,QACL,cAAA,EAAgB,kBAAA;AAAA,QAChB,eAAA,EAAiB,CAAA,OAAA,EAAU,MAAA,CAAO,MAAM,CAAA;AAAA,OAC5C;AAAA,MACA,IAAA,EAAM,KAAK,SAAA,CAAU;AAAA,QACjB,KAAA,EAAO,OAAO,KAAA,IAAS,aAAA;AAAA,QACvB,QAAA,EAAU;AAAA,UACN,EAAE,IAAA,EAAM,QAAA,EAAU,OAAA,EAAS,YAAA,EAAa;AAAA,UACxC,EAAE,IAAA,EAAM,MAAA,EAAQ,OAAA,EAAS,UAAA;AAAW,SACxC;AAAA,QACA,WAAA,EAAa,CAAA;AAAA;AAAA,QACb,eAAA,EAAiB,EAAE,IAAA,EAAM,aAAA;AAAc;AAAA,OAC1C;AAAA,KACJ,CAAA;AAED,IAAA,IAAI,CAAC,SAAS,EAAA,EAAI;AACd,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,uBAAA,EAA0B,QAAA,CAAS,UAAU,CAAA,CAAE,CAAA;AAAA,IACnE;AAEA,IAAA,MAAM,IAAA,GAAO,MAAM,QAAA,CAAS,IAAA,EAAK;AAGjC,IAAA,IAAI;AACA,MAAA,MAAM,MAAA,GAAS,KAAK,KAAA,CAAM,IAAA,CAAK,QAAQ,CAAC,CAAA,CAAE,QAAQ,OAAO,CAAA;AACzD,MAAA,OAAO,EAAE,SAAA,EAAW,MAAA,CAAO,SAAA,EAAU;AAAA,IACzC,SAAS,CAAA,EAAG;AACR,MAAA,OAAA,CAAQ,KAAA,CAAM,gCAAgC,CAAC,CAAA;AAC/C,MAAA,OAAO,EAAE,WAAW,IAAA,EAAK;AAAA,IAC7B;AAAA,EACJ,CAAA;AACJ","file":"index.js","sourcesContent":["import { VoiceCommand } from '../types';\n\n/**\n * Generates the System Prompt for the LLM.\n * This ensures consistent behavior across different AI providers.\n */\nexport const createSystemPrompt = (commands: Omit<VoiceCommand, 'action'>[]) => {\n // Format the list of commands for the AI to read\n const commandList = commands.map(cmd =>\n `- ID: \"${cmd.id}\" | Description: \"${cmd.description}\"`\n ).join('\\n');\n\n return `\nYou are a precise Voice Command Router.\nYour goal is to map the user's spoken input to the correct Command ID from the list below.\n\nRULES:\n1. Analyze the user's input and find the intent.\n2. Match it to the command with the most relevant \"Description\".\n3. Use fuzzy matching (e.g., \"Dark mode\" matches \"Toggle Theme\").\n4. If NO command matches the intent, return null.\n5. IMPORTANT: Output ONLY valid JSON. Do not include markdown formatting.\n\nAVAILABLE COMMANDS:\n${commandList}\n\nRESPONSE FORMAT:\n{ \"commandId\": \"string_id_or_null\" }\n`;\n};\n\n/**\n * Standardizes how the user's voice transcript is presented to the AI.\n */\nexport const createUserPrompt = (transcript: string) => {\n return `User Input: \"${transcript}\"`;\n};","import { LLMAdapter } from '../types';\nimport { createSystemPrompt } from '../core/prompt';\n\ninterface OpenAIConfig {\n apiKey: string;\n /** @default \"gpt-4o-mini\" */\n model?: string;\n}\n\n/**\n * A Factory that creates an Adapter for OpenAI.\n * Users call this: createOpenAIAdapter({ apiKey: '...' })\n */\nexport const createOpenAIAdapter = (config: OpenAIConfig): LLMAdapter => {\n return async (transcript, commands) => {\n\n // 1. Generate the optimized system instructions\n const systemPrompt = createSystemPrompt(commands);\n\n // 2. Call the API\n const response = await fetch('https://api.openai.com/v1/chat/completions', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${config.apiKey}`\n },\n body: JSON.stringify({\n model: config.model || \"gpt-4o-mini\",\n messages: [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: transcript }\n ],\n temperature: 0, // Deterministic results\n response_format: { type: \"json_object\" } // Force JSON mode\n })\n });\n\n if (!response.ok) {\n throw new Error(`OpenAI Adapter Failed: ${response.statusText}`);\n }\n\n const data = await response.json();\n\n // 3. Parse the result\n try {\n const parsed = JSON.parse(data.choices[0].message.content);\n return { commandId: parsed.commandId };\n } catch (e) {\n console.error(\"Failed to parse LLM response\", e);\n return { commandId: null };\n }\n };\n};"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/core/prompt.ts","../../src/adapters/openai.ts"],"names":[],"mappings":";AAMO,IAAM,kBAAA,GAAqB,CAAC,QAAA,KAA6C;AAE5E,EAAA,MAAM,cAAc,QAAA,CAAS,GAAA;AAAA,IAAI,SAC7B,CAAA,OAAA,EAAU,GAAA,CAAI,EAAE,CAAA,kBAAA,EAAqB,IAAI,WAAW,CAAA,CAAA;AAAA,GACxD,CAAE,KAAK,IAAI,CAAA;AAEX,EAAA,OAAO;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA,EAYT,WAAW;;AAAA;AAAA;AAAA,CAAA;AAKb,CAAA;;;A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O,EAAE,WAAW,IAAA,EAAK;AAAA,IAC7B;AAAA,EACJ,CAAA;AACJ","file":"index.mjs","sourcesContent":["import { VoiceCommand } from '../types';\
|
|
1
|
+
{"version":3,"sources":["../../src/core/prompt.ts","../../src/adapters/openai.ts"],"names":[],"mappings":";AAMO,IAAM,kBAAA,GAAqB,CAAC,QAAA,KAA6C;AAE5E,EAAA,MAAM,cAAc,QAAA,CAAS,GAAA;AAAA,IAAI,SAC7B,CAAA,OAAA,EAAU,GAAA,CAAI,EAAE,CAAA,kBAAA,EAAqB,IAAI,WAAW,CAAA,CAAA;AAAA,GACxD,CAAE,KAAK,IAAI,CAAA;AAEX,EAAA,OAAO;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA,EAYT,WAAW;;AAAA;AAAA;AAAA,CAAA;AAKb,CAAA;;;AChBO,IAAM,mBAAA,GAAsB,CAAC,MAAA,KAAqC;AACrE,EAAA,OAAO,OAAO,YAAY,QAAA,KAAa;AAGnC,IAAA,MAAM,YAAA,GAAe,mBAAmB,QAAQ,CAAA;AAGhD,IAAA,MAAM,QAAA,GAAW,MAAM,KAAA,CAAM,4CAAA,EAA8C;AAAA,MACvE,MAAA,EAAQ,MAAA;AAAA,MACR,OAAA,EAAS;AAAA,QACL,cAAA,EAAgB,kBAAA;AAAA,QAChB,eAAA,EAAiB,CAAA,OAAA,EAAU,MAAA,CAAO,MAAM,CAAA;AAAA,OAC5C;AAAA,MACA,IAAA,EAAM,KAAK,SAAA,CAAU;AAAA,QACjB,KAAA,EAAO,OAAO,KAAA,IAAS,aAAA;AAAA,QACvB,QAAA,EAAU;AAAA,UACN,EAAE,IAAA,EAAM,QAAA,EAAU,OAAA,EAAS,YAAA,EAAa;AAAA,UACxC,EAAE,IAAA,EAAM,MAAA,EAAQ,OAAA,EAAS,UAAA;AAAW,SACxC;AAAA,QACA,WAAA,EAAa,CAAA;AAAA;AAAA,QACb,eAAA,EAAiB,EAAE,IAAA,EAAM,aAAA;AAAc;AAAA,OAC1C;AAAA,KACJ,CAAA;AAED,IAAA,IAAI,CAAC,SAAS,EAAA,EAAI;AACd,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,uBAAA,EAA0B,QAAA,CAAS,UAAU,CAAA,CAAE,CAAA;AAAA,IACnE;AAEA,IAAA,MAAM,IAAA,GAAO,MAAM,QAAA,CAAS,IAAA,EAAK;AAGjC,IAAA,IAAI;AACA,MAAA,MAAM,MAAA,GAAS,KAAK,KAAA,CAAM,IAAA,CAAK,QAAQ,CAAC,CAAA,CAAE,QAAQ,OAAO,CAAA;AACzD,MAAA,OAAO,EAAE,SAAA,EAAW,MAAA,CAAO,SAAA,EAAU;AAAA,IACzC,SAAS,CAAA,EAAG;AACR,MAAA,OAAA,CAAQ,KAAA,CAAM,gCAAgC,CAAC,CAAA;AAC/C,MAAA,OAAO,EAAE,WAAW,IAAA,EAAK;AAAA,IAC7B;AAAA,EACJ,CAAA;AACJ","file":"index.mjs","sourcesContent":["import { VoiceCommand } from '../types';\n\n/**\n * Generates the System Prompt for the LLM.\n * This ensures consistent behavior across different AI providers.\n */\nexport const createSystemPrompt = (commands: Omit<VoiceCommand, 'action'>[]) => {\n // Format the list of commands for the AI to read\n const commandList = commands.map(cmd =>\n `- ID: \"${cmd.id}\" | Description: \"${cmd.description}\"`\n ).join('\\n');\n\n return `\nYou are a precise Voice Command Router.\nYour goal is to map the user's spoken input to the correct Command ID from the list below.\n\nRULES:\n1. Analyze the user's input and find the intent.\n2. Match it to the command with the most relevant \"Description\".\n3. Use fuzzy matching (e.g., \"Dark mode\" matches \"Toggle Theme\").\n4. If NO command matches the intent, return null.\n5. IMPORTANT: Output ONLY valid JSON. Do not include markdown formatting.\n\nAVAILABLE COMMANDS:\n${commandList}\n\nRESPONSE FORMAT:\n{ \"commandId\": \"string_id_or_null\" }\n`;\n};\n\n/**\n * Standardizes how the user's voice transcript is presented to the AI.\n */\nexport const createUserPrompt = (transcript: string) => {\n return `User Input: \"${transcript}\"`;\n};","import { LLMAdapter } from '../types';\nimport { createSystemPrompt } from '../core/prompt';\n\ninterface OpenAIConfig {\n apiKey: string;\n /** @default \"gpt-4o-mini\" */\n model?: string;\n}\n\n/**\n * A Factory that creates an Adapter for OpenAI.\n * Users call this: createOpenAIAdapter({ apiKey: '...' })\n */\nexport const createOpenAIAdapter = (config: OpenAIConfig): LLMAdapter => {\n return async (transcript, commands) => {\n\n // 1. Generate the optimized system instructions\n const systemPrompt = createSystemPrompt(commands);\n\n // 2. Call the API\n const response = await fetch('https://api.openai.com/v1/chat/completions', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${config.apiKey}`\n },\n body: JSON.stringify({\n model: config.model || \"gpt-4o-mini\",\n messages: [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: transcript }\n ],\n temperature: 0, // Deterministic results\n response_format: { type: \"json_object\" } // Force JSON mode\n })\n });\n\n if (!response.ok) {\n throw new Error(`OpenAI Adapter Failed: ${response.statusText}`);\n }\n\n const data = await response.json();\n\n // 3. Parse the result\n try {\n const parsed = JSON.parse(data.choices[0].message.content);\n return { commandId: parsed.commandId };\n } catch (e) {\n console.error(\"Failed to parse LLM response\", e);\n return { commandId: null };\n }\n };\n};"]}
|
|
@@ -38,4 +38,15 @@ interface VoiceProviderProps {
|
|
|
38
38
|
onStateChange?: (state: VoiceControlState) => void;
|
|
39
39
|
}
|
|
40
40
|
|
|
41
|
-
|
|
41
|
+
interface OpenAIConfig {
|
|
42
|
+
apiKey: string;
|
|
43
|
+
/** @default "gpt-4o-mini" */
|
|
44
|
+
model?: string;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* A Factory that creates an Adapter for OpenAI.
|
|
48
|
+
* Users call this: createOpenAIAdapter({ apiKey: '...' })
|
|
49
|
+
*/
|
|
50
|
+
declare const createOpenAIAdapter: (config: OpenAIConfig) => LLMAdapter;
|
|
51
|
+
|
|
52
|
+
export { type LLMAdapter as L, type VoiceProviderProps as V, type VoiceControlState as a, type VoiceCommand as b, createOpenAIAdapter as c };
|
|
@@ -38,4 +38,15 @@ interface VoiceProviderProps {
|
|
|
38
38
|
onStateChange?: (state: VoiceControlState) => void;
|
|
39
39
|
}
|
|
40
40
|
|
|
41
|
-
|
|
41
|
+
interface OpenAIConfig {
|
|
42
|
+
apiKey: string;
|
|
43
|
+
/** @default "gpt-4o-mini" */
|
|
44
|
+
model?: string;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* A Factory that creates an Adapter for OpenAI.
|
|
48
|
+
* Users call this: createOpenAIAdapter({ apiKey: '...' })
|
|
49
|
+
*/
|
|
50
|
+
declare const createOpenAIAdapter: (config: OpenAIConfig) => LLMAdapter;
|
|
51
|
+
|
|
52
|
+
export { type LLMAdapter as L, type VoiceProviderProps as V, type VoiceControlState as a, type VoiceCommand as b, createOpenAIAdapter as c };
|
package/dist/index.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import React from 'react';
|
|
2
|
-
import { V as VoiceProviderProps, a as VoiceControlState, b as VoiceCommand } from './index-
|
|
3
|
-
export { L as LLMAdapter } from './index-
|
|
2
|
+
import { V as VoiceProviderProps, a as VoiceControlState, b as VoiceCommand } from './index-DyZ8YKh9.mjs';
|
|
3
|
+
export { L as LLMAdapter, c as createOpenAIAdapter } from './index-DyZ8YKh9.mjs';
|
|
4
4
|
|
|
5
5
|
interface VoiceContextValue extends VoiceControlState {
|
|
6
6
|
register: (cmd: VoiceCommand) => void;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import React from 'react';
|
|
2
|
-
import { V as VoiceProviderProps, a as VoiceControlState, b as VoiceCommand } from './index-
|
|
3
|
-
export { L as LLMAdapter } from './index-
|
|
2
|
+
import { V as VoiceProviderProps, a as VoiceControlState, b as VoiceCommand } from './index-DyZ8YKh9.js';
|
|
3
|
+
export { L as LLMAdapter, c as createOpenAIAdapter } from './index-DyZ8YKh9.js';
|
|
4
4
|
|
|
5
5
|
interface VoiceContextValue extends VoiceControlState {
|
|
6
6
|
register: (cmd: VoiceCommand) => void;
|
package/dist/index.js
CHANGED
|
@@ -79,7 +79,68 @@ var useVoiceCommand = (command) => {
|
|
|
79
79
|
}, [register, unregister, command]);
|
|
80
80
|
};
|
|
81
81
|
|
|
82
|
+
// src/core/prompt.ts
|
|
83
|
+
var createSystemPrompt = (commands) => {
|
|
84
|
+
const commandList = commands.map(
|
|
85
|
+
(cmd) => `- ID: "${cmd.id}" | Description: "${cmd.description}"`
|
|
86
|
+
).join("\n");
|
|
87
|
+
return `
|
|
88
|
+
You are a precise Voice Command Router.
|
|
89
|
+
Your goal is to map the user's spoken input to the correct Command ID from the list below.
|
|
90
|
+
|
|
91
|
+
RULES:
|
|
92
|
+
1. Analyze the user's input and find the intent.
|
|
93
|
+
2. Match it to the command with the most relevant "Description".
|
|
94
|
+
3. Use fuzzy matching (e.g., "Dark mode" matches "Toggle Theme").
|
|
95
|
+
4. If NO command matches the intent, return null.
|
|
96
|
+
5. IMPORTANT: Output ONLY valid JSON. Do not include markdown formatting.
|
|
97
|
+
|
|
98
|
+
AVAILABLE COMMANDS:
|
|
99
|
+
${commandList}
|
|
100
|
+
|
|
101
|
+
RESPONSE FORMAT:
|
|
102
|
+
{ "commandId": "string_id_or_null" }
|
|
103
|
+
`;
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
// src/adapters/openai.ts
|
|
107
|
+
var createOpenAIAdapter = (config) => {
|
|
108
|
+
return async (transcript, commands) => {
|
|
109
|
+
const systemPrompt = createSystemPrompt(commands);
|
|
110
|
+
const response = await fetch("https://api.openai.com/v1/chat/completions", {
|
|
111
|
+
method: "POST",
|
|
112
|
+
headers: {
|
|
113
|
+
"Content-Type": "application/json",
|
|
114
|
+
"Authorization": `Bearer ${config.apiKey}`
|
|
115
|
+
},
|
|
116
|
+
body: JSON.stringify({
|
|
117
|
+
model: config.model || "gpt-4o-mini",
|
|
118
|
+
messages: [
|
|
119
|
+
{ role: "system", content: systemPrompt },
|
|
120
|
+
{ role: "user", content: transcript }
|
|
121
|
+
],
|
|
122
|
+
temperature: 0,
|
|
123
|
+
// Deterministic results
|
|
124
|
+
response_format: { type: "json_object" }
|
|
125
|
+
// Force JSON mode
|
|
126
|
+
})
|
|
127
|
+
});
|
|
128
|
+
if (!response.ok) {
|
|
129
|
+
throw new Error(`OpenAI Adapter Failed: ${response.statusText}`);
|
|
130
|
+
}
|
|
131
|
+
const data = await response.json();
|
|
132
|
+
try {
|
|
133
|
+
const parsed = JSON.parse(data.choices[0].message.content);
|
|
134
|
+
return { commandId: parsed.commandId };
|
|
135
|
+
} catch (e) {
|
|
136
|
+
console.error("Failed to parse LLM response", e);
|
|
137
|
+
return { commandId: null };
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
};
|
|
141
|
+
|
|
82
142
|
exports.VoiceControlProvider = VoiceControlProvider;
|
|
143
|
+
exports.createOpenAIAdapter = createOpenAIAdapter;
|
|
83
144
|
exports.useVoiceCommand = useVoiceCommand;
|
|
84
145
|
exports.useVoiceContext = useVoiceContext;
|
|
85
146
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/components/VoiceContext.tsx","../src/hooks/useVoiceCommand.ts"],"names":["createContext","useRef","useState","useCallback","jsx","useContext","useEffect"],"mappings":";;;;;;AASA,IAAM,YAAA,GAAeA,oBAAwC,IAAI,CAAA;AAE1D,IAAM,uBAAqD,CAAC;AAAA,EACjE,QAAA;AAAA,EACA;AACF,CAAA,KAAM;AAEJ,EAAA,MAAM,WAAA,GAAcC,YAAA,iBAAkC,IAAI,GAAA,EAAK,CAAA;AAG/D,EAAA,MAAM,CAAC,KAAA,EAAO,QAAQ,CAAA,GAAIC,cAAA,CAA4B;AAAA,IACpD,WAAA,EAAa,KAAA;AAAA,IACb,YAAA,EAAc,KAAA;AAAA,IACd,cAAA,EA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A,QAAA,CAAS,WAAS,EAAE,GAAG,IAAA,EAAM,YAAA,EAAc,OAAM,CAAE,CAAA;AAAA,IACrD;AAAA,EACF,CAAA,EAAG,CAAC,OAAO,CAAC,CAAA;AAEZ,EAAA,uBACEC,cAAA,CAAC,YAAA,CAAa,QAAA,EAAb,EAAsB,KAAA,EAAO,EAAE,GAAG,KAAA,EAAO,QAAA,EAAU,UAAA,EAAY,iBAAA,EAAkB,EAC/E,QAAA,EACH,CAAA;AAEJ;AAEO,IAAM,kBAAkB,MAAM;AACnC,EAAA,MAAM,GAAA,GAAMC,iBAAW,YAAY,CAAA;AACnC,EAAA,IAAI,CAAC,GAAA,EAAK,MAAM,IAAI,MAAM,4DAA4D,CAAA;AACtF,EAAA,OAAO,GAAA;AACT;ACjFO,IAAM,eAAA,GAAkB,CAAC,OAAA,KAA0B;AACtD,EAAA,MAAM,EAAE,QAAA,EAAU,UAAA,EAAW,GAAI,eAAA,EAAgB;AAGjD,EAAA,MAAM,KAAA,GAAQJ,YAAAA,CAAO,OAAA,CAAQ,EAAE,CAAA;AAE/B,EAAAK,eAAA,CAAU,MAAM;AAEZ,IAAA,QAAA,CAAS,OAAO,CAAA;AAGhB,IAAA,OAAO,MAAM;AACT,MAAA,UAAA,CAAW,MAAM,OAAO,CAAA;AAAA,IAC5B,CAAA;AAAA,EACJ,CAAA,EAAG,CAAC,QAAA,EAAU,UAAA,EAAY,OAAO,CAAC,CAAA;AACtC","file":"index.js","sourcesContent":["import React, { createContext, useContext, useState, useCallback, useRef } from 'react';\r\nimport { VoiceCommand, VoiceControlState, VoiceProviderProps } from '../types';\r\n\r\ninterface VoiceContextValue extends VoiceControlState {\r\n register: (cmd: VoiceCommand) => void;\r\n unregister: (id: string) => void;\r\n processTranscript: (text: string) => Promise<void>;\r\n}\r\n\r\nconst VoiceContext = createContext<VoiceContextValue | null>(null);\r\n\r\nexport const VoiceControlProvider: React.FC<VoiceProviderProps> = ({ \r\n children, \r\n adapter \r\n}) => {\r\n // THE REGISTRY: A Map ensures O(1) lookups and prevents duplicate IDs\r\n const commandsRef = useRef<Map<string, VoiceCommand>>(new Map());\r\n \r\n // UI STATE\r\n const [state, setState] = useState<VoiceControlState>({\r\n isListening: false,\r\n isProcessing: false,\r\n lastTranscript: null,\r\n activeCommands: [],\r\n });\r\n\r\n // 1. REGISTRATION LOGIC\r\n const register = useCallback((cmd: VoiceCommand) => {\r\n commandsRef.current.set(cmd.id, cmd);\r\n // Update generic state for debugging UI\r\n setState(prev => ({ ...prev, activeCommands: Array.from(commandsRef.current.values()) }));\r\n }, []);\r\n\r\n const unregister = useCallback((id: string) => {\r\n commandsRef.current.delete(id);\r\n setState(prev => ({ ...prev, activeCommands: Array.from(commandsRef.current.values()) }));\r\n }, []);\r\n\r\n // 2. THE ROUTER LOGIC\r\n const processTranscript = useCallback(async (transcript: string) => {\r\n const cleanText = transcript.trim().toLowerCase();\r\n setState(prev => ({ ...prev, isProcessing: true, lastTranscript: cleanText }));\r\n\r\n const allCommands = Array.from(commandsRef.current.values());\r\n\r\n // PHASE 1: EXACT MATCH (0ms Latency)\r\n const exactMatch = allCommands.find(c => c.phrase?.toLowerCase() === cleanText);\r\n \r\n if (exactMatch) {\r\n console.log(`⚡ Instant Match: \"${cleanText}\" -> ${exactMatch.id}`);\r\n exactMatch.action();\r\n setState(prev => ({ ...prev, isProcessing: false }));\r\n return;\r\n }\r\n\r\n // PHASE 2: FUZZY MATCH (AI Adapter)\r\n try {\r\n console.log(`🤖 AI Routing: \"${cleanText}\"...`);\r\n \r\n // We strip the 'action' function before sending to the AI\r\n const commandListForAI = allCommands.map(({ id, description, phrase }) => ({ \r\n id, \r\n description, \r\n phrase \r\n }));\r\n\r\n const result = await adapter(cleanText, commandListForAI);\r\n\r\n if (result.commandId) {\r\n const cmd = commandsRef.current.get(result.commandId);\r\n if (cmd) {\r\n console.log(`✅ Matched: ${cmd.id}`);\r\n cmd.action();\r\n } else {\r\n console.warn(`⚠️ Adapter returned unknown ID: ${result.commandId}`);\r\n }\r\n }\r\n } catch (error) {\r\n console.error(\"Adapter Error:\", error);\r\n } finally {\r\n setState(prev => ({ ...prev, isProcessing: false }));\r\n }\r\n }, [adapter]);\r\n\r\n return (\r\n <VoiceContext.Provider value={{ ...state, register, unregister, processTranscript }}>\r\n {children}\r\n </VoiceContext.Provider>\r\n );\r\n};\r\n\r\nexport const useVoiceContext = () => {\r\n const ctx = useContext(VoiceContext);\r\n if (!ctx) throw new Error(\"useVoiceContext must be used within a VoiceControlProvider\");\r\n return ctx;\r\n};","import { useEffect, useRef } from 'react';\r\nimport { useVoiceContext } from '../components/VoiceContext';\r\nimport { VoiceCommand } from '../types';\r\n\r\n/**\r\n * The Developer Hook\r\n * Wraps the lifecycle logic so the developer doesn't have to.\r\n * * Usage:\r\n * useVoiceCommand({\r\n * id: 'nav_home',\r\n * description: 'Go to home',\r\n * action: () => navigate('/')\r\n * });\r\n */\r\nexport const useVoiceCommand = (command: VoiceCommand) => {\r\n const { register, unregister } = useVoiceContext();\r\n\r\n // Use a ref to keep the ID stable across renders\r\n const idRef = useRef(command.id);\r\n\r\n useEffect(() => {\r\n // 1. Mount: Register the tool\r\n register(command);\r\n\r\n // 2. Unmount: Remove the tool\r\n return () => {\r\n unregister(idRef.current);\r\n };\r\n }, [register, unregister, command]); // Re-register if command definition changes\r\n};"]}
|
|
1
|
+
{"version":3,"sources":["../src/components/VoiceContext.tsx","../src/hooks/useVoiceCommand.ts","../src/core/prompt.ts","../src/adapters/openai.ts"],"names":["createContext","useRef","useState","useCallback","jsx","useContext","useEffect"],"mappings":";;;;;;AASA,IAAM,YAAA,GAAeA,oBAAwC,IAAI,CAAA;AAE1D,IAAM,uBAAqD,CAAC;AAAA,EACjE,QAAA;AAAA,EACA;AACF,CAAA,KAAM;AAEJ,EAAA,MAAM,WAAA,GAAcC,YAAA,iBAAkC,IAAI,GAAA,EAAK,CAAA;AAG/D,EAAA,MAAM,CAAC,KAAA,EAAO,QAAQ,CAAA,GAAIC,cAAA,C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,EAAU;AAAA,IACzC,SAAS,CAAA,EAAG;AACR,MAAA,OAAA,CAAQ,KAAA,CAAM,gCAAgC,CAAC,CAAA;AAC/C,MAAA,OAAO,EAAE,WAAW,IAAA,EAAK;AAAA,IAC7B;AAAA,EACJ,CAAA;AACJ","file":"index.js","sourcesContent":["import React, { createContext, useContext, useState, useCallback, useRef } from 'react';\nimport { VoiceCommand, VoiceControlState, VoiceProviderProps } from '../types';\n\ninterface VoiceContextValue extends VoiceControlState {\n register: (cmd: VoiceCommand) => void;\n unregister: (id: string) => void;\n processTranscript: (text: string) => Promise<void>;\n}\n\nconst VoiceContext = createContext<VoiceContextValue | null>(null);\n\nexport const VoiceControlProvider: React.FC<VoiceProviderProps> = ({ \n children, \n adapter \n}) => {\n // THE REGISTRY: A Map ensures O(1) lookups and prevents duplicate IDs\n const commandsRef = useRef<Map<string, VoiceCommand>>(new Map());\n \n // UI STATE\n const [state, setState] = useState<VoiceControlState>({\n isListening: false,\n isProcessing: false,\n lastTranscript: null,\n activeCommands: [],\n });\n\n // 1. REGISTRATION LOGIC\n const register = useCallback((cmd: VoiceCommand) => {\n commandsRef.current.set(cmd.id, cmd);\n // Update generic state for debugging UI\n setState(prev => ({ ...prev, activeCommands: Array.from(commandsRef.current.values()) }));\n }, []);\n\n const unregister = useCallback((id: string) => {\n commandsRef.current.delete(id);\n setState(prev => ({ ...prev, activeCommands: Array.from(commandsRef.current.values()) }));\n }, []);\n\n // 2. THE ROUTER LOGIC\n const processTranscript = useCallback(async (transcript: string) => {\n const cleanText = transcript.trim().toLowerCase();\n setState(prev => ({ ...prev, isProcessing: true, lastTranscript: cleanText }));\n\n const allCommands = Array.from(commandsRef.current.values());\n\n // PHASE 1: EXACT MATCH (0ms Latency)\n const exactMatch = allCommands.find(c => c.phrase?.toLowerCase() === cleanText);\n \n if (exactMatch) {\n console.log(`⚡ Instant Match: \"${cleanText}\" -> ${exactMatch.id}`);\n exactMatch.action();\n setState(prev => ({ ...prev, isProcessing: false }));\n return;\n }\n\n // PHASE 2: FUZZY MATCH (AI Adapter)\n try {\n console.log(`🤖 AI Routing: \"${cleanText}\"...`);\n \n // We strip the 'action' function before sending to the AI\n const commandListForAI = allCommands.map(({ id, description, phrase }) => ({ \n id, \n description, \n phrase \n }));\n\n const result = await adapter(cleanText, commandListForAI);\n\n if (result.commandId) {\n const cmd = commandsRef.current.get(result.commandId);\n if (cmd) {\n console.log(`✅ Matched: ${cmd.id}`);\n cmd.action();\n } else {\n console.warn(`⚠️ Adapter returned unknown ID: ${result.commandId}`);\n }\n }\n } catch (error) {\n console.error(\"Adapter Error:\", error);\n } finally {\n setState(prev => ({ ...prev, isProcessing: false }));\n }\n }, [adapter]);\n\n return (\n <VoiceContext.Provider value={{ ...state, register, unregister, processTranscript }}>\n {children}\n </VoiceContext.Provider>\n );\n};\n\nexport const useVoiceContext = () => {\n const ctx = useContext(VoiceContext);\n if (!ctx) throw new Error(\"useVoiceContext must be used within a VoiceControlProvider\");\n return ctx;\n};","import { useEffect, useRef } from 'react';\nimport { useVoiceContext } from '../components/VoiceContext';\nimport { VoiceCommand } from '../types';\n\n/**\n * The Developer Hook\n * Wraps the lifecycle logic so the developer doesn't have to.\n * * Usage:\n * useVoiceCommand({\n * id: 'nav_home',\n * description: 'Go to home',\n * action: () => navigate('/')\n * });\n */\nexport const useVoiceCommand = (command: VoiceCommand) => {\n const { register, unregister } = useVoiceContext();\n\n // Use a ref to keep the ID stable across renders\n const idRef = useRef(command.id);\n\n useEffect(() => {\n // 1. Mount: Register the tool\n register(command);\n\n // 2. Unmount: Remove the tool\n return () => {\n unregister(idRef.current);\n };\n }, [register, unregister, command]); // Re-register if command definition changes\n};","import { VoiceCommand } from '../types';\n\n/**\n * Generates the System Prompt for the LLM.\n * This ensures consistent behavior across different AI providers.\n */\nexport const createSystemPrompt = (commands: Omit<VoiceCommand, 'action'>[]) => {\n // Format the list of commands for the AI to read\n const commandList = commands.map(cmd =>\n `- ID: \"${cmd.id}\" | Description: \"${cmd.description}\"`\n ).join('\\n');\n\n return `\nYou are a precise Voice Command Router.\nYour goal is to map the user's spoken input to the correct Command ID from the list below.\n\nRULES:\n1. Analyze the user's input and find the intent.\n2. Match it to the command with the most relevant \"Description\".\n3. Use fuzzy matching (e.g., \"Dark mode\" matches \"Toggle Theme\").\n4. If NO command matches the intent, return null.\n5. IMPORTANT: Output ONLY valid JSON. Do not include markdown formatting.\n\nAVAILABLE COMMANDS:\n${commandList}\n\nRESPONSE FORMAT:\n{ \"commandId\": \"string_id_or_null\" }\n`;\n};\n\n/**\n * Standardizes how the user's voice transcript is presented to the AI.\n */\nexport const createUserPrompt = (transcript: string) => {\n return `User Input: \"${transcript}\"`;\n};","import { LLMAdapter } from '../types';\nimport { createSystemPrompt } from '../core/prompt';\n\ninterface OpenAIConfig {\n apiKey: string;\n /** @default \"gpt-4o-mini\" */\n model?: string;\n}\n\n/**\n * A Factory that creates an Adapter for OpenAI.\n * Users call this: createOpenAIAdapter({ apiKey: '...' })\n */\nexport const createOpenAIAdapter = (config: OpenAIConfig): LLMAdapter => {\n return async (transcript, commands) => {\n\n // 1. Generate the optimized system instructions\n const systemPrompt = createSystemPrompt(commands);\n\n // 2. Call the API\n const response = await fetch('https://api.openai.com/v1/chat/completions', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${config.apiKey}`\n },\n body: JSON.stringify({\n model: config.model || \"gpt-4o-mini\",\n messages: [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: transcript }\n ],\n temperature: 0, // Deterministic results\n response_format: { type: \"json_object\" } // Force JSON mode\n })\n });\n\n if (!response.ok) {\n throw new Error(`OpenAI Adapter Failed: ${response.statusText}`);\n }\n\n const data = await response.json();\n\n // 3. Parse the result\n try {\n const parsed = JSON.parse(data.choices[0].message.content);\n return { commandId: parsed.commandId };\n } catch (e) {\n console.error(\"Failed to parse LLM response\", e);\n return { commandId: null };\n }\n };\n};"]}
|
package/dist/index.mjs
CHANGED
|
@@ -77,6 +77,66 @@ var useVoiceCommand = (command) => {
|
|
|
77
77
|
}, [register, unregister, command]);
|
|
78
78
|
};
|
|
79
79
|
|
|
80
|
-
|
|
80
|
+
// src/core/prompt.ts
|
|
81
|
+
var createSystemPrompt = (commands) => {
|
|
82
|
+
const commandList = commands.map(
|
|
83
|
+
(cmd) => `- ID: "${cmd.id}" | Description: "${cmd.description}"`
|
|
84
|
+
).join("\n");
|
|
85
|
+
return `
|
|
86
|
+
You are a precise Voice Command Router.
|
|
87
|
+
Your goal is to map the user's spoken input to the correct Command ID from the list below.
|
|
88
|
+
|
|
89
|
+
RULES:
|
|
90
|
+
1. Analyze the user's input and find the intent.
|
|
91
|
+
2. Match it to the command with the most relevant "Description".
|
|
92
|
+
3. Use fuzzy matching (e.g., "Dark mode" matches "Toggle Theme").
|
|
93
|
+
4. If NO command matches the intent, return null.
|
|
94
|
+
5. IMPORTANT: Output ONLY valid JSON. Do not include markdown formatting.
|
|
95
|
+
|
|
96
|
+
AVAILABLE COMMANDS:
|
|
97
|
+
${commandList}
|
|
98
|
+
|
|
99
|
+
RESPONSE FORMAT:
|
|
100
|
+
{ "commandId": "string_id_or_null" }
|
|
101
|
+
`;
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
// src/adapters/openai.ts
|
|
105
|
+
var createOpenAIAdapter = (config) => {
|
|
106
|
+
return async (transcript, commands) => {
|
|
107
|
+
const systemPrompt = createSystemPrompt(commands);
|
|
108
|
+
const response = await fetch("https://api.openai.com/v1/chat/completions", {
|
|
109
|
+
method: "POST",
|
|
110
|
+
headers: {
|
|
111
|
+
"Content-Type": "application/json",
|
|
112
|
+
"Authorization": `Bearer ${config.apiKey}`
|
|
113
|
+
},
|
|
114
|
+
body: JSON.stringify({
|
|
115
|
+
model: config.model || "gpt-4o-mini",
|
|
116
|
+
messages: [
|
|
117
|
+
{ role: "system", content: systemPrompt },
|
|
118
|
+
{ role: "user", content: transcript }
|
|
119
|
+
],
|
|
120
|
+
temperature: 0,
|
|
121
|
+
// Deterministic results
|
|
122
|
+
response_format: { type: "json_object" }
|
|
123
|
+
// Force JSON mode
|
|
124
|
+
})
|
|
125
|
+
});
|
|
126
|
+
if (!response.ok) {
|
|
127
|
+
throw new Error(`OpenAI Adapter Failed: ${response.statusText}`);
|
|
128
|
+
}
|
|
129
|
+
const data = await response.json();
|
|
130
|
+
try {
|
|
131
|
+
const parsed = JSON.parse(data.choices[0].message.content);
|
|
132
|
+
return { commandId: parsed.commandId };
|
|
133
|
+
} catch (e) {
|
|
134
|
+
console.error("Failed to parse LLM response", e);
|
|
135
|
+
return { commandId: null };
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
export { VoiceControlProvider, createOpenAIAdapter, useVoiceCommand, useVoiceContext };
|
|
81
141
|
//# sourceMappingURL=index.mjs.map
|
|
82
142
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/components/VoiceContext.tsx","../src/hooks/useVoiceCommand.ts"],"names":["useRef"],"mappings":";;;;AASA,IAAM,YAAA,GAAe,cAAwC,IAAI,CAAA;AAE1D,IAAM,uBAAqD,CAAC;AAAA,EACjE,QAAA;AAAA,EACA;AACF,CAAA,KAAM;AAEJ,EAAA,MAAM,WAAA,GAAc,MAAA,iBAAkC,IAAI,GAAA,EAAK,CAAA;AAG/D,EAAA,MAAM,CAAC,KAAA,EAAO,QAAQ,CAAA,GAAI,QAAA,CAA4B;AAAA,IACpD,WAAA,EAAa,KAAA;AAAA,IACb,YAAA,EAAc,KAAA;AAAA,IACd,cAAA,EAAgB,IAAA;AAAA,IAChB,gBAAgB;AAAC,GAClB,CAAA;AAGD,EAAA,MAAM,QAAA,GAAW,WAAA,CAAY,CAAC,GAAA,KAAsB;AAClD,IAAA,WAAA,CAAY,OAAA,CAAQ,GAAA,CAAI,GAAA,CAAI,EAAA,EAAI,GAAG,CAAA;AAEnC,IA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,GAAG,KAAA,EAAO,QAAA,EAAU,UAAA,EAAY,iBAAA,EAAkB,EAC/E,QAAA,EACH,CAAA;AAEJ;AAEO,IAAM,kBAAkB,MAAM;AACnC,EAAA,MAAM,GAAA,GAAM,WAAW,YAAY,CAAA;AACnC,EAAA,IAAI,CAAC,GAAA,EAAK,MAAM,IAAI,MAAM,4DAA4D,CAAA;AACtF,EAAA,OAAO,GAAA;AACT;ACjFO,IAAM,eAAA,GAAkB,CAAC,OAAA,KAA0B;AACtD,EAAA,MAAM,EAAE,QAAA,EAAU,UAAA,EAAW,GAAI,eAAA,EAAgB;AAGjD,EAAA,MAAM,KAAA,GAAQA,MAAAA,CAAO,OAAA,CAAQ,EAAE,CAAA;AAE/B,EAAA,SAAA,CAAU,MAAM;AAEZ,IAAA,QAAA,CAAS,OAAO,CAAA;AAGhB,IAAA,OAAO,MAAM;AACT,MAAA,UAAA,CAAW,MAAM,OAAO,CAAA;AAAA,IAC5B,CAAA;AAAA,EACJ,CAAA,EAAG,CAAC,QAAA,EAAU,UAAA,EAAY,OAAO,CAAC,CAAA;AACtC","file":"index.mjs","sourcesContent":["import React, { createContext, useContext, useState, useCallback, useRef } from 'react';\r\nimport { VoiceCommand, VoiceControlState, VoiceProviderProps } from '../types';\r\n\r\ninterface VoiceContextValue extends VoiceControlState {\r\n register: (cmd: VoiceCommand) => void;\r\n unregister: (id: string) => void;\r\n processTranscript: (text: string) => Promise<void>;\r\n}\r\n\r\nconst VoiceContext = createContext<VoiceContextValue | null>(null);\r\n\r\nexport const VoiceControlProvider: React.FC<VoiceProviderProps> = ({ \r\n children, \r\n adapter \r\n}) => {\r\n // THE REGISTRY: A Map ensures O(1) lookups and prevents duplicate IDs\r\n const commandsRef = useRef<Map<string, VoiceCommand>>(new Map());\r\n \r\n // UI STATE\r\n const [state, setState] = useState<VoiceControlState>({\r\n isListening: false,\r\n isProcessing: false,\r\n lastTranscript: null,\r\n activeCommands: [],\r\n });\r\n\r\n // 1. REGISTRATION LOGIC\r\n const register = useCallback((cmd: VoiceCommand) => {\r\n commandsRef.current.set(cmd.id, cmd);\r\n // Update generic state for debugging UI\r\n setState(prev => ({ ...prev, activeCommands: Array.from(commandsRef.current.values()) }));\r\n }, []);\r\n\r\n const unregister = useCallback((id: string) => {\r\n commandsRef.current.delete(id);\r\n setState(prev => ({ ...prev, activeCommands: Array.from(commandsRef.current.values()) }));\r\n }, []);\r\n\r\n // 2. THE ROUTER LOGIC\r\n const processTranscript = useCallback(async (transcript: string) => {\r\n const cleanText = transcript.trim().toLowerCase();\r\n setState(prev => ({ ...prev, isProcessing: true, lastTranscript: cleanText }));\r\n\r\n const allCommands = Array.from(commandsRef.current.values());\r\n\r\n // PHASE 1: EXACT MATCH (0ms Latency)\r\n const exactMatch = allCommands.find(c => c.phrase?.toLowerCase() === cleanText);\r\n \r\n if (exactMatch) {\r\n console.log(`⚡ Instant Match: \"${cleanText}\" -> ${exactMatch.id}`);\r\n exactMatch.action();\r\n setState(prev => ({ ...prev, isProcessing: false }));\r\n return;\r\n }\r\n\r\n // PHASE 2: FUZZY MATCH (AI Adapter)\r\n try {\r\n console.log(`🤖 AI Routing: \"${cleanText}\"...`);\r\n \r\n // We strip the 'action' function before sending to the AI\r\n const commandListForAI = allCommands.map(({ id, description, phrase }) => ({ \r\n id, \r\n description, \r\n phrase \r\n }));\r\n\r\n const result = await adapter(cleanText, commandListForAI);\r\n\r\n if (result.commandId) {\r\n const cmd = commandsRef.current.get(result.commandId);\r\n if (cmd) {\r\n console.log(`✅ Matched: ${cmd.id}`);\r\n cmd.action();\r\n } else {\r\n console.warn(`⚠️ Adapter returned unknown ID: ${result.commandId}`);\r\n }\r\n }\r\n } catch (error) {\r\n console.error(\"Adapter Error:\", error);\r\n } finally {\r\n setState(prev => ({ ...prev, isProcessing: false }));\r\n }\r\n }, [adapter]);\r\n\r\n return (\r\n <VoiceContext.Provider value={{ ...state, register, unregister, processTranscript }}>\r\n {children}\r\n </VoiceContext.Provider>\r\n );\r\n};\r\n\r\nexport const useVoiceContext = () => {\r\n const ctx = useContext(VoiceContext);\r\n if (!ctx) throw new Error(\"useVoiceContext must be used within a VoiceControlProvider\");\r\n return ctx;\r\n};","import { useEffect, useRef } from 'react';\r\nimport { useVoiceContext } from '../components/VoiceContext';\r\nimport { VoiceCommand } from '../types';\r\n\r\n/**\r\n * The Developer Hook\r\n * Wraps the lifecycle logic so the developer doesn't have to.\r\n * * Usage:\r\n * useVoiceCommand({\r\n * id: 'nav_home',\r\n * description: 'Go to home',\r\n * action: () => navigate('/')\r\n * });\r\n */\r\nexport const useVoiceCommand = (command: VoiceCommand) => {\r\n const { register, unregister } = useVoiceContext();\r\n\r\n // Use a ref to keep the ID stable across renders\r\n const idRef = useRef(command.id);\r\n\r\n useEffect(() => {\r\n // 1. Mount: Register the tool\r\n register(command);\r\n\r\n // 2. Unmount: Remove the tool\r\n return () => {\r\n unregister(idRef.current);\r\n };\r\n }, [register, unregister, command]); // Re-register if command definition changes\r\n};"]}
|
|
1
|
+
{"version":3,"sources":["../src/components/VoiceContext.tsx","../src/hooks/useVoiceCommand.ts","../src/core/prompt.ts","../src/adapters/openai.ts"],"names":["useRef"],"mappings":";;;;AASA,IAAM,YAAA,GAAe,cAAwC,IAAI,CAAA;AAE1D,IAAM,uBAAqD,CAAC;AAAA,EACjE,QAAA;AAAA,EACA;AACF,CAAA,KAAM;AAEJ,EAAA,MAAM,WAAA,GAAc,MAAA,iBAAkC,IAAI,GAAA,EAAK,CAAA;AAG/D,EAAA,MAAM,CAAC,KAAA,EAAO,QAAQ,CAAA,GAAI,QAAA,CAA4B;AAAA,IACpD,WAAA,EAAa,KAAA;AAAA,IACb,YAAA,EAAc,KAAA;AAAA,IACd,cAAA,EAAgB,IAAA;AAAA,IAChB,gBAAgB;AAAC,GAClB,CAAA;AAGD,EAAA,MAAM,QAAA,GAAW,WAAA,CAAY,CAAC,GAAA,KAAsB;AAClD,IAAA,WAAA,CAAY,OAAA,CAAQ,GAAA,CAAI,GAAA,CAA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M,QAAA,GAAW,MAAM,KAAA,CAAM,4CAAA,EAA8C;AAAA,MACvE,MAAA,EAAQ,MAAA;AAAA,MACR,OAAA,EAAS;AAAA,QACL,cAAA,EAAgB,kBAAA;AAAA,QAChB,eAAA,EAAiB,CAAA,OAAA,EAAU,MAAA,CAAO,MAAM,CAAA;AAAA,OAC5C;AAAA,MACA,IAAA,EAAM,KAAK,SAAA,CAAU;AAAA,QACjB,KAAA,EAAO,OAAO,KAAA,IAAS,aAAA;AAAA,QACvB,QAAA,EAAU;AAAA,UACN,EAAE,IAAA,EAAM,QAAA,EAAU,OAAA,EAAS,YAAA,EAAa;AAAA,UACxC,EAAE,IAAA,EAAM,MAAA,EAAQ,OAAA,EAAS,UAAA;AAAW,SACxC;AAAA,QACA,WAAA,EAAa,CAAA;AAAA;AAAA,QACb,eAAA,EAAiB,EAAE,IAAA,EAAM,aAAA;AAAc;AAAA,OAC1C;AAAA,KACJ,CAAA;AAED,IAAA,IAAI,CAAC,SAAS,EAAA,EAAI;AACd,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,uBAAA,EAA0B,QAAA,CAAS,UAAU,CAAA,CAAE,CAAA;AAAA,IACnE;AAEA,IAAA,MAAM,IAAA,GAAO,MAAM,QAAA,CAAS,IAAA,EAAK;AAGjC,IAAA,IAAI;AACA,MAAA,MAAM,MAAA,GAAS,KAAK,KAAA,CAAM,IAAA,CAAK,QAAQ,CAAC,CAAA,CAAE,QAAQ,OAAO,CAAA;AACzD,MAAA,OAAO,EAAE,SAAA,EAAW,MAAA,CAAO,SAAA,EAAU;AAAA,IACzC,SAAS,CAAA,EAAG;AACR,MAAA,OAAA,CAAQ,KAAA,CAAM,gCAAgC,CAAC,CAAA;AAC/C,MAAA,OAAO,EAAE,WAAW,IAAA,EAAK;AAAA,IAC7B;AAAA,EACJ,CAAA;AACJ","file":"index.mjs","sourcesContent":["import React, { createContext, useContext, useState, useCallback, useRef } from 'react';\nimport { VoiceCommand, VoiceControlState, VoiceProviderProps } from '../types';\n\ninterface VoiceContextValue extends VoiceControlState {\n register: (cmd: VoiceCommand) => void;\n unregister: (id: string) => void;\n processTranscript: (text: string) => Promise<void>;\n}\n\nconst VoiceContext = createContext<VoiceContextValue | null>(null);\n\nexport const VoiceControlProvider: React.FC<VoiceProviderProps> = ({ \n children, \n adapter \n}) => {\n // THE REGISTRY: A Map ensures O(1) lookups and prevents duplicate IDs\n const commandsRef = useRef<Map<string, VoiceCommand>>(new Map());\n \n // UI STATE\n const [state, setState] = useState<VoiceControlState>({\n isListening: false,\n isProcessing: false,\n lastTranscript: null,\n activeCommands: [],\n });\n\n // 1. REGISTRATION LOGIC\n const register = useCallback((cmd: VoiceCommand) => {\n commandsRef.current.set(cmd.id, cmd);\n // Update generic state for debugging UI\n setState(prev => ({ ...prev, activeCommands: Array.from(commandsRef.current.values()) }));\n }, []);\n\n const unregister = useCallback((id: string) => {\n commandsRef.current.delete(id);\n setState(prev => ({ ...prev, activeCommands: Array.from(commandsRef.current.values()) }));\n }, []);\n\n // 2. THE ROUTER LOGIC\n const processTranscript = useCallback(async (transcript: string) => {\n const cleanText = transcript.trim().toLowerCase();\n setState(prev => ({ ...prev, isProcessing: true, lastTranscript: cleanText }));\n\n const allCommands = Array.from(commandsRef.current.values());\n\n // PHASE 1: EXACT MATCH (0ms Latency)\n const exactMatch = allCommands.find(c => c.phrase?.toLowerCase() === cleanText);\n \n if (exactMatch) {\n console.log(`⚡ Instant Match: \"${cleanText}\" -> ${exactMatch.id}`);\n exactMatch.action();\n setState(prev => ({ ...prev, isProcessing: false }));\n return;\n }\n\n // PHASE 2: FUZZY MATCH (AI Adapter)\n try {\n console.log(`🤖 AI Routing: \"${cleanText}\"...`);\n \n // We strip the 'action' function before sending to the AI\n const commandListForAI = allCommands.map(({ id, description, phrase }) => ({ \n id, \n description, \n phrase \n }));\n\n const result = await adapter(cleanText, commandListForAI);\n\n if (result.commandId) {\n const cmd = commandsRef.current.get(result.commandId);\n if (cmd) {\n console.log(`✅ Matched: ${cmd.id}`);\n cmd.action();\n } else {\n console.warn(`⚠️ Adapter returned unknown ID: ${result.commandId}`);\n }\n }\n } catch (error) {\n console.error(\"Adapter Error:\", error);\n } finally {\n setState(prev => ({ ...prev, isProcessing: false }));\n }\n }, [adapter]);\n\n return (\n <VoiceContext.Provider value={{ ...state, register, unregister, processTranscript }}>\n {children}\n </VoiceContext.Provider>\n );\n};\n\nexport const useVoiceContext = () => {\n const ctx = useContext(VoiceContext);\n if (!ctx) throw new Error(\"useVoiceContext must be used within a VoiceControlProvider\");\n return ctx;\n};","import { useEffect, useRef } from 'react';\nimport { useVoiceContext } from '../components/VoiceContext';\nimport { VoiceCommand } from '../types';\n\n/**\n * The Developer Hook\n * Wraps the lifecycle logic so the developer doesn't have to.\n * * Usage:\n * useVoiceCommand({\n * id: 'nav_home',\n * description: 'Go to home',\n * action: () => navigate('/')\n * });\n */\nexport const useVoiceCommand = (command: VoiceCommand) => {\n const { register, unregister } = useVoiceContext();\n\n // Use a ref to keep the ID stable across renders\n const idRef = useRef(command.id);\n\n useEffect(() => {\n // 1. Mount: Register the tool\n register(command);\n\n // 2. Unmount: Remove the tool\n return () => {\n unregister(idRef.current);\n };\n }, [register, unregister, command]); // Re-register if command definition changes\n};","import { VoiceCommand } from '../types';\n\n/**\n * Generates the System Prompt for the LLM.\n * This ensures consistent behavior across different AI providers.\n */\nexport const createSystemPrompt = (commands: Omit<VoiceCommand, 'action'>[]) => {\n // Format the list of commands for the AI to read\n const commandList = commands.map(cmd =>\n `- ID: \"${cmd.id}\" | Description: \"${cmd.description}\"`\n ).join('\\n');\n\n return `\nYou are a precise Voice Command Router.\nYour goal is to map the user's spoken input to the correct Command ID from the list below.\n\nRULES:\n1. Analyze the user's input and find the intent.\n2. Match it to the command with the most relevant \"Description\".\n3. Use fuzzy matching (e.g., \"Dark mode\" matches \"Toggle Theme\").\n4. If NO command matches the intent, return null.\n5. IMPORTANT: Output ONLY valid JSON. Do not include markdown formatting.\n\nAVAILABLE COMMANDS:\n${commandList}\n\nRESPONSE FORMAT:\n{ \"commandId\": \"string_id_or_null\" }\n`;\n};\n\n/**\n * Standardizes how the user's voice transcript is presented to the AI.\n */\nexport const createUserPrompt = (transcript: string) => {\n return `User Input: \"${transcript}\"`;\n};","import { LLMAdapter } from '../types';\nimport { createSystemPrompt } from '../core/prompt';\n\ninterface OpenAIConfig {\n apiKey: string;\n /** @default \"gpt-4o-mini\" */\n model?: string;\n}\n\n/**\n * A Factory that creates an Adapter for OpenAI.\n * Users call this: createOpenAIAdapter({ apiKey: '...' })\n */\nexport const createOpenAIAdapter = (config: OpenAIConfig): LLMAdapter => {\n return async (transcript, commands) => {\n\n // 1. Generate the optimized system instructions\n const systemPrompt = createSystemPrompt(commands);\n\n // 2. Call the API\n const response = await fetch('https://api.openai.com/v1/chat/completions', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${config.apiKey}`\n },\n body: JSON.stringify({\n model: config.model || \"gpt-4o-mini\",\n messages: [\n { role: \"system\", content: systemPrompt },\n { role: \"user\", content: transcript }\n ],\n temperature: 0, // Deterministic results\n response_format: { type: \"json_object\" } // Force JSON mode\n })\n });\n\n if (!response.ok) {\n throw new Error(`OpenAI Adapter Failed: ${response.statusText}`);\n }\n\n const data = await response.json();\n\n // 3. Parse the result\n try {\n const parsed = JSON.parse(data.choices[0].message.content);\n return { commandId: parsed.commandId };\n } catch (e) {\n console.error(\"Failed to parse LLM response\", e);\n return { commandId: null };\n }\n };\n};"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-voice-action-router",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.2",
|
|
4
4
|
"description": "A headless voice action router for React",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"module": "./dist/index.mjs",
|
|
@@ -46,4 +46,4 @@
|
|
|
46
46
|
"tsup": "^8.5.1",
|
|
47
47
|
"typescript": "^5.9.3"
|
|
48
48
|
}
|
|
49
|
-
}
|
|
49
|
+
}
|