Перейти к содержанию

Надежность tool use агентов

~9 минут чтения

URL: arXiv, Composio, Zylos Research, Statsig, Temporal, Vellum AI Тип: tool-use / function-calling / agent-reliability / error-handling Дата: Февраль 2026 Сбор: Ralph Research ФАЗА 5


Предварительно: LLM-агенты, MCP vs Function Calling

Зачем это нужно

LLM-агент без инструментов -- это просто чат. Но как только агент начинает вызывать API, читать файлы, писать код -- появляется каскад ошибок. Модель выбирает не тот инструмент (15-40% случаев), извлекает неверные параметры (30-50% на сложных схемах), API падает или таймаутит. Одна ошибка пропагируется через весь pipeline: неверный tool call -> неверные данные -> неверный вывод -> неверное действие. Надежный агент -- это не только умная модель, но и правильный retry, circuit breaker, constrained decoding и fail-safe архитектура.

Part 1: Overview

Executive Summary

Key Insight:

"Error propagation is the central bottleneck to robust agents—a single failure cascades through planning, memory, and action modules." Tool calling accuracy varies significantly: GPT-4o achieves 95%+ schema adherence on simple tools, but drops to 60-70% on complex nested schemas. 2026 focus is on structured outputs, retry patterns, and fail-safe architectures.

2026 Agent Tool Use Landscape:

Challenge Impact Solution
Tool selection errors 15-40% failure rate Better descriptions, few-shot examples
Parameter extraction 30-50% errors on complex schemas Constrained decoding, validation
Execution failures Cascading errors Circuit breakers, retries
Timeout handling Agent hangs Timeouts + graceful degradation

Part 2: Tool Calling Fundamentals

Architecture

graph TD
    SEL["1. Tool Selection<br/>Query + Tools → Выбор инструмента"] -->|"Error: неверный tool"| PAR
    PAR["2. Parameter Extraction<br/>Query + Schema → JSON параметры"] -->|"Error: пропущены/неверные params"| VAL
    VAL["3. Validation<br/>Schema validation, type checking"] -->|"Error: type mismatch"| EXEC
    EXEC["4. Execution<br/>Вызов внешнего API/функции"] -->|"Error: timeout, rate limit"| RESP
    RESP["5. Response Handling<br/>Parse, validate, format для LLM"]

    style SEL fill:#e8eaf6,stroke:#3f51b5
    style PAR fill:#e8eaf6,stroke:#3f51b5
    style VAL fill:#fff3e0,stroke:#ef6c00
    style EXEC fill:#fce4ec,stroke:#c62828
    style RESP fill:#e8f5e9,stroke:#4caf50

Tool Schema Example

{
  "name": "search_documents",
  "description": "Search through document corpus",
  "parameters": {
    "type": "object",
    "properties": {
      "query": {
        "type": "string",
        "description": "Search query string"
      },
      "limit": {
        "type": "integer",
        "description": "Max results to return",
        "default": 10
      },
      "filters": {
        "type": "object",
        "properties": {
          "date_range": {"type": "string"},
          "category": {"type": "string"}
        }
      }
    },
    "required": ["query"]
  }
}

Part 3: Error Sources and Rates

Error Taxonomy

Тип ошибки Error Rate Примеры Причины
1. Selection Errors 15-40% Неверный tool, пропущенный tool, over-selecting Нечеткие описания, похожие инструменты
2. Parameter Errors 30-50% (complex) Пропущены required params, неверные типы, невалидный JSON Сложные nested schemas, неоднозначность
3. Execution Errors 5-20% Rate limits, timeouts, auth failures, 5xx Внешние зависимости, инфраструктура
4. Context Errors 10-25% Недостающий контекст, устаревшая информация, overflow Плохой context management, длинные диалоги

Error Rate by Schema Complexity

Schema Type Error Rate Example
Simple (1-2 params) 5-15% get_weather(city: str)
Medium (3-5 params) 15-30% search(query, filters, limit, offset)
Complex (nested objects) 30-50% Multi-level objects, arrays
Very complex (arrays of objects) 50-70% Nested arrays, conditional schemas

Part 4: Error Handling Patterns

Retry Strategies

Паттерн Формула / Логика Применение
1. Exponential Backoff delay = base × 2^attempt (1s → 2s → 4s → 8s) Rate limits, transient failures
2. Jittered Backoff delay = base × 2^attempt + random(0, jitter) -- предотвращает thundering herd Multi-agent, distributed systems
3. Circuit Breaker States: CLOSED → OPEN → HALF-OPEN → CLOSED. Open = fail fast без вызова tool Предотвращение каскадных сбоев
4. Smart Retry Анализ типа ошибки → решение: retry / re-plan / escalate. Учится на прошлых ошибках Production agents

Retry Decision Matrix

Error Type Retry? Max Attempts Backoff
Rate limit (429) Yes 3 Exponential
Timeout Yes 2 Linear
Auth failure (401) No
Not found (404) No
Server error (5xx) Yes 3 Exponential
Invalid params (400) Re-plan

Part 5: Constrained Decoding

Structured Output Methods

Подход Механизм Error Rate Доступность
1. JSON Mode Вывод гарантированно валидный JSON, но без schema enforcement 5-15% GPT-4, Claude, Gemini
2. Structured Output Вывод соответствует JSON schema, type enforcement при генерации 1-5% GPT-4o, Claude (tools), Gemini
3. Grammar-based Ограничение на уровне токенов, 100% schema compliance by construction 0% Outlines, LMQL, guidance
4. Post-hoc Validation Генерация свободная, затем валидация + регенерация при ошибке (max N попыток) 5-20% Любая модель + Pydantic/Instructor

Framework Comparison

Framework Method Latency Impact Accuracy
OpenAI Structured Output Native +5-10% 95-99%
Instructor Validation + retry +20-50% 99%+
Outlines Grammar-based +10-20% 100%
LMQL Grammar-based +15-25% 100%
Pydantic validation Post-hoc +5-10% 95%+

Part 6: Tool Design Best Practices

Tool Description Guidelines

Aspect Bad Good
Name func1, search search_user_documents
Description "Searches" "Search user's uploaded documents using semantic similarity. Returns top K results with relevance scores."
Parameters Vague types Specific types + examples + constraints

Tool Design Checklist

Naming: формат verb_noun (get_user, create_document). Конкретика: search_recent_emails вместо search. Избегать: do_, process_, handle_ -- слишком размыто.

Descriptions: начинать с глагола действия. Включить: что делает, когда использовать, что возвращает. Добавить edge cases и ограничения.

Parameters: специфичные типы (не "string" для дат). Описание для КАЖДОГО параметра с примерами. Разумные defaults. Четкое разделение required/optional.

Output Schema: явный return type, поля для ошибок, плоская структура (избегать deep nesting).

Error Handling: структурированные ошибки (не exceptions), error code + message + retry hint, идемпотентность.


Part 7: Fail-Safe Architectures

Agent Error Recovery Flow

graph TD
    OBS["1. Observe<br/>Состояние среды"] --> PLAN["2. Plan<br/>Выбор действия"]
    PLAN --> EXEC["3. Execute<br/>Вызов инструмента"]
    EXEC --> LEARN["4. Learn<br/>Обновление памяти"]
    LEARN --> OBS

    PLAN -->|"Ошибка"| FH1["Failure Handler:<br/>Re-plan"]
    EXEC -->|"Ошибка"| FH2["Failure Handler:<br/>Retry"]
    FH1 --> FALL["FALLBACK CHAIN"]
    FH2 --> FALL

    FALL --> F1["1. Retry with backoff"]
    FALL --> F2["2. Alternative tool"]
    FALL --> F3["3. Re-plan"]
    FALL --> F4["4. Ask user"]
    FALL --> F5["5. Graceful degradation"]

    style OBS fill:#e8eaf6,stroke:#3f51b5
    style PLAN fill:#e8eaf6,stroke:#3f51b5
    style EXEC fill:#fff3e0,stroke:#ef6c00
    style LEARN fill:#e8f5e9,stroke:#4caf50
    style FALL fill:#fce4ec,stroke:#c62828
    style FH1 fill:#fce4ec,stroke:#c62828
    style FH2 fill:#fce4ec,stroke:#c62828

Temporal Orchestration Pattern

# Temporal pattern for durable agent execution
@workflow.defn
class ToolCallingWorkflow:
    @workflow.run
    async def run(self, query: str) -> Result:
        max_retries = 3

        for attempt in range(max_retries):
            try:
                # Step 1: Select tool
                tool = await workflow.execute_activity(
                    select_tool,
                    query,
                    start_to_close_timeout=timedelta(seconds=30)
                )

                # Step 2: Extract parameters
                params = await workflow.execute_activity(
                    extract_params,
                    {"query": query, "tool": tool},
                    start_to_close_timeout=timedelta(seconds=30)
                )

                # Step 3: Execute with retry
                result = await workflow.execute_activity(
                    execute_tool,
                    params,
                    start_to_close_timeout=timedelta(seconds=60),
                    retry_policy=RetryPolicy(
                        maximum_attempts=3,
                        backoff_coefficient=2.0
                    )
                )

                return result

            except ApplicationError as e:
                if attempt == max_retries - 1:
                    return self.graceful_degradation(query, e)

Part 8: Model Comparison for Tool Use

Tool Calling Performance

Model Selection Accuracy Parameter Accuracy Complex Schema
GPT-4o 92-95% 90-93% 80-85%
Claude 3.5 Sonnet 90-93% 88-92% 75-82%
Gemini 1.5 Pro 88-92% 85-90% 70-78%
Llama 3.1 70B 80-85% 75-82% 55-65%
Mistral Large 82-87% 78-84% 60-70%

Benchmark Results (CallNavi Dataset)

Model Single-Tool Multi-Tool Cross-Category
GPT-4o 95.2% 87.3% 78.5%
Claude 3.5 93.8% 85.1% 75.2%
Gemini 1.5 91.4% 82.7% 72.8%

Part 9: Monitoring and Observability

Key Metrics

Reliability Metrics:

Метрика Target
Tool selection accuracy > 95%
Parameter extraction success > 90%
End-to-end success rate > 85%
Error recovery rate > 80%

Performance Metrics:

Метрика Target
Tool selection latency < 500ms
Parameter extraction latency < 1s
Total tool call latency < 5s
Retry overhead < 20% от общего времени

Cost Metrics:

Метрика Зачем отслеживать
Tokens per tool call Оптимизация стоимости
API calls per request Обнаружение неэффективностей
Retry cost Должен быть < 10% от общих затрат

Alert Thresholds

Metric Warning Critical
Tool selection accuracy < 90% < 85%
End-to-end success < 85% < 75%
P95 latency > 5s > 10s
Error rate > 10% > 20%
Retry rate > 20% > 35%

Part 10: Interview-Relevant Numbers

Error Rates

Stage Error Rate Top Cause
Tool selection 15-40% Unclear descriptions
Parameter extraction 30-50% Complex schemas
Execution 5-20% External APIs
End-to-end 25-45% Cascading failures

Retry Statistics

Scenario Retry Success Avg Attempts
Rate limit 85-95% 1.5
Timeout 70-80% 1.8
Invalid params 40-60% 2.1 (with re-plan)
Server error 60-75% 2.0

Performance Benchmarks

Metric Simple Tool Complex Tool Multi-Tool Chain
Selection latency 200-400ms 400-800ms 500-1200ms
Parameter extraction 300-600ms 600-1500ms 800-2000ms
Total latency 1-3s 3-8s 5-15s

Cost Impact

Improvement Cost Reduction
Better tool descriptions 15-25% fewer retries
Constrained decoding 20-30% fewer validation errors
Circuit breakers 40-60% fewer cascading failures
Smart retry logic 25-35% faster recovery

Gotchas

Retry 401/404 -- бесконечный цикл

Exponential backoff для rate limit (429) и server error (5xx) -- правильно. Но retry для auth failure (401) или not found (404) -- бессмысленно. 401 = проблема с credentials, нужен re-auth. 404 = ресурс не существует, retry не поможет. 400 (invalid params) -- не retry, а re-plan с другими параметрами.

JSON Mode -- это не Structured Output

JSON Mode гарантирует валидный JSON, но не schema compliance. Модель может вернуть {"foo": "bar"} вместо {"name": "...", "age": 42}. Structured Output (OpenAI) или grammar-based (Outlines) enforce schema при генерации. Разница в error rate: 5-15% vs 0-5%.

Больше инструментов = хуже accuracy

Tool selection accuracy падает с ростом числа инструментов: 5 tools = 92-95%, 20 tools = 80-88%, 50+ tools = 60-75%. Решения: группировка в namespaces, двухшаговый выбор (сначала категория, потом tool), динамическая фильтрация по контексту.


Interview Q&A

Q: Как обеспечить надёжность tool-calling агента в production?

❌ Red flag: "Использовать самую мощную модель и надеяться на лучшее"

✅ Strong answer: "Defense-in-depth: (1) Structured Output для schema compliance -- снижает parameter errors с 30-50% до 1-5%. (2) Retry с exponential backoff для transient failures, circuit breaker для cascading. (3) Smart retry: анализ типа ошибки -- 429 retry, 401 re-auth, 400 re-plan. (4) Fail-safe chain: retry -> alternative tool -> re-plan -> ask user -> graceful degradation. (5) Monitoring: tool selection accuracy > 95%, end-to-end success > 85%, retry cost < 10%."

Q: Что такое circuit breaker для tool calling?

❌ Red flag: "Это просто retry с лимитом попыток"

✅ Strong answer: "Circuit breaker -- state machine с 3 состояниями: CLOSED (нормальная работа), OPEN (fail fast без вызова tool), HALF-OPEN (пробный вызов). После N подряд ошибок переход в OPEN на timeout, потом HALF-OPEN -- один пробный вызов. Успех = CLOSED, ошибка = снова OPEN. Ключевое отличие от retry: circuit breaker предотвращает cascading failures, не делая вызов вообще. Один сломанный tool не должен повалить весь pipeline."

Q: Как улучшить tool selection accuracy?

✅ Strong answer: "Три уровня: (1) Tool design -- чёткие verb_noun имена, детальные описания с примерами когда использовать/не использовать. (2) Schema design -- минимум required params, плоские структуры (не nested), конкретные типы (не string для всего). (3) Few-shot examples в system prompt -- 2-3 примера правильного выбора для ambiguous случаев. Снижает selection errors с 15-40% до 5-10%."


Sources

  1. arXiv — "Think-Augmented Function Calling: Improving LLM Parameter Accuracy" (2601.18282)
  2. Composio — "Tool Calling Explained: The Core of AI Agents" (Jan 2026)
  3. Zylos Research — "AI Agent Error Handling & Recovery" (Jan 2026)
  4. Zylos Research — "LLM Structured Output & Tool Use Patterns 2025"
  5. Statsig — "Tool Calling Optimization: Efficient Agent Actions" (Oct 2025)
  6. Temporal Docs — "Tool Calling Agent" (Dec 2025)
  7. Vellum AI — "Built-In Tool Calling for Complex Agent Workflows" (Sep 2025)
  8. ACM DL — "CallNavi: Challenge and Study on LLM Function Calling" (3756681.3756975)
  9. OpenReview — "Online-Optimized RAG for Tool Use" (Y4xzgpLrWc)
  10. Reddit r/MachineLearning — "Plain English outperforms JSON for LLM tool calling"
  11. Substack — "Fail-Safe Patterns for AI Agent Workflows" (Sep 2025)
  12. mbrenndoerfer.com — "Function Calling and Tool Use: Practical AI Agents" (Aug 2025)