Skip to main content

langchain-xpenvo

Hard spending limits for LangChain and LangGraph agents.

Xpenvo Agents is a proxy that sits between your agent and the model provider. It checks every model call against your limits before the call is sent: per agent key, per run, per end customer, per hour and per request, plus a kill switch, loop pausing and approvals for big calls. This package plugs it into LangChain:

What For
chat_openai(), chat_anthropic(), xpenvo_kwargs() Chat models that send every call through Xpenvo
XpenvoMiddleware create_agent middleware: a run id per invocation, a cheaper model when money runs short, a clean stop (or typed error) when a limit is reached, waiting for approvals, and tool costs on the same budget
XpenvoToolSpendHandler A callback that charges tool costs anywhere LangChain runs tools (LangGraph ToolNode, chains, tool.invoke)
XpenvoBudgetExceededError, XpenvoStoppedError, ... and refusal_from() Typed errors that say why a call was refused

Your provider key stays yours: it goes on to the provider with each request and is never stored. Xpenvo never stores prompts or answers, and this package never sends them anywhere new.

Install

pip install "langchain-xpenvo[agents,openai]"      # or [agents,anthropic], or [all]

The base package needs only langchain-core. agents adds langchain (for XpenvoMiddleware); openai and anthropic add the provider packages.

Make a free account at agents.xpenvo.com, create a budget (for example $20 a day, $2 a run) and an agent key for it, then:

export XPENVO_KEY=xpv_...            # your agent key
export OPENAI_API_KEY=sk-...         # your own provider key, as usual

1. A chat model that goes through Xpenvo

from langchain_xpenvo import chat_openai, chat_anthropic, new_run_id

llm = chat_openai("gpt-5-mini", run=new_run_id(), customer="customer-42")
llm.invoke("Hello")

claude = chat_anthropic("claude-sonnet-5-5")

chat_openai(..., provider="gemini") (or "mistral", "openrouter") uses that provider's OpenAI-compatible API through Xpenvo; pass that provider's key as api_key=. Any other argument goes to ChatOpenAI / ChatAnthropic as usual. For other classes, or init_chat_model, use the keyword arguments directly:

from langchain.chat_models import init_chat_model
from langchain_xpenvo import xpenvo_kwargs

llm = init_chat_model("openai:gpt-5-mini", **xpenvo_kwargs("openai", customer="customer-42"))

Labels (run, step, customer) must be your own ids, never email addresses or other personal data. fallback_model="gpt-5-nano" lets Xpenvo itself switch to a cheaper model of the same provider when money runs short.

2. Middleware for create_agent

from langchain.agents import create_agent
from langchain_xpenvo import XpenvoMiddleware, chat_openai

agent = create_agent(
    chat_openai("gpt-5"),
    tools=[web_search],
    middleware=[
        XpenvoMiddleware(
            customer=lambda request: request.runtime.context.customer_id,  # your own id
            fallback_models=[chat_openai("gpt-5-mini")],  # tried when a call is refused for money
            switch_below_usd=1.00,                         # or switch early when under $1 is left
            tool_prices={"web_search": 0.005},             # tool costs count against the same budget
        )
    ],
)

result = agent.invoke({"messages": [("user", "Find three suppliers")]})

What it does:

  • A run id for every invocation. All model calls and tool charges of one invoke share it, so per-run limits work and the Runs tab shows each run step by step. Pass run= to set your own.
  • Fallback. When Xpenvo refuses a call because of money (over_budget, run_limit, request_limit, customer_limit, hourly_limit) or a model rule, the same request is tried on each fallback model in order. With switch_below_usd, it checks what is left first (a free call, cached for 5 seconds) and goes straight to the fallback.
  • A clean stop. If nothing fits, the agent ends with a short AIMessage such as Stopped by Xpenvo: This run reached its spending limit. The reason code is in message.response_metadata["xpenvo"]["code"]. Prefer an exception? on_stop="raise".
  • Approvals. With wait_for_approval=True, a call that needs a person's approval waits (up to approval_timeout seconds) and runs again once approved.
  • Tool costs. For each priced tool, the cost is checked and recorded before the tool runs. If it is refused, the tool does not run and the model gets an error ToolMessage saying why (or on_tool_refusal="raise"). If Xpenvo cannot be reached, priced tools do not run unless you set fail_open_tools=True.

Variable tool costs: hold the most it could cost, then charge the real amount.

from langchain_xpenvo import ToolPrice

XpenvoMiddleware(tool_prices={
    "browser": ToolPrice(max_usd=0.50, cost=lambda msg: msg.artifact["cost_usd"]),
})

A hold that is never closed (for example, the process crashed) is charged in full when it expires, so no spending goes unrecorded.

3. Tool costs outside create_agent

from langchain_xpenvo import XpenvoToolSpendHandler

spend = XpenvoToolSpendHandler({"web_search": 0.005}, run=run_id, customer="customer-42")
graph.invoke(inputs, config={"callbacks": [spend]})

The charge happens before the tool runs. If it is refused, the tool does not run and the typed error is raised.

4. Errors

from langchain_xpenvo import refusal_from, XpenvoBudgetExceededError

try:
    llm.invoke("Hello")
except Exception as e:
    r = refusal_from(e)          # None if Xpenvo did not refuse it
    if r is not None:
        print(r.code, r.reason)  # "run_limit", "This run reached its spending limit."
Error Codes
XpenvoBudgetExceededError over_budget, run_limit, customer_limit, hourly_limit, request_limit
XpenvoApprovalRequiredError approval_required, approval_pending, approval_denied, approval_limit (see .approval_id)
XpenvoStoppedError kill_switch, key_paused, budget_paused, loop_detected, spend_spike, billing_inactive
XpenvoPolicyError policy_model, policy_provider, policy_time, customer_required
XpenvoRateLimitError rate_limit
XpenvoUnavailableError Xpenvo could not be reached for a tool charge or status check

All inherit from XpenvoRefusedError (except XpenvoUnavailableError) and XpenvoError.

5. Checking and charging by hand

from langchain_xpenvo import XpenvoClient

x = XpenvoClient()                         # reads XPENVO_KEY
x.status()                                 # {"canSpend": True, "leftUsd": 14.2, "budgets": [...]}
x.spend("serpapi", usd=0.005)              # charge a known price, or raise
hold = x.spend("browser", max_usd=0.50)    # hold the most it could cost, then
x.settle(hold["id"], 0.12)                 # charge the real cost (or x.release(hold["id"]))

Every method has an async twin: astatus, aspend, asettle, arelease.

Security and privacy

  • The agent key is sent only to Xpenvo, and only over HTTPS. It is never printed in repr().
  • Your provider key is forwarded to the provider and never stored by Xpenvo.
  • Prompts, answers and tool inputs are never stored by Xpenvo and never sent anywhere new by this package. Tool charges send only a label (the tool name), the amount and your run, step and customer ids.
  • Labels that look like email addresses are rejected.
  • Releases are published from GitHub with PyPI trusted publishing and attestations; no tokens.

Report security issues to the address in SECURITY.md.

MIT licensed.

Metadata

Release files for langchain-xpenvo 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for langchain-xpenvo 0.1.0
File Size Uploaded Provenance Actions
langchain_xpenvo-0.1.0.tar.gz 26.2 kB With provenance Details for langchain_xpenvo-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for langchain-xpenvo 0.1.0
File Interpreter ABI Platform Actions
langchain_xpenvo-0.1.0-py3-none-any.whl Python 3 none any Details for langchain_xpenvo-0.1.0-py3-none-any.whl

Total release size: 48.1 kB

Release files / langchain_xpenvo-0.1.0.tar.gz

Download URL langchain_xpenvo-0.1.0.tar.gz
Size 26.2 kB
Tags Source
SHA-256 checksum
How to use checksums
433876007f54179340bc669c98410c3b5427878818e0c90a0ff4dd81aeae1205
BLAKE2b-256 checksum
How to use checksums
3e85100a914fda9c70bab73be185e0cb63d374edd8c7b70ddf1ddf5c8e7d11d5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

Release files / langchain_xpenvo-0.1.0-py3-none-any.whl

Download URL langchain_xpenvo-0.1.0-py3-none-any.whl
Size 21.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7141850228d95db463df46a7d9e70ad89e8b2e01242af461f603d0784ffbad99
BLAKE2b-256 checksum
How to use checksums
dfdde93e28b76fe0a7540099ee41348da4832a2e59058bafbf68ff360f00b2ae
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

Security for langchain-xpenvo 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for langchain_xpenvo-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page