All articles
13 min read
#LLM#Function Calling#OpenAI#Production

Six Function-Calling Patterns I Evaluate

I examine six tool-interface patterns with illustrative code: schemas, typed results, concurrency, loop limits, routing, and tool choice.

On this page

Update, 29 October 2026. I revised the title, production-use claims, and schema example. The update section records the scope.

Why this matters

I use the six patterns below to make tool inputs, results, retries, and routing explicit. The examples are illustrative code, not measurements from a production deployment. I focus on failure cases I can test: invalid arguments, ambiguous errors, unnecessary sequential work, repeated calls, and routing based on unstructured text.

I would evaluate these choices against the actual tools and workloads before adopting them. Independent calls, retryable reads, and external writes need different execution policies.

1. Schema-first tool contracts

I distinguish inferred argument types from explicit domain constraints. LangChain’s @tool can infer a schema from type hints; it does not automatically know that a search limit must be between 1 and 20. I add those constraints explicitly. The LangChain tool documentation describes both inferred schemas and custom Pydantic argument models.

I configure the executor to validate tool inputs against a Pydantic schema before execution. I can apply the same ordering with a JSON Schema on the provider tool definition or a provider “strict” / structured-outputs mode that rejects non-conforming arguments at the API boundary. The schema also documents the tool: it is what the model reads when it decides how to call it. Framework APIs change (args_schema=…, type-annotation inference, OpenAI-compatible parameters objects); the invariant does not.

# Inferred argument types, without domain-specific bounds
@tool
def search_documents(query: str, max_results: int = 5):
    # Type validation does not impose a 1..20 search limit
    return document_store.search(query, limit=max_results)

# Pattern: explicit schema with field constraints and descriptions
class SearchInput(BaseModel):
    query: str = Field(description="Search terms for semantic retrieval. No boolean operators.")
    max_results: int = Field(default=5, ge=1, le=20, description="Number of documents to return.")
    date_filter: str | None = Field(default=None, description="ISO 8601 date prefix, e.g. '2024-03'.")

@tool(args_schema=SearchInput)  # or the current framework equivalent
def search_documents(query: str, max_results: int, date_filter: str | None = None):
    results = document_store.search(query, limit=max_results)
    if date_filter:
        results = [r for r in results if r.date.startswith(date_filter)]
    return results

I use the schema for validation and field documentation. Type coercion depends on the validator and its mode: Pydantic can convert "5" to 5 in lax mode, while strict integer validation rejects that string. I choose and test that behavior explicitly; Pydantic’s strict-mode documentation describes the distinction. I keep authorization and other business checks in application code even when a provider enforces argument shape.

I write field descriptions as part of the tool interface: meaning, format, constraints, and defaults. When a tool call is malformed, I inspect the schema, descriptions, and validation errors before deciding whether the model or prompt needs changing.

2. Typed error unions, not exception traces

When a tool fails, I prefer an explicit result status to a traceback as the recovery interface. A traceback may expose internal details and leaves the caller to infer whether retry is permitted.

I keep diagnostic exceptions in protected logs and return bounded, documented error categories to the workflow. The executor owns retry limits and backoff; a model suggestion must not bypass those limits.

# Anti-pattern: exception trace as error recovery context
try:
    result = search_documents(query=query, max_results=max_results)
    return result
except Exception as e:
    return f"Error: {traceback.format_exc()}"  # 20 lines of internal stack trace

# Pattern: shared typed result model and a search-specific result model
class ToolResult(BaseModel):
    status: Literal[
        "ok", "empty", "rate_limited", "auth_error", "execution_error", "loop_detected"
    ]
    error_detail: str | None = None
    message: str | None = None

class SearchResult(ToolResult):
    documents: list[Document] = Field(default_factory=list)
    retry_after_s: int | None = None  # set when status == "rate_limited"

def search_documents(query: str, max_results: int) -> SearchResult:
    try:
        docs = document_store.search(query, limit=max_results)
        if not docs:
            return SearchResult(status="empty")
        return SearchResult(status="ok", documents=docs)
    except RateLimitError as e:
        return SearchResult(status="rate_limited", retry_after_s=e.retry_after)
    except AuthError:
        return SearchResult(status="auth_error", error_detail="API key invalid or expired.")

I use status: rate_limited and retry_after_s: 30 as explicit recovery signals. This is a deliberate interface design: the caller can evaluate documented fields rather than infer recovery behavior from traceback text. The union type also makes the tool contract explicit: these are the known failure modes, and this is what each one means for the caller.

I include retry_after_s for rate limits. The agent loop can use this signal to request backoff or escalation, while the executor enforces both policies. Without it, an agent loop may retry immediately and amplify rate-limit problems.

3. Parallel dispatch and why sequential is the default anti-pattern

A sequential dispatcher calls tool A, waits for the result, then decides whether to call tool B. This is correct when the second call depends on the first. For independent tools, I treat sequential dispatch as a design choice that may add avoidable waiting time.

Some tool-calling APIs support multiple tool calls in a single response turn when the model determines that the work is independent. Where an API emits multiple independent calls, I configure the executor to preserve that concurrency when the tool contracts permit it. If I serialise those calls one by one, I choose sequential execution instead. When there is no dependency between calls, I can route them to concurrent execution.

import asyncio

# Anti-pattern: sequential dispatch
async def run_tools_sequential(tool_calls: list[ToolCall]) -> list[ToolResult]:
    results = []
    for call in tool_calls:
        result = await execute_tool(call)  # wait for each before starting next
        results.append(result)
    return results

# Pattern: concurrent dispatch
async def run_tools_parallel(tool_calls: list[ToolCall]) -> list[ToolResult]:
    tasks = [execute_tool(call) for call in tool_calls]
    results = await asyncio.gather(*tasks, return_exceptions=True)
    return [
        ToolResult(status="execution_error", error_detail=str(r)) if isinstance(r, Exception) else r
        for r in results
    ]

The concrete gain depends on tool latency, executor overhead, scheduling overhead, network overhead, and whether the calls are truly independent. If three independent calls each took 300ms, they would take about 900ms sequentially; this is an illustrative calculation, not an observed measurement. If tool latency dominates and the executor can run them concurrently, parallel dispatch can reduce wall-clock time toward the duration of the slowest call, plus overhead. Across an agent loop with multiple independent tool steps, this can reduce wall-clock time under the same conditions.

Two caveats matter. First, asyncio.gather with return_exceptions=True is important: one failing tool should not crash the entire gather. I handle exceptions per result with the execution_error status declared in the shared result model. Second, not all tool calls are independent. If call B depends on the result of call A, sequential execution is correct. The LLM may represent this by placing dependent calls in separate turns. If I see sequential calls in the same turn for tools that should be independent, I inspect the tool descriptions first. They may not be clear enough about what each tool returns.

4. Loop detection via call fingerprinting

I treat repeated identical tool calls as a case to bound and test. A model can repeat a call without resolving the task, so I apply explicit call and token limits rather than relying on it to stop.

I check a fingerprint before each tool dispatch:

from hashlib import sha256
import json

class LoopDetector:
    def __init__(self, max_repeats: int = 2):
        self.call_counts: dict[str, int] = {}
        self.max_repeats = max_repeats

    def is_looping(self, tool_name: str, args: dict) -> bool:
        key = sha256(
            json.dumps({"tool": tool_name, "args": args}, sort_keys=True).encode()
        ).hexdigest()[:16]
        self.call_counts[key] = self.call_counts.get(key, 0) + 1
        return self.call_counts[key] > self.max_repeats

# In the executor:
detector = LoopDetector(max_repeats=2)
for call in tool_calls:
    if detector.is_looping(call.name, call.arguments):
        return ToolResult(
            status="loop_detected",
            message=f"Tool '{call.name}' called with identical arguments {detector.max_repeats + 1} times."
        )
    result = await execute_tool(call)

When the executor returns status: loop_detected, I route the graph's conditional edge to an escalation node, usually a supervisor agent or a HITL interrupt. I do not send it back to the tool-calling agent. The model receives a clear, structured signal that it needs a different strategy.

I fingerprint the tool name and normalized arguments. Identical arguments give the same fingerprint; a changed query gives a different one. The example threshold of two repeats is an illustrative policy, not a measured indication that a third call is wrong. I would scope and reset the counter per run, bound total calls independently, and handle permitted retries according to the tool’s idempotency contract.

5. Status-based routing between tool calls

Once I have typed error unions, I can route the graph based on status instead of parsing tool content. This follows the same principle as LangGraph conditional edges: routing logic lives in state, not in edge functions.

After each tool result, a lightweight router node reads result.status and writes a routing signal to state. The conditional edge reads that signal. The routing map is direct: rate_limited → wait and retry; auth_error → escalate to HITL; empty → try an alternate tool; ok → continue. I design this arrangement so that routing behavior can be tested and inspected in state traces.

I avoid parsing tool content inside the edge function. In this design, output phrasing can change with model versions or system prompts, while a typed status remains the declared routing input. For example, a routing decision based on whether output contains the word Error depends on output wording. A routing decision based on status: Literal["ok", "rate_limited", "auth_error", "empty"] evaluates a documented field instead.

One concrete consequence is that I can write unit tests for routing logic without mocking the LLM. I can create a SearchResult(status="rate_limited", retry_after_s=30), pass it through the router, and assert that the next node is "wait_and_retry". That test is deterministic and covers the failure mode I care about.

6. Tool choice and prompt hygiene

One sign that tool definitions need work is that I am forcing a named tool via tool_choice (OpenAI-style {"type": "function", "function": {"name": "…"}}, or the provider's equivalent of “required” / named selection). Forced tool choice is a valid escape hatch. As a default pattern, I treat it as a design signal to inspect.

When I force tool choice, I may be compensating for a prompt or schema that does not make tool selection clear enough for the model. I prefer to clarify the tool descriptions and system prompt until tool_choice="auto" (or the provider default) routes correctly on the actual query distribution. I use this as a design goal to keep inference-time control logic narrow and reduce dependence on one query shape.

There is one exception. For the final step of a structured output pipeline, where I want the model to always call a "finalize" tool — or emit a fixed JSON schema via structured outputs / strict mode — forcing the channel is correct. It is a structural constraint, not compensation for unclear descriptions.

For tool-heavy agents, I keep the system prompt focused on the agent's role and scope. I avoid putting tool-selection logic there. If I find myself writing “use the search tool when the user asks about documents” in the system prompt, I treat that as a sign that the tool description does not state it clearly enough. I fix the tool description.

The category frame

Six patterns share one principle: I make the interface between the LLM and the tool layer explicit, typed, and inspectable. I use schema contracts instead of raw dicts. I use typed error unions instead of exception traces. I use concurrent dispatch instead of sequential dispatch when calls are independent and tool latency dominates. I use loop detection instead of assuming the model will self-correct. I use status signals instead of content parsing in routing logic. I use clear tool descriptions and prompt hygiene instead of relying on forced tool choice by default.

I use these patterns as design questions for evaluation cases: which inputs are rejected, which failures can be retried, and which transitions require escalation? The examples do not establish latency improvements or production reliability.

When I build or review a tool-use agent and find reliability or latency issues, I look for these failure modes and apply the corresponding fixes.

Update — October 2026

I revised the title to match the six sections and removed unsupported production-use claims. I also corrected the schema example: inferred type validation and explicit field constraints are different capabilities. The snippets illustrate the design; they are not a complete application or a production benchmark.

The validation discussion now states the Pydantic lax/strict distinction in the main text. I would test the chosen mode and authorization checks at the application boundary.

FAQ

How should I validate LLM tool arguments before execution?

I use a Pydantic schema for every tool and pass it as the tool argument schema. I configure the executor to validate tool inputs against a Pydantic schema before execution. The schema documents each field for the model and, in Pydantic's default lax mode, can coerce values such as converting max_results: "5" into 5.

Why avoid returning Python tracebacks to the model?

I avoid tracebacks because they are unstructured, verbose, and full of internal names the model may not interpret correctly. They also inflate the context window on retries. A typed error union gives the model explicit statuses such as rate_limited, auth_error, empty, ok, and loop_detected.

When should tool calls run in parallel instead of sequentially?

I dispatch tool calls concurrently when they are independent and there is no dependency between them. Sequential execution is correct when call B depends on call A. Independent calls in the same turn can be gathered concurrently and handled per result when the executor supports it and tool latency dominates.

How can I detect an infinite LLM tool loop?

I fingerprint each call from the tool name and JSON-normalized, sorted arguments before dispatch. If the same fingerprint appears more than the configured repeat limit, the executor returns status: loop_detected and routes to escalation instead of sending the agent back into the same loop.

How should routing work after a tool result?

I route from structured status values, not by parsing tool content. A router reads result.status and writes a routing signal to state, so cases such as rate_limited, auth_error, empty, and ok can map to clear next steps that I can inspect in state traces and cover with unit tests.

Share this article

Related articles

  • How I Design Source Checks for Autonomous Research Agents

    I describe a planner-executor-critic workflow for checking source support. Examples define routing and retained evidence, without measured detection accuracy.

    Nov 15, 202410 min read
    #AI Agents#Research#LLM#Production
  • How I Diagnose RAG Retrieval: Chunking, Ranking, and Embeddings

    I diagnose RAG retrieval with a fixed query set, inspect document boundaries, and test ranking and embedding changes against quality, latency, and cost.

    Dec 20, 202412 min read
    #RAG#Retrieval#LLM#Production
  • I Record Tokens Even When an Answer Is Refused

    When the runtime refuses an answer, I still charge the tokens of the produce call the provider already billed. Ledger accuracy, mklang 1.3.7 / pull 111.

    Oct 4, 20268 min read
    #mklang#LLM#Cost#Agents#Production