All files / src/tools index.ts

47.16% Statements 75/159
60% Branches 6/10
60% Functions 3/5
47.16% Lines 75/159

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                        1x                                                                                                                           1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x   1x 1x 1x 1x 1x       1x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 2x 2x   2x 4x 4x 4x 4x 4x 4x 2x   2x   2x 2x                                                                                                                                                                 2x                                           2x 3x 3x 2x 2x         1x 5x 5x 5x 5x 5x 5x 5x   5x 5x 5x 5x   5x 5x 5x 5x 5x 5x 5x 5x 5x 5x  
/**
 * AgentKits — Tool Calling Module
 *
 * Unified function/tool calling adapter across providers.
 * Normalizes OpenAI, Gemini, DeepSeek, DashScope tool call formats.
 *
 * Usage:
 *   import { createToolChat } from 'agentkits/tools';
 *   const chat = createToolChat({ provider: 'deepseek', tools: [...] });
 *   const result = await chat.run('What is the weather in Beijing?');
 */
 
import OpenAI from 'openai';
import type { ChatCompletionMessageParam, ChatCompletionTool } from 'openai/resources/chat/completions';
 
// ── Types ──────────────────────────────────────────────────────────
 
export interface ToolDefinition {
  name: string;
  description: string;
  parameters: Record<string, any>; // JSON Schema
}
 
export interface ToolCall {
  id: string;
  name: string;
  arguments: Record<string, any>;
}
 
export interface ToolResult {
  toolCallId: string;
  result: string;
}
 
export interface ToolChatConfig {
  provider?: string;
  model?: string;
  apiKey?: string;
  baseUrl?: string;
  tools: ToolDefinition[];
  /** Function to execute tool calls. Return string result. */
  execute?: (name: string, args: Record<string, any>) => Promise<string>;
  temperature?: number;
  maxTokens?: number;
  /** Max tool call rounds before stopping (default: 5) */
  maxRounds?: number;
}
 
export interface ToolChatResponse {
  content: string;
  toolCalls: ToolCall[];
  toolResults: ToolResult[];
  rounds: number;
  usage?: {
    promptTokens: number;
    completionTokens: number;
    totalTokens: number;
  };
}
 
export interface ToolChatClient {
  /** Run a message with tool calling. Auto-executes tools if execute() is provided. */
  run(prompt: string, options?: { system?: string }): Promise<ToolChatResponse>;
  /** Single step: get tool calls without executing */
  step(messages: Array<{ role: string; content: string }>): Promise<{
    content: string | null;
    toolCalls: ToolCall[];
  }>;
  /** Current resolved tools */
  readonly tools: readonly ToolDefinition[];
}
 
// ── Provider Config (reuse from llm module) ────────────────────────
 
const PROVIDER_URLS: Record<string, string> = {
  openai:    'https://api.openai.com/v1',
  gemini:    'https://generativelanguage.googleapis.com/v1beta/openai/',
  ollama:    'http://localhost:11434/v1',
  dashscope: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
  deepseek:  'https://api.deepseek.com/v1',
  zhipu:     'https://open.bigmodel.cn/api/paas/v4',
  moonshot:  'https://api.moonshot.cn/v1',
  minimax:   'https://api.minimax.chat/v1',
};
 
const PROVIDER_MODELS: Record<string, string> = {
  openai: 'gpt-4o', gemini: 'gemini-2.5-flash', ollama: 'llama3.3',
  dashscope: 'qwen-max', deepseek: 'deepseek-chat', zhipu: 'glm-4-plus',
  moonshot: 'moonshot-v1-auto', minimax: 'MiniMax-Text-01',
};
 
const PROVIDER_KEYS: Record<string, string[]> = {
  openai: ['OPENAI_API_KEY'], gemini: ['GEMINI_API_KEY', 'GOOGLE_API_KEY'],
  ollama: [], dashscope: ['DASHSCOPE_API_KEY'], deepseek: ['DEEPSEEK_API_KEY'],
  zhipu: ['ZHIPU_API_KEY'], moonshot: ['MOONSHOT_API_KEY'], minimax: ['MINIMAX_API_KEY'],
};
 
// ── Factory ────────────────────────────────────────────────────────
 
export function createToolChat(config: ToolChatConfig): ToolChatClient {
  const provider = config.provider ?? 'openai';
  const model = config.model ?? PROVIDER_MODELS[provider] ?? 'gpt-4o';
  const baseUrl = config.baseUrl ?? PROVIDER_URLS[provider];
  const apiKey = config.apiKey
    ?? (PROVIDER_KEYS[provider] ?? []).map(k => process.env[k]).find(Boolean)
    ?? (provider === 'ollama' ? 'ollama' : undefined);
 
  const clientOpts: Record<string, unknown> = {};
  if (apiKey) clientOpts.apiKey = apiKey;
  if (baseUrl) clientOpts.baseURL = baseUrl;
  if (provider !== 'openai') {
    clientOpts.organization = null;
    clientOpts.project = null;
  }
  const client = new OpenAI(clientOpts as any);
 
  const openAITools: ChatCompletionTool[] = config.tools.map(t => ({
    type: 'function' as const,
    function: {
      name: t.name,
      description: t.description,
      parameters: t.parameters,
    },
  }));
 
  const maxRounds = config.maxRounds ?? 5;
 
  return {
    async run(prompt, options = {}) {
      const messages: ChatCompletionMessageParam[] = [];
      if (options.system) messages.push({ role: 'system', content: options.system });
      messages.push({ role: 'user', content: prompt });
 
      const allToolCalls: ToolCall[] = [];
      const allToolResults: ToolResult[] = [];
      let rounds = 0;
      let totalUsage = { promptTokens: 0, completionTokens: 0, totalTokens: 0 };
 
      while (rounds < maxRounds) {
        rounds++;
 
        const response = await client.chat.completions.create({
          model,
          messages,
          tools: openAITools,
          temperature: config.temperature ?? 0.7,
          max_tokens: config.maxTokens ?? 4096,
        });
 
        const choice = response.choices[0];
        if (response.usage) {
          totalUsage.promptTokens += response.usage.prompt_tokens;
          totalUsage.completionTokens += response.usage.completion_tokens;
          totalUsage.totalTokens += response.usage.total_tokens;
        }
 
        // No tool calls — done
        if (!choice.message.tool_calls?.length) {
          return {
            content: choice.message.content ?? '',
            toolCalls: allToolCalls,
            toolResults: allToolResults,
            rounds,
            usage: totalUsage,
          };
        }
 
        // Process tool calls
        messages.push(choice.message as any);
 
        for (const tc of choice.message.tool_calls) {
          const parsed: ToolCall = {
            id: tc.id,
            name: tc.function.name,
            arguments: JSON.parse(tc.function.arguments || '{}'),
          };
          allToolCalls.push(parsed);
 
          if (config.execute) {
            const result = await config.execute(parsed.name, parsed.arguments);
            allToolResults.push({ toolCallId: tc.id, result });
            messages.push({
              role: 'tool',
              tool_call_id: tc.id,
              content: result,
            });
          } else {
            // No executor — return with pending tool calls
            return {
              content: choice.message.content ?? '',
              toolCalls: allToolCalls,
              toolResults: allToolResults,
              rounds,
              usage: totalUsage,
            };
          }
        }
      }
 
      // Max rounds reached
      return {
        content: '[max tool call rounds reached]',
        toolCalls: allToolCalls,
        toolResults: allToolResults,
        rounds,
        usage: totalUsage,
      };
    },
 
    async step(messages) {
      const response = await client.chat.completions.create({
        model,
        messages: messages as ChatCompletionMessageParam[],
        tools: openAITools,
        temperature: config.temperature ?? 0.7,
        max_tokens: config.maxTokens ?? 4096,
      });
 
      const choice = response.choices[0];
      const toolCalls: ToolCall[] = (choice.message.tool_calls ?? []).map(tc => ({
        id: tc.id,
        name: tc.function.name,
        arguments: JSON.parse(tc.function.arguments || '{}'),
      }));
 
      return {
        content: choice.message.content,
        toolCalls,
      };
    },
 
    get tools() {
      return config.tools;
    },
  };
}
 
// ── Helpers ─────────────────────────────────────────────────────────
 
/** Create a ToolDefinition from a simple spec */
export function defineTool(
  name: string,
  description: string,
  parameters: Record<string, { type: string; description: string; required?: boolean }>,
): ToolDefinition {
  const required = Object.entries(parameters)
    .filter(([, v]) => v.required !== false)
    .map(([k]) => k);
 
  const properties: Record<string, any> = {};
  for (const [k, v] of Object.entries(parameters)) {
    properties[k] = { type: v.type, description: v.description };
  }
 
  return {
    name,
    description,
    parameters: {
      type: 'object',
      properties,
      required,
    },
  };
}