Özer Cem KELAHMETKELAHMET
Articles · End-to-end workflows

An agentic workflow end to end: build, guard, trace, evaluate and deploy a refund agent

A working agent is the start, not the end. This walk-through takes one refund agent through every production stage, from tools and guardrails to Langfuse traces, a DeepEval and RAGAS release gate and a validated LangGraph deployment config, with code that was run offline against current versions.

Download Markdown
At a glance
Reading time
15 min
Sections
9
Code examples
9
Sources
8
Published
23 Nov 2026
In 30 seconds
What changed
The stack used here was refreshed in the past three weeks
Why it matters
The pieces reinforce each other.
What to do
Move hard rules into middleware

Most agent tutorials stop when the agent answers a question. Production starts there. A team shipping an agent needs to know that it follows business rules, that risky actions wait for a person, that every run can be inspected, that a change cannot silently make it worse, and that it can be deployed and resumed after a crash. Each of those needs a separate piece of tooling, and the pieces have to fit together.

This article builds one small but complete system: a refund agent for an online shop. It searches a refund policy, looks up the order and issues refunds, with refunds above 50 EUR paused for approval. The same code is then traced with Langfuse, scored by DeepEval and RAGAS in a release gate that fails the build on regressions, and wired for deployment with a validated langgraph.json. Everything below was run offline with a scripted model, so the numbers are real outputs of the code shown. The site's earlier from-scratch build with LangGraph, Langfuse, DeepEval and RAGAS focuses on graph design; this one focuses on the release pipeline around the agent.

What happened

The stack used here was refreshed in the past three weeks (5 to 20 November 2026)

The libraries in this pipeline all have recent releases: Langfuse 5.2.0 (5 November 2026), DeepEval 4.3.4 (11 November), langgraph-cli 0.4.43 (12 November), RAGAS 0.4.4 (14 November), LangChain 1.5.2 (18 November) and LangGraph 1.2.24 (20 November). The code in this article pins exactly these versions.

LangChain's approval middleware supports conditional interrupts (since 1.3.3)

The LangChain documentation notes that conditional interrupts, a when predicate on InterruptOnConfig, require langchain>=1.3.3. The predicate receives the pending tool call and returns True to pause for review or False to auto-approve. This lets a policy such as "refunds above 50 EUR need approval" live in code instead of in the prompt. Resuming uses a Command(resume={"decisions": [...]}) with decisions such as approve, edit, reject or respond.

Stage 1: the agent and its guardrails

The application has three tools and three middleware layers. Business rules that must always hold are enforced in code, not left to the model.

# agent_app.py: a refund agent with retrieval, approval for large refunds, call limits and PII redaction.
# pip install langchain==1.5.2 langgraph==1.2.24
from langchain.agents import create_agent
from langchain.agents.middleware import (HumanInTheLoopMiddleware, InterruptOnConfig,
                                         ModelCallLimitMiddleware, PIIMiddleware)
from langchain.tools import tool

POLICIES = {
    "P1": "Damaged items: refund the full price if the customer reports damage within 30 days of delivery.",
    "P2": "Late delivery: offer a 10 percent voucher when a parcel arrives more than 5 days late.",
    "P3": "Refunds above 50 EUR need approval from a support lead before they are issued.",
}
ORDERS = {"1042": {"price": 59.90, "days_since_delivery": 3, "damaged": True},
          "3001": {"price": 24.50, "days_since_delivery": 12, "damaged": True}}
REFUNDS = []

@tool
def search_policy(query: str) -> str:
    """Search refund policies. Returns the best matching policies with their ids."""
    words = set(query.lower().split())
    ranked = sorted(POLICIES.items(), key=lambda kv: -len(words & set(kv[1].lower().split())))
    return "\n".join(f"[{pid}] {text}" for pid, text in ranked[:2])

@tool
def get_order(order_id: str) -> dict:
    """Look up an order by id."""
    return ORDERS.get(order_id, {"error": "order not found"})

@tool
def issue_refund(order_id: str, amount: float) -> str:
    """Refund an order. Large refunds pause for human approval."""
    REFUNDS.append((order_id, amount))
    return f"refunded {amount:.2f} EUR on order {order_id}"

def needs_approval(request) -> bool:
    return request.tool_call["args"].get("amount", 0) > 50       # policy P3, enforced in code

def build_agent(model, checkpointer=None):
    return create_agent(
        model,
        tools=[search_policy, get_order, issue_refund],
        system_prompt="You handle refunds. Check policy and the order before refunding.",
        middleware=[
            PIIMiddleware("email", strategy="redact"),                       # redact emails in user input
            ModelCallLimitMiddleware(run_limit=6, exit_behavior="end"),      # hard stop for loops
            HumanInTheLoopMiddleware(interrupt_on={
                "issue_refund": InterruptOnConfig(allowed_decisions=["approve", "reject"], when=needs_approval)}),
        ],
        checkpointer=checkpointer,
    )

Each guardrail has one job:

  • PII redaction. PIIMiddleware("email", strategy="redact") replaces email addresses in user input before the model sees them. Other built-in types include credit cards, IP addresses, MAC addresses and URLs, and strategies include block, mask and hash.
  • Loop limit. ModelCallLimitMiddleware(run_limit=6) ends a run after six model calls, so a confused agent cannot spin forever. See the tool call retries simulation for why limits and retries must be designed together.
  • Approval. The when=needs_approval predicate pauses issue_refund only when the amount exceeds 50 EUR. Reviewers may approve or reject but not edit.

Approval needs a checkpointer, because the run must stop, wait for a person and resume later. Here is one case run end to end, with a scripted model standing in for the LLM (a small ScriptedModel helper: a GenericFakeChatModel subclass that accepts bind_tools, replays scripted messages and counts calls).

# run_case.py
from langgraph.types import Command
from langgraph.checkpoint.memory import InMemorySaver
# script = [search_policy, get_order, issue_refund(59.90), final answer]  as scripted AIMessages
agent = build_agent(ScriptedModel(messages=iter(script)), InMemorySaver())
cfg = {"configurable": {"thread_id": "case-1"}}
out = agent.invoke({"messages": [("user", "Order 1042 arrived broken, refund me. Email me at ayla@example.com")]},
                   cfg, version="v2")
print("first user message:", out.value["messages"][0].content)
print("paused for:", [(a["name"], a["args"]) for a in out.interrupts[0].value["action_requests"]])
print("refunds so far:", REFUNDS)
out = agent.invoke(Command(resume={"decisions": [{"type": "approve"}]}), cfg, version="v2")
print("final:", out.value["messages"][-1].content)
first user message: Order 1042 arrived broken, refund me. Email me at [REDACTED_EMAIL]
paused for: [('issue_refund', {'order_id': '1042', 'amount': 59.9})]
refunds so far: []
final: Refunded 59.90 EUR for order 1042 under policy P1.
refunds: [('1042', 59.9)] | model calls: 4

The email never reached the model, and no money moved until the reviewer approved. A 24.50 EUR refund would have gone through without a pause, because the predicate returned False. For more layers, such as injection classifiers, see layered agent guardrails and the guardrails simulation.

Stage 2: tracing every run

Langfuse's LangChain integration is a callback handler. Passing CallbackHandler() in the run config records each chain, model and tool call as an OpenTelemetry span. For tests, the Langfuse client accepts an in-memory span_exporter, so nothing leaves the machine:

exporter = InMemorySpanExporter()
Langfuse(public_key="pk-lf-local", secret_key="sk-lf-local", base_url="http://localhost:3000", span_exporter=exporter)
cfg = {"configurable": {"thread_id": case_id}, "callbacks": [CallbackHandler()]}

Two test cases produced 63 spans. Langfuse also logged that it could not parse the model name, which is expected for a fake model and a useful reminder: in production, check that every model span carries a model name, or cost tracking will be blank. In production you drop the span_exporter argument and set the LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY and LANGFUSE_BASE_URL environment variables. See Langfuse for the hosted and self-hosted options.

What should you look for in these traces once the agent is live? Three things matter most for this workflow. First, the order of tool calls: a run where issue_refund appears before get_order is a policy breach even if the refund was correct. Second, the interrupt rate: the share of runs that pause for approval should track the share of orders above 50 EUR; a sudden rise suggests the model is splitting or inflating refunds. Third, model calls per run: the happy path takes four, so runs that hit the six-call limit deserve a look. Each of these is a filter or a count over span attributes, and each one is also a candidate for a new test case.

Designing the test cases

Before writing metrics, decide what the suite must prove. For this agent there are four business rules: check policy before refunding, check the order before refunding, refund the right amount, and pause refunds above 50 EUR. Each rule needs at least one case that exercises it and, ideally, one case where a careless agent would break it.

A good case has five parts: the user input, the expected tools with their arguments, the expected policy id, a reference answer, and, for the scripted run, the sequence of model outputs. The expected tools define the trajectory; the policy id checks retrieval; the reference answer checks the wording loosely. Keep the reference answer short and factual, because string similarity punishes harmless rephrasing in long answers.

Write the regression case on purpose. A suite in which every case passes tells you little about whether the gate works. Including a case that is designed to fail, here an agent that skips the policy search, proves that each metric responds to the defect it is meant to catch. When you later run the suite against the real model, that case moves into a separate "known bad" fixture used only to test the gate itself.

Stage 3: an evaluation gate with DeepEval and RAGAS

The suite has two cases. The first is the happy path above. The second is a deliberate regression: for order 3001 the scripted agent skips search_policy and goes straight to the refund, and its answer omits the policy reference. A good gate must pass the first and fail the second.

Four metrics run on each case, all without an LLM judge:

  • DeepEval ToolCorrectnessMetric: the share of expected tools that were called. DeepEval 4.3 initialises a judge model in the constructor, so a stub DeepEvalBaseLLM subclass is passed; with include_reason=False and no available_tools, the metric never calls it.
  • RAGAS ToolCallF1: precision and recall over tool calls including their arguments.
  • RAGAS NonLLMStringSimilarity: Levenshtein similarity between the answer and a reference answer (needs the rapidfuzz package).
  • Policy hit: whether the expected policy id appeared in the retrieval results, a simple retrieval check.

The scoring function at the heart of the gate:

# eval_gate.py (core). pip install deepeval==4.3.4 ragas==0.4.4 langfuse==5.2.0 rapidfuzz
async def score(case):
    model = ScriptedModel(messages=iter(case["script"]))
    agent = build_agent(model, InMemorySaver())
    cfg = {"configurable": {"thread_id": case["id"]}, "callbacks": [CallbackHandler()]}
    out = agent.invoke({"messages": [("user", case["input"])]}, cfg, version="v2")
    while out.interrupts:                                                  # the test reviewer approves
        out = agent.invoke(Command(resume={"decisions": [{"type": "approve"}]}), cfg, version="v2")
    msgs = out.value["messages"]
    called = [c for m in msgs if isinstance(m, AIMessage) for c in m.tool_calls]
    de = ToolCorrectnessMetric(threshold=1.0, include_reason=False, async_mode=False, model=NoJudge())
    de.measure(LLMTestCase(input=case["input"], actual_output=msgs[-1].content,
                           tools_called=[DEToolCall(name=c["name"]) for c in called],
                           expected_tools=[DEToolCall(name=n) for n, _ in case["expected_tools"]]))
    f1 = await ToolCallF1().ascore(user_input=to_ragas(msgs),
                                   reference_tool_calls=[rm.ToolCall(name=n, args=a) for n, a in case["expected_tools"]])
    sim = await NonLLMStringSimilarity().ascore(reference=case["reference"], response=msgs[-1].content)
    retrieved = " ".join(m.content for m in msgs if isinstance(m, ToolMessage) and m.name == "search_policy")
    return {"case": case["id"], "deepeval_tools": round(de.score, 3), "ragas_tool_f1": round(f1.value, 3),
            "answer_sim": round(sim.value, 3), "policy_hit": float(f"[{case['expected_policy']}]" in retrieved),
            "model_calls": model.calls}

GATES = {"deepeval_tools": 1.0, "ragas_tool_f1": 0.9, "answer_sim": 0.8, "policy_hit": 1.0}
fails = [(r["case"], k) for r in results for k, t in GATES.items() if r[k] < t]
sys.exit(1 if fails else 0)
{'case': 'damaged-large', 'deepeval_tools': 1.0, 'ragas_tool_f1': 1.0, 'answer_sim': 1.0, 'policy_hit': 1.0, 'model_calls': 4}
{'case': 'damaged-small-skips-policy', 'deepeval_tools': 0.667, 'ragas_tool_f1': 0.8, 'answer_sim': 0.68, 'policy_hit': 0.0, 'model_calls': 3}
spans traced: 63
GATE: FAIL [('damaged-small-skips-policy', 'deepeval_tools'), ('damaged-small-skips-policy', 'ragas_tool_f1'), ('damaged-small-skips-policy', 'answer_sim'), ('damaged-small-skips-policy', 'policy_hit')]

The script exits with status 1, which fails a CI job. Check the regression scores by hand. Two of three expected tools were called, so DeepEval gives 2/3 = 0.667. For RAGAS, precision is 2/2 = 1.0 and recall is 2/3, so F1 = 2 × 1.0 × 0.667 / 1.667 = 0.8. The policy check fails because search_policy never ran. All four gates caught the same defect from different angles, which is the point of using more than one metric.

One integration detail is worth knowing. In our test, RAGAS 0.4.4's convert_to_ragas_messages helper returned AI messages with tool_calls=None for LangChain 1.x messages that carry native tool calls, which made ToolCallF1 score 0.0 on the perfect case. A 12-line converter that maps AIMessage.tool_calls to ragas.messages.ToolCall fixed it. Always sanity-check a metric on a known-good case before trusting it in a gate.

In a real pipeline, add LLM-judged metrics such as RAGAS Faithfulness or DeepEval's TaskCompletionMetric in a nightly job, where their cost and variance matter less than in every pull request. Our guides to DeepEval 4.3 and RAGAS 0.4.4 cover those metrics.

Stage 4: deployment

LangGraph's CLI deploys any compiled graph named in a langgraph.json file. The deployed graph is built without a local checkpointer, because the Agent Server provides persistence for threads and interrupts:

{
  "dependencies": ["."],
  "graphs": {"refund_agent": "./deploy_graph.py:agent"},
  "env": ".env"
}
# deploy_graph.py
import os
from agent_app import build_agent
agent = build_agent(os.environ["AGENT_MODEL"], checkpointer=None)   # e.g. "provider:model-id"; the server adds persistence

langgraph validate reported "Configuration file ... is valid. (1 graph found)". From here, langgraph dev runs a local Agent Server for testing, langgraph build produces a Docker image, and langgraph deploy (marked Beta in langgraph-cli 0.4.43) builds and deploys to a hosted Agent Server. Keep secrets out of the image: the env entry points at a .env file for local runs, while hosted deployments should take model keys, Langfuse keys and the AGENT_MODEL value from the platform's secret store. Run the evaluation gate against the exact image you deploy, not just the source tree, so dependency drift between build and test cannot slip through. Approvals then become API calls: your support tool lists threads waiting on an interrupt and resumes them with the reviewer's decision.

What it means in practice

The pieces reinforce each other. Guardrails in code make the agent's riskiest behaviour deterministic, which makes it testable. Traces from production supply new test cases. The gate turns those cases into a release rule. Deployment with durable threads makes approval workflows possible at all. Skipping any one stage weakens the others: a gate without traces has no realistic cases, and approval without persistence loses work on every restart.

Rolling out a change safely is the last step of the loop. Passing the gate means a change is not worse on known cases; it does not prove it is better on live traffic. A cautious rollout runs the new version in shadow mode first, receiving copies of real requests but with issue_refund disabled, and compares its traces with the live version: tool order, model calls per run, interrupt rate and answer quality from sampled reviews. Then route a small share of real traffic to it and watch the same numbers before switching fully. Because every refund above the threshold already waits for a human reviewer, the blast radius of a bad release is limited to small refunds, which is another reason to set that threshold deliberately. The agent trace simulation shows how to read the traces you will compare.

The workflow also shows where models are and are not needed. Policy retrieval, approval thresholds, limits, redaction and three of the four metrics are plain code. The model decides the order of steps and writes the answer. Keeping that split explicit is what makes the system auditable.

What to do now

  1. Move hard rules into middleware. Encode thresholds and forbidden actions as predicates and limits, not prompt text.
  2. Use conditional approval. Pause only the risky calls with a when predicate so reviewers are not flooded.
  3. Redact before the model. Apply PII middleware to user input and, where needed, to tool results.
  4. Trace in tests too. Use an in-memory exporter in CI to assert that runs produce spans with model names.
  5. Seed the suite with failures. Include at least one deliberate regression case so you know the gate can fail.
  6. Verify metrics on a known-good case. Check that a perfect run scores 1.0 before adding a metric to the gate.
  7. Split fast and slow checks. Run deterministic metrics on every pull request and LLM-judged metrics nightly.
  8. Validate the deployment config. Run langgraph validate in CI so a broken graph path fails early.

Risks and open questions

Scripted tests are not model tests. The gate here proves the harness and metrics work. To test the agent itself, run the same suite against the real model several times and track pass rates.

Approval fatigue. If too many calls pause, reviewers approve without reading. Set thresholds from data and audit approvals.

Metric drift. Library updates can change scores, as the converter issue showed. Pin versions and keep a known-good baseline run.

State in deployment. Interrupted threads hold state for as long as they wait. Decide how long a refund can wait for approval and what happens after.

Watch next: whether evaluation libraries converge on a shared trace format so the same traces feed DeepEval, RAGAS and observability tools without converters, and how the Beta langgraph deploy command evolves.

Frequently asked questions

Why enforce the 50 EUR rule in code instead of the prompt?

A prompt rule is a request the model may ignore; a predicate on the tool call runs every time. In the demo the refund of 59.90 EUR paused before any money moved, regardless of what the model intended.

Can DeepEval and RAGAS run without an API key?

Some metrics can. In this pipeline DeepEval's tool correctness score and RAGAS's tool call F1 and string similarity ran offline. LLM-judged metrics such as faithfulness need a model, so they suit a nightly job.

What does the scripted model prove?

It proves the wiring: tools, middleware, approvals, tracing and metrics all behave as expected, quickly and deterministically. It does not prove the real model makes good decisions, which needs the same suite run against the real model.

Why does the deployed graph have no checkpointer?

The LangGraph Agent Server provides persistence for threads, so the graph module only needs the compiled agent. Locally and in tests, an InMemorySaver plays that role so interrupts can be resumed.

How many test cases does the gate need?

Start with a handful that cover each business rule and at least one known failure, then add cases from production traces every week. The aim is coverage of rules and past failures, not a large number.

Summary

This walk-through took one refund agent through the full lifecycle. Middleware enforced PII redaction, a six-call limit and approval for refunds above 50 EUR; the demo paused a 59.90 EUR refund until a reviewer approved it. Langfuse recorded 63 spans across two test runs through an in-memory exporter. A gate built on DeepEval tool correctness, RAGAS tool call F1, string similarity and a retrieval check passed the good case and failed the regression on all four metrics, with scores of 0.667 and 0.8 that check out by hand. A langgraph.json validated cleanly for deployment. Put hard rules in code, trace everything, gate releases on metrics you have verified, and deploy with durable state.

Sources

Cite this article

Kelahmet, Ö. C. (2026, November 23). An agentic workflow end to end: build, guard, trace, evaluate and deploy a refund agent. Özer Cem KELAHMET. https://www.ozercemkelahmet.com/articles/refund-agent-end-to-end-ci-gate

BibTeX
@online{kelahmet2026refund,
  author = {Kelahmet, {\"O}zer Cem},
  title  = {{An agentic workflow end to end: build, guard, trace, evaluate and deploy a refund agent}},
  year   = {2026},
  month  = {nov},
  url    = {https://www.ozercemkelahmet.com/articles/refund-agent-end-to-end-ci-gate}
}
Version historyfirst version
  1. Published

Factual corrections are listed here with what changed. Wording and formatting edits are not listed.

Last updated Nov 23, 2026
Type to search.
    ↑↓ navigate↵ open