All files / src/utils ai-format-generator.ts

94.11% Statements 16/17
83.33% Branches 5/6
100% Functions 2/2
94.11% Lines 16/17

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 5741x                             41x 65x 65x       65x     65x         65x 178x 113x 113x 113x 113x           65x 65x                       41x 1x    
import {
  ACTION_ITEM_END_TAG,
  ACTION_ITEM_START_TAG,
  FIELD_TOOL_NAME,
  SPECIAL_FIELD_TOKEN,
} from '../llm-orchestration/parser/parsing.constants';
 
/**
 * Generates a formatted string for a tool call that the AI model can understand.
 *
 * @param toolCall - An object representing the tool call. Must include a 'tool_name' property.
 *                   The other keys will be treated as arguments.
 * @returns A formatted string representing the tool call.
 * @throws An error if 'tool_name' is missing.
 */
export function generateToolCall(toolCall: Record<string, any>): string {
  const toolName = toolCall[FIELD_TOOL_NAME];
  Iif (!toolName) {
    throw new Error(`The '${FIELD_TOOL_NAME}' property is required.`);
  }
 
  const parts: string[] = [ACTION_ITEM_START_TAG];
 
  // Ensure tool_name is the first field
  parts.push(
    `${SPECIAL_FIELD_TOKEN}${FIELD_TOOL_NAME}${SPECIAL_FIELD_TOKEN} ${toolName}`,
  );
 
  // Add other arguments
  for (const key in toolCall) {
    if (key !== FIELD_TOOL_NAME) {
      const value = toolCall[key];
      const isMultiLine = typeof value === 'string' && value.includes('\n');
      const separator = isMultiLine ? '\n' : ' ';
      parts.push(
        `${SPECIAL_FIELD_TOKEN}${key}${SPECIAL_FIELD_TOKEN}${separator}${value}`,
      );
    }
  }
 
  parts.push(ACTION_ITEM_END_TAG);
  return parts.join('\n');
}
 
/**
 * Generates a JSON-formatted string for a tool call example.
 * Alternative to generateToolCall() which uses XML-style formatting.
 *
 * @param toolCall - An object representing the tool call. Must include a 'tool_name' property.
 *                   The other keys will be treated as arguments.
 * @returns A JSON string representing the tool call, formatted with 2-space indentation.
 * @throws An error if 'tool_name' is missing.
 */
export function generateToolCallJson(toolCall: Record<string, any>): string {
  return JSON.stringify(toolCall, null, 2);
}