Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

feat: migrate agent mode to Vercel AI SDK

Gabriel Stein8413080abf5c
diff --git a/package-lock.json b/package-lock.json
index 6487b0348..c6ba9fab2 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -10,6 +10,10 @@
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
+ "@ai-sdk/anthropic": "^3.0.58",
+ "@ai-sdk/google": "^3.0.43",
+ "@ai-sdk/groq": "^3.0.29",
+ "@ai-sdk/openai": "^3.0.41",
"@neondatabase/auth": "^0.1.0-beta.21",
"@neondatabase/neon-js": "^0.1.0-beta.22",
"@radix-ui/react-accordion": "^1.1.2",
@@ -21,6 +25,7 @@
"@radix-ui/react-slot": "^1.2.3",
"@radix-ui/react-tabs": "^1.1.12",
"@vercel/blob": "^2.3.0",
+ "ai": "^6.0.116",
"better-sqlite3": "^12.4.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
@@ -73,6 +78,116 @@
"node": ">=22"
}
},
+ "node_modules/@ai-sdk/anthropic": {
+ "version": "3.0.58",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/anthropic/-/anthropic-3.0.58.tgz",
+ "integrity": "sha512-/53SACgmVukO4bkms4dpxpRlYhW8Ct6QZRe6sj1Pi5H00hYhxIrqfiLbZBGxkdRvjsBQeP/4TVGsXgH5rQeb8Q==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@ai-sdk/provider": "3.0.8",
+ "@ai-sdk/provider-utils": "4.0.19"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "zod": "^3.25.76 || ^4.1.8"
+ }
+ },
+ "node_modules/@ai-sdk/gateway": {
+ "version": "3.0.66",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/gateway/-/gateway-3.0.66.tgz",
+ "integrity": "sha512-SIQ0YY0iMuv+07HLsZ+bB990zUJ6S4ujORAh+Jv1V2KGNn73qQKnGO0JBk+w+Res8YqOFSycwDoWcFlQrVxS4A==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@ai-sdk/provider": "3.0.8",
+ "@ai-sdk/provider-utils": "4.0.19",
+ "@vercel/oidc": "3.1.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "zod": "^3.25.76 || ^4.1.8"
+ }
+ },
+ "node_modules/@ai-sdk/google": {
+ "version": "3.0.43",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/google/-/google-3.0.43.tgz",
+ "integrity": "sha512-NGCgP5g8HBxrNdxvF8Dhww+UKfqAkZAmyYBvbu9YLoBkzAmGKDBGhVptN/oXPB5Vm0jggMdoLycZ8JReQM8Zqg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@ai-sdk/provider": "3.0.8",
+ "@ai-sdk/provider-utils": "4.0.19"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "zod": "^3.25.76 || ^4.1.8"
+ }
+ },
+ "node_modules/@ai-sdk/groq": {
+ "version": "3.0.29",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/groq/-/groq-3.0.29.tgz",
+ "integrity": "sha512-I/tUoHuOvGXbIr1dJ0CLRLA7W0UPDMtrYT5mgeb3O+P+6I5BAm/7riPwr22Xw5YTzpwQxcoDQlIczOU9XDXBpA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@ai-sdk/provider": "3.0.8",
+ "@ai-sdk/provider-utils": "4.0.19"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "zod": "^3.25.76 || ^4.1.8"
+ }
+ },
+ "node_modules/@ai-sdk/openai": {
+ "version": "3.0.41",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/openai/-/openai-3.0.41.tgz",
+ "integrity": "sha512-IZ42A+FO+vuEQCVNqlnAPYQnnUpUfdJIwn1BEDOBywiEHa23fw7PahxVtlX9zm3/zMvTW4JKPzWyvAgDu+SQ2A==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@ai-sdk/provider": "3.0.8",
+ "@ai-sdk/provider-utils": "4.0.19"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "zod": "^3.25.76 || ^4.1.8"
+ }
+ },
+ "node_modules/@ai-sdk/provider": {
+ "version": "3.0.8",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-3.0.8.tgz",
+ "integrity": "sha512-oGMAgGoQdBXbZqNG0Ze56CHjDZ1IDYOwGYxYjO5KLSlz5HiNQ9udIXsPZ61VWaHGZ5XW/jyjmr6t2xz2jGVwbQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "json-schema": "^0.4.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@ai-sdk/provider-utils": {
+ "version": "4.0.19",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/provider-utils/-/provider-utils-4.0.19.tgz",
+ "integrity": "sha512-3eG55CrSWCu2SXlqq2QCsFjo3+E7+Gmg7i/oRVoSZzIodTuDSfLb3MRje67xE9RFea73Zao7Lm4mADIfUETKGg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@ai-sdk/provider": "3.0.8",
+ "@standard-schema/spec": "^1.1.0",
+ "eventsource-parser": "^3.0.6"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "zod": "^3.25.76 || ^4.1.8"
+ }
+ },
"node_modules/@babel/code-frame": {
"version": "7.29.0",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz",
@@ -7073,6 +7188,15 @@
"node": ">=20.0.0"
}
},
+ "node_modules/@vercel/oidc": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/@vercel/oidc/-/oidc-3.1.0.tgz",
+ "integrity": "sha512-Fw28YZpRnA3cAHHDlkt7xQHiJ0fcL+NRcIqsocZQUSmbzeIKRpwttJjik5ZGanXP+vlA4SbTg+AbA3bP363l+w==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">= 20"
+ }
+ },
"node_modules/@vitejs/plugin-react": {
"version": "4.7.0",
"resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz",
@@ -7190,6 +7314,24 @@
"node": ">= 14"
}
},
+ "node_modules/ai": {
+ "version": "6.0.116",
+ "resolved": "https://registry.npmjs.org/ai/-/ai-6.0.116.tgz",
+ "integrity": "sha512-7yM+cTmyRLeNIXwt4Vj+mrrJgVQ9RMIW5WO0ydoLoYkewIvsMcvUmqS4j2RJTUXaF1HphwmSKUMQ/HypNRGOmA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@ai-sdk/gateway": "3.0.66",
+ "@ai-sdk/provider": "3.0.8",
+ "@ai-sdk/provider-utils": "4.0.19",
+ "@opentelemetry/api": "1.9.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "zod": "^3.25.76 || ^4.1.8"
+ }
+ },
"node_modules/ajv": {
"version": "6.14.0",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz",
@@ -10019,7 +10161,6 @@
"resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.6.tgz",
"integrity": "sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==",
"license": "MIT",
- "peer": true,
"engines": {
"node": ">=18.0.0"
}
@@ -11760,8 +11901,7 @@
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz",
"integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==",
- "license": "(AFL-2.1 OR BSD-3-Clause)",
- "optional": true
+ "license": "(AFL-2.1 OR BSD-3-Clause)"
},
"node_modules/json-schema-ref-resolver": {
"version": "1.0.1",
diff --git a/package.json b/package.json
index 9b8d20615..94d832c74 100644
--- a/package.json
+++ b/package.json
@@ -102,6 +102,10 @@
"vite": "^6.3.5"
},
"dependencies": {
+ "@ai-sdk/anthropic": "^3.0.58",
+ "@ai-sdk/google": "^3.0.43",
+ "@ai-sdk/groq": "^3.0.29",
+ "@ai-sdk/openai": "^3.0.41",
"@neondatabase/auth": "^0.1.0-beta.21",
"@neondatabase/neon-js": "^0.1.0-beta.22",
"@radix-ui/react-accordion": "^1.1.2",
@@ -113,6 +117,7 @@
"@radix-ui/react-slot": "^1.2.3",
"@radix-ui/react-tabs": "^1.1.12",
"@vercel/blob": "^2.3.0",
+ "ai": "^6.0.116",
"better-sqlite3": "^12.4.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
diff --git a/src/components/AgentOverlay.tsx b/src/components/AgentOverlay.tsx
index 0687de051..0c5af4e02 100644
--- a/src/components/AgentOverlay.tsx
+++ b/src/components/AgentOverlay.tsx
@@ -8,7 +8,6 @@ import AudioManager from "../helpers/audioManager";
import ReasoningService from "../services/ReasoningService";
import { getSettings } from "../stores/settingsStore";
import { getAgentSystemPrompt } from "../config/prompts";
-import { run as runAgentLoop } from "../services/AgentLoop";
import { createToolRegistry } from "../services/tools";
type AgentState =
@@ -101,7 +100,7 @@ export default function AgentOverlay() {
const settings = getSettings();
const isCloudAgent = settings.isSignedIn && settings.cloudAgentMode === "openwhispr";
- const toolSupportedProviders = ["openai", "groq", "custom"];
+ const toolSupportedProviders = ["openai", "groq", "custom", "anthropic", "gemini"];
const supportsTools =
!isCloudAgent && toolSupportedProviders.includes(settings.agentProvider);
@@ -129,23 +128,26 @@ export default function AgentOverlay() {
let fullContent = "";
if (supportsTools && registry) {
- await runAgentLoop({
- messages: llmMessages,
- model: settings.agentModel,
- provider: settings.agentProvider,
- systemPrompt,
- tools: registry,
- callbacks: {
- onContentChunk: (text) => {
- fullContent += text;
- setMessages((prev) =>
- prev.map((m) => (m.id === assistantId ? { ...m, content: fullContent } : m))
- );
- },
- onToolStart: (toolName) => {
+ const aiTools = registry.toAISDKFormat();
+ const stream = ReasoningService.processTextStreamingAI(
+ llmMessages,
+ settings.agentModel,
+ settings.agentProvider,
+ { systemPrompt },
+ aiTools
+ );
+
+ for await (const chunk of stream) {
+ if (chunk.type === "content") {
+ fullContent += chunk.text;
+ setMessages((prev) =>
+ prev.map((m) => (m.id === assistantId ? { ...m, content: fullContent } : m))
+ );
+ } else if (chunk.type === "tool_calls") {
+ for (const call of chunk.calls) {
setAgentState("tool-executing");
setToolStatus(
- t(`agentMode.tools.${toolName}Status`, { defaultValue: `Using ${toolName}...` })
+ t(`agentMode.tools.${call.name}Status`, { defaultValue: `Using ${call.name}...` })
);
setMessages((prev) =>
prev.map((m) =>
@@ -155,57 +157,47 @@ export default function AgentOverlay() {
toolCalls: [
...(m.toolCalls || []),
{
- id: crypto.randomUUID(),
- name: toolName,
- arguments: "",
- status: "executing" as const,
+ id: call.id,
+ name: call.name,
+ arguments: call.arguments,
+ status: "completed" as const,
+ result: "Done",
},
],
}
: m
)
);
- },
- onToolComplete: (toolName, result) => {
setAgentState("streaming");
setToolStatus("");
- setMessages((prev) =>
- prev.map((m) =>
- m.id === assistantId
- ? {
- ...m,
- toolCalls: m.toolCalls?.map((tc) =>
- tc.name === toolName && tc.status === "executing"
- ? { ...tc, status: "completed" as const, result: result.displayText }
- : tc
- ),
- }
- : m
- )
- );
- },
- onError: (error) => {
- console.error("Agent loop error:", error);
- },
- },
- maxIterations: 5,
+ }
+ }
+ }
+ } else if (isCloudAgent) {
+ const streamSource = ReasoningService.processTextStreamingCloud(llmMessages, {
+ systemPrompt,
});
- } else {
- const streamSource = isCloudAgent
- ? ReasoningService.processTextStreamingCloud(llmMessages, { systemPrompt })
- : ReasoningService.processTextStreaming(
- llmMessages,
- settings.agentModel,
- settings.agentProvider,
- { systemPrompt }
- );
-
for await (const chunk of streamSource) {
fullContent += chunk;
setMessages((prev) =>
prev.map((m) => (m.id === assistantId ? { ...m, content: fullContent } : m))
);
}
+ } else {
+ const stream = ReasoningService.processTextStreamingAI(
+ llmMessages,
+ settings.agentModel,
+ settings.agentProvider,
+ { systemPrompt }
+ );
+ for await (const chunk of stream) {
+ if (chunk.type === "content") {
+ fullContent += chunk.text;
+ setMessages((prev) =>
+ prev.map((m) => (m.id === assistantId ? { ...m, content: fullContent } : m))
+ );
+ }
+ }
}
setMessages((prev) =>
diff --git a/src/services/AgentLoop.ts b/src/services/AgentLoop.ts
deleted file mode 100644
index 6b6f37ab6..000000000
--- a/src/services/AgentLoop.ts
+++ /dev/null
@@ -1,185 +0,0 @@
-import ReasoningService, { type AgentStreamChunk } from "./ReasoningService";
-import type { ToolRegistry, ToolResult } from "./tools";
-import logger from "../utils/logger";
-
-export interface AgentLoopCallbacks {
- onContentChunk: (text: string) => void;
- onToolStart: (toolName: string, args: Record<string, unknown>) => void;
- onToolComplete: (toolName: string, result: ToolResult) => void;
- onError: (error: Error) => void;
-}
-
-export interface AgentLoopOptions {
- messages: Array<{ role: string; content: string }>;
- model: string;
- provider: string;
- systemPrompt: string;
- tools: ToolRegistry;
- callbacks: AgentLoopCallbacks;
- isCloud?: boolean;
- maxIterations?: number;
-}
-
-interface ToolCallMessage {
- role: "assistant";
- tool_calls: Array<{
- id: string;
- type: "function";
- function: { name: string; arguments: string };
- }>;
-}
-
-interface ToolResultMessage {
- role: "tool";
- tool_call_id: string;
- content: string;
-}
-
-type Message = { role: string; content: string } | ToolCallMessage | ToolResultMessage;
-
-async function executeTool(
- tools: ToolRegistry,
- name: string,
- rawArgs: string,
- callbacks: AgentLoopCallbacks
-): Promise<ToolResult> {
- const tool = tools.get(name);
- if (!tool) {
- const result: ToolResult = {
- success: false,
- data: null,
- displayText: `Unknown tool: ${name}`,
- };
- return result;
- }
-
- let args: Record<string, unknown>;
- try {
- args = JSON.parse(rawArgs);
- } catch {
- const result: ToolResult = {
- success: false,
- data: null,
- displayText: `Invalid arguments for ${name}: failed to parse JSON`,
- };
- return result;
- }
-
- callbacks.onToolStart(name, args);
-
- try {
- const result = await tool.execute(args);
- callbacks.onToolComplete(name, result);
- return result;
- } catch (error) {
- const result: ToolResult = {
- success: false,
- data: null,
- displayText: `Tool ${name} error: ${(error as Error).message}`,
- };
- callbacks.onToolComplete(name, result);
- return result;
- }
-}
-
-export async function run(options: AgentLoopOptions): Promise<void> {
- const {
- messages: initialMessages,
- model,
- provider,
- systemPrompt,
- tools,
- callbacks,
- maxIterations = 5,
- } = options;
-
- const conversationMessages: Message[] = [
- { role: "system", content: systemPrompt },
- ...initialMessages,
- ];
-
- const toolDefs = tools.toOpenAIFormat();
-
- for (let iteration = 0; iteration < maxIterations; iteration++) {
- let pendingToolCalls: Array<{ id: string; name: string; arguments: string }> = [];
-
- try {
- const stream = ReasoningService.processTextStreamingWithTools(
- conversationMessages as Array<{ role: string; content: string }>,
- model,
- provider,
- { systemPrompt },
- toolDefs
- ) as AsyncGenerator<AgentStreamChunk, void, unknown>;
-
- for await (const chunk of stream) {
- if (chunk.type === "content") {
- callbacks.onContentChunk(chunk.text);
- } else if (chunk.type === "tool_calls") {
- pendingToolCalls = chunk.calls;
- } else if (chunk.type === "done") {
- if (pendingToolCalls.length === 0) return;
- }
- }
- } catch (error) {
- callbacks.onError(error as Error);
- return;
- }
-
- if (pendingToolCalls.length === 0) return;
-
- // Append assistant message with tool_calls
- const assistantMessage: ToolCallMessage = {
- role: "assistant",
- tool_calls: pendingToolCalls.map((call) => ({
- id: call.id,
- type: "function",
- function: { name: call.name, arguments: call.arguments },
- })),
- };
- conversationMessages.push(assistantMessage);
-
- // Classify calls: read-only tools run in parallel, write tools run sequentially
- const readOnlyCalls = pendingToolCalls.filter((c) => tools.get(c.name)?.readOnly);
- const writeCalls = pendingToolCalls.filter((c) => !tools.get(c.name)?.readOnly);
-
- const toolResults: ToolResultMessage[] = [];
-
- // Execute read-only tools in parallel
- if (readOnlyCalls.length > 0) {
- const results = await Promise.all(
- readOnlyCalls.map(async (call) => {
- const result = await executeTool(tools, call.name, call.arguments, callbacks);
- return { id: call.id, result };
- })
- );
- for (const { id, result } of results) {
- toolResults.push({
- role: "tool",
- tool_call_id: id,
- content: JSON.stringify({ success: result.success, data: result.data }),
- });
- }
- }
-
- // Execute write tools sequentially
- for (const call of writeCalls) {
- const result = await executeTool(tools, call.name, call.arguments, callbacks);
- toolResults.push({
- role: "tool",
- tool_call_id: call.id,
- content: JSON.stringify({ success: result.success, data: result.data }),
- });
- }
-
- conversationMessages.push(...toolResults);
-
- logger.logReasoning("AGENT_LOOP_ITERATION", {
- iteration: iteration + 1,
- toolCallCount: pendingToolCalls.length,
- toolNames: pendingToolCalls.map((c) => c.name),
- });
- }
-
- logger.warn("Agent loop reached max iterations", { maxIterations }, "agent");
-}
diff --git a/src/services/ReasoningService.ts b/src/services/ReasoningService.ts
index de79c9e88..76625ad85 100644
--- a/src/services/ReasoningService.ts
+++ b/src/services/ReasoningService.ts
@@ -7,20 +7,14 @@ import logger from "../utils/logger";
import { isSecureEndpoint } from "../utils/urlUtils";
import { withSessionRefresh } from "../lib/neonAuth";
import { getSettings, isCloudReasoningMode } from "../stores/settingsStore";
+import { streamText, stepCountIs } from "ai";
+import { getAIModel } from "./ai/providers";
export type AgentStreamChunk =
| { type: "content"; text: string }
| { type: "tool_calls"; calls: Array<{ id: string; name: string; arguments: string }> }
| { type: "done"; finishReason?: string };
-interface ResolvedEndpoint {
- endpoint: string;
- apiKey: string;
- isLocalProvider: boolean;
- apiConfig: ReturnType<typeof getOpenAiApiConfig>;
- useOldTokenParam: boolean;
-}
-
class ReasoningService extends BaseReasoningService {
private apiKeyCache: SecureCache<string>;
private openAiEndpointPreference = new Map<string, "responses" | "chat">();
@@ -263,43 +257,6 @@ class ReasoningService extends BaseReasoningService {
return apiKey;
}
- private async resolveEndpoint(model: string, provider: string): Promise<ResolvedEndpoint> {
- const cloudProviders = ["openai", "groq", "gemini", "anthropic", "custom"];
- const isLocalProvider = !cloudProviders.includes(provider);
-
- let endpoint: string;
- let apiKey = "";
-
- if (isLocalProvider) {
- const serverResult = await window.electronAPI.llamaServerStart(model);
- if (!serverResult.success || !serverResult.port) {
- throw new Error(serverResult.error || "Failed to start local model server");
- }
- endpoint = `http://127.0.0.1:${serverResult.port}/v1/chat/completions`;
- } else {
- const providerKey = provider as "openai" | "groq" | "gemini" | "anthropic" | "custom";
- apiKey = await this.getApiKey(providerKey);
-
- switch (providerKey) {
- case "groq":
- endpoint = buildApiUrl(API_ENDPOINTS.GROQ_BASE, "/chat/completions");
- break;
- case "openai":
- case "custom":
- endpoint = buildApiUrl(this.getConfiguredOpenAIBase(), "/chat/completions");
- break;
- default:
- endpoint = buildApiUrl(API_ENDPOINTS.OPENAI_BASE, "/chat/completions");
- break;
- }
- }
-
- const apiConfig = getOpenAiApiConfig(model);
- const useOldTokenParam = isLocalProvider || provider === "groq";
-
- return { endpoint, apiKey, isLocalProvider, apiConfig, useOldTokenParam };
- }
-
private async callChatCompletionsApi(
endpoint: string,
apiKey: string,
@@ -1312,20 +1269,17 @@ class ReasoningService extends BaseReasoningService {
}
}
- async *processTextStreamingWithTools(
+ async *processTextStreamingAI(
messages: Array<{ role: string; content: string }>,
model: string,
provider: string,
config: ReasoningConfig & { systemPrompt: string },
- tools: Array<{
- type: "function";
- function: { name: string; description: string; parameters: Record<string, unknown> };
- }>
+ tools?: Record<string, import("ai").Tool>
): AsyncGenerator<AgentStreamChunk, void, unknown> {
- const { endpoint, apiKey, isLocalProvider, apiConfig, useOldTokenParam } =
- await this.resolveEndpoint(model, provider);
+ const cloudProviders = ["openai", "groq", "gemini", "anthropic", "custom"];
+ const isLocalProvider = !cloudProviders.includes(provider);
- // Local providers don't support tools — fall back to content-only streaming
+ // Local models don't work with AI SDK — fall back to content-only streaming
if (isLocalProvider) {
const contentGen = this.processTextStreaming(messages, model, provider, config);
for await (const text of contentGen) {
@@ -1335,158 +1289,50 @@ class ReasoningService extends BaseReasoningService {
return;
}
- const maxTokens = config.maxTokens || Math.max(4096, TOKEN_LIMITS.MAX_TOKENS);
-
- const requestBody: Record<string, unknown> = {
- model,
- messages,
- stream: true,
- tools,
- tool_choice: "auto",
- };
+ const providerKey = provider as "openai" | "groq" | "gemini" | "anthropic" | "custom";
+ const apiKey = await this.getApiKey(providerKey);
+ const baseURL = provider === "custom" ? this.getConfiguredOpenAIBase() : undefined;
+ const apiConfig = getOpenAiApiConfig(model);
- if (useOldTokenParam) {
- requestBody.temperature = config.temperature ?? 0.3;
- requestBody.max_tokens = maxTokens;
- } else {
- requestBody[apiConfig.tokenParam] = maxTokens;
- if (apiConfig.supportsTemperature) {
- requestBody.temperature = config.temperature ?? 0.3;
- }
- }
+ const aiModel = getAIModel(provider, model, apiKey, baseURL);
- logger.logReasoning("AGENT_TOOL_STREAM_REQUEST", {
- endpoint,
+ logger.logReasoning("AGENT_AI_SDK_STREAM_REQUEST", {
model,
provider,
- toolCount: tools.length,
+ hasTools: !!tools,
+ toolCount: tools ? Object.keys(tools).length : 0,
messageCount: messages.length,
});
- const headers: Record<string, string> = {
- "Content-Type": "application/json",
- };
- if (apiKey) {
- headers["Authorization"] = `Bearer ${apiKey}`;
- }
-
- const response = await fetch(endpoint, {
- method: "POST",
- headers,
- body: JSON.stringify(requestBody),
+ const result = streamText({
+ model: aiModel,
+ messages: messages.map((m) => ({
+ role: m.role as "system" | "user" | "assistant",
+ content: m.content,
+ })),
+ tools: tools || undefined,
+ stopWhen: stepCountIs(tools ? 5 : 1),
+ ...(apiConfig.supportsTemperature ? { temperature: config.temperature ?? 0.3 } : {}),
+ maxOutputTokens: config.maxTokens || 4096,
});
- if (!response.ok) {
- const errorText = await response.text();
- let errorMessage: string;
- try {
- const errorData = JSON.parse(errorText);
- errorMessage =
- errorData.error?.message ||
- errorData.message ||
- errorData.error ||
- `API error: ${response.status}`;
- } catch {
- errorMessage = errorText || `API error: ${response.status}`;
- }
- logger.logReasoning("AGENT_TOOL_STREAM_ERROR", { status: response.status, errorMessage });
- throw new Error(errorMessage);
- }
-
- const reader = response.body?.getReader();
- if (!reader) throw new Error("No response body");
-
- const decoder = new TextDecoder();
- let buffer = "";
- // Accumulate tool calls by index — OpenAI streams arguments incrementally
- const toolCallAccumulator = new Map<number, { id: string; name: string; arguments: string }>();
-
- try {
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
-
- buffer += decoder.decode(value, { stream: true });
- const lines = buffer.split("\n");
- buffer = lines.pop() || "";
-
- for (const line of lines) {
- const trimmed = line.trim();
- if (!trimmed || !trimmed.startsWith("data: ")) continue;
-
- const data = trimmed.slice(6);
- if (data === "[DONE]") {
- // Flush any remaining accumulated tool calls
- if (toolCallAccumulator.size > 0) {
- const sortedCalls = Array.from(toolCallAccumulator.entries())
- .sort(([a], [b]) => a - b)
- .map(([, call]) => call);
- yield { type: "tool_calls", calls: sortedCalls };
- toolCallAccumulator.clear();
- }
- yield { type: "done" };
- return;
- }
-
- try {
- const parsed = JSON.parse(data);
- const choice = parsed.choices?.[0];
- if (!choice) continue;
-
- const delta = choice.delta;
- const finishReason = choice.finish_reason;
-
- // Accumulate text content
- if (delta?.content) {
- yield { type: "content", text: delta.content };
- }
-
- // Accumulate tool call deltas
- if (delta?.tool_calls) {
- for (const toolCallDelta of delta.tool_calls) {
- const idx = toolCallDelta.index;
- const existing = toolCallAccumulator.get(idx);
-
- if (existing) {
- // Append incremental argument fragments
- if (toolCallDelta.function?.arguments) {
- existing.arguments += toolCallDelta.function.arguments;
- }
- } else {
- // First chunk for this tool call — initialize
- toolCallAccumulator.set(idx, {
- id: toolCallDelta.id || "",
- name: toolCallDelta.function?.name || "",
- arguments: toolCallDelta.function?.arguments || "",
- });
- }
- }
- }
-
- // When finish_reason arrives, yield accumulated state
- if (finishReason === "tool_calls") {
- if (toolCallAccumulator.size > 0) {
- const sortedCalls = Array.from(toolCallAccumulator.entries())
- .sort(([a], [b]) => a - b)
- .map(([, call]) => call);
- yield { type: "tool_calls", calls: sortedCalls };
- toolCallAccumulator.clear();
- }
- yield { type: "done", finishReason: "tool_calls" };
- return;
- }
-
- if (finishReason === "stop") {
- yield { type: "done", finishReason: "stop" };
- return;
- }
- } catch {
- // skip malformed SSE chunks
- }
- }
+ for await (const chunk of result.fullStream) {
+ if (chunk.type === "text-delta") {
+ yield { type: "content", text: chunk.text };
+ } else if (chunk.type === "tool-call") {
+ yield {
+ type: "tool_calls",
+ calls: [
+ {
+ id: chunk.toolCallId,
+ name: chunk.toolName,
+ arguments: JSON.stringify(chunk.input),
+ },
+ ],
+ };
+ } else if (chunk.type === "finish") {
+ yield { type: "done", finishReason: chunk.finishReason };
}
- } finally {
- reader.releaseLock();
}
}
diff --git a/src/services/ai/providers.ts b/src/services/ai/providers.ts
new file mode 100644
index 000000000..b760cf958
--- /dev/null
+++ b/src/services/ai/providers.ts
@@ -0,0 +1,27 @@
+import { createOpenAI } from "@ai-sdk/openai";
+import { createGroq } from "@ai-sdk/groq";
+import { createAnthropic } from "@ai-sdk/anthropic";
+import { createGoogleGenerativeAI } from "@ai-sdk/google";
+import type { LanguageModel } from "ai";
+
+export function getAIModel(
+ provider: string,
+ model: string,
+ apiKey: string,
+ baseURL?: string
+): LanguageModel {
+ switch (provider) {
+ case "openai":
+ return createOpenAI({ apiKey })(model);
+ case "groq":
+ return createGroq({ apiKey })(model);
+ case "anthropic":
+ return createAnthropic({ apiKey })(model);
+ case "gemini":
+ return createGoogleGenerativeAI({ apiKey })(model);
+ case "custom":
+ return createOpenAI({ apiKey, baseURL })(model);
+ default:
+ throw new Error(`Unsupported AI SDK provider: ${provider}`);
+ }
+}
diff --git a/src/services/tools/ToolRegistry.ts b/src/services/tools/ToolRegistry.ts
index 80f8a0039..7f6c2e612 100644
--- a/src/services/tools/ToolRegistry.ts
+++ b/src/services/tools/ToolRegistry.ts
@@ -1,3 +1,6 @@
+import { jsonSchema } from "ai";
+import type { Tool } from "ai";
+
export interface ToolResult {
success: boolean;
data: unknown;
@@ -12,16 +15,6 @@ export interface ToolDefinition {
execute: (args: Record<string, unknown>) => Promise<ToolResult>;
}
-interface OpenAIFunctionTool {
- type: "function";
- function: {
- name: string;
- description: string;
- parameters: Record<string, unknown>;
- strict: true;
- };
-}
-
export class ToolRegistry {
private tools = new Map<string, ToolDefinition>();
@@ -37,15 +30,18 @@ export class ToolRegistry {
return Array.from(this.tools.values());
}
- toOpenAIFormat(): OpenAIFunctionTool[] {
- return this.getAll().map((tool) => ({
- type: "function",
- function: {
- name: tool.name,
- description: tool.description,
- parameters: tool.parameters,
- strict: true,
- },
- }));
+ toAISDKFormat(): Record<string, Tool> {
+ const result: Record<string, Tool> = {};
+ for (const def of this.getAll()) {
+ result[def.name] = {
+ description: def.description,
+ inputSchema: jsonSchema(def.parameters),
+ execute: async (args: unknown) => {
+ const toolResult = await def.execute(args as Record<string, unknown>);
+ return toolResult.data;
+ },
+ } as Tool;
+ }
+ return result;
}
}