LangChain vs LangGraph in ASP.NET Core 10: Build a Support Ticket Retry Workflow

A support ticket branches to a retry loop and successful resolution or to escalation.

Use LangChain when you want to compose operations such as calling a model and formatting its output. Use LangGraph when the next step depends on the current workflow state. This tutorial runs the same fictional support ticket through both. The LangChain example reads the service status once. The LangGraph example remembers how many times it checked and retries a temporary failure once before escalating.

Imagine the on-call queue getting a ticket because the VPN status page briefly stopped responding. On the first read, the service looks unavailable. The second read succeeds. Escalating after the first read creates work for someone who can’t reproduce it. Retrying forever keeps the caller waiting. A two-attempt limit makes both outcomes predictable.

What is the difference between LangChain and LangGraph?

QuestionLangChain composition in this labLangGraph workflow in this lab
What happens next?The probe runs once, then a formatter runs.A conditional edge chooses resolve, retry, or escalate.
Where is the attempt count?The caller supplies the first-attempt constant.The graph carries attempts in its state.
Does it need a model?No. RunnableLambda wraps ordinary Python functions.No. StateGraph can orchestrate ordinary Python functions.
Can they work together?A runnable can perform a step such as structured extraction.A node can invoke that runnable and route from its result.

LangChain can also express branches and its higher-level agents are built on LangGraph. The contrast here is about which abstraction you reach for first. A fixed, two-step transform reads well as a chain. A loop with explicit business outcomes reads well as a graph. If the production rule remains a lone two-attempt loop, plain Python is also a reasonable choice.

How does the ticket move through the graph?

Support ticket routing flowchart

Client → ASP.NET Core → HTTP → Python FastAPI → check service

  • OK → resolved → end.
  • Temporary failure and one attempt left → check service again.
  • Missing service or attempt budget exhausted → escalated → end.

check increments attempts before route runs. Each node returns a partial state update. The router reads the updated state and its return type lists possible destinations. Both terminal nodes are connected to END. There is no checkpointer in this synchronous example. A second request starts a new graph invocation.

Build and test the Python worker

Use Python 3.12 and the pinned packages below. Put worker.py and requirements.txt together. The fixture is deterministic and requires no model account, credentials, or external service. The scenario field exists to drive the lab’s fake backend.

requirements.txt
langgraph==1.2.22
langchain-core==1.8.3
fastapi==0.115.12
uvicorn==0.34.2
worker.py
from typing import Literal, TypedDict

from fastapi import FastAPI
from langchain_core.runnables import RunnableLambda
from langgraph.graph import END, START, StateGraph
from pydantic import BaseModel

Scenario = Literal["healthy", "recovers", "offline", "unknown"]
Reading = Literal["ok", "temporary", "missing"]
MAX_ATTEMPTS = 2

class Ticket(BaseModel):
    scenario: Scenario

class State(TypedDict):
    scenario: Scenario
    attempts: int
    reading: Reading
    status: str

def probe(scenario: Scenario, attempt: int) -> Reading:
    if scenario == "unknown":
        return "missing"
    if scenario == "offline" or (scenario == "recovers" and attempt == 1):
        return "temporary"
    return "ok"

# LangChain composition: exactly one read, then format the result.
one_pass = (
    RunnableLambda(lambda scenario: probe(scenario, 1))
    | RunnableLambda(lambda reading: {"firstReading": reading})
)

def check(state: State) -> dict:
    attempt = state["attempts"] + 1
    return {"attempts": attempt, "reading": probe(state["scenario"], attempt)}

def route(state: State) -> Literal["resolved", "check", "escalated"]:
    if state["reading"] == "ok":
        return "resolved"
    if state["reading"] == "temporary" and state["attempts"] < MAX_ATTEMPTS:
        return "check"
    return "escalated"

def resolved(_: State) -> dict:
    return {"status": "resolved"}

def escalated(_: State) -> dict:
    return {"status": "escalated"}

builder = StateGraph(State)
builder.add_node("check", check)
builder.add_node("resolved", resolved)
builder.add_node("escalated", escalated)
builder.add_edge(START, "check")
builder.add_conditional_edges("check", route)
builder.add_edge("resolved", END)
builder.add_edge("escalated", END)
graph = builder.compile()

app = FastAPI()

@app.post("/triage")
def triage(ticket: Ticket):
    result = graph.invoke({
        "scenario": ticket.scenario, "attempts": 0,
        "reading": "missing", "status": "pending",
    })
    return {"status": result["status"], "attempts": result["attempts"]}

if __name__ == "__main__":
    assert one_pass.invoke("recovers") == {"firstReading": "temporary"}
    for scenario, expected in [
        ("healthy", ("resolved", 1)),
        ("recovers", ("resolved", 2)),
        ("offline", ("escalated", 2)),
        ("unknown", ("escalated", 1)),
    ]:
        result = triage(Ticket(scenario=scenario))
        assert (result["status"], result["attempts"]) == expected, result
    print("5 checks passed")

Windows PowerShell

Windows PowerShell
py -3 -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements.txt
.\.venv\Scripts\python.exe .\worker.py
.\.venv\Scripts\python.exe -m uvicorn worker:app --host 127.0.0.1 --port 8000

macOS or Linux

Terminal
python3 -m venv .venv
.venv/bin/python -m pip install -r requirements.txt
.venv/bin/python worker.py
.venv/bin/python -m uvicorn worker:app --host 127.0.0.1 --port 8000

Call the workflow from ASP.NET Core 10

Open a second terminal. Create a minimal project with dotnet new web -n TriageGateway -f net10.0, then replace TriageGateway/Program.cs with the code below. The two HTTP addresses assume both processes run on the same machine. If you containerize them later, configure the worker’s address to use its internal service name because 127.0.0.1 would point back to the gateway container.

Program.cs
using System.Net.Http.Json;
using System.Text.Json;

var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(options =>
    options.Limits.MaxRequestBodySize = 4096);

builder.Services.AddHttpClient<TriageClient>(client =>
{
    client.BaseAddress = new Uri("http://127.0.0.1:8000/");
    client.Timeout = TimeSpan.FromSeconds(5);
    client.MaxResponseContentBufferSize = 8192;
});
var app = builder.Build();

app.MapPost("/api/triage", async (Ticket ticket, TriageClient worker,
    HttpContext http, CancellationToken cancellationToken) =>
{
    if (ticket.Scenario is not ("healthy" or "recovers" or "offline" or "unknown"))
        return Results.BadRequest(new { code = "invalid_scenario" });

    try
    {
        var result = await worker.Run(ticket, cancellationToken);
        return Results.Ok(new {
            result.Status, result.Attempts, traceId = http.TraceIdentifier
        });
    }
    catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
    {
        return Results.Json(new { code = "worker_timeout",
            traceId = http.TraceIdentifier }, statusCode: 504);
    }
    catch (Exception error) when (error is HttpRequestException or JsonException or InvalidDataException)
    {
        return Results.Json(new { code = "worker_unavailable",
            traceId = http.TraceIdentifier }, statusCode: 502);
    }
});

app.Run();

sealed record Ticket(string? Scenario);
sealed record Outcome(string? Status, int Attempts);

sealed class TriageClient(HttpClient client)
{
    public async Task<Outcome> Run(Ticket ticket, CancellationToken cancellationToken)
    {
        using var response = await client.PostAsJsonAsync("triage", ticket, cancellationToken);
        response.EnsureSuccessStatusCode();
        var result = await response.Content.ReadFromJsonAsync<Outcome>(
            cancellationToken: cancellationToken);
        if (result is null || result.Status is not ("resolved" or "escalated")
            || result.Attempts is < 1 or > 2)
            throw new InvalidDataException("Invalid worker response.");
        return result;
    }
}
PowerShell · run and call the gateway
dotnet run --project ./TriageGateway --no-launch-profile -- --urls http://127.0.0.1:5080
# In a separate PowerShell window:
$body = @{ scenario = 'recovers' } | ConvertTo-Json
Invoke-RestMethod -Uri http://127.0.0.1:5080/api/triage `
  -Method Post -ContentType 'application/json' -Body $body

What should each test return?

InputWorker resultWhat it proves
healthyresolved, 1A good first read stops immediately.
recoversresolved, 2The graph retries once and reuses its attempt count.
offlineescalated, 2Two temporary failures consume the budget.
unknownescalated, 1A missing service skips the retry.
otherHTTP 422 from FastAPIThe worker rejects a value outside the contract.

On Python 3.12, the script passed five assertions, including the one-pass LangChain result. Five additional FastAPI TestClient checks passed across the four routes and invalid input. The .NET SDK was unavailable in the verification environment, so the gateway was reviewed but not executed. Its expected result for recovers is HTTP 200 with status: resolved, attempts: 2, and a gateway trace ID.

Troubleshoot and prepare for production

SymptomFirst checkFix
Gateway returns 502Is Uvicorn listening on port 8000?Run the Python worker and confirm the gateway URI.
Gateway returns 504Is the worker finishing inside the five-second HTTP budget?Set a smaller deadline per dependency call and keep total attempts bounded.
Unknown service is retriedDoes the router classify a missing record separately?Escalate known permanent outcomes on the first attempt.
Duplicate tickets appear after retryIs the retried node writing to a queue?Use an idempotency key or transactional outbox for real enqueue operations.

Here “escalated” is a result for the caller. The example doesn’t write a support ticket. In production, keep the retry around read-only checks where possible. Real network retries need a total deadline and usually backoff. If you also retry at the HTTP gateway, count the combined attempts across both layers. Map worker connection faults to 502 and timeouts to 504. A completed escalation still returns 200 because the workflow reached a valid outcome. For multi-request workflows, add persistence and handle state ownership separately.

Frequently asked questions

Can I use LangGraph without LangChain?

You can write application nodes as plain Python functions without creating a LangChain chain or agent. LangGraph itself uses packages from the LangChain ecosystem.

Can a LangGraph node run a LangChain runnable?

Yes. For example, run a structured extraction step inside a node, validate the returned fields, then let the graph decide whether to retry or escalate. Keep deterministic business rules in application code.

Does running two attempts require a checkpointer?

No. Both attempts happen within a single invocation in this example. A checkpointer is relevant when you need persisted state for features such as resuming a workflow across requests.

How does this relate to the ASP.NET PB RAG tutorials?

Both patterns keep Python behind an ASP.NET Core boundary. In the citation verification tutorial, the worker returns evidence to validate. Here, the worker returns a routing outcome. For workflow pauses across requests, see the LangGraph approval and checkpoint walkthrough.

Official documentation and GitHub source

Comments