Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Enable support email tools in LLM fallbacks
Richie McIlroy9e6a769aa817
diff --git a/apps/web/__tests__/unit/messenger-agent.test.ts b/apps/web/__tests__/unit/messenger-agent.test.tsindex 7fdb08f59..396fc00a6 100644--- a/apps/web/__tests__/unit/messenger-agent.test.ts+++ b/apps/web/__tests__/unit/messenger-agent.test.ts@@ -1,7 +1,15 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+type ServerEnvMockValue = {+ ANTHROPIC_API_KEY: string | undefined;+ OPENAI_API_KEY: string | undefined;+ GROQ_API_KEY: string | undefined;+ SUPERMEMORY_API_KEY: string | undefined;+ SUPERMEMORY_KNOWLEDGE_TAG: string | undefined;+};+const serverEnvMock = vi.hoisted(() =>- vi.fn(() => ({+ vi.fn<() => ServerEnvMockValue>(() => ({ANTHROPIC_API_KEY: "anthropic-key",OPENAI_API_KEY: undefined,GROQ_API_KEY: undefined,@@ -36,15 +44,25 @@ const readFetchBody = (call: unknown[]) => {return JSON.parse(init.body) as {model?: string;max_tokens?: number;+ tool_choice?: string;+ parallel_tool_calls?: boolean;tools?: Array<{name?: string;input_schema?: {properties?: Record<string, unknown>;};+ function?: {+ name?: string;+ parameters?: {+ properties?: Record<string, unknown>;+ };+ };}>;messages?: Array<{role?: string;content?: unknown;+ tool_calls?: unknown;+ tool_call_id?: string;}>;};};@@ -52,6 +70,13 @@ const readFetchBody = (call: unknown[]) => {describe("generateMessengerAgentReply", () => {beforeEach(() => {vi.clearAllMocks();+ serverEnvMock.mockReturnValue({+ ANTHROPIC_API_KEY: "anthropic-key",+ OPENAI_API_KEY: undefined,+ GROQ_API_KEY: undefined,+ SUPERMEMORY_API_KEY: undefined,+ SUPERMEMORY_KNOWLEDGE_TAG: undefined,+ });searchSupermemoryMock.mockResolvedValue([]);getGroqClientMock.mockReturnValue(null);});@@ -221,4 +246,304 @@ describe("generateMessengerAgentReply", () => {},]);});++ it("executes the support email tool through OpenAI fallback", async () => {+ serverEnvMock.mockReturnValue({+ ANTHROPIC_API_KEY: undefined,+ OPENAI_API_KEY: "openai-key",+ GROQ_API_KEY: undefined,+ SUPERMEMORY_API_KEY: undefined,+ SUPERMEMORY_KNOWLEDGE_TAG: undefined,+ });+ const toolCalls = [+ {+ id: "call-1",+ type: "function",+ function: {+ name: "send_support_email",+ arguments: JSON.stringify({+ subject: "Upload issue",+ message: "The user cannot upload their recording.",+ email: "[email protected]",+ }),+ },+ },+ ];+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ choices: [+ {+ message: {+ content: null,+ tool_calls: toolCalls,+ },+ },+ ],+ }),+ { status: 200 },+ ),+ )+ .mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ choices: [+ {+ message: {+ content:+ "Done, I sent that to the team from your account email.",+ },+ },+ ],+ }),+ { status: 200 },+ ),+ );+ vi.stubGlobal("fetch", fetchMock);++ const execute = vi.fn().mockResolvedValue({+ status: "sent" as const,+ remainingToday: 1,+ });+ const { generateMessengerAgentReply } = await import(+ "@/lib/messenger/agent"+ );++ const result = await generateMessengerAgentReply({+ userIdentity: "Test User <[email protected]>",+ identityTag: "user:user-123",+ query: "Please send this to support",+ history: [+ {+ role: "user",+ content: "Uploads keep failing. Please send this to support.",+ },+ ],+ supportEmailTool: {+ execute,+ },+ });++ expect(result).toBe(+ "Done, I sent that to the team from your account email.",+ );+ expect(fetchMock).toHaveBeenCalledTimes(2);+ const firstBody = readFetchBody(fetchMock.mock.calls[0] ?? []);+ expect(firstBody.model).toBe("gpt-4o-mini");+ expect(firstBody.max_tokens).toBe(512);+ expect(firstBody.tool_choice).toBe("auto");+ expect(firstBody.parallel_tool_calls).toBe(false);+ expect(firstBody.tools?.[0]?.function?.name).toBe("send_support_email");+ expect(firstBody.tools?.[0]?.function?.parameters?.properties?.email).toBe(+ undefined,+ );+ expect(firstBody.messages?.[0]?.content).toContain("Support email tool");+ expect(firstBody.messages?.[0]?.content).not.toContain(+ "You cannot send support email",+ );+ expect(execute).toHaveBeenCalledWith({+ subject: "Upload issue",+ message: "The user cannot upload their recording.",+ });++ const secondBody = readFetchBody(fetchMock.mock.calls[1] ?? []);+ expect(secondBody.max_tokens).toBe(350);+ expect(secondBody.tools).toBeUndefined();+ expect(secondBody.messages?.at(-2)?.role).toBe("assistant");+ expect(secondBody.messages?.at(-2)?.tool_calls).toEqual(toolCalls);+ expect(secondBody.messages?.at(-1)).toEqual({+ role: "tool",+ tool_call_id: "call-1",+ content:+ "Support email sent to [email protected] from the user's account email. Remaining sends today: 1.",+ });+ });++ it("executes the support email tool through Groq fallback", async () => {+ serverEnvMock.mockReturnValue({+ ANTHROPIC_API_KEY: undefined,+ OPENAI_API_KEY: undefined,+ GROQ_API_KEY: "groq-key",+ SUPERMEMORY_API_KEY: undefined,+ SUPERMEMORY_KNOWLEDGE_TAG: undefined,+ });+ const create = vi+ .fn()+ .mockResolvedValueOnce({+ choices: [+ {+ message: {+ content: null,+ tool_calls: [+ {+ id: "call-1",+ type: "function",+ function: {+ name: "send_support_email",+ arguments: JSON.stringify({+ subject: "Upload issue",+ message: "The user cannot upload their recording.",+ }),+ },+ },+ ],+ },+ },+ ],+ })+ .mockResolvedValueOnce({+ choices: [+ {+ message: {+ content: "Done, I sent that to the team from your account email.",+ },+ },+ ],+ });+ getGroqClientMock.mockReturnValue({+ chat: {+ completions: {+ create,+ },+ },+ });++ const execute = vi.fn().mockResolvedValue({+ status: "sent" as const,+ remainingToday: 1,+ });+ const { generateMessengerAgentReply } = await import(+ "@/lib/messenger/agent"+ );++ const result = await generateMessengerAgentReply({+ userIdentity: "Test User <[email protected]>",+ identityTag: "user:user-123",+ query: "Please send this to support",+ history: [+ {+ role: "user",+ content: "Uploads keep failing. Please send this to support.",+ },+ ],+ supportEmailTool: {+ execute,+ },+ });++ expect(result).toBe(+ "Done, I sent that to the team from your account email.",+ );+ expect(create).toHaveBeenCalledTimes(2);+ expect(create.mock.calls[0]?.[0]).toMatchObject({+ model: "groq-model",+ max_tokens: 512,+ tool_choice: "auto",+ parallel_tool_calls: false,+ tools: [+ {+ type: "function",+ function: {+ name: "send_support_email",+ },+ },+ ],+ });+ expect(create.mock.calls[1]?.[0]).toMatchObject({+ max_tokens: 350,+ messages: expect.arrayContaining([+ {+ role: "tool",+ tool_call_id: "call-1",+ content:+ "Support email sent to [email protected] from the user's account email. Remaining sends today: 1.",+ },+ ]),+ });+ expect(execute).toHaveBeenCalledWith({+ subject: "Upload issue",+ message: "The user cannot upload their recording.",+ });+ });++ it("does not retry another provider after a fallback provider sends support email", async () => {+ serverEnvMock.mockReturnValue({+ ANTHROPIC_API_KEY: undefined,+ OPENAI_API_KEY: "openai-key",+ GROQ_API_KEY: "groq-key",+ SUPERMEMORY_API_KEY: undefined,+ SUPERMEMORY_KNOWLEDGE_TAG: undefined,+ });+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ choices: [+ {+ message: {+ content: null,+ tool_calls: [+ {+ id: "call-1",+ type: "function",+ function: {+ name: "send_support_email",+ arguments: JSON.stringify({+ subject: "Upload issue",+ message: "The user cannot upload their recording.",+ }),+ },+ },+ ],+ },+ },+ ],+ }),+ { status: 200 },+ ),+ )+ .mockResolvedValueOnce(new Response("provider failed", { status: 500 }));+ vi.stubGlobal("fetch", fetchMock);++ const create = vi.fn();+ getGroqClientMock.mockReturnValue({+ chat: {+ completions: {+ create,+ },+ },+ });+ const execute = vi.fn().mockResolvedValue({+ status: "sent" as const,+ remainingToday: 1,+ });+ const { generateMessengerAgentReply } = await import(+ "@/lib/messenger/agent"+ );++ const result = await generateMessengerAgentReply({+ userIdentity: "Test User <[email protected]>",+ identityTag: "user:user-123",+ query: "Please send this to support",+ history: [+ {+ role: "user",+ content: "Uploads keep failing. Please send this to support.",+ },+ ],+ supportEmailTool: {+ execute,+ },+ });++ expect(result).toBe(+ "Done, I sent that to the team from your account email. We'll follow up with you there.",+ );+ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(create).not.toHaveBeenCalled();+ expect(execute).toHaveBeenCalledTimes(1);+ });});diff --git a/apps/web/lib/messenger/agent.ts b/apps/web/lib/messenger/agent.tsindex 61ca34fd4..a40b7d9aa 100644--- a/apps/web/lib/messenger/agent.ts+++ b/apps/web/lib/messenger/agent.ts@@ -2,6 +2,12 @@ import "server-only";import type { MessengerMessageRole } from "@cap/database/schema";import { serverEnv } from "@cap/env";+import type {+ ChatCompletionAssistantMessageParam,+ ChatCompletionMessageParam,+ ChatCompletionMessageToolCall,+ ChatCompletionTool,+} from "groq-sdk/resources/chat";import { GROQ_MODEL, getGroqClient } from "@/lib/groq-client";import { CAP_REFERENCE_GUIDE, MESSENGER_AGENT_PROMPT } from "./constants";import { getKnowledgeTag, searchSupermemory } from "./supermemory";@@ -51,6 +57,11 @@ type AnthropicToolResultBlock = {is_error?: boolean;};+type SupportEmailExecutionResult = {+ content: string;+ isError?: boolean;+};+const MESSENGER_ANTHROPIC_MODEL = "claude-sonnet-5";const MESSENGER_MAX_TOKENS = 350;const MESSENGER_TOOL_DISPATCH_MAX_TOKENS = 512;@@ -85,6 +96,15 @@ const supportEmailToolDefinition = {},} as const;+const openAiCompatibleSupportEmailToolDefinition = {+ type: "function",+ function: {+ name: supportEmailToolDefinition.name,+ description: supportEmailToolDefinition.description,+ parameters: supportEmailToolDefinition.input_schema,+ },+} satisfies ChatCompletionTool;+const buildSystemPrompt = ({userIdentity,context,@@ -202,49 +222,76 @@ const formatSupportEmailToolResult = (result: SupportEmailToolResult) => {return "Support email was not sent because this user has reached the 2 emails per day limit.";};-const executeSupportEmailToolUse = async ({- toolUse,+const fallbackReplyFromSupportEmailToolResults = (+ toolResults: SupportEmailExecutionResult[],+) => {+ const firstToolResult = toolResults[0];+ if (firstToolResult?.content.includes("Support email sent")) {+ return "Done, I sent that to the team from your account email. We'll follow up with you there.";+ }+ if (firstToolResult?.isError) {+ return "I couldn't send that to the team right now. Please email [email protected] directly.";+ }+ return "I couldn't send another support email from your account today. You're limited to 2 per day, but you can still email [email protected] directly.";+};++const executeSupportEmailTool = async ({+ name,+ input,supportEmailTool,}: {- toolUse: AnthropicToolUseBlock;+ name: string;+ input: unknown;supportEmailTool: SupportEmailTool;-}): Promise<AnthropicToolResultBlock> => {- if (toolUse.name !== supportEmailToolDefinition.name) {+}): Promise<SupportEmailExecutionResult> => {+ if (name !== supportEmailToolDefinition.name) {return {- type: "tool_result",- tool_use_id: toolUse.id,content: "Unknown tool.",- is_error: true,+ isError: true,};}- const input = readSupportEmailInput(toolUse.input);- if (!input) {+ const parsedInput = readSupportEmailInput(input);+ if (!parsedInput) {return {- type: "tool_result",- tool_use_id: toolUse.id,content: "Missing subject or message.",- is_error: true,+ isError: true,};}try {- const result = await supportEmailTool.execute(input);+ const result = await supportEmailTool.execute(parsedInput);return {- type: "tool_result",- tool_use_id: toolUse.id,content: formatSupportEmailToolResult(result),};} catch {return {- type: "tool_result",- tool_use_id: toolUse.id,content: "Failed to send support email.",- is_error: true,+ isError: true,};}};+const executeSupportEmailToolUse = async ({+ toolUse,+ supportEmailTool,+}: {+ toolUse: AnthropicToolUseBlock;+ supportEmailTool: SupportEmailTool;+}): Promise<AnthropicToolResultBlock> => {+ const result = await executeSupportEmailTool({+ name: toolUse.name,+ input: toolUse.input,+ supportEmailTool,+ });+ return {+ type: "tool_result",+ tool_use_id: toolUse.id,+ content: result.content,+ ...(result.isError ? { is_error: true } : {}),+ };+};+const postAnthropicMessages = async ({key,systemPrompt,@@ -353,93 +400,256 @@ const callAnthropic = async ({content: toolResults,},],- });+ }).catch(() => null);if (final?.text) return final.text;- const firstToolResult = toolResults[0];- if (firstToolResult?.content.includes("Support email sent")) {- return "Done, I sent that to the team from your account email. We'll follow up with you there.";- }- if (firstToolResult?.is_error) {- return "I couldn't send that to the team right now. Please email [email protected] directly.";- }- return "I couldn't send another support email from your account today. You're limited to 2 per day, but you can still email [email protected] directly.";+ return fallbackReplyFromSupportEmailToolResults(+ toolResults.map((result) => ({+ content: result.content,+ isError: result.is_error,+ })),+ );+};++const parseOpenAiCompatibleToolCalls = (message: { tool_calls?: unknown }) => {+ if (!Array.isArray(message.tool_calls)) return [];++ return message.tool_calls.flatMap(+ (toolCall): ChatCompletionMessageToolCall[] => {+ if (!toolCall || typeof toolCall !== "object") return [];+ const id = (toolCall as { id?: unknown }).id;+ const type = (toolCall as { type?: unknown }).type;+ const fn = (toolCall as { function?: unknown }).function;+ if (typeof id !== "string" || type !== "function") return [];+ if (!fn || typeof fn !== "object") return [];+ const name = (fn as { name?: unknown }).name;+ const args = (fn as { arguments?: unknown }).arguments;+ if (typeof name !== "string" || typeof args !== "string") return [];+ return [+ {+ id,+ type,+ function: {+ name,+ arguments: args,+ },+ },+ ];+ },+ );};-const parseOpenAiContent = (payload: unknown) => {+const parseOpenAiCompatibleMessage = (payload: unknown) => {if (!payload || typeof payload !== "object") return null;const choices = (payload as { choices?: unknown }).choices;if (!Array.isArray(choices) || choices.length === 0) return null;const first = choices[0] as {message?: {content?: unknown;+ tool_calls?: unknown;};};- const content = first.message?.content;- if (typeof content === "string") return content.trim();- return null;+ const message = first.message;+ if (!message) return null;+ const content =+ typeof message.content === "string" ? message.content.trim() : "";+ const toolCalls = parseOpenAiCompatibleToolCalls(message);+ if (!content && toolCalls.length === 0) return null;+ return {+ text: content.length > 0 ? content : null,+ toolCalls,+ };+};++const parseOpenAiToolInput = (args: string) => {+ try {+ return JSON.parse(args) as unknown;+ } catch {+ return null;+ }+};++const executeOpenAiCompatibleToolCalls = async ({+ toolCalls,+ supportEmailTool,+}: {+ toolCalls: ChatCompletionMessageToolCall[];+ supportEmailTool: SupportEmailTool;+}) => {+ const toolResults: Array<+ SupportEmailExecutionResult & { toolCall: ChatCompletionMessageToolCall }+ > = [];+ let sentEmailToolResult = false;++ for (const toolCall of toolCalls) {+ if (sentEmailToolResult) {+ toolResults.push({+ toolCall,+ content: "Only one support email can be sent per assistant response.",+ isError: true,+ });+ continue;+ }++ toolResults.push({+ toolCall,+ ...(await executeSupportEmailTool({+ name: toolCall.function.name,+ input: parseOpenAiToolInput(toolCall.function.arguments),+ supportEmailTool,+ })),+ });+ sentEmailToolResult = true;+ }++ return toolResults;+};++const runOpenAiCompatibleToolLoop = async ({+ systemPrompt,+ history,+ supportEmailTool,+ createCompletion,+}: {+ systemPrompt: string;+ history: ConversationMessage[];+ supportEmailTool: SupportEmailTool | null;+ createCompletion: ({+ messages,+ tools,+ maxTokens,+ }: {+ messages: ChatCompletionMessageParam[];+ tools?: ChatCompletionTool[];+ maxTokens: number;+ }) => Promise<ReturnType<typeof parseOpenAiCompatibleMessage>>;+}) => {+ const messages: ChatCompletionMessageParam[] = [+ { role: "system", content: systemPrompt },+ ...mapHistoryForLlm(history),+ ];++ const initial = await createCompletion({+ messages,+ tools: supportEmailTool+ ? [openAiCompatibleSupportEmailToolDefinition]+ : undefined,+ maxTokens: supportEmailTool+ ? MESSENGER_TOOL_DISPATCH_MAX_TOKENS+ : MESSENGER_MAX_TOKENS,+ });++ if (!initial) return null;+ if (!supportEmailTool || initial.toolCalls.length === 0) {+ return initial.text;+ }++ const toolResults = await executeOpenAiCompatibleToolCalls({+ toolCalls: initial.toolCalls,+ supportEmailTool,+ });+ const assistantMessage: ChatCompletionAssistantMessageParam = {+ role: "assistant",+ content: initial.text,+ tool_calls: initial.toolCalls,+ };+ const final = await createCompletion({+ messages: [+ ...messages,+ assistantMessage,+ ...toolResults.map(+ (result): ChatCompletionMessageParam => ({+ role: "tool",+ tool_call_id: result.toolCall.id,+ content: result.content,+ }),+ ),+ ],+ maxTokens: MESSENGER_MAX_TOKENS,+ }).catch(() => null);++ if (final?.text) return final.text;+ return fallbackReplyFromSupportEmailToolResults(toolResults);};const callOpenAi = async ({systemPrompt,history,+ supportEmailTool,}: {systemPrompt: string;history: ConversationMessage[];+ supportEmailTool: SupportEmailTool | null;}) => {const key = serverEnv().OPENAI_API_KEY;if (!key) return null;- const response = await fetch("https://api.openai.com/v1/chat/completions", {- method: "POST",- headers: {- Authorization: `Bearer ${key}`,- "Content-Type": "application/json",- },- body: JSON.stringify({- model: "gpt-4o-mini",- temperature: 0.65,- max_tokens: MESSENGER_MAX_TOKENS,- messages: [- { role: "system", content: systemPrompt },- ...mapHistoryForLlm(history),- ],- }),- signal: AbortSignal.timeout(35000),- });+ return runOpenAiCompatibleToolLoop({+ systemPrompt,+ history,+ supportEmailTool,+ createCompletion: async ({ messages, tools, maxTokens }) => {+ const response = await fetch(+ "https://api.openai.com/v1/chat/completions",+ {+ method: "POST",+ headers: {+ Authorization: `Bearer ${key}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ model: "gpt-4o-mini",+ temperature: 0.65,+ max_tokens: maxTokens,+ messages,+ tools,+ tool_choice: tools ? "auto" : undefined,+ parallel_tool_calls: tools ? false : undefined,+ }),+ signal: AbortSignal.timeout(35000),+ },+ );- if (!response.ok) {- const text = await response.text();- throw new Error(`OpenAI chat failed: ${response.status} ${text}`);- }+ if (!response.ok) {+ const text = await response.text();+ throw new Error(`OpenAI chat failed: ${response.status} ${text}`);+ }- const payload = await response.json();- return parseOpenAiContent(payload);+ const payload = await response.json();+ return parseOpenAiCompatibleMessage(payload);+ },+ });};const callGroq = async ({systemPrompt,history,+ supportEmailTool,}: {systemPrompt: string;history: ConversationMessage[];+ supportEmailTool: SupportEmailTool | null;}) => {const client = getGroqClient();if (!client) return null;- const completion = await client.chat.completions.create({- model: GROQ_MODEL,- temperature: 0.65,- max_tokens: MESSENGER_MAX_TOKENS,- messages: [- { role: "system", content: systemPrompt },- ...mapHistoryForLlm(history),- ],+ return runOpenAiCompatibleToolLoop({+ systemPrompt,+ history,+ supportEmailTool,+ createCompletion: async ({ messages, tools, maxTokens }) => {+ const completion = await client.chat.completions.create({+ model: GROQ_MODEL,+ temperature: 0.65,+ max_tokens: maxTokens,+ messages,+ tools,+ tool_choice: tools ? "auto" : undefined,+ parallel_tool_calls: tools ? false : undefined,+ });+ return parseOpenAiCompatibleMessage(completion);+ },});-- const content = completion.choices[0]?.message?.content;- if (!content) return null;- return content.trim();};export const generateMessengerAgentReply = async ({@@ -479,23 +689,17 @@ export const generateMessengerAgentReply = async ({}).catch(() => null);if (fromAnthropic) return fromAnthropic;- const fallbackSystemPrompt = supportEmailTool- ? buildSystemPrompt({- userIdentity,- context: normalizeContext([...knowledgeContext, ...personalContext]),- supportEmailAvailable: false,- })- : systemPrompt;-const fromOpenAi = await callOpenAi({- systemPrompt: fallbackSystemPrompt,+ systemPrompt,history,+ supportEmailTool,}).catch(() => null);if (fromOpenAi) return fromOpenAi;const fromGroq = await callGroq({- systemPrompt: fallbackSystemPrompt,+ systemPrompt,history,+ supportEmailTool,}).catch(() => null);if (fromGroq) return fromGroq;