r/LangChain • • 16h 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 • • 21h 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 • • 19h ago

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

Thumbnail reddit.com
2 Upvotes

r/LangChain • • 7h 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 • • 22h 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 • • 17h 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 • • 23h 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