How do you prevent an LLM from hallucinating nonexistent function names when given 50+ available tools? | A1Lab@HamzaM to AI & LLMEnglish • 3 days ago

How do you prevent an LLM from hallucinating nonexistent function names when given 50+ available tools?

message-square
0

Overview

When an LLM sees 50+ tools at once, its context gets crowded and similar tool names overlap. The model can easily invent a plausible-sounding function name that is not in your registry.

  • Retrieve a small tool subset per turn (Tool RAG): Only pass the top 5–12 relevant tool schemas for the current user turn instead of all 50+ schemas.
  • Enforce strict allow-list validation and self-correction: Always check requested function names against a registered Set before execution. If a name is missing, return a clear error with valid tool names so the model can recover or answer directly.

Steps

  1. Index tool descriptions and schemas for retrieval: Store each tool’s name, summary, examples, and parameter schema so you can match relevant tools to the user’s intent.
  2. Select only top-k tools per request: Rank tools by relevance to the current prompt/conversation and attach only that small subset to the LLM request.
  3. Validate tool names against a strict allow-list: Reject any requested tool name that does not exist in your registered tool map before running code.
  4. Return actionable feedback on unknown tool calls: Send a structured tool error listing available tools (or close matches) so the model can retry with a real tool or explain what it cannot do.

Example

import type OpenAI from "openai";

export interface RegisteredTool {
  name: string;
  description: string;
  tags: string[];
  definition: OpenAI.Chat.Completions.ChatCompletionTool;
  handler: (args: Record<string, unknown>) => Promise<unknown>;
}

export class SafeToolRegistry {
  private readonly toolsByName = new Map<string, RegisteredTool>();

  register(tool: RegisteredTool): void {
    this.toolsByName.set(tool.name, tool);
  }

  /**
   * Selects a small subset of relevant tools for the turn instead of all 50+ tools.
   */
  selectRelevantTools(query: string, maxTools = 8): OpenAI.Chat.Completions.ChatCompletionTool[] {
    const terms = query
      .toLowerCase()
      .split(/[^a-z0-9_]+/)
      .filter((t) => t.length > 1);

    const scored = Array.from(this.toolsByName.values()).map((tool) => {
      const haystack = `\${tool.name} ${tool.description}${tool.tags.join(" ")}`.toLowerCase();
      let score = 0;
      for (const term of terms) {
        if (tool.name.toLowerCase().includes(term)) score += 3;
        if (tool.tags.some((tag) => tag.toLowerCase().includes(term))) score += 2;
        if (haystack.includes(term)) score += 1;
      }
      return { tool, score };
    });

    scored.sort((a, b) => b.score - a.score || a.tool.name.localeCompare(b.tool.name));
    return scored.slice(0, maxTools).map((entry) => entry.tool.definition);
  }

  /**
   * Executes a tool call only if the function name exists in the allow-list.
   * Returns a safe error payload if the model hallucinates a nonexistent name.
   */
  async executeToolCall(
    toolCallId: string,
    rawName: string,
    rawArgumentsJson: string
  ): Promise<OpenAI.Chat.Completions.ChatCompletionToolMessageParam> {
    const registered = this.toolsByName.get(rawName);

    if (!registered) {
      const availableNames = Array.from(this.toolsByName.keys());
      return {
        role: "tool",
        tool_call_id: toolCallId,
        content: JSON.stringify({
          error: "UNKNOWN_TOOL_NAME",
          requestedTool: rawName,
          message:
            "That tool does not exist. Choose only from availableTools or answer without a tool.",
          availableTools: availableNames,
        }),
      };
    }

    let parsedArgs: Record<string, unknown>;
    try {
      const value = JSON.parse(rawArgumentsJson || "{}");
      if (!value || typeof value !== "object" || Array.isArray(value)) {
        throw new Error("Arguments must be a JSON object.");
      }
      parsedArgs = value as Record<string, unknown>;
    } catch (err) {
      return {
        role: "tool",
        tool_call_id: toolCallId,
        content: JSON.stringify({
          error: "INVALID_TOOL_ARGUMENTS",
          toolName: registered.name,
          message: err instanceof Error ? err.message : "Invalid JSON arguments.",
        }),
      };
    }

    const output = await registered.handler(parsedArgs);
    return {
      role: "tool",
      tool_call_id: toolCallId,
      content: JSON.stringify({
        ok: true,
        toolName: registered.name,
        result: output,
      }),
    };
  }
}

Tips

  • Use clear, non-overlapping tool names and descriptions: Give each tool a distinct action verb and object (like get_invoice_by_id vs. list_invoices), and state boundaries clearly.
  • Keep temperature low for tool selection: Lower temperature reduces random guessing when picking function names.
  • Cap retry loops on unknown tool names: Limit unknown-tool retries per turn (such as max 2 retries) so a confused model cannot loop forever.