Building a Production LLM Agent with Tool Access and State
Machine LearningModel answerLast updated
Design a production system where an LLM agent uses external APIs to complete multi-step tasks, handling state, failures, security, and evaluation.
You're building a production system where an LLM acts as an autonomous agent, calling external APIs and services to accomplish business tasks. The agent might query databases, retrieve documents, create support tickets, send messages, or trigger workflows.
Your system needs to handle:
- Employees using the agent for tasks ranging from quick lookups (seconds) to multi-day workflows with human approvals
- Around 50,000 users with peak load of 200 concurrent tasks
- Each task involves 8–15 API calls on average
- Enterprise requirements: audit logs, access control, data residency, cost control
Address these design areas:
-
Failure modes: What are the primary ways tool-using agents fail in production, and how do you mitigate them?
-
State management: How do you handle complex state across long-running tasks that may pause for hours, branch into alternatives, or need to resume after interruption?
-
Evaluation: How do you measure whether the system is working correctly, both during development and in production?
Provide a system architecture and explain your choices around safety, observability, and reliability.
Hints
Hint 1
Think about what happens when the LLM picks the wrong tool, hallucinates parameters, or loops forever—architectural safeguards beat better prompts
Hint 2
Long-running workflows need durable state outside the LLM context; consider event sourcing and checkpoints so tasks survive restarts
Hint 3
Security is critical: the agent should never have more permissions than the user who invoked it, and all tool outputs should be treated as untrusted
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Building a Production LLM Agent: Model Answer
The interviewer wants to see if you understand that an LLM agent is a distributed system with a nondeterministic orchestrator, not just a chatbot with API access. Strong answers identify concrete failure patterns, architect state and permissions outside the model, and tie evaluation to actual business impact.
1. Core Failure Modes and Mitigations
Production agents fail in predictable ways. Organize your answer by failure category:
Planning failures
- The agent loops on the same action, abandons the goal partway through, or drifts from the original objective over long tasks
- Mitigation: Set step limits (max 25 tool calls per task), maintain an explicit plan with completion markers in durable state, detect loops by tracking tool+argument pairs, include goal reminder in every prompt
Tool execution errors
- Selects wrong tool, invents nonexistent parameters, generates malformed SQL, misinterprets truncated or paginated responses
- Mitigation: Enforce strict JSON schemas on all tool inputs, validate SQL with EXPLAIN before execution, set row limits on queries, explicitly mark when responses are truncated, provide tool selection examples in prompts
Grounding problems
- Generates answers unsupported by retrieved data, uses stale information, confidently invents statistics
- Mitigation: Require citations for factual claims, add a verification step that checks answer against sources, include timestamps on all retrieved data, flag low-confidence outputs
Unintended side effects
- Creates duplicate tickets on retry, sends messages multiple times, partially completes multi-step operations
- Mitigation: Use idempotency tokens for all write operations, implement compensation logic for failed multi-step transactions, require explicit confirmation before irreversible actions
Security vulnerabilities
- Prompt injection through retrieved documents or messages, privilege escalation by calling tools the user shouldn't access, data exfiltration via messaging APIs
- Mitigation: Treat all tool outputs as untrusted input, authenticate tool calls with the requesting user's credentials (not agent credentials), scan outbound messages for sensitive data, enforce least-privilege access
Reliability issues
- API timeouts, rate limit exhaustion, breaking changes in tool schemas, model version drift
- Mitigation: Implement circuit breakers and exponential backoff, set per-tool rate limits, version all tool schemas with compatibility tests, pin model versions and canary new releases
Critical insight: errors compound multiplicatively. If each step succeeds 95% of the time, a 10-step workflow succeeds only 60% of the time. Per-step validation matters more than a smarter model.
2. System Architecture
User Interface Layer
├─ Web/Mobile/Slack clients
└─ API Gateway (auth, rate limiting)
Orchestration Layer (durable workflow engine)
├─ Agent Loop
│ ├─ Context Builder: state → prompt
│ ├─ LLM Planner: generates next actions
│ └─ Verifier: checks outputs for grounding
├─ Policy Engine
│ ├─ Authorization: user permissions check
│ ├─ Risk Assessment: flags high-risk operations
│ └─ Approval Router: human-in-loop when needed
└─ Tool Gateway
├─ Schema Validation
├─ Credential Management (on-behalf-of tokens)
├─ Idempotency & Rate Limiting
└─ Output Sanitization
Tool Integration Layer
└─ Adapters for: Document Retrieval, SQL, Search,
Ticketing, Messaging, Workflow APIs
Storage Layer
├─ Event Log (append-only task history)
├─ Checkpoint Store (point-in-time state snapshots)
├─ Artifact Store (query results, files)
└─ Metrics & Traces (observability)
Key principle: The LLM proposes, infrastructure enforces. The model never holds credentials or executes operations directly.
3. State Management for Long-Running Workflows
Data model
Separate conversation history (for the LLM) from authoritative state (for the system):
- Task: id, user, goal, status, policy profile, cost budget, creation time
- Event log (append-only): Each LLM call, tool invocation, result, approval, or error is an immutable event with sequence number, parent pointer (for branching), trace_id, cost, latency
- Working state (structured, versioned):
- Goal and plan with step completion status
- Extracted facts with source citations (e.g.,
ticket_id=PROJ-123from event #7) - Pending questions and proposed actions
- Checkpoint: Snapshot of working state at sequence N, enabling fast replay
- Artifacts: Large responses (query results, documents) stored in object storage, referenced by URI not inlined in prompts
Persistence strategy
Use event sourcing with a durable workflow engine (Temporal-style):
- Every step (LLM call, tool execution) is recorded as an event with its result
- After interruption, replay from events instead of re-executing (deterministic replay prevents duplicate side effects)
- Checkpoint every 10 steps or before human waits
- Long pauses (approval pending) use workflow timers, not active compute
Handling branches
Tasks may split when exploring alternatives or user asks "what if":
- Events form a tree via parent sequence pointers
- Each branch gets a copy-on-write view of read-only state
- Side effects stay in "proposed" state until branch is selected for commit
- Only one branch can execute writes; others remain speculative
Keeping state synchronized with external systems
External state changes independently (a ticket gets updated by someone else):
- Store version tags (ETags, timestamps) with cached facts
- Re-validate before writes: "update ticket PROJ-123 WHERE version=5"
- On conflict, either abort or re-plan with fresh data
- Don't cache writes; always read-after-write for confirmation
4. Evaluation Strategy
Offline evaluation (during development)
- Unit tests per tool: Assert correct parameters for known inputs, validate schema compliance, test error handling
- End-to-end task replays: Curate 100–200 representative tasks (successful, failed, edge cases), replay with new model/code versions, compare outputs
- Metrics: task success rate, tool selection accuracy (via manual annotation), plan quality (does it include necessary steps?), groundedness score (citations match sources)
- Adversarial tests: Prompt injection attempts, privilege escalation scenarios, malformed tool outputs
Online evaluation (production)
- Instrumentation: Log every event with trace_id, record user feedback (thumbs up/down, explicit corrections), track time-to-completion and cost per task
- Success metrics:
- Task completion rate (goal achieved without escalation)
- User satisfaction (feedback signals, repeat usage)
- Efficiency (time saved vs. manual alternative, cost per task)
- Safety metrics:
- Incident rate (wrong writes, data leaks, access violations)
- Human escalation rate
- Policy violations flagged
- Operational metrics: P50/P95/P99 latency, error rate by tool, retry rate, cost per user per month
Continuous validation
- Sampling and review: Human auditors review random 2% of completed tasks weekly for correctness, safety, and quality
- A/B testing: Canary new model versions to 5% of traffic, compare success rates before full rollout
- Regression detection: Alert if success rate drops >5% or incident rate rises >2x baseline
- User reports: Integrate feedback loop where users can flag bad outputs; prioritize fixing common failure patterns
Business outcome tracking
Connect agent metrics to business KPIs:
- Reduction in average support ticket resolution time
- Increase in analyst queries answered without engineering help
- Cost savings: (manual hours saved × hourly cost) - (agent infrastructure + LLM API costs)
5. Safety and Observability
Authorization architecture
- Agent authenticates tool calls using on-behalf-of tokens scoped to the requesting user
- Policy engine checks user permissions before every tool call
- High-risk operations (database writes, external messages) require explicit approval
Prompt injection defense
- Treat all tool outputs as untrusted; never directly interpolate into prompts
- Use structured representations (JSON) with clear boundaries between system instructions and external data
- Scan retrieved documents for injection patterns before inclusion
Observability
- OpenTelemetry traces link every tool call back to originating task and user
- Structured logging of all state transitions
- Cost attribution: track LLM tokens and API calls per task, per user, per department
- Real-time dashboards: active tasks, error rates by tool, P95 latency, daily cost burn
Common mistakes to avoid
- Keeping all state in LLM context (doesn't scale, expensive, loses early constraints)
- Giving agent service credentials instead of user credentials (confused deputy vulnerability)
- No idempotency (duplicate side effects on retry)
- Evaluating only on short happy-path examples (misses real complexity)
- Treating the agent as a prompt optimization problem instead of a distributed system
This architecture supports reliable, safe, and auditable agent deployments at enterprise scale.