Metadata-Version: 2.4
Name: langchain-xpenvo
Version: 0.1.0
Summary: Hard spending limits for LangChain and LangGraph agents: Xpenvo Agents middleware, model helpers, tool-cost charging and typed budget errors.
Author-email: Xpenvo <agents@xpenvo.com>
License-Expression: MIT
Project-URL: Homepage, https://agents.xpenvo.com
Project-URL: Documentation, https://agents.xpenvo.com/guides/langgraph-budget
Project-URL: Security, https://agents.xpenvo.com/security
Project-URL: Source, https://github.com/Joel-hub-dotcom/xpenvo-agents-sdk/tree/main/langchain
Project-URL: Issues, https://github.com/Joel-hub-dotcom/xpenvo-agents-sdk/issues
Project-URL: Changelog, https://github.com/Joel-hub-dotcom/xpenvo-agents-sdk/releases
Keywords: langchain,langgraph,agents,middleware,llm,budget,spending limit,cost,guardrails,xpenvo
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Operating System :: OS Independent
Classifier: Intended Audience :: Developers
Classifier: Topic :: Software Development :: Libraries
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: langchain-core<2,>=1.0
Requires-Dist: httpx<1,>=0.25
Requires-Dist: xpenvo<0.2,>=0.1.1
Provides-Extra: agents
Requires-Dist: langchain<2,>=1.0; extra == "agents"
Provides-Extra: openai
Requires-Dist: langchain-openai<2,>=1.0; extra == "openai"
Provides-Extra: anthropic
Requires-Dist: langchain-anthropic<2,>=1.0; extra == "anthropic"
Provides-Extra: all
Requires-Dist: langchain<2,>=1.0; extra == "all"
Requires-Dist: langchain-openai<2,>=1.0; extra == "all"
Requires-Dist: langchain-anthropic<2,>=1.0; extra == "all"
Provides-Extra: test
Requires-Dist: pytest>=8; extra == "test"
Requires-Dist: pytest-asyncio>=0.23; extra == "test"
Requires-Dist: langchain<2,>=1.0; extra == "test"
Requires-Dist: langchain-openai<2,>=1.0; extra == "test"
Requires-Dist: langchain-anthropic<2,>=1.0; extra == "test"
Dynamic: license-file

# langchain-xpenvo

Hard spending limits for LangChain and LangGraph agents.

[Xpenvo Agents](https://agents.xpenvo.com) 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

```bash
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](https://agents.xpenvo.com), create a budget (for example
$20 a day, $2 a run) and an agent key for it, then:

```bash
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

```python
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:

```python
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`

```python
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.

```python
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`

```python
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

```python
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

```python
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](https://github.com/Joel-hub-dotcom/xpenvo-agents-sdk/blob/main/SECURITY.md).

## Links

* Guide: <https://agents.xpenvo.com/guides/langgraph-budget>
* Docs: <https://agents.xpenvo.com/docs>
* Source: <https://github.com/Joel-hub-dotcom/xpenvo-agents-sdk/tree/main/langchain>

MIT licensed.
