Skip to main content

AgentBill LangChain Integration

Automatic usage tracking and billing for LangChain applications.

PyPI version License: MIT

Installation

Install via pip:

pip install agentbill-langchain

With OpenAI support:

pip install agentbill-langchain[openai]

With Anthropic support:

pip install agentbill-langchain[anthropic]

Quick Start

from agentbill_langchain import AgentBillCallback
from langchain_openai import ChatOpenAI
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate

# 1. Initialize AgentBill callback
callback = AgentBillCallback(
    api_key="agb_your_api_key_here",  # Get from AgentBill dashboard
    base_url="https://api.agentbill.io",
    customer_id="customer-123",
    debug=True
)

# 2. Create LangChain chain with callback
llm = ChatOpenAI(model="gpt-4o-mini")
prompt = PromptTemplate.from_template("Tell me a joke about {topic}")
chain = LLMChain(llm=llm, prompt=prompt)

# 3. Run - everything is auto-tracked!
result = chain.invoke(
    {"topic": "programming"},
    config={"callbacks": [callback]}
)

print(result["text"])

# ✅ Automatically captured:
# - Prompt text (hashed for privacy)
# - Model name (gpt-4o-mini)
# - Provider (openai)
# - Token usage (prompt + completion)
# - Latency (ms)
# - Costs (calculated automatically)

Features

  • ✅ Zero-config instrumentation - Just add the callback
  • ✅ Automatic token tracking - Captures all LLM calls
  • ✅ Multi-provider support - OpenAI, Anthropic, any LangChain LLM
  • ✅ Chain tracking - Tracks entire chain executions
  • ✅ Cost calculation - Auto-calculates costs per model
  • ✅ Prompt profitability - Compare costs vs revenue
  • ✅ OpenTelemetry compatible - Standard observability

Advanced Usage

Track Custom Revenue

# Track revenue for profitability analysis
callback.track_revenue(
    event_name="chat_completion",
    revenue=0.50,  # What you charged the customer
    metadata={"subscription_tier": "pro"}
)

Use with Agents

from langchain.agents import initialize_agent, load_tools

tools = load_tools(["serpapi", "llm-math"], llm=llm)
agent = initialize_agent(
    tools,
    llm,
    agent="zero-shot-react-description",
    callbacks=[callback]  # Add callback here
)

# All agent steps auto-tracked!
response = agent.run("What is 25% of 300?")

Use with Sequential Chains

from langchain.chains import SimpleSequentialChain

# All chain steps tracked automatically
overall_chain = SimpleSequentialChain(
    chains=[chain1, chain2, chain3],
    callbacks=[callback]
)

result = overall_chain.run(input_text)

Configuration

callback = AgentBillCallback(
    api_key="agb_...",           # Required - get from dashboard
    base_url="https://...",      # Required - your AgentBill instance
    customer_id="customer-123",  # Optional - for multi-tenant apps
    account_id="account-456",    # Optional - for account-level tracking
    debug=True,                  # Optional - enable debug logging
    batch_size=10,               # Optional - batch signals before sending
    flush_interval=5.0           # Optional - flush interval in seconds
)

How It Works

The callback hooks into LangChain's lifecycle:

  1. on_llm_start - Captures prompt, model, provider
  2. on_llm_end - Captures tokens, latency, response
  3. on_llm_error - Captures errors and retries
  4. on_chain_start - Tracks chain execution start
  5. on_chain_end - Tracks chain completion

All data is sent to AgentBill via the unified OTEL pipeline (otel-collector endpoint) with proper authentication.

Supported Models

Auto-cost calculation for:

  • OpenAI: GPT-4, GPT-4o, GPT-3.5-turbo, etc.
  • Anthropic: Claude 3.5 Sonnet, Claude 3 Opus, etc.
  • Any LangChain-compatible LLM

Troubleshooting

Not seeing data in dashboard?

  1. Check API key is correct
  2. Enable debug=True to see logs
  3. Verify base_url matches your instance
  4. Check network connectivity to AgentBill

Token counts are zero?

  • Some LLMs don't return token usage
  • Callback will estimate based on response length
  • OpenAI/Anthropic provide accurate counts

Idempotent Ingestion (X-Request-Id)

Every OTLP batch this SDK exports to /functions/v1/otel-collector carries an X-Request-Id: <uuid4> header (auto-generated per export, reused across transport-level retries within that export). The collector deduplicates on (company_id, request_id), so a transient 5xx / network retry will not double-write WAL rows, spans, or billing events.

  • No configuration required — the header is emitted automatically by the v7.x line of this SDK.
  • Server fallback: clients that cannot set custom headers may send {"requestId": "..."} at the JSON envelope root.
  • Native OTLP exporters: the standard OTLP-HTTP exporter keeps headers static across batches, so per-batch rotation is not yet wired on that path (PHASE3-R3-SDK-REQUESTID-NATIVE — tracked); the collector still dedupes those payloads on the natural key (company_id, trace_id, span_id).

See the OpenTelemetry Integration docs for the full request-id contract.

License

MIT

Metadata

Release files for agentbill-py-langchain 11.0.2

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

Source distribution (sdist)

Source distribution for agentbill-py-langchain 11.0.2
File Size Uploaded Provenance Actions
agentbill_py_langchain-11.0.2.tar.gz 25.3 kB Without provenance Details for agentbill_py_langchain-11.0.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for agentbill-py-langchain 11.0.2
File Interpreter ABI Platform Actions
agentbill_py_langchain-11.0.2-py3-none-any.whl Python 3 none any Details for agentbill_py_langchain-11.0.2-py3-none-any.whl

Total release size: 51.6 kB

Release files / agentbill_py_langchain-11.0.2.tar.gz

Download URL agentbill_py_langchain-11.0.2.tar.gz
Size 25.3 kB
Tags Source
SHA-256 checksum
How to use checksums
4d94136f8e8a3f23ca6672aa83532aa0c7e771167de10e0115ade13e925593fa
BLAKE2b-256 checksum
How to use checksums
23ee56bde49314ee46bea3192931d27389d2f200f5c3645f77d8ee59714cd9ad
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.15

Release files / agentbill_py_langchain-11.0.2-py3-none-any.whl

Download URL agentbill_py_langchain-11.0.2-py3-none-any.whl
Size 26.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
23492af97ca4d74606463b875687d480cac5346d70963e173c2c0da1cb5f0e68
BLAKE2b-256 checksum
How to use checksums
cafa3ee3994f15a403c2c5aba1cdb0b5f69ac75a43e4ea58153c818bc3818973
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.15

Security for agentbill-py-langchain 11.0.2

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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

11.0.2 This release

2 release files No 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