File size: 8,114 Bytes
63eaa16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import {
  ToolDefinition,
  ToolCall,
  ToolChoice,
  ChatCompletionMessage,
  FunctionDefinition,
} from "./types";

export class ToolService {
  /**
   * Generates a system prompt that instructs the AI how to use the provided tools
   */
  generateToolSystemPrompt(
    tools: ToolDefinition[],
    toolChoice: ToolChoice = "auto"
  ): string {
    const toolDescriptions = tools
      .map((tool) => {
        const func = tool.function;
        let description = `${func.name}`;

        if (func.description) {
          description += `: ${func.description}`;
        }

        if (func.parameters) {
          const params = func.parameters.properties || {};
          const required = func.parameters.required || [];

          const paramDescriptions = Object.entries(params)
            .map(([name, schema]: [string, any]) => {
              const isRequired = required.includes(name);
              const type = schema.type || "any";
              const desc = schema.description || "";
              return `  - ${name} (${type}${isRequired ? ", required" : ", optional"}): ${desc}`;
            })
            .join("\n");

          if (paramDescriptions) {
            description += `\nParameters:\n${paramDescriptions}`;
          }
        }

        return description;
      })
      .join("\n\n");

    let prompt = `You are an AI assistant with access to the following functions. When you need to call a function, respond with a JSON object in this exact format:

{
  "tool_calls": [
    {
      "id": "call_<unique_id>",
      "type": "function",
      "function": {
        "name": "<function_name>",
        "arguments": "<json_string_of_arguments>"
      }
    }
  ]
}

Available functions:
${toolDescriptions}

Important rules:
1. Only call functions when necessary to answer the user's question
2. Use the exact function names provided
3. Provide arguments as a JSON string
4. Generate unique IDs for each tool call (e.g., call_1, call_2, etc.)
5. If you don't need to call any functions, respond normally without the tool_calls format`;

    if (toolChoice === "required") {
      prompt +=
        "\n6. You MUST call at least one function to answer this request";
    } else if (toolChoice === "none") {
      prompt += "\n6. Do NOT call any functions, respond normally";
    } else if (
      typeof toolChoice === "object" &&
      toolChoice.type === "function"
    ) {
      prompt += `\n6. You MUST call the function "${toolChoice.function.name}"`;
    }

    return prompt;
  }

  /**
   * Detects if a response contains function calls
   */
  detectFunctionCalls(content: string): boolean {
    try {
      const parsed = JSON.parse(content.trim());
      return (
        parsed.tool_calls &&
        Array.isArray(parsed.tool_calls) &&
        parsed.tool_calls.length > 0
      );
    } catch {
      // Try to find tool_calls pattern in the text
      return /["']?tool_calls["']?\s*:\s*\[/.test(content);
    }
  }

  /**
   * Extracts function calls from AI response
   */
  extractFunctionCalls(content: string): ToolCall[] {
    try {
      // First try to parse as complete JSON
      const parsed = JSON.parse(content.trim());
      if (parsed.tool_calls && Array.isArray(parsed.tool_calls)) {
        return parsed.tool_calls.map((call: any, index: number) => ({
          id: call.id || `call_${Date.now()}_${index}`,
          type: "function",
          function: {
            name: call.function.name,
            arguments:
              typeof call.function.arguments === "string"
                ? call.function.arguments
                : JSON.stringify(call.function.arguments),
          },
        }));
      }
    } catch {
      // Try to extract from partial or malformed JSON
      const toolCallsMatch = content.match(
        /["']?tool_calls["']?\s*:\s*\[(.*?)\]/s
      );
      if (toolCallsMatch) {
        try {
          const toolCallsStr = `[${toolCallsMatch[1]}]`;
          const toolCalls = JSON.parse(toolCallsStr);
          return toolCalls.map((call: any, index: number) => ({
            id: call.id || `call_${Date.now()}_${index}`,
            type: "function",
            function: {
              name: call.function.name,
              arguments:
                typeof call.function.arguments === "string"
                  ? call.function.arguments
                  : JSON.stringify(call.function.arguments),
            },
          }));
        } catch {
          // Fallback: try to extract individual function calls
          return this.extractFunctionCallsFromText(content);
        }
      }
    }

    return [];
  }

  /**
   * Fallback method to extract function calls from text
   */
  private extractFunctionCallsFromText(content: string): ToolCall[] {
    const calls: ToolCall[] = [];

    // Look for function call patterns
    const functionPattern =
      /["']?function["']?\s*:\s*\{[^}]*["']?name["']?\s*:\s*["']([^"']+)["'][^}]*["']?arguments["']?\s*:\s*["']([^"']*)["']/g;
    let match;
    let index = 0;

    while ((match = functionPattern.exec(content)) !== null) {
      calls.push({
        id: `call_${Date.now()}_${index}`,
        type: "function",
        function: {
          name: match[1],
          arguments: match[2],
        },
      });
      index++;
    }

    return calls;
  }

  /**
   * Executes a function call (mock implementation - in real use, this would call actual functions)
   */
  async executeFunctionCall(
    toolCall: ToolCall,
    availableFunctions: Record<string, Function>
  ): Promise<string> {
    const functionName = toolCall.function.name;
    const functionToCall = availableFunctions[functionName];

    if (!functionToCall) {
      return JSON.stringify({
        error: `Function '${functionName}' not found`,
        available_functions: Object.keys(availableFunctions),
      });
    }

    try {
      const args = JSON.parse(toolCall.function.arguments);
      const result = await functionToCall(args);
      return typeof result === "string" ? result : JSON.stringify(result);
    } catch (error) {
      return JSON.stringify({
        error: `Error executing function '${functionName}': ${error instanceof Error ? error.message : "Unknown error"}`,
        arguments_received: toolCall.function.arguments,
      });
    }
  }

  /**
   * Creates a tool result message
   */
  createToolResultMessage(
    toolCallId: string,
    result: string
  ): ChatCompletionMessage {
    return {
      role: "tool",
      content: result,
      tool_call_id: toolCallId,
    };
  }

  /**
   * Validates tool definitions
   */
  validateTools(tools: ToolDefinition[]): { valid: boolean; errors: string[] } {
    const errors: string[] = [];

    if (!Array.isArray(tools)) {
      errors.push("Tools must be an array");
      return { valid: false, errors };
    }

    tools.forEach((tool, index) => {
      if (!tool.type || tool.type !== "function") {
        errors.push(`Tool at index ${index}: type must be "function"`);
      }

      if (!tool.function) {
        errors.push(`Tool at index ${index}: function definition is required`);
        return;
      }

      if (!tool.function.name || typeof tool.function.name !== "string") {
        errors.push(
          `Tool at index ${index}: function name is required and must be a string`
        );
      }

      if (tool.function.parameters) {
        if (tool.function.parameters.type !== "object") {
          errors.push(
            `Tool at index ${index}: function parameters type must be "object"`
          );
        }
      }
    });

    return { valid: errors.length === 0, errors };
  }

  /**
   * Checks if the request requires function calling
   */
  shouldUseFunctionCalling(
    tools?: ToolDefinition[],
    toolChoice?: ToolChoice
  ): boolean {
    if (!tools || tools.length === 0) {
      return false;
    }

    if (toolChoice === "none") {
      return false;
    }

    return true;
  }

  /**
   * Generates a unique ID for tool calls
   */
  generateToolCallId(): string {
    return `call_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }
}