|
| 1 | +import type { DatabaseChatTool } from "./tools"; |
| 2 | + |
| 3 | +export type ToolExecutionContext = { |
| 4 | + runQuery: (handler: any, args: Record<string, unknown>) => Promise<unknown>; |
| 5 | + runMutation: (handler: any, args: Record<string, unknown>) => Promise<unknown>; |
| 6 | + runAction: (handler: any, args: Record<string, unknown>) => Promise<unknown>; |
| 7 | +}; |
| 8 | + |
| 9 | +export function mergeToolArgs( |
| 10 | + parsedArgs: Record<string, unknown>, |
| 11 | + toolContext?: Record<string, unknown> |
| 12 | +): Record<string, unknown> { |
| 13 | + if (!toolContext || Object.keys(toolContext).length === 0) { |
| 14 | + return { ...parsedArgs }; |
| 15 | + } |
| 16 | + return { ...parsedArgs, ...toolContext }; |
| 17 | +} |
| 18 | + |
| 19 | +export async function executeToolWithContext( |
| 20 | + ctx: ToolExecutionContext, |
| 21 | + tool: DatabaseChatTool, |
| 22 | + parsedArgs: Record<string, unknown>, |
| 23 | + toolContext?: Record<string, unknown> |
| 24 | +): Promise<{ result: unknown; args: Record<string, unknown> }> { |
| 25 | + const mergedArgs = mergeToolArgs(parsedArgs, toolContext); |
| 26 | + const result = await executeToolHandler(ctx, tool, mergedArgs); |
| 27 | + return { result, args: mergedArgs }; |
| 28 | +} |
| 29 | + |
| 30 | +async function executeToolHandler( |
| 31 | + ctx: ToolExecutionContext, |
| 32 | + tool: DatabaseChatTool, |
| 33 | + args: Record<string, unknown> |
| 34 | +) { |
| 35 | + const handlerType = tool.handlerType ?? "query"; |
| 36 | + switch (handlerType) { |
| 37 | + case "mutation": |
| 38 | + return await ctx.runMutation(tool.handler as any, args); |
| 39 | + case "action": |
| 40 | + return await ctx.runAction(tool.handler as any, args); |
| 41 | + case "query": |
| 42 | + default: |
| 43 | + return await ctx.runQuery(tool.handler as any, args); |
| 44 | + } |
| 45 | +} |
0 commit comments