---
title: "Coding Agent MVP"
domain: "Software Development"
summary: "Essential patterns for building a minimum viable AI coding agent that can write, debug, and improve code."
url: "https://agentic-patterns.com/packs/coding-agent-mvp"
markdown_url: "https://agentic-patterns.com/packs/coding-agent-mvp.md"
pattern_count: 4
---

# Coding Agent MVP

> Essential patterns for building a minimum viable AI coding agent that can write, debug, and improve code.

**Domain:** Software Development

## How to apply this stack with a coding agent

```text
Apply the "Coding Agent MVP" pattern pack to this repository.
Check each pattern's "Use when" and "Avoid when" conditions against our codebase,
identify gaps in order of risk, and list the files to update before making edits.
```

## Patterns in this pack

1. **Specification-Driven Agent Development** — Makes a version-controlled spec the agent's main input, scaffolds code from it, and regenerates executable tests from it on every commit to catch drift ([page](https://agentic-patterns.com/patterns/specification-driven-agent-development) | [.md](https://agentic-patterns.com/patterns/specification-driven-agent-development.md))
2. **Code-Then-Execute Pattern** — LLM writes a sandboxed program or DSL script, a static taint checker verifies data flows, and an interpreter runs it in a locked sandbox ([page](https://agentic-patterns.com/patterns/code-then-execute-pattern) | [.md](https://agentic-patterns.com/patterns/code-then-execute-pattern.md))
3. **Human-in-the-Loop Approval Framework** — Systematically insert human approval gates for designated high-risk functions while maintaining agent autonomy for safe operations, with multi-channel approval interfaces and comprehensive audit trails. ([page](https://agentic-patterns.com/patterns/human-in-loop-approval-framework) | [.md](https://agentic-patterns.com/patterns/human-in-loop-approval-framework.md))
4. **LLM Observability** — Sends agent runs to an LLM observability platform for span-level traces of each LLM call and tool use, plus aggregate cost, latency, and success metrics ([page](https://agentic-patterns.com/patterns/llm-observability) | [.md](https://agentic-patterns.com/patterns/llm-observability.md))

---

## Specification-Driven Agent Development

- URL: https://agentic-patterns.com/patterns/specification-driven-agent-development
- Markdown: https://agentic-patterns.com/patterns/specification-driven-agent-development.md
- Category: Orchestration & Control | Status: emerging

> Makes a version-controlled spec the agent's main input, scaffolds code from it, and regenerates executable tests from it on every commit to catch drift

### Use when

- Loose prompts cause agents to drift from stakeholder intent
- Requirements can be written as Markdown, OpenAPI, or JSON Schema
- Team needs audit trails from code back to requirements
- Spec and code change often and drift apart

### Avoid when

- Requirements are too coarse or unknown to specify
- Quick exploratory work where writing a spec costs more than it saves
- CI capacity cannot run generated tests on each commit

<details>
<summary>Full pattern specification</summary>

---
title: "Specification-Driven Agent Development"
summary: "Makes a version-controlled spec the agent's main input, scaffolds code from it, and regenerates executable tests from it on every commit to catch drift"
status: "emerging"
category: "Orchestration & Control"
url: "https://agentic-patterns.com/patterns/specification-driven-agent-development"
source: "https://jorypestorious.com/blog/ai-engineer-spec/"
authors: ["Nikola Balic (@nibzard)"]
tags: ["spec-first","scaffolding","contract","requirements","validation","drift-detection","continuous-testing"]
signals: ["Loose prompts cause agents to drift from stakeholder intent","Requirements can be written as Markdown, OpenAPI, or JSON Schema","Team needs audit trails from code back to requirements","Spec and code change often and drift apart"]
anti_signals: ["Requirements are too coarse or unknown to specify","Quick exploratory work where writing a spec costs more than it saves","CI capacity cannot run generated tests on each commit"]
updated_at: "2026-11-23"
---

# Specification-Driven Agent Development

> Makes a version-controlled spec the agent's main input, scaffolds code from it, and regenerates executable tests from it on every commit to catch drift

## Use when

- Loose prompts cause agents to drift from stakeholder intent
- Requirements can be written as Markdown, OpenAPI, or JSON Schema
- Team needs audit trails from code back to requirements
- Spec and code change often and drift apart

## Avoid when

- Requirements are too coarse or unknown to specify
- Quick exploratory work where writing a spec costs more than it saves
- CI capacity cannot run generated tests on each commit

## Problem

Hand-crafted prompts or loose user stories leave room for ambiguity; agents can wander, over-interpret, or produce code that conflicts with stakeholder intent.

A spec fixes that at the start, but it introduces a second problem. Even in spec-first projects, implementations drift as code evolves and the spec changes (or vice-versa). Silent divergence erodes the trust the spec was meant to provide.

## Solution

Adopt a **spec-first workflow** in which a formal specification file (e.g., Markdown, OpenAPI, JSON Schema) is the agent's *primary* input and source of truth, and then keep that spec executable for the life of the project.

- **Parse spec** → agent builds an explicit task graph.
- **Scaffold** project structure & stub code straight from the spec.
- **Enforce** that every generated artifact links back to a spec clause.
- **Iterate** only by editing the spec, *not* by re-prompting ad-hoc.
- **Verify** by regenerating executable tests from the spec on every change.

```pseudo
if new_feature_requested:
    write_spec(update)
    agent.sync_with(spec)
    regenerate_tests(spec)
```

**Core Framework (SPEC/EXPOSURE/TASK DELTA):**

- **SPEC**: Version-controlled markdown capturing intent and values
- **EXPOSURE**: What customers experience; spec is permanent, code is temporary
- **TASK DELTA**: Continuous loop evaluating SPEC ↔ PRODUCT to identify gaps

The source article describes TASK DELTA as a human-driven loop: a person re-derives the checks after each spec change. Coding agents make the loop practical to automate, which turns the spec from a one-shot scaffolding input into a continuous feedback mechanism.

**Spec-to-test feedback loop:**

1. **Specification Layer**: Parse specs (structured Markdown, YAML, JSON Schema, BDD) into an internal representation
2. **Test Generation Layer**: Create executable tests (unit, integration, property) from that representation
3. **Execution Layer**: Run tests in parallel in CI on every code commit
4. **Feedback Layer**: Route each failure to an agent-authored PR that either fixes the code to match the spec, or flags the unclear spec segment for human review

**Vendor tooling (2025-2026):** GitHub Spec Kit drives a `/speckit-specify → /speckit-plan → /speckit-tasks → /speckit-implement` command sequence from a constitution and spec documents, and AWS Kiro ships spec-driven agentic development in the editor.

## Evidence

- **Evidence Grade:** `low`
- **Most Valuable Findings:**

  - Academic foundations in QuickCheck (property-based testing) and Design by Contract
  - Effective when combined with [Feature List as Immutable Contract](feature-list-as-immutable-contract.md), which makes the loop immune to "pass by deletion"
  - Test state persists across agent session boundaries, so context loss does not reset verification

- **Unverified:** An earlier claim of production use at Anthropic, OpenAI, and LangChain misattributed training-time and model-eval techniques to this CI pattern and has been removed.

## How to use it

Write specifications first (Markdown files in git), then let agents scaffold from them. Documentation IS the spec: write it before code.

Use tiered review: AI for patterns, humans for logic. Parallelize via git worktrees or multiple agents coordinating through shared spec files.

**Keeping the loop running:**

- Keep the spec in a machine-parseable subset so tests can be regenerated from it.
- Regenerate the derived test suite on every spec commit, not on a schedule, so tests never lag the spec.
- Run generated tests in CI on every code commit and treat a spec-test failure as drift, not as a flaky test.
- Route each failure explicitly: an agent-authored fix PR, or a flagged spec-ambiguity issue for a human.
- Record which spec clause each test came from, so spec edits show exactly which tests must change.

Pitfalls: coarse or under-specified requirements still propagate errors, and ambiguous spec wording produces false-positive test failures.

## Trade-offs

- **Pros:**

  - Repeatable, audit-friendly, easy diffing
  - Catches drift early; prevents silent spec-implementation divergence
  - Provides measurable progress metrics (X/Y features passing)

- **Cons:**

  - Up-front spec writing effort; initial ramp-up for teams new to spec formats
  - Heavy CI usage; overhead exceeds benefit for small or one-off tasks
  - Test explosion risk without intelligent selection; spec churn creates test churn

## References

- Primary source: [The AI Engineer Spec](https://jorypestorious.com/blog/ai-engineer-spec/) - Jory Pestorious (AI Engineer World's Fair 2025), describes the SPEC / EXPOSURE / TASK DELTA loop as a human-driven verification process
- Anthropic Engineering: [Effective Harnesses for Long-Running Agents](https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents)
- [GitHub Spec Kit](https://github.com/github/spec-kit) - spec-driven development toolkit (`/speckit-specify`, `/speckit-plan`, `/speckit-tasks`, `/speckit-implement`, `/speckit-converge`), launched September 2025
- AWS Kiro (spec-driven agentic development): https://kiro.dev
- QuickCheck (Claessen & Hughes, ICFP 2000) - property-based testing foundation
- Related pattern: [Feature List as Immutable Contract](feature-list-as-immutable-contract.md) freezes a JSON feature list with acceptance steps rather than a full specification

</details>

---

## Code-Then-Execute Pattern

- URL: https://agentic-patterns.com/patterns/code-then-execute-pattern
- Markdown: https://agentic-patterns.com/patterns/code-then-execute-pattern.md
- Category: Security & Safety | Status: emerging

> LLM writes a sandboxed program or DSL script, a static taint checker verifies data flows, and an interpreter runs it in a locked sandbox

### Use when

- Security-sensitive workflows where tainted input must not reach dangerous sinks
- Multi-step agents such as SQL copilots or workflow automators that need auditability
- You need formal verification or replay logs of agent actions

### Avoid when

- You cannot invest in DSL design and static-analysis infrastructure
- Simple tasks where sandbox execution overhead outweighs audit value

<details>
<summary>Full pattern specification</summary>

---
title: "Code-Then-Execute Pattern"
summary: "LLM writes a sandboxed program or DSL script, a static taint checker verifies data flows, and an interpreter runs it in a locked sandbox"
status: "emerging"
category: "Security & Safety"
url: "https://agentic-patterns.com/patterns/code-then-execute-pattern"
source: "https://arxiv.org/abs/2506.08837"
authors: ["Nikola Balic (@nibzard)"]
tags: ["dsl","sandbox","program-synthesis","auditability"]
signals: ["Security-sensitive workflows where tainted input must not reach dangerous sinks","Multi-step agents such as SQL copilots or workflow automators that need auditability","You need formal verification or replay logs of agent actions"]
anti_signals: ["You cannot invest in DSL design and static-analysis infrastructure","Simple tasks where sandbox execution overhead outweighs audit value"]
updated_at: "2026-11-23"
---

# Code-Then-Execute Pattern

> LLM writes a sandboxed program or DSL script, a static taint checker verifies data flows, and an interpreter runs it in a locked sandbox

## Use when

- Security-sensitive workflows where tainted input must not reach dangerous sinks
- Multi-step agents such as SQL copilots or workflow automators that need auditability
- You need formal verification or replay logs of agent actions

## Avoid when

- You cannot invest in DSL design and static-analysis infrastructure
- Simple tasks where sandbox execution overhead outweighs audit value

## Problem

Free-form plan-and-act loops are difficult to audit because critical control decisions stay implicit in natural-language reasoning. In security-sensitive workflows, teams need verifiable guarantees that tainted inputs cannot flow into dangerous sinks (for example, external messages, payments, or destructive commands). Plain-text plans are too weak for formal validation.

## Solution

Have the LLM output a **sandboxed program or DSL script**:

1. LLM writes code that calls tools and untrusted-data processors.
2. Static checker/Taint engine verifies flows (e.g., no tainted var to `send_email.recipient`).
3. Interpreter runs the code in a locked sandbox.

The key shift is to move from "reasoning about actions" to "compiling actions" into an inspectable artifact. Once actions are code, policy engines and static analyzers can enforce data-flow rules before execution.

Scope note: step 2 is an optional hardening layer, not part of the base pattern. The survey's Code-Then-Execute pattern (Beurer-Kellner et al., §3.1, pattern 5) defines no checker step and states it cannot stop injected content that arrives inside tool data. CaMeL (Debenedetti et al.) is the stronger variant that adds taint tracking and security-classified variables on top.

This pattern also serves a complementary purpose: **token optimization**. When tool calls execute within the sandbox rather than through special tokens, only condensed results return to the LLM context. Published measurements: Anthropic reports 98.7% (150K → 2K tokens) for tool definitions loaded on demand, and Bifrost measures 58.2-92.8% input-token reductions for code-mode tool calling.

For token reduction alone, see [Code-Over-API Pattern](code-over-api-pattern.md). This pattern complements it with a security control: a static check separates control flow (which tool runs, with which fixed arguments) from untrusted data, so that a tainted value cannot reach a dangerous sink.

```dsl
x = calendar.read(today)
y = QuarantineLLM.format(x)
email.write(to="john@acme.com", body=y)
```

## Example

The calendar-to-email flow above illustrates the three steps separately:

**1. The DSL script (what the LLM writes):** three lines, each a tool call with explicit arguments; the recipient and body are visible as data flows, not buried in prose.

**2. The checker (optional CaMeL-style hardening):** a static pass over the script that rejects forbidden flows before anything runs:

```pseudo
tainted = {x}                       # calendar data is untrusted
policy: email.recipient must be untainted_constant
check(x -> y -> email.body)  = ok   # body may carry quaranted content
check(email.recipient == "john@acme.com")  = ok
# email.write(to=user_input) would be rejected at compile time
```

**3. The sandbox (where it runs):** an interpreter with no network egress except the two tool endpoints, a per-run time and write budget, and a replay log keyed by script hash, so any executed action can be re-verified after the fact.

## How to use it

Use this for complex multi-step agents such as SQL copilots, software-engineering bots, and workflow automators where auditability matters. Start with a small DSL and explicit forbidden flows, then expand language features as checks mature.

## Trade-offs

* **Pros:** Formal verifiability; replay logs; reduced token costs for data-heavy workflows.
* **Cons:** Requires DSL design and static-analysis infra; sandbox execution overhead.

## References

* Debenedetti et al., [CaMeL: Defeating Prompt Injections by Design](https://arxiv.org/abs/2503.18813) (Google DeepMind, 2025) - origin of the taint-tracked variant
* Beurer-Kellner et al., [Design Patterns for Securing LLM Agents against Prompt Injections](https://arxiv.org/abs/2506.08837) (2025) - names Code-Then-Execute as §3.1 pattern 5, without a checker step
* Anthropic Engineering, [Code Execution with MCP](https://www.anthropic.com/engineering/code-execution-with-mcp) (November 4, 2025) - 98.7% tool-definition token reduction
* Bifrost, [Code Mode benchmarks](https://docs.getbifrost.ai/mcp/code-mode) - 58.2-92.8% measured input-token reduction
* Distinct from [Plan-Then-Execute Pattern](plan-then-execute-pattern.md): that pattern structures reasoning before acting, while this pattern compiles actions into a verifiable program
* Distinct from [Code-Over-API Pattern](code-over-api-pattern.md): that pattern optimizes tokens for data processing, while this pattern prioritizes auditability and data-flow control

- Primary source: https://arxiv.org/abs/2506.08837
- Industry implementation: https://www.anthropic.com/engineering/code-execution-with-mcp

</details>

---

## Human-in-the-Loop Approval Framework

- URL: https://agentic-patterns.com/patterns/human-in-loop-approval-framework
- Markdown: https://agentic-patterns.com/patterns/human-in-loop-approval-framework.md
- Category: UX & Collaboration | Status: foundational

> Systematically insert human approval gates for designated high-risk functions while maintaining agent autonomy for safe operations, with multi-channel approval interfaces and comprehensive audit trails.

### Use when

- Agents run high-risk or irreversible operations such as production DB writes, payments, or deploys
- Compliance requires a record of who approved each sensitive action
- Humans can respond fast enough through Slack, email, or a dashboard

### Avoid when

- All agent actions are safe or easily reversible
- No human is available to respond in time
- Approval volume would be so high that reviewers rubber-stamp requests

<details>
<summary>Full pattern specification</summary>

---
title: "Human-in-the-Loop Approval Framework"
summary: "Systematically insert human approval gates for designated high-risk functions while maintaining agent autonomy for safe operations, with multi-channel approval interfaces and comprehensive audit trails."
status: "foundational"
category: "UX & Collaboration"
url: "https://agentic-patterns.com/patterns/human-in-loop-approval-framework"
source: "https://claude.com/blog/building-companies-with-claude-code"
authors: ["Nikola Balic (@nibzard)"]
tags: ["human-oversight","safety","approvals","risk-management","collaboration","slack-integration"]
signals: ["Agents run high-risk or irreversible operations such as production DB writes, payments, or deploys","Compliance requires a record of who approved each sensitive action","Humans can respond fast enough through Slack, email, or a dashboard"]
anti_signals: ["All agent actions are safe or easily reversible","No human is available to respond in time","Approval volume would be so high that reviewers rubber-stamp requests"]
updated_at: "2026-11-06"
---

# Human-in-the-Loop Approval Framework

> Systematically insert human approval gates for designated high-risk functions while maintaining agent autonomy for safe operations, with multi-channel approval interfaces and comprehensive audit trails.

## Use when

- Agents run high-risk or irreversible operations such as production DB writes, payments, or deploys
- Compliance requires a record of who approved each sensitive action
- Humans can respond fast enough through Slack, email, or a dashboard

## Avoid when

- All agent actions are safe or easily reversible
- No human is available to respond in time
- Approval volume would be so high that reviewers rubber-stamp requests

## Problem

Autonomous AI agents need to execute high-risk or irreversible operations (database modifications, production deployments, system configurations, API calls) but allowing unsupervised execution creates unacceptable safety and compliance risks. Blocking all such operations defeats the purpose of agent automation.

## Solution

Systematically insert human approval gates for designated high-risk functions while maintaining agent autonomy for safe operations. Create lightweight feedback loops that enable time-sensitive human decisions without blocking the entire agent workflow.

**Core components:**

**Risk classification:**

- Identify functions that require human approval
- Define approval criteria (cost thresholds, data sensitivity, reversibility)
- Categorize operations by risk level

**Multi-channel approval interface:**

- Slack integration for real-time notifications
- Email for asynchronous approvals
- SMS for urgent/critical operations
- Web dashboard for batch reviews

**Approval workflow:**

- Agent requests permission before executing risky function
- Human receives context-rich approval request
- Quick approve/reject/modify decision
- Agent proceeds or adapts based on response
- Timeout handling with configurable escalation (default deny recommended)

**Audit trail:**

- Log all approval requests and responses
- Track who approved what and when
- Enable compliance and debugging

```mermaid
sequenceDiagram
    participant Agent as AI Agent
    participant Framework as Approval Framework
    participant Slack as Slack Channel
    participant Human as Human Reviewer
    participant DB as Database

    Agent->>Framework: Request: DROP old_users table
    Framework->>Framework: Classify as HIGH RISK
    Framework->>Slack: Send approval request with context
    Slack->>Human: Notification with approve/reject buttons

    alt Approved
        Human->>Slack: Click "Approve"
        Slack->>Framework: Approval granted
        Framework->>Agent: Permission granted
        Agent->>DB: Execute DROP table
        Framework->>Framework: Log approval & execution
    else Rejected
        Human->>Slack: Click "Reject + provide reason"
        Slack->>Framework: Rejection + context
        Framework->>Agent: Permission denied + reason
        Agent->>Agent: Adapt plan (skip or find alternative)
    end
```

## How to use it

**When to apply:**

- Production database operations (DELETE, DROP, ALTER)
- External API calls with side effects (payments, emails, webhooks)
- System configuration changes (firewall rules, permissions)
- Destructive file operations (bulk deletes, overwrites)
- Compliance-sensitive operations (GDPR, HIPAA, SOC2)

**Implementation examples:**

**Permission rules (Claude Code settings):**

```json
// .claude/settings.json — rules are evaluated deny, then ask, then allow
{
  "permissions": {
    "allow": ["Bash(git add:*)", "Bash(npm test:*)"],
    "ask": ["Bash(git push:*)"],
    "deny": ["Read(.env)", "Read(secrets/**)"]
  }
}
```

Commands on the `ask` list pause the agent until a human answers the permission prompt, which is the same gate-then-resume flow the Slack-based implementations use.

**Interrupt pattern (LangGraph):**

```python
from langgraph.types import interrupt

def risky_operation(state):
    approval = interrupt({
        "question": "Should I proceed with this operation?",
        "operation": state["message"]
    })
    return {"user_approval": approval}

# Compile with checkpointer for state preservation
app = workflow.compile(checkpointer=MemorySaver())
```

**Protocol-level elicitation (MCP):**

An MCP server can pause mid-flow and send an `elicitation/create` request to the client, which renders the question and schema to the user and returns the answer to the agent. This gives any MCP-connected client the same interrupt semantics without a bespoke approval service.

**2. Configure approval channels:**

```yaml
approval_channels:
  high_risk:
    
- slack: "#agent-approvals"
    - sms: "+1234567890"  # For urgent
  medium_risk:
    
- slack: "#agent-review"
  low_risk:
    
- email: "team@company.com"
```

**3. Set context requirements:**

- Why is the operation needed?
- What data will be affected?
- Is it reversible?
- What are the alternatives?

**Prerequisites:**

- Integration with communication platforms (Slack, email, SMS)
- Clear risk classification criteria
- Fast human response time for time-sensitive operations
- Fallback strategies when approval is denied

## Trade-offs

**Pros:**

- Enables safe autonomous execution of risky operations
- Maintains human oversight where it matters most
- Lightweight integration (Slack buttons, not complex UIs)
- Audit trail for compliance and debugging
- Reduces agent anxiety about mistakes
- Allows gradual trust expansion over time

**Cons:**

- Requires human availability and responsiveness
- Can bottleneck agent workflows if approvals are slow
- Infrastructure complexity (notification systems, state management)
- Risk of approval fatigue leading to rubber-stamping
- Requires clear classification of what needs approval
- May interrupt human focus with frequent requests

## References

- [Building Companies with Claude Code](https://claude.com/blog/building-companies-with-claude-code) - HumanLayer's core product coordinates agent actions with "human approval steps" via Slack
- [HumanLayer on GitHub](https://github.com/humanlayer/humanlayer) - the open-source SDK is now largely deprecated ("the code here is pretty much all deprecated"); the company pivoted to a coding-agent IDE ([humanlayer.dev](https://www.humanlayer.dev))
- [12-Factor Agents](https://github.com/humanlayer/12-factor-agents) - Factor 7 covers contacting humans via tool calls
- [Claude Code permissions](https://code.claude.com/docs/en/permissions) - permission modes plus allow/ask/deny rules as a maintained standard implementation
- [MCP elicitation specification](https://modelcontextprotocol.io/specification/2025-06-18/client/elicitation) - protocol-level mid-flow approval requests
- [Design Patterns for Securing LLM Agents](https://arxiv.org/abs/2506.08837) (Beurer-Kellner et al., ETH Zurich, 2025) - Academic treatment of approval systems as security pattern, including separation of proposal and execution
- [Impri](https://github.com/sekera-radim/impri) - Self-hostable, framework-agnostic implementation of this pattern (contributor-owned, disclosed): agents propose actions via MCP or REST, a human approves/edits/rejects from a web inbox, Slack, Telegram, or phone, then the agent executes. MIT-licensed open-core, included as a concrete alternative to the vendor-SDK references above.
- [Duct](https://github.com/5hirish/duct) - Open-source marketing agent (contributor-owned, disclosed) that applies the proposal/execution separation from the ETH Zurich paper at the tool-list level: the model can only propose a change set as data, no approve or apply tool exists for it to call, a human approves through an HTTP route, and a per-project autonomy level (`ask` by default) can let reversible, guardrail-clean changes auto-apply but never widens what may apply. MIT-licensed, included as a second concrete implementation beside Impri.
- Related patterns: [Spectrum of Control / Blended Initiative](spectrum-of-control-blended-initiative.md), [Chain-of-Thought Monitoring & Interruption](chain-of-thought-monitoring-interruption.md)

</details>

---

## LLM Observability

- URL: https://agentic-patterns.com/patterns/llm-observability
- Markdown: https://agentic-patterns.com/patterns/llm-observability.md
- Category: Reliability & Eval | Status: production

> Sends agent runs to an LLM observability platform for span-level traces of each LLM call and tool use, plus aggregate cost, latency, and success metrics

### Use when

- Multi-step agent workflows are hard to debug from raw logs
- Non-engineers need to inspect workflow runs
- Team needs cost, latency, and success metrics across runs

### Avoid when

- Simple, deterministic tools with no agent behavior
- Single-step operations where standard logs suffice
- Budget does not cover observability spend

<details>
<summary>Full pattern specification</summary>

---
title: "LLM Observability"
summary: "Sends agent runs to an LLM observability platform for span-level traces of each LLM call and tool use, plus aggregate cost, latency, and success metrics"
status: "production"
category: "Reliability & Eval"
url: "https://agentic-patterns.com/patterns/llm-observability"
source: "https://lethain.com/agents-logging/"
authors: ["Nikola Balic (@nibzard)"]
tags: ["observability","logging","debugging","tracing","datadog","langsmith","spans","monitoring","llmops"]
signals: ["Multi-step agent workflows are hard to debug from raw logs","Non-engineers need to inspect workflow runs","Team needs cost, latency, and success metrics across runs"]
anti_signals: ["Simple, deterministic tools with no agent behavior","Single-step operations where standard logs suffice","Budget does not cover observability spend"]
updated_at: "2026-10-13"
---

# LLM Observability

> Sends agent runs to an LLM observability platform for span-level traces of each LLM call and tool use, plus aggregate cost, latency, and success metrics

## Use when

- Multi-step agent workflows are hard to debug from raw logs
- Non-engineers need to inspect workflow runs
- Team needs cost, latency, and success metrics across runs

## Avoid when

- Simple, deterministic tools with no agent behavior
- Single-step operations where standard logs suffice
- Budget does not cover observability spend

## Problem

Agents introduce **non-determinism**—the same input can produce different outputs. When agents do something sub-optimal, users flag it as a "bug" even if it's just prompt ambiguity. Debugging these issues requires tracing through complex multi-step workflows, but standard logging (CloudWatch, Lambda logs) is painful to navigate. Engineers need easy access to workflow execution details to debug quickly, or agents won't get adopted.

## Solution

Integrate **LLM observability platforms** (Datadog LLM Observability, LangSmith, etc.) that provide **span-level tracing** of agent workflows. Instead of spelunking through raw logs, get a visual UI showing each step of the agent's execution.

**Key capabilities:**

- **Span visualization**: See each LLM call, tool use, and intermediate result
- **Workflow linking**: Trace from user input through all sub-steps to final output
- **Dashboarding**: Aggregate metrics on cost, latency, success rates
- **Accessible debugging**: Non-engineers can inspect runs without raw log access (in the source deployment, Datadog access was still limited to the technology organization)
- **Event sourcing**: Structured logs enable replay, state reconstruction, and verification
- **Vendor-neutral tracing**: OpenTelemetry GenAI semantic conventions and OpenInference define portable span attributes, so traces are not locked to one platform

**Evolution from standard logging:**

1. **Print to stdout** → Captured in Lambda logs (hard to access)
2. **Slack channel** → Post run summary + AWS log link (better, still spelunking)
3. **LLM observability** → Visual span tracing, easy navigation

```mermaid
graph LR
    A[Agent Run] --> B[Observability SDK]
    B --> C[Span: LLM Call 1]
    B --> D[Span: Tool Use]
    B --> E[Span: LLM Call 2]
    C --> F[Trace UI]
    D --> F
    E --> F
    F --> G[Debug View]

    style F fill:#e8f5e9,stroke:#388e3c,stroke-width:2px
```

## How to use it

**Integration steps:**

1. **Choose observability platform**: Datadog LLM Observability, LangSmith, Arize, etc.
2. **Install SDK**: Add to your agent code (often 1-2 lines)
3. **Configure tracing**: Tag workflows, users, environments
4. **Access controls**: Give broader team access (not just engineers)

**Example with Datadog:**

```python
from ddtrace import tracer

# Automatically traces LLM calls
@tracer.wrap("agent_workflow")
def run_agent(query):
    result = agent.run(query)
    # Each LLM call, tool use becomes a span
    return result
```

**Best practices:**

- **Tag everything**: Workflow name, user ID, environment (prod/staging)
- **Link to dashboards**: Make observability UI discoverable from chat
- **Share access**: Don't restrict to eng org; workflow creators need visibility
- **Monitor aggregate metrics**: Track success rates, latency, costs over time
- **Use structured formats**: JSONL with schema versioning for long-running systems
- **Aggregate at write time**: Log enrichment happens during capture, not during queries

## Trade-offs

**Pros:**

- **Fast debugging**: Navigate complex workflows visually
- **Accessible**: Broader teams can debug without log permissions; the source deployment still limited access to the technology organization
- **Aggregated metrics**: See patterns across many runs
- **Span-level detail**: Drill into any step of execution

**Cons:**

- **Vendor dependency**: Locked into observability platform
- **Cost**: Enterprise observability can be expensive
- **Overhead**: Adds latency (usually minimal)
- **Access control**: Balancing visibility with security

**When NOT to use:**

- Simple, deterministic tools (no agent behavior)
- Single-step operations (standard logs suffice)
- Budget constraints preventing observability spend

## References

* [Building an internal agent: Logging and debugability](https://lethain.com/agents-logging/) - Will Larson (Imprint, 2025)
* [Monitoring Reasoning Models for Misbehavior and the Risks of Promoting Obfuscation](https://arxiv.org/abs/2503.11926) - OpenAI (March 2025); the reasoning-monitoring evidence behind CoT observability
* [OpenTelemetry GenAI semantic conventions](https://github.com/open-telemetry/semantic-conventions/tree/main/docs/gen-ai) - vendor-neutral span attributes for LLM and agent calls (in development)
* [OpenInference](https://github.com/Arize-ai/openinference) - open instrumentation standard for LLM/agent tracing
* [ESAA: Event Sourcing for Autonomous Agents](https://arxiv.org/abs/2602.23193v1) - Elzo Brito dos Santos Filho et al. (February 2026)
* [Chain of Thought Monitorability: A Fragile Opportunity](https://arxiv.org/abs/2510.19476) - Korbak et al. (October 2025)
* Datadog LLM Observability documentation
* LangSmith documentation
* Related: Agent-First Tooling and Logging, Chain-of-Thought Monitoring & Interruption

</details>
