| 86 | } |
| 87 | |
| 88 | export class Pipe { |
| 89 | private request: Request; |
| 90 | private pipe: any; |
| 91 | private tools: Record<string, (...args: any[]) => Promise<any>>; |
| 92 | private maxCalls: number; |
| 93 | private hasTools: boolean; |
| 94 | private prod: boolean; |
| 95 | private baseUrl: string; |
| 96 | private entityApiKey?: string; |
| 97 | |
| 98 | constructor(options: PipeOptions) { |
| 99 | this.prod = options.prod ?? isProd(); |
| 100 | this.baseUrl = getApiUrl(this.prod); |
| 101 | |
| 102 | this.request = new Request({ |
| 103 | apiKey: options.apiKey, |
| 104 | baseUrl: this.baseUrl, |
| 105 | }); |
| 106 | this.pipe = options; |
| 107 | this.entityApiKey = options.apiKey; |
| 108 | |
| 109 | delete this.pipe.prod; |
| 110 | delete this.pipe.apiKey; |
| 111 | |
| 112 | this.tools = this.getToolsFromPipe(this.pipe); |
| 113 | this.maxCalls = options.maxCalls || 100; // TODO: Find a sane default. |
| 114 | this.hasTools = Object.keys(this.tools).length > 0; |
| 115 | } |
| 116 | |
| 117 | private getToolsFromPipe( |
| 118 | pipe: Pipe, |
| 119 | ): Record<string, (...args: any[]) => Promise<any>> { |
| 120 | const tools: Record<string, (...args: any[]) => Promise<any>> = {}; |
| 121 | if (pipe.tools && Array.isArray(pipe.tools)) { |
| 122 | pipe.tools.forEach((tool: Tool) => { |
| 123 | tools[tool.function.name] = tool.run; |
| 124 | }); |
| 125 | } |
| 126 | return tools; |
| 127 | } |
| 128 | |
| 129 | private async runTools(toolCalls: ToolCallResult[]): Promise<Message[]> { |
| 130 | const toolPromises = toolCalls.map(async (toolCall: ToolCallResult) => { |
| 131 | const toolName = toolCall.function.name; |
| 132 | const toolParameters = JSON.parse(toolCall.function.arguments); |
| 133 | const toolFunction = this.tools[toolName]; |
| 134 | |
| 135 | if (!toolFunction) { |
| 136 | throw new Error( |
| 137 | `Tool ${toolName} not found. If this is intentional, please set runTools to false to disable tool execution by default.`, |
| 138 | ); |
| 139 | } |
| 140 | |
| 141 | const toolResponse = await toolFunction(toolParameters); |
| 142 | |
| 143 | return { |
| 144 | tool_call_id: toolCall.id, |
| 145 | role: 'tool' as MessageRole, |
nothing calls this directly
no outgoing calls
no test coverage detected