Library

Volume 2 · Agentic AI Systems

Notebook
Sign in

Section 28

Tool Use, Function Calling & API Orchestration

894 words · about 4 min

28.1 Tool Use Architecture

    User Query → LLM → Decision: Use tool? ── No → Direct response
                                │
                               Yes
                                │
                        ┌───────▼───────┐
                        │ Select tool &  │
                        │ generate args  │
                        └───────┬───────┘
                                │
                        ┌───────▼───────┐
                        │ Validate args  │ ← type checking, bounds
                        │ + permissions  │ ← RBAC check
                        └───────┬───────┘
                                │
                        ┌───────▼───────┐
                        │ Execute tool   │
                        │ (sandbox)      │
                        └───────┬───────┘
                                │
                        ┌───────▼───────┐
                        │ Validate output│
                        │ + sanitize     │ ← strip sensitive data if needed
                        └───────┬───────┘
                                │
                            Response

28.2 Function Calling Best Practices

  1. Clear descriptions — the LLM decides whether to call a function almost entirely from its description; ambiguous descriptions cause both false triggers and missed calls.
  2. Parameter documentation — include types, constraints (enums, ranges), and examples in the schema.
  3. Structured error handling — functions return structured errors, never crash or return an unstructured stack trace.
  4. Timeout enforcement — every network-backed tool call has an explicit timeout.
  5. Result validation — validate tool output against an expected schema before it re-enters the LLM context.
  6. Idempotency — tools must be safe to retry; use idempotency keys for anything that mutates state.
  7. PHI/PII-aware audit logging — any access to sensitive data is logged regardless of read/write.

28.3 Python Example — Tool Definition and Dispatch

from dataclasses import dataclass
from typing import Any, Callable
import time

@dataclass
class ToolSpec:
    name: str
    description: str
    parameters: dict          # JSON Schema
    handler: Callable[..., Any]
    timeout_s: float = 10.0
    risk_level: str = "low"   # low | medium | high

class ToolRegistry:
    def __init__(self):
        self._tools: dict[str, ToolSpec] = {}

    def register(self, spec: ToolSpec):
        self._tools[spec.name] = spec

    def as_llm_schema(self) -> list[dict]:
        """Return tool definitions in the shape expected by the model API."""
        return [
            {
                "name": t.name,
                "description": t.description,
                "input_schema": t.parameters,
            }
            for t in self._tools.values()
        ]

    def execute(self, name: str, arguments: dict, user_ctx) -> dict:
        spec = self._tools.get(name)
        if spec is None:
            return {"error": f"Unknown tool: {name}"}

        if not user_ctx.is_authorized(spec.risk_level):
            return {"error": "Not authorized for this tool's risk level"}

        start = time.monotonic()
        try:
            result = _run_with_timeout(spec.handler, arguments, spec.timeout_s)
            return {"success": True, "result": result,
                    "duration_ms": (time.monotonic() - start) * 1000}
        except TimeoutError:
            return {"success": False, "error": "tool_timeout"}
        except Exception as exc:                       # never let a tool crash the loop
            return {"success": False, "error": str(exc)}


def lookup_order(order_id: str) -> dict:
    # ... call the real order service ...
    return {"order_id": order_id, "status": "shipped", "carrier": "FedEx"}

registry = ToolRegistry()
registry.register(ToolSpec(
    name="lookup_order",
    description="Look up an order by ID and return its shipping status.",
    parameters={
        "type": "object",
        "properties": {"order_id": {"type": "string"}},
        "required": ["order_id"],
    },
    handler=lookup_order,
    risk_level="low",
))

28.4 API Orchestration Patterns

When an agent must coordinate multiple downstream APIs, treat orchestration as a first-class architectural concern, not an implementation detail:

  • Fan-out / fan-in — call several independent APIs concurrently (e.g., asyncio.gather) and merge results; use per-call timeouts so one slow API doesn’t stall the whole step.
  • Circuit breakers per downstream system — trip after N consecutive failures, fall back to cached data or a deterministic path.
  • Retries with backoff + jitter — only for idempotent operations; never blindly retry a write.
  • Saga/compensation for multi-step writes — if step 3 of a 4-step write sequence fails, run compensating actions for steps 1–2 rather than leaving inconsistent state.

Section 28 — Interview Q&A

Q1: How do you prevent an LLM from hallucinating tool arguments that violate business rules? Layered validation, never trust the model’s raw JSON: (1) JSON Schema validation of types/enums/ranges, (2) business-rule validation (e.g., “you can’t discount an order below cost”), (3) RBAC check against the calling user’s permissions, (4) for high-risk actions, a dry-run/simulation pass before real execution, and (5) structured errors fed back to the model so it can self-correct on the next turn rather than the pipeline crashing.

Q2: How is MCP different from “plain” function calling, and when do you pick one over the other? Function calling is defined per API request — tight coupling between the calling application and the model provider, tools are ephemeral and app-specific. MCP is a standardized, discoverable protocol: any MCP-compliant client can connect to any MCP server, servers advertise their own capabilities, and connections are persistent with their own lifecycle. Use function calling for a single application with under ~10 tools and fast iteration; use MCP when building a platform where multiple applications share tools, when integrating 10+ external systems, or when tool ownership should live with the system owner rather than the AI application team. (Full comparison in Section 45.)

Q3: What’s your strategy for orchestrating five downstream APIs in a single agent step, two of which are known to be flaky? Isolate the flaky APIs behind circuit breakers with short timeouts and cached fallbacks so their failure doesn’t cascade; run the independent calls concurrently rather than serially; make the overall step idempotent so a partial failure can be safely retried; and expose partial results with a degraded: true flag rather than failing the entire step when only the non-critical calls fail.