Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

Phase 9: Embedding-based tool routing (v2.4.0)

PurpleDoubleD81ac39d4153d
diff --git a/src/api/agents/__tests__/embedding-router.test.ts b/src/api/agents/__tests__/embedding-router.test.ts
new file mode 100644
index 00000000..67d9aff6
--- /dev/null
+++ b/src/api/agents/__tests__/embedding-router.test.ts
@@ -0,0 +1,166 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import {
+ precomputeToolEmbeddings,
+ rankToolsByEmbedding,
+ selectToolsByEmbedding,
+ clearEmbeddingCache,
+ __internal,
+} from '../embedding-router'
+
+// Deterministic fake embeddings: character-frequency vectors of length 26
+// ('a'..'z'). Two similar-topic strings will share character distribution
+// and hence a high cosine similarity without needing real nomic-embed.
+const fakeEmbed = async (texts: string[]): Promise<number[][]> =>
+ texts.map((t) => {
+ const v = new Array(26).fill(0)
+ const s = t.toLowerCase()
+ for (let i = 0; i < s.length; i++) {
+ const code = s.charCodeAt(i)
+ if (code >= 97 && code <= 122) v[code - 97] += 1
+ }
+ return v
+ })
+
+describe('embedding-router — precompute / cache', () => {
+ beforeEach(() => clearEmbeddingCache())
+
+ it('embeds tools on first pass and caches them', async () => {
+ const tools = [
+ { name: 'a', description: 'apple' },
+ { name: 'b', description: 'banana' },
+ ]
+ const added = await precomputeToolEmbeddings(tools, fakeEmbed)
+ expect(added).toBe(2)
+ expect(__internal.CACHE.size).toBe(2)
+ })
+
+ it('skips tools whose description has not changed', async () => {
+ const tools = [{ name: 'a', description: 'apple' }]
+ await precomputeToolEmbeddings(tools, fakeEmbed)
+ const embedSpy = vi.fn(fakeEmbed)
+ const added = await precomputeToolEmbeddings(tools, embedSpy)
+ expect(added).toBe(0)
+ expect(embedSpy).not.toHaveBeenCalled()
+ })
+
+ it('re-embeds a tool whose description changed', async () => {
+ await precomputeToolEmbeddings([{ name: 'a', description: 'apple' }], fakeEmbed)
+ const embedSpy = vi.fn(fakeEmbed)
+ const added = await precomputeToolEmbeddings(
+ [{ name: 'a', description: 'apple banana' }],
+ embedSpy
+ )
+ expect(added).toBe(1)
+ expect(embedSpy).toHaveBeenCalledOnce()
+ })
+})
+
+describe('embedding-router — ranking', () => {
+ beforeEach(() => clearEmbeddingCache())
+
+ it('ranks the most similar-text tool first', async () => {
+ const tools = [
+ { name: 'search_web', description: 'find things on the internet and return results' },
+ { name: 'read_file', description: 'open a file on disk and return contents' },
+ { name: 'run_shell', description: 'execute a terminal command and return output' },
+ ]
+ await precomputeToolEmbeddings(tools, fakeEmbed)
+ const ranked = await rankToolsByEmbedding(
+ 'please open the readme file on my disk',
+ tools,
+ fakeEmbed,
+ { topN: 3 }
+ )
+ expect(ranked[0].tool.name).toBe('read_file')
+ })
+
+ it('respects topN truncation', async () => {
+ const tools = Array.from({ length: 10 }, (_, i) => ({
+ name: `t${i}`,
+ description: `description ${i}`,
+ }))
+ await precomputeToolEmbeddings(tools, fakeEmbed)
+ const ranked = await rankToolsByEmbedding('query', tools, fakeEmbed, { topN: 3 })
+ expect(ranked).toHaveLength(3)
+ })
+
+ it('skips uncached tools silently', async () => {
+ const tools = [{ name: 'a', description: 'apple' }, { name: 'b', description: 'banana' }]
+ // Only embed "a" first
+ await precomputeToolEmbeddings([tools[0]], fakeEmbed)
+ const ranked = await rankToolsByEmbedding('apple', tools, fakeEmbed, { topN: 5 })
+ expect(ranked.map((r) => r.tool.name)).toEqual(['a'])
+ })
+
+ it('returns [] on empty query embedding', async () => {
+ const tools = [{ name: 'a', description: 'apple' }]
+ await precomputeToolEmbeddings(tools, fakeEmbed)
+ const ranked = await rankToolsByEmbedding(
+ 'x',
+ tools,
+ async () => [] as number[][], // pathological — returns no vector
+ { topN: 3 }
+ )
+ expect(ranked).toEqual([])
+ })
+})
+
+describe('embedding-router — selectToolsByEmbedding', () => {
+ beforeEach(() => clearEmbeddingCache())
+
+ it('precomputes, ranks topN tools, unions with alwaysInclude', async () => {
+ const tools = [
+ { name: 'search_web', description: 'find things on the internet' },
+ { name: 'read_file', description: 'open a file on disk' },
+ { name: 'get_current_time', description: 'return current local time' },
+ ]
+ const out = await selectToolsByEmbedding(
+ 'any query — topN is the contract being tested, not specific ranking',
+ tools,
+ fakeEmbed,
+ { topN: 1, alwaysInclude: ['get_current_time'] }
+ )
+ // Exactly 1 ranked + get_current_time always appended = 2 (unless the
+ // top-ranked happens to be get_current_time, then 1).
+ expect(out.length).toBeGreaterThanOrEqual(1)
+ expect(out).toContain('get_current_time')
+ })
+
+ it('does not duplicate when an always-include name is already ranked', async () => {
+ const tools = [
+ { name: 'get_current_time', description: 'return current local date and time now' },
+ ]
+ const out = await selectToolsByEmbedding(
+ 'what time is it',
+ tools,
+ fakeEmbed,
+ { topN: 3, alwaysInclude: ['get_current_time'] }
+ )
+ expect(out.filter((n) => n === 'get_current_time')).toHaveLength(1)
+ })
+})
+
+describe('embedding-router — cosine edge cases', () => {
+ it('zero vector → similarity 0', () => {
+ expect(__internal.cosine([0, 0, 0], [1, 1, 1])).toBe(0)
+ })
+ it('identical vector → 1', () => {
+ expect(__internal.cosine([1, 2, 3], [1, 2, 3])).toBeCloseTo(1, 5)
+ })
+ it('opposite vector → -1', () => {
+ expect(__internal.cosine([1, 2, 3], [-1, -2, -3])).toBeCloseTo(-1, 5)
+ })
+ it('different-length vectors use the shorter length', () => {
+ const v = __internal.cosine([1, 2, 3], [1, 2])
+ expect(Number.isFinite(v)).toBe(true)
+ })
+})
+
+describe('embedding-router — hashDescription', () => {
+ it('is stable', () => {
+ expect(__internal.hashDescription('hello')).toBe(__internal.hashDescription('hello'))
+ })
+ it('differs for different descriptions', () => {
+ expect(__internal.hashDescription('a')).not.toBe(__internal.hashDescription('b'))
+ })
+})
diff --git a/src/api/agents/embedding-router.ts b/src/api/agents/embedding-router.ts
new file mode 100644
index 00000000..618acd1a
--- /dev/null
+++ b/src/api/agents/embedding-router.ts
@@ -0,0 +1,142 @@
+/**
+ * Phase 9 (v2.4.0) — Embedding-based tool routing.
+ *
+ * When the total tool count exceeds ~15 (typical once MCP servers are
+ * connected), the keyword-only tool-selection misses the right tools for
+ * novel requests. This module adds a semantic layer:
+ *
+ * 1. Precompute nomic-embed-text vectors for every tool description.
+ * 2. Embed the user message.
+ * 3. Return the top-N tools by cosine similarity + ALWAYS_INCLUDE.
+ *
+ * Design points:
+ * - Embeddings are cached by tool name + description hash so recompute
+ * only happens when a description actually changes.
+ * - All embedding work is best-effort: if Ollama is unreachable or the
+ * nomic-embed model is missing, the router falls back silently and
+ * signals the caller to use keyword routing.
+ * - The module is side-effect-light in node (no localStorage calls);
+ * the cache lives in a per-module Map that survives hot reload but
+ * resets between sessions.
+ * - The embedding client is dependency-injected so tests can stub it
+ * without pulling Ollama.
+ */
+
+export type EmbeddingFn = (texts: string[]) => Promise<number[][]>
+
+interface ToolLike {
+ name: string
+ description: string
+}
+
+interface CachedVector {
+ descriptionHash: string
+ vector: number[]
+}
+
+const CACHE = new Map<string, CachedVector>()
+
+function hashDescription(s: string): string {
+ // djb2; plenty to detect description changes.
+ let h = 5381
+ for (let i = 0; i < s.length; i++) h = (h * 33) ^ s.charCodeAt(i)
+ return (h >>> 0).toString(16)
+}
+
+export function clearEmbeddingCache(): void {
+ CACHE.clear()
+}
+
+/**
+ * Precompute embeddings for each tool's description. Cheaply skips any
+ * tool whose (name, descriptionHash) is already cached. Returns the
+ * number of newly embedded tools (useful for logs/tests).
+ */
+export async function precomputeToolEmbeddings(
+ tools: ToolLike[],
+ embed: EmbeddingFn
+): Promise<number> {
+ const toEmbed: ToolLike[] = []
+ for (const t of tools) {
+ const hash = hashDescription(t.description)
+ const cached = CACHE.get(t.name)
+ if (!cached || cached.descriptionHash !== hash) toEmbed.push(t)
+ }
+ if (toEmbed.length === 0) return 0
+
+ const vectors = await embed(toEmbed.map((t) => t.description))
+ for (let i = 0; i < toEmbed.length; i++) {
+ CACHE.set(toEmbed[i].name, {
+ descriptionHash: hashDescription(toEmbed[i].description),
+ vector: vectors[i],
+ })
+ }
+ return toEmbed.length
+}
+
+function cosine(a: number[], b: number[]): number {
+ let dot = 0
+ let magA = 0
+ let magB = 0
+ const n = Math.min(a.length, b.length)
+ for (let i = 0; i < n; i++) {
+ dot += a[i] * b[i]
+ magA += a[i] * a[i]
+ magB += b[i] * b[i]
+ }
+ const denom = Math.sqrt(magA) * Math.sqrt(magB)
+ return denom === 0 ? 0 : dot / denom
+}
+
+/**
+ * Rank tools by cosine similarity against the query. Tools missing from
+ * the embedding cache are skipped silently (caller is responsible for
+ * precomputing or merging with keyword fallback).
+ */
+export async function rankToolsByEmbedding(
+ query: string,
+ tools: ToolLike[],
+ embed: EmbeddingFn,
+ opts: { topN?: number } = {}
+): Promise<Array<{ tool: ToolLike; score: number }>> {
+ const topN = opts.topN ?? 10
+ const [queryVec] = await embed([query])
+ if (!queryVec) return []
+
+ const scored: Array<{ tool: ToolLike; score: number }> = []
+ for (const t of tools) {
+ const c = CACHE.get(t.name)
+ if (!c) continue
+ scored.push({ tool: t, score: cosine(queryVec, c.vector) })
+ }
+ scored.sort((a, b) => b.score - a.score)
+ return scored.slice(0, topN)
+}
+
+/**
+ * End-to-end helper: precompute + rank + union with always-include names.
+ * Returns the final tool-name set ordered most-relevant-first. Callers
+ * should treat this as a soft hint — keep permissions filtering, keep
+ * your keyword fallback in case this module returns too few tools.
+ */
+export async function selectToolsByEmbedding(
+ query: string,
+ tools: ToolLike[],
+ embed: EmbeddingFn,
+ opts: { topN?: number; alwaysInclude?: string[] } = {}
+): Promise<string[]> {
+ const topN = opts.topN ?? 10
+ const always = opts.alwaysInclude ?? []
+
+ // Precompute on the way in — cheap once cached.
+ await precomputeToolEmbeddings(tools, embed)
+
+ const ranked = await rankToolsByEmbedding(query, tools, embed, { topN })
+ const names = ranked.map((r) => r.tool.name)
+ const out = [...names]
+ for (const a of always) if (!out.includes(a)) out.push(a)
+ return out
+}
+
+/** Exposed for tests. */
+export const __internal = { CACHE, hashDescription, cosine }
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 8b539c19..9eef7846 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -23,7 +23,8 @@ import { buildExtractionPrompt, parseExtractionResponse } from '../lib/memory-ex
import { useAgentWorkflowStore } from '../stores/agentWorkflowStore'
import { WorkflowEngine } from '../lib/workflow-engine'
import type { AgentBlock, AgentToolCall, OllamaChatMessage } from '../types/agent-mode'
-import { selectRelevantTools } from '../lib/tool-selection'
+import { selectRelevantTools, selectRelevantToolsAsync } from '../lib/tool-selection'
+import { generateEmbeddings } from '../api/rag'
import type { ChatMessage, ToolCall, ToolDefinition } from '../api/providers/types'
import type { StepResult, WorkflowEngineCallbacks } from '../types/agent-workflows'
import { executeParallel, applyResultToToolCall, type ExecutionRequest } from '../api/agents/tool-executor'
@@ -408,9 +409,17 @@ export function useAgentChat() {
timestamp: Date.now(),
})
- // Intelligent tool selection — only include relevant tools
+ // Intelligent tool selection — keyword for small lists, embedding
+ // routing once the total tool count grows past the threshold
+ // (Phase 9). The embedding call is best-effort: if Ollama is
+ // unreachable it silently falls back to keyword-only.
const lastUserMsg = agentMessages.filter(m => m.role === 'user').pop()?.content || ''
- const relevantDefs = selectRelevantTools(lastUserMsg, toolRegistry.getAll(), permissions)
+ const relevantDefs = await selectRelevantToolsAsync(
+ lastUserMsg,
+ toolRegistry.getAll(),
+ permissions,
+ { embed: (texts) => generateEmbeddings(texts) }
+ )
const tools: ToolDefinition[] = relevantDefs.map(t => ({
type: 'function' as const,
function: { name: t.name, description: t.description, parameters: t.inputSchema },
diff --git a/src/lib/__tests__/tool-selection-async.test.ts b/src/lib/__tests__/tool-selection-async.test.ts
new file mode 100644
index 00000000..df6180b3
--- /dev/null
+++ b/src/lib/__tests__/tool-selection-async.test.ts
@@ -0,0 +1,120 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import { selectRelevantToolsAsync, EMBEDDING_ROUTING_THRESHOLD } from '../tool-selection'
+import { clearEmbeddingCache } from '../../api/agents/embedding-router'
+import type { MCPToolDefinition, PermissionMap } from '../../api/mcp/types'
+
+const fullPerms: PermissionMap = {
+ filesystem: 'auto',
+ terminal: 'auto',
+ desktop: 'auto',
+ web: 'auto',
+ system: 'auto',
+ image: 'auto',
+ video: 'auto',
+ workflow: 'auto',
+}
+
+const mkTool = (name: string, description: string, category: keyof PermissionMap = 'system'): MCPToolDefinition => ({
+ name,
+ description,
+ inputSchema: { type: 'object', properties: {}, required: [] },
+ category,
+ source: 'builtin',
+})
+
+const fakeEmbed = async (texts: string[]): Promise<number[][]> =>
+ texts.map((t) => {
+ const v = new Array(26).fill(0)
+ const s = t.toLowerCase()
+ for (let i = 0; i < s.length; i++) {
+ const c = s.charCodeAt(i)
+ if (c >= 97 && c <= 122) v[c - 97] += 1
+ }
+ return v
+ })
+
+describe('tool-selection — selectRelevantToolsAsync', () => {
+ beforeEach(() => clearEmbeddingCache())
+
+ it('below threshold: keyword path only, never calls embed', async () => {
+ const tools = [
+ mkTool('file_read', 'read a file on disk', 'filesystem'),
+ mkTool('file_write', 'write a file on disk', 'filesystem'),
+ mkTool('get_current_time', 'return current local time', 'system'),
+ ]
+ const embedSpy = vi.fn(fakeEmbed)
+ const out = await selectRelevantToolsAsync(
+ 'what time is it',
+ tools,
+ fullPerms,
+ { embed: embedSpy, embeddingThreshold: EMBEDDING_ROUTING_THRESHOLD }
+ )
+ expect(embedSpy).not.toHaveBeenCalled()
+ expect(out.some((t) => t.name === 'get_current_time')).toBe(true)
+ })
+
+ it('no embed fn provided: keyword path', async () => {
+ const tools = Array.from({ length: 20 }, (_, i) =>
+ mkTool(`tool_${i}`, `description number ${i}`)
+ )
+ const out = await selectRelevantToolsAsync('random query', tools, fullPerms)
+ // keyword path unions with ALWAYS_INCLUDE so size > 0
+ expect(out.length).toBeGreaterThan(0)
+ })
+
+ it('above threshold with embed: union of semantic + keyword selection', async () => {
+ const tools = [
+ mkTool('file_read', 'read a file on disk', 'filesystem'),
+ mkTool('file_write', 'write a file on disk', 'filesystem'),
+ mkTool('web_search', 'search the web for current information', 'web'),
+ mkTool('web_fetch', 'fetch a URL and return text', 'web'),
+ mkTool('get_current_time', 'return current local date time', 'system'),
+ mkTool('shell_execute', 'run a terminal command', 'terminal'),
+ mkTool('code_execute', 'execute python code', 'terminal'),
+ mkTool('system_info', 'os architecture hostname', 'system'),
+ mkTool('process_list', 'list running processes', 'system'),
+ mkTool('screenshot', 'take a screenshot', 'desktop'),
+ mkTool('image_generate', 'generate an image from prompt', 'image'),
+ mkTool('run_workflow', 'run a saved workflow', 'workflow'),
+ mkTool('file_list', 'list directory contents', 'filesystem'),
+ mkTool('file_search', 'search file contents with regex', 'filesystem'),
+ mkTool('custom_mcp_1', 'some external tool about search indexing', 'workflow'),
+ mkTool('custom_mcp_2', 'some external tool about image analysis', 'workflow'),
+ ]
+ // > EMBEDDING_ROUTING_THRESHOLD — embedding path triggers.
+ const out = await selectRelevantToolsAsync(
+ 'please read the file on disk',
+ tools,
+ fullPerms,
+ { embed: fakeEmbed, topN: 3 }
+ )
+ // ALWAYS_INCLUDE means file_read and file_write + get_current_time are in.
+ expect(out.some((t) => t.name === 'file_read')).toBe(true)
+ expect(out.some((t) => t.name === 'get_current_time')).toBe(true)
+ })
+
+ it('embed failure falls back silently to keyword', async () => {
+ const tools = Array.from({ length: 20 }, (_, i) =>
+ mkTool(`t${i}`, `desc ${i}`, 'filesystem')
+ )
+ const broken = vi.fn(async () => {
+ throw new Error('Ollama down')
+ }) as any
+ const out = await selectRelevantToolsAsync('any', tools, fullPerms, {
+ embed: broken,
+ embeddingThreshold: 5, // force embedding path
+ })
+ // keyword fallback still returns something usable
+ expect(out.length).toBeGreaterThan(0)
+ })
+
+ it('permission-blocked categories are filtered out in either path', async () => {
+ const restricted: PermissionMap = { ...fullPerms, filesystem: 'blocked' }
+ const tools = [
+ mkTool('file_read', 'read disk', 'filesystem'),
+ mkTool('web_search', 'search', 'web'),
+ ]
+ const out = await selectRelevantToolsAsync('read a file please', tools, restricted)
+ expect(out.some((t) => t.name === 'file_read')).toBe(false)
+ })
+})
diff --git a/src/lib/tool-selection.ts b/src/lib/tool-selection.ts
index 03a7c67b..eecccd2c 100644
--- a/src/lib/tool-selection.ts
+++ b/src/lib/tool-selection.ts
@@ -65,7 +65,13 @@ const TOOL_GROUPS: ToolGroup[] = [
// a tool result reveals the user really wanted a file read). Keeping
// `get_current_time` here means the agent NEVER has to fall back to web
// for a trivial date question just because the keyword list missed.
-const ALWAYS_INCLUDE = ['file_read', 'file_write', 'get_current_time']
+export const ALWAYS_INCLUDE = ['file_read', 'file_write', 'get_current_time']
+
+/** Tool count at which embedding-based routing becomes worth the round trip. */
+export const EMBEDDING_ROUTING_THRESHOLD = 15
+
+import type { EmbeddingFn } from '../api/agents/embedding-router'
+import { selectToolsByEmbedding } from '../api/agents/embedding-router'
/**
* Select relevant tools based on user message content.
@@ -107,3 +113,37 @@ export function selectRelevantTools(
return selected
}
+
+/**
+ * Embedding-aware variant (Phase 9 v2.4.0). When `embed` is provided AND
+ * the permission-filtered tool count exceeds EMBEDDING_ROUTING_THRESHOLD,
+ * rank tools by semantic similarity to the user message and union the
+ * result with the keyword-based selection (belt + braces). When `embed`
+ * is absent, throws, or fails, silently falls back to the keyword-only
+ * path.
+ */
+export async function selectRelevantToolsAsync(
+ userMessage: string,
+ allTools: MCPToolDefinition[],
+ permissions: PermissionMap,
+ opts?: { embed?: EmbeddingFn; embeddingThreshold?: number; topN?: number },
+): Promise<MCPToolDefinition[]> {
+ const threshold = opts?.embeddingThreshold ?? EMBEDDING_ROUTING_THRESHOLD
+ const available = allTools.filter((t) => permissions[t.category] !== 'blocked')
+ if (!opts?.embed || available.length <= threshold) {
+ return selectRelevantTools(userMessage, allTools, permissions)
+ }
+ try {
+ const semanticNames = await selectToolsByEmbedding(
+ userMessage,
+ available.map((t) => ({ name: t.name, description: t.description })),
+ opts.embed,
+ { topN: opts.topN ?? 10, alwaysInclude: ALWAYS_INCLUDE },
+ )
+ const keyword = selectRelevantTools(userMessage, allTools, permissions)
+ const union = new Set<string>([...semanticNames, ...keyword.map((t) => t.name)])
+ return available.filter((t) => union.has(t.name))
+ } catch {
+ return selectRelevantTools(userMessage, allTools, permissions)
+ }
+}