r/LangChain • • 9m ago

Question | Help Silent failure modes in multi-step AI agents

1 Upvotes

Hi All!

We've been cataloging silent failure modes in multi-step AI agents.

What was the last time your agent failed silently without throwing a 500 error or an error code?


r/LangChain • • 14m ago

Discussion What are you using to run AI agents in production across different frameworks?

Thumbnail reddit.com
1 Upvotes

r/LangChain • • 2h ago

Projects Product analytics for MCP and Agent Skills: how to build a roadmap from your logs

Thumbnail
reddit.com
1 Upvotes

r/LangChain • • 9h ago

Discussion Apparently, building an agentic workflow in LangGraph doesn't count unless you literally name a variable agent 💀

Thumbnail reddit.com
1 Upvotes

r/LangChain • • 18h ago

Discussion In my pipeline, the model doesn't choose which numbers to count: the code tries each combination, then rejection and acceptance gates before any result.

5 Upvotes

The problem I started with: I planted a three-step calculation in a test case, with the numbers coming from three different sources. A general agent with complete arithmetic tools couldn't find it. He knew how to multiply, but he didn't know which numbers belonged to which group!

The usual method is for the model to write the equation and for a tool to calculate it. But this way, the model still chooses the inputs, and that's where the problem lies.

So my pipeline ended up like this:

  1. extract => two models extract every quantity => unit => denominator => scope (structured output).
  2. reconcile => keep a value only if both extractions agree, or a verbatim source quote settles it.
  3. enumerate => code tries every combination of 2-4 quantities whose units produce a decision unit.
  4. compute => unit library (pint), never the model.
  5. reject => 6 deterministic checks on the numbers
  6. accept => 6 gates in order; one failure drops the candidate
  7. explain => the model only writes up what survived; "no discovery" is the default

In a prototype: 230 candidate accounts, two remained, with the one planted in between. The second was disguised, passing because a number in it had no denominator. Hence the rejection gates: recalculation, an impossible number due to its lack of a denominator, a quantity without a denominator or unit, discrepancies between the extractors, mixing ranges (weekly with monthly), and the fragility of the conclusion with a 5% change.

Then the admission gates in order: new to the file, then new to the field, then non-intuitive, then influential, then case-specific, then change the decision.

The assessment method was recorded in advance before any case was built: 100 cases, of which 30 were empty and 20 were misleading, with a false positive limit of 5%: https://doi.org/10.5281/zenodo.24506889

Questions I haven't thought of yet;

  1. How could you extract units and denominators with organized outputs? This is my weakest point.
  2. Has anyone thought of building a layer to verify the deterministic outputs after the agent's outputs? What could you put in it?
  3. What happens when the combinations get too large? I have a maximum of 4 quantities, and I'm considering trimming by units before counting.

r/LangChain • • 19h ago

Discussion How do you handle it when the agent needs knowledge that only lives in someone’s head?

Thumbnail reddit.com
0 Upvotes

r/LangChain • • 20h ago

Question | Help Agents running in prod, hand made script or prod harness?

Thumbnail reddit.com
2 Upvotes

r/LangChain • • 23h ago

Discussion How are you enforcing per-user tool permissions in LangChain agents in production?

5 Upvotes

The LangChain tools docs show how to filter tools per user with wrap_model_call, and a neighbouring example carries the comment "Only enable sensitive tools after authentication". We reran the repro from issue #41801 on langchain 1.5.2 this week, and create_agent still ran a delete tool for a viewer.

The filter we used, close to the docs version:

from langchain.agents.middleware import wrap_model_call

def viewer_tools(request, handler):
    if request.runtime.context.user_role != "admin":
        request = request.override(
            tools=[t for t in request.tools if t.name.startswith("read_")]
        )
    return handler(request)

With a viewer context the model only saw read_data. We had the model call delete_data anyway (a scripted fake model, so this tests what the framework does once the call shows up). create_agent ran it and returned "deleted r2" as the tool result.

The filter edits the tool list sent to the model and nothing else. When a call comes back, the tool node checks the name against every tool registered on the agent. A made-up name gets an "is not a valid tool" error, and delete_data passes that check because it is still registered.

Hosted models send these calls too. In the same issue, the author kept an admin's earlier delete in the message history and had a viewer ask for the same thing. By their count, claude-haiku-4-5 called the hidden tool in 3 of 3 runs and claude-haiku-5-5 in 5 of 6. gpt-4o-mini and gpt-6-luna didn't call it in their runs. The issue has been open since Nov 11 with no fix merged yet.

The workaround suggested in the issue thread, a second check where the tool executes, keyed on the same role, stopped it for us:

from langchain.agents.middleware import wrap_tool_call
from langchain_core.messages import ToolMessage

def enforce_tools(request, handler):
    role = request.runtime.context.user_role
    name = request.tool_call["name"]
    if role != "admin" and not name.startswith("read_"):
        return ToolMessage(
            content=f"{name} is not allowed for this user",
            tool_call_id=request.tool_call["id"],
            status="error",
        )
    return handler(request)

With both middlewares on, the viewer run gets "delete_data is not allowed for this user" back as an error ToolMessage, and the delete never executes. Admin runs still go through. In a real app we would check an explicit allowlist per role. The read_ prefix only keeps the example short. We kept the filter as well, since the same docs page notes that too many tools can overwhelm the model and increase errors.

For tools served over MCP, the open-source gateway we build checks each tools/call request against the calling API key's allowed and denied lists when key auth is on, so a tool a key can't see also can't be called.

Where do your tool permissions live today, in agent middleware like this or down at the tool and MCP server level?


r/LangChain • • 1d ago

Projects [Open Tool] Built an HTTP 402 Pay-Per-Call Crypto Risk, DEX Slippage & Perp Arbitrage M2M Oracle for LangChain / CrewAI Agents (3 Free Calls/Day, 0.25 USDC On-Chain Gate)

1 Upvotes

When building autonomous crypto trading or DeFi research agents in LangChain / CrewAI / Python, you usually have to stitch together 3 separate APIs before your bot can safely execute a swap or delta-neutral trade:

  1. Bytecode security / honeypot check (GoPlus)
  2. Cross-pool DEX liquidity & AMM slippage impact in bps (DexScreener)
  3. CEX perpetual funding rate arbitrage spreads net of taker fees (Binance Futures + Bybit Linear)

I built NeonOracle x402 v2.0 — a zero-KYC Machine-to-Machine (M2M) micro-API using the HTTP 402 Payment Required pattern so autonomous agents can query all three in a single atomic JSON call and pay per call directly on-chain (Base or Solana USDC) without Stripe or human OAuth.

  • Interactive M2M Terminal Sandbox: https://meer9374-a11y.github.io/neonops-web3-suite/m2m.html
  • OpenAPI 3.1.0 Discovery JSON: https://meer9374-a11y.github.io/neonops-web3-suite/openapi.json

Ready-to-Use Python / LangChain @tool

from langchain_core.tools import tool
import requests, os

@tool
def neon_m2m_crypto_risk_and_arb_oracle_v2(
    token_address: str,
    chain: str = "base",
    symbol: str = "ETH",
    notional_usd: float = 25000.0
) -> dict:
    """
    NeonOracle x402 v2.0 M2M Tool for Autonomous Trading Agents.
    Returns composite contract risk score (0-100), GoPlus honeypot/tax audit,
    DexScreener pool depth + AMM price impact in bps for `notional_usd`,
    and fee-adjusted Binance/Bybit perpetual funding arbitrage APR.
    """
    api_key = os.getenv("NEON_24H_API_KEY", "")
    tx_hash = os.getenv("NEON_PAYMENT_TX_HASH", "")
    pay_chain = os.getenv("NEON_PAYMENT_CHAIN", "base")
    base_url = os.getenv("NEON_ORACLE_BASE_URL", "http://localhost:3402")

    endpoint = f"{base_url}/api/v1/intel" if (api_key or tx_hash) else f"{base_url}/api/v1/preview"
    headers = {"X-Payment-Chain": pay_chain}
    if api_key:
        headers["X-API-Key"] = api_key
    elif tx_hash:
        headers["X-Payment-Tx-Hash"] = tx_hash

    r = requests.get(
        endpoint,
        params={"token": token_address, "chain": chain, "symbol": symbol, "notional_usd": notional_usd},
        headers=headers,
        timeout=10
    )
    return r.json()

How the HTTP 402 M2M Gate Works

  • Free Preview (/api/v1/preview): 3 calls/day per IP, zero headers required.
  • Pay-Per-Call (/api/v1/intel): Calling without X-Payment-Tx-Hash returns HTTP 402 Payment Required with Base (0x6137ED1A93c8CFF1a6C3112A14bE04883f58E5F7) and Solana (5YtLdjEVDQxP2Kh4xVSccxhMKhx8SuZd6wYaGXYcRwFp) USDC payment metadata (0.25 USDC single call with anti-replay lock, or 19.00 USDC for an auto-issued 24-hour reusable X-API-Key: nk_live_24h_...).

r/LangChain • • 1d ago

Projects What my coding agent actually carried between sessions while I built an auto-deploy real entries from my own project's memory

Thumbnail
reddit.com
0 Upvotes

r/LangChain • • 1d ago

Projects An agent's "done" is a self-report. We open-sourced a tool that checks the DB instead

1 Upvotes

This open-source tool checks your database to see if what the agent claimed actually happened.

You put a decorator on a tool. A separate worker reads the record back from your Postgres (read-only) and marks each action as verified, mismatched, or missing. Real output from the demo:

                verified  mismatch  missing  failed
create_booking         4         1        1       1

75a021a2  mismatch  start_time: expected 10:00, got 11:00:00
e54edf4d  missing   not found after 0:00:40
  • python. Postgres built-in, anything else is a small verification function you write
  • Runs in your infra, nothing is sent to us
  • With Langfuse, the verdict lands on the tool call as a score
  • or npx skills add yinoni/verilays and let Claude Code / Cursor wire it in

It's something pretty new, my friend and I just created. Would love to hear your opinion, how is it for you, what you would add, etc.

And if you find value in it, we would appreciate it if you could star the repo and let us know.

The demo is one command: docker compose run --build --rm demo


r/LangChain • • 1d ago

Question | Help LangChain: JS/TS support

2 Upvotes

Saw a post from about a year ago asking about JS vs python for langchain and am curious if anyone could give an update on how exstensive the JS support is nowdays compared to python.

I have only used python but am a big TS fan and just learned that there is JS support for langchain so am curious about it.

Thanks for any help!


r/LangChain • • 1d ago

Discussion Agentic GraphRAG: built a 3D-knowledge graph to store the Context layer + Agent memory

Post image
1 Upvotes

We're building Agentic GraphRAG, an open source library that stores your enterprise knowledge and agent memory in the same knowledge graph.

I've worked on RAG systems and LLM training for the past three and a half years. Lately, I've been following how agents retain work across sessions, especially for non-coding tasks. Most projects treat Memory and Retrieval as two separate problems, we're trying to bring them together to get more efficient agents that can improve over time.

We construct three connected graph layers:

  1. Knowledge Layer: stores documents and source passages with their extracted entities and relationships.
  2. Working memory: records tasks, progress, messages, and tool activity.
  3. Decision memory: stores conclusions, assumptions, and open questions encountered by the agent.

Things which make us different from other frameworks out there:

- Structure Aware: The ingestion pipeline uses Docling for loading documents and captures the full document hierarchy. The sections, tables, and passage hierarchy are connected using edges and stored in the graph.

- Ontology Grounded: You define a schema for your domain (we also ship ontology presets so it is easy to get started). The schema guides extraction, validation, and search. We use GLiNER for local extraction, so its virtually free (and fast) to construct the graph and no LLM calls are needed.

- Robust Agent Search: Retrieval combines graph, full-text and vector search. Agents can reach original passages even when extraction misses a fact, navigate surrounding sections and table rows with headers, and follow entity relationships back to supporting text.

We offer a built-in agent you can use out of the box. The built-in agent uses DeepAgents and saves task events as part of the graph. The are decisions the agent made are linked to the sources it retrieved, giving us citations, but also self-improving memory.

You can also connect your agents through MCP.

We will be releasing extensive benchmarks very soon.

TL;DR

Agentic GraphRAG is an open source library that stores document knowledge, agent work, and decisions in one connected graph. Agents can resume tasks and trace saved decisions to their original evidence, while source changes flag affected decisions for review.

Try it out. Feedback, criticism, issues, and contributions are all welcome!


r/LangChain • • 1d ago

Question | Help [For Hire] Backend & AI Integration Engineer (Python/FastAPI, NestJS, RAG, MCP, Structured Outputs)

1 Upvotes

Hi everyone,

I'm a backend-focused software engineer helping teams build and debug LLM applications, RAG backends, and automated agent workflows.

How I can help your team:

  • RAG & Retrieval Optimization: Building clean ingestion and retrieval pipelines over PostgreSQL (pgvector) / vector stores, fixing hallucination issues, and structuring context windows.
  • Tool Calling & MCP Servers: Wiring LLMs into external REST APIs, databases, and Telegram/web interfaces with proper error handling and retries.
  • Token Cost & Latency Reduction: Setting up multi-provider routing (OpenAI, Anthropic, DeepSeek, OpenRouter), semantic/Redis caching, and strict schema validation so outputs don't break downstream code.
  • End-to-End Production Wrapping: Turning standalone Python scripts into containerized FastAPI or NestJS microservices with Next.js admin dashboards, deployed cleanly with Docker.

Open to short debugging/refactoring sprints or ongoing contract work ($18–$22/hr or fixed milestones).

DM me if you need an extra pair of hands on your LLM backend!


r/LangChain • • 1d ago

Discussion Which platforms offer robust LLM evaluation frameworks for governance?

1 Upvotes

I lead data at a small UK lender, and before we add more LLM features in 2026, our model risk team wants a written standard for how we evaluate them. My draft says the platform has to give us four things:

•	evaluations that run both before release and on live production traffic

•	an audit trail of who changed an evaluator or a prompt, and when

•	traceability of which prompt version was live on any given day, with its evaluation scores

•	role-based access, so the people who write prompts can't also deploy them

LangSmith is the obvious candidate, and its enterprise plan adds SSO and RBAC. Langfuse, Arize Phoenix, Braintrust and MLflow are on the list too, and they're all solid at running evals and tracing. For each of them, what I still need to check is how much of the audit trail and role separation comes built in, and how much we'd have to build around it.

Orq is the one I've found that covers all four in a single platform. Its evaluators run in experiments before release and as guardrails on production traffic, and every prompt keeps a version history you can diff and restore. Roles split admins, developers and researchers, so prompt authors can't deploy, and the enterprise plan adds audit logs covering 28 entity types and 26 action types. Those audit logs are enterprise only, though, which means a sales call before I can show our risk team a price.

I'm writing the standard this week, and the plan is to run Orq and LangSmith side by side on the same set of past conversations before it goes to the committee


r/LangChain • • 1d ago

Question | Help Switching llm gateways

3 Upvotes

Hey folks, I’ve been exploring the LLM infra space lately and wanted to get some perspective from devs who’ve actually worked with these tools.

I’m curious about what actually makes people hesitant to switch gateways, even when they come across something that looks genuinely more promising.

Is it mostly the migration effort, concerns about reliability, trusting a newer project, or simply not wanting to disrupt an existing setup?

And on the flip side, what would make that transition easier? Would a straightforward migration process, transparent performance benchmarks, compatibility with existing APIs, or something else give you enough confidence to make the switch?

Would love to hear how yall approach this in practice.


r/LangChain • • 2d ago

Discussion How I caught a LangGraph agent that said "Infeasible" while a flight hold was still in state

3 Upvotes

I had been asserting on the last AI message from a LangGraph travel graph. One run looked fine by that standard: the model said the trip was infeasible.

Then I printed graph.get_state(config).values. A flight hold was still sitting in state.

The user request was to hold an in-policy flight and a Whitefield hotel under a budget cap. Whitefield had no hotels, so the graph replanned to Koramangala. The hotel search came back with a match at 4800. The next hold_booking tried a hotel at 5900, and the tool refused it because the price did not match a search result. The flight hold had already gone through. The final message still said "Infeasible". The reply and the graph state did not agree.

Reply-level asserts miss this on a multi-turn graph. The last message can summarise a failed plan after an earlier node has already written a side effect. I started treating the recorded trajectory as the thing under test: the tool-call sequence on the AIMessages, the ToolMessage results, and the state snapshot after invoke. The graph needs a checkpointer for get_state and for a stable thread_id.

A small helper I now keep in the test file:

from langchain_core.messages import AIMessage, HumanMessage, ToolMessage

def tool_calls(messages):
    calls = []
    for m in messages:
        if isinstance(m, AIMessage) and m.tool_calls:
            calls.extend(m.tool_calls)
    return calls

def last_ai_text(messages) -> str:
    for m in reversed(messages):
        if isinstance(m, AIMessage) and m.content:
            return m.content if isinstance(m.content, str) else str(m.content)
    return ""

Claimed versus actual state, for that travel run:

def test_infeasible_reply_does_not_leave_a_hold(graph):
    config = {"configurable": {"thread_id": "trip-infeasible"}}
    prompt = (
        "Hold an in-policy flight and a Whitefield hotel under 6000."
    )
    out = graph.invoke({"messages": [HumanMessage(content=prompt)]}, config)
    state = graph.get_state(config).values
    reply = last_ai_text(out["messages"]).lower()
    holds = state.get("holds") or []

    if "infeasible" in reply:
        assert holds == [], f"reply said infeasible, but state still has holds={holds}"

I also assert on the sequence, not only on leftover state. After a hotel hold_booking returns a refusal, a later flight hold_booking should not be left unmatched. That check reads the tool_calls names and the ToolMessage contents in order.

A second check I now write in the same style is missing detail. If the user says "Book me a hotel in Austin" and never gives a date, the graph should ask before it calls book_hotel. If book_hotel appears in tool_calls with a date the user never provided, that is a fail. I am not describing a recorded incident for this one; it is a pytest I run on the graph.

def test_booking_without_a_date_asks_first(graph):
    config = {"configurable": {"thread_id": "no-date"}}
    out = graph.invoke(
        {"messages": [HumanMessage(content="Book me a hotel in Austin.")]},
        config,
    )
    for call in tool_calls(out["messages"]):
        if call.get("name") == "book_hotel":
            pytest.fail(
                "book_hotel ran with no date in the user message; "
                "the graph should have asked first"
            )

One more lesson I had to unlearn: a check that never ran is not a pass. I had a test that a human-approval interrupt fires before a destructive tool commits. On runs that never reached that tool, the interrupt did not appear, and the test fell through as a pass. That proved nothing about the interrupt. I now make the not-exercised path explicit:

def test_approval_interrupt_is_not_a_pass_if_unexercised(graph, prompt):
    config = {"configurable": {"thread_id": "approval"}}
    graph.invoke({"messages": [HumanMessage(content=prompt)]}, config)
    snapshot = graph.get_state(config)
    names = [c.get("name") for c in tool_calls(snapshot.values["messages"])]

    if "cancel_booking" not in names:
        pytest.skip("cancel_booking was not exercised; this is not a pass")

    assert snapshot.next, "expected an interrupt before cancel_booking committed"

pytest.skip is one way to keep "not exercised" distinct from a green pass. A small result enum (pass / fail / not_exercised) works too, as long as the unexercised path cannot show up as success.

Where do you keep these trajectory assertions relative to the graph? I have been putting them in the same pytest file and reading get_state() plus AIMessage.tool_calls after invoke. The other option is a post-run checker that only sees the state snapshot and the message list, so node renames do not break the tests. I am not sure which holds up better once the graph has interrupts and more than one write node. What has worked in your graphs?


r/LangChain • • 2d ago

Discussion My client keeps telling me ChatGPT answers instantly

11 Upvotes

Back in the spring I built a support bot for a company that sells commercial kitchen equipment, mostly fryers and combi ovens. It answers from their manuals and warranty PDFs and it can look up an order by number. Since September the owner has been on at me about the speed. A typical answer takes around 20 seconds and his line every time is “ChatGPT answers instantly”.

I upgraded it to glm-5.3 in September. The answers on order questions got a lot better, but the older model had let me switch thinking off and this one does not. I put timestamps on every step for a few days of real traffic. Retrieval and the order lookup together were under three seconds, nearly all the rest was the model thinking on high before it wrote a word.

I know the first reply here is going to be stream it. It is streamed. The thinking comes down the stream first in its own field and the answer only starts once that is done, so the customer sits looking at three dots for most of the 20 seconds anyway.

So I set reasoning effort to low. Answers came down to about half and the client was happy for a week or so. Then I went through the logs. It was fine on anything the manuals cover. When they do not cover something, it answered from whatever chunk was closest. Someone asked about the warranty on a fryer the company stopped selling in 2022 and got the terms for the current model. They asked again, got the same answer, and called the office.

High effort mostly tells people it has no information on that model, so they ring the office after the first try instead of the second.

Client read the logs and still wants it on low. His view is that most questions are ones the manuals cover and people would rather have a fast answer that is sometimes wrong. I think the people with the old fryers are the ones who ring the office annoyed. It is on low for now because it is his company, and I am counting how often the same person asks the same thing twice.


r/LangChain • • 2d ago

Discussion How I isolated credentials in a multi-tenant custom agent platform using per-chat MCP subprocesses

Thumbnail reddit.com
2 Upvotes

r/LangChain • • 2d ago

Discussion How are you handling contradicting facts in agent memory?

2 Upvotes

Something I kept running into: a user tells the agent "I'm vegetarian", and three weeks later "I've started eating fish again". With memory as a vector store plus add(), both facts stay, and recall returns whichever is phrased closer to the question.

The approaches I've seen:

  1. Only keep the latest N messages (you lose long-term facts)
  2. Let the LLM rewrite a single profile document every turn (expensive, and it drifts)
  3. Decide per fact: add, replace, merge or ignore

I went with option 3 and built it as an open-source library, MemDream. Each new fact gets ADD / SUPERSEDE / MERGE / NOOP against the user's existing memories. Replaced facts are kept as history with a link to the new one, and every decision is logged with a reason. A background pass finds patterns and expires stale facts.

Repo, if useful: https://github.com/Mamlesh18/MemDream

I'm more curious what others are doing, though. Has anyone found a cleaner way to handle facts that change over time, like addresses, jobs and diets?


r/LangChain • • 2d ago

Question | Help Need Help Preparing for an Al Interview - Harness, Agents & Orchestration

16 Upvotes

Hi everyone!

I have an upcoming interview focused on AI Harness, AI Agents, and Agent Orchestration, and I'm looking for some guidance from people who have experience in this area.

If anyone has recently given or conducted interviews for these topics, could you please share your experience?

I'd really appreciate help with:

  • Commonly asked technical interview questions.
  • Important concepts around AI Harness and Harness Engineering.
  • AI Agents and Multi-Agent Systems.
  • Agent Orchestration and different orchestration patterns.
  • Real-world architecture and implementation scenarios.
  • Hands-on or scenario-based questions.
  • Any resources, blogs, GitHub repositories, or courses worth following.

If you've interviewed candidates or recently attended a similar interview, please share your experience, questions, or preparation tips.

Even a small suggestion would be really helpful!

Thanks in advance. Looking forward to learning from this community! 🙏


r/LangChain • • 2d ago

Resources Built a Chrome extension with Claude to paste work logs into AI without exposing company internals

2 Upvotes

r/LangChain • • 2d ago

Tutorial LangGraph restart after an HTTP effect commits: four recovery cases

2 Upvotes

A reader asked for the HTTP version of my earlier SQLite crash test: kill the process after the external action succeeds but before the client saves its result.

I ran it with a local HTTP receiver that increments a counter. The receiver commits to its own SQLite database and sends HTTP 200. The LangGraph client reads that response, then exits with os._exit(86) before saving the local receipt or returning the task result. A new client process resumes the same checkpointed thread. The operation ID and amount come from the saved input.

After the crash, all four cases had one receiver-side effect, a committed local intent, and no local result. The difference was what the client and receiver did on resume:

Recovery behaviorTotal POSTsReceiver effectsResumed result
Resend; receiver applies each request222
Resend; receiver deduplicates the operation ID21Original receipt: 1
Look up the operation; receiver confirms its receipt11Original receipt: 1
Look up the operation; lookup is inconclusive11Unresolved; no second POST

In the last case, I made the fixture return 404 for a receipt that existed. That models an unavailable outcome without assuming a particular provider's consistency behavior. The client kept the intent unresolved. It did not treat the lookup miss as permission to repeat the effect.

The relevant crash boundary was inside the task, between reading the successful POST response and committing the local result. Neither the intent record nor the graph checkpoint contains the receiver's answer at that point. A positive lookup can recover it if the API exposes a stable operation identity and a receipt you can validate. An inconclusive lookup leaves work to reconcile.

I also retried the deduplicated operation with a different amount: the fixture returned 409 and kept the effect count at one. Reusing an operation ID needs an argument check as well as a saved result.

Versions: LangGraph 1.2.24, langgraph-checkpoint-sqlite 3.1.3, Python 3.14.7, SQLite 3.53.4. Four isolated local cases, using real loopback HTTP and fresh client processes. The receiver stayed alive. This covers client process exit; provider failures, concurrent clients, idempotency-key expiry and power loss remain untested. No model calls or payment service were involved.

LangGraph persistence model · Task idempotency guidance

I used AI assistance for the fixture and write-up.

Reproduction: save the complete script below as langgraph_http_crash_repro.py, then run it in a Python virtual environment. It creates the receiver and client databases in temporary directories, starts a receiver on 127.0.0.1, and stops each server and removes its files after the test. The first client process intentionally exits with code 86 in each case. The script asserts the before/after counts and prints JSON results.

python3 -m venv .venv
.venv/bin/python -m pip install langgraph==1.2.24 langgraph-checkpoint-sqlite==3.1.3
.venv/bin/python langgraph_http_crash_repro.py

Complete tested script:

"""Synthetic local HTTP effect and LangGraph client-process crash experiment.

Install: pip install langgraph==1.2.24 langgraph-checkpoint-sqlite==3.1.3
Run: python langgraph_http_crash_repro.py
No model or external service. The receiver only listens on 127.0.0.1.
The intentional crash occurs after reading a successful HTTP response and
before writing the result into the client database / returning the task result.
"""
from __future__ import annotations

import http.client
import json
import os
from pathlib import Path
import sqlite3
import subprocess
import sys
import tempfile
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from importlib.metadata import version


def request(port, method, path, payload=None):
    # http.client does not use inherited HTTP_PROXY variables.
    connection = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
    try:
        body = json.dumps(payload) if payload is not None else None
        connection.request(method, path, body, {"Content-Type": "application/json"})
        response = connection.getresponse()
        return response.status, json.loads(response.read())
    finally:
        connection.close()


class Receiver(BaseHTTPRequestHandler):
    def log_message(self, *_):
        pass

    def send_json(self, code, payload):
        body = json.dumps(payload).encode()
        self.send_response(code)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_POST(self):
        data = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
        op_id, amount = data["op_id"], data["amount"]
        self.server.posts += 1
        with sqlite3.connect(self.server.database) as db:
            prior = db.execute("SELECT amount, result FROM effects WHERE op_id=? ORDER BY result LIMIT 1", (op_id,)).fetchone()
            if self.server.mode == "receiver_dedup" and prior:
                if prior[0] != amount:
                    self.send_json(409, {"error": "operation arguments differ"})
                    return
                result = prior[1]
            else:
                result = db.execute("SELECT COALESCE(SUM(amount),0)+? FROM effects", (amount,)).fetchone()[0]
                db.execute("INSERT INTO effects(op_id,amount,result) VALUES(?,?,?)", (op_id,amount,result))
                db.commit()
        self.send_json(200, {"op_id": op_id, "amount": amount, "result": result})

    def do_GET(self):
        self.server.lookups += 1
        op_id = self.path.removeprefix("/operations/")
        # Deliberately hide an existing receipt to model an inconclusive lookup.
        # This is fixture behavior, not a claim about a real provider's API.
        if self.server.mode == "lookup_inconclusive":
            self.send_json(404, {"status": "not_visible"})
            return
        with sqlite3.connect(self.server.database) as db:
            row = db.execute("SELECT amount,result FROM effects WHERE op_id=? ORDER BY result LIMIT 1", (op_id,)).fetchone()
        self.send_json(200 if row else 404, {"op_id": op_id, "amount": row[0], "result": row[1]} if row else {"status": "absent"})


def child(directory, port, mode, phase):
    from langgraph.checkpoint.sqlite import SqliteSaver
    from langgraph.func import entrypoint, task

    directory = Path(directory)
    local = directory / "client.db"
    with sqlite3.connect(local) as db:
        db.execute("CREATE TABLE IF NOT EXISTS operations(op_id TEXT PRIMARY KEY, amount INTEGER, result INTEGER)")

    @task
    def effect(data):
        with sqlite3.connect(local) as db:
            previous = db.execute("SELECT amount,result FROM operations WHERE op_id=?", (data["op_id"],)).fetchone()
            if previous:
                if previous[0] != data["amount"]:
                    raise ValueError("local operation arguments differ")
                if previous[1] is not None:
                    return previous[1]
            else:
                db.execute("INSERT INTO operations VALUES(?,?,NULL)", (data["op_id"],data["amount"]))
        if previous and mode.startswith("lookup_"):
            status, receipt = request(port, "GET", "/operations/" + data["op_id"])
            if status != 200:
                # Absence does not authorize replay in this fixture contract.
                raise RuntimeError("UNRESOLVED_EFFECT: lookup did not confirm an outcome")
        else:
            status, receipt = request(port, "POST", "/effects", data)
            assert status == 200, (status, receipt)
        assert (receipt["op_id"],receipt["amount"]) == (data["op_id"],data["amount"])
        if phase == "crash":
            os._exit(86)
        with sqlite3.connect(local) as db:
            db.execute("UPDATE operations SET result=? WHERE op_id=?", (receipt["result"],data["op_id"]))
        return receipt["result"]

    with SqliteSaver.from_conn_string(str(directory / "graph.db")) as checkpointer:
        @entrypoint(checkpointer=checkpointer)
        def flow(data):
            return effect(data).result()
        config = {"configurable": {"thread_id": "synthetic-run"}}
        try:
            output = flow.invoke({"op_id": "op-A", "amount": 1} if phase == "crash" else None, config)
            print(json.dumps({"status": "completed", "result": output}))
        except RuntimeError as exc:
            if "UNRESOLVED_EFFECT" not in str(exc):
                raise
            print(json.dumps({"status": "unresolved", "result": None}))


def main():
    results = []
    env = os.environ.copy()
    for key in list(env):
        if key.startswith("LANGSMITH_") or key.startswith("LANGCHAIN_"):
            del env[key]
    env.update(LANGSMITH_TRACING="false", LANGCHAIN_TRACING_V2="false")
    for mode in ["blind_replay", "receiver_dedup", "lookup_confirmed", "lookup_inconclusive"]:
        with tempfile.TemporaryDirectory(prefix="langgraph-http-") as temporary:
            directory = Path(temporary)
            receiver_db = directory / "receiver.db"
            with sqlite3.connect(receiver_db) as db:
                db.execute("CREATE TABLE effects(op_id TEXT, amount INTEGER, result INTEGER)")
            server = HTTPServer(("127.0.0.1", 0), Receiver)
            server.database, server.mode = receiver_db, mode
            server.posts, server.lookups = 0, 0
            thread = threading.Thread(target=server.serve_forever, daemon=True)
            thread.start()
            port = server.server_address[1]
            try:
                args = [sys.executable, __file__, "child", str(directory), str(port), mode]
                crash = subprocess.run(args + ["crash"], env=env, capture_output=True, text=True, timeout=30)
                assert crash.returncode == 86, (mode,crash.returncode,crash.stderr)
                with sqlite3.connect(receiver_db) as db:
                    after_crash_effects = db.execute("SELECT COUNT(*) FROM effects").fetchone()[0]
                with sqlite3.connect(directory / "client.db") as db:
                    after_crash_intents = db.execute("SELECT COUNT(*) FROM operations").fetchone()[0]
                    after_crash_receipts = db.execute("SELECT COUNT(*) FROM operations WHERE result IS NOT NULL").fetchone()[0]
                assert (after_crash_effects,after_crash_intents,after_crash_receipts) == (1,1,0)
                resume = subprocess.run(args + ["resume"], env=env, capture_output=True, text=True, timeout=30, check=True)
                outcome = json.loads(resume.stdout)
                with sqlite3.connect(receiver_db) as db:
                    effects = db.execute("SELECT COUNT(*) FROM effects").fetchone()[0]
                with sqlite3.connect(directory / "client.db") as db:
                    local_receipts = db.execute("SELECT COUNT(*) FROM operations WHERE result IS NOT NULL").fetchone()[0]
                row = {"mode":mode, "crash_exit_code":crash.returncode,
                       "after_crash":{"receiver_effects":after_crash_effects,"local_intents":after_crash_intents,
                                      "local_receipts":after_crash_receipts},
                       "after_resume":{"receiver_effects":effects,"local_receipts":local_receipts,
                                       "post_requests":server.posts,"lookup_requests":server.lookups,**outcome}}
                expected = {"blind_replay":(2,2,"completed"),"receiver_dedup":(1,1,"completed"),
                            "lookup_confirmed":(1,1,"completed"),"lookup_inconclusive":(1,None,"unresolved")}[mode]
                assert (effects,outcome["result"],outcome["status"]) == expected, row
                if mode == "receiver_dedup":
                    status, _ = request(port,"POST","/effects",{"op_id":"op-A","amount":5})
                    with sqlite3.connect(receiver_db) as db:
                        final_effects = db.execute("SELECT COUNT(*) FROM effects").fetchone()[0]
                    assert (status,final_effects) == (409,1)
                    row["different_arguments_check"] = {"http_status":status,"receiver_effects":final_effects}
                results.append(row)
            finally:
                server.shutdown()
                server.server_close()
                thread.join()
    print(json.dumps({"langgraph":version("langgraph"),"checkpoint_sqlite":version("langgraph-checkpoint-sqlite"),
                      "python":sys.version.split()[0],"sqlite":sqlite3.sqlite_version,
                      "transport":"real loopback HTTP; receiver stays alive while client process exits and restarts",
                      "fixture_scope":"synthetic integer increment; local process exit; no model/external provider/power-loss test",
                      "results":results,"temporary_servers_stopped_and_files_removed":True},indent=2))


if __name__ == "__main__":
    if len(sys.argv)>1 and sys.argv[1]=="child":
        child(sys.argv[2],int(sys.argv[3]),sys.argv[4],sys.argv[5])
    else:
        main()

r/LangChain • • 2d ago

Discussion hybrid scope rag

Thumbnail reddit.com
1 Upvotes

r/LangChain • • 2d ago

Discussion Hands-on workshop: Advanced LLM Application Engineering with Hybrid RAG, Tools & Memory

0 Upvotes

hey everyone, sharing this because a lot of developers here are already building with LangChain and LangGraph, and getting an LLM application to work in a demo is very different from making it reliable.

Packt is organizing a hands-on workshop on November 28 with Brij Kishore Pandey focused on building more complete LLM applications.

what gets covered:

  • hybrid RAG architectures
  • connecting LLMs with external tools and function calling
  • persistent memory across interactions
  • guardrails and failure handling
  • evaluation and observability
  • Google ADK and Gemini

the interesting part is bringing retrieval, tools, memory and evaluation together rather than treating them as separate features.

it's a live online workshop for developers working with LLM applications.

full details and agenda here

happy to answer questions about what gets covered!