Skip to main content

openai_cost_calculator_with_langchain

License

This is a package forked of the original openai_cost_calculator, which integrates support for Langchain.

Instant, accurate USD cost estimates for OpenAI & Azure OpenAI API calls. Works with Chat Completions and the Responses API, streaming or not. It also works with Langchain invoke responses. Offers a typed Decimal-based API for finance-safe math and a legacy string API for drop-ins.

Docs: https://orkunkinay.github.io/openai_cost_calculator/


Installation

pip install openai-cost-calculator-with-langchain

Import name uses underscores: import openai_cost_calculator-with-langchain


Quickstart

Typed (recommended)

from openai import OpenAI
from openai_cost_calculator import estimate_cost_typed

client = OpenAI()
resp = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "Hi there!"}],
)

cost = estimate_cost_typed(resp)  # -> CostBreakdown (Decimal fields)
print(cost.total_cost)            # Decimal('0.00000750')
print(cost.as_dict(stringify=True))  # 8-dp strings if you prefer

Legacy (string output)

from openai_cost_calculator import estimate_cost
print(estimate_cost(resp))  # dict of 8-dp strings

Responses API

resp = client.responses.create(model="gpt-4.1-mini", input=[{"role":"user","content":"Hi"}])
from openai_cost_calculator import estimate_cost_typed
print(estimate_cost_typed(resp))

Streaming

stream = client.chat.completions.create(
  model="gpt-4o-mini",
  messages=[{"role":"user","content":"Hi"}],
  stream=True,
  stream_options={"include_usage": True},
)
from openai_cost_calculator import estimate_cost_typed
print(estimate_cost_typed(stream))

Langchain

import os
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from openai_cost_calculator import estimate_cost_typed

load_dotenv()

model = ChatOpenAI(
    api_key=os.getenv("OPENAI_API_KEY"),
    model="gpt-4o-mini",
    temperature=0,
    max_tokens=None,
    timeout=None,
    max_retries=2,
)

messages = [
    (
        "system",
        "You are a helpful translator. Translate the user sentence to French.",
    ),
    ("human", "I love programming."),
]

response = model.invoke(messages)
print(estimate_cost_typed(response, is_langchain_response=True))

Highlights

  • Typed API: CostBreakdown dataclass with Decimal precision
  • Drop-in legacy API: 8-decimal strings (backward compatible)
  • Handles edge cases: cached tokens, undated model strings, streaming generators, Azure deployment names
  • Pricing sources: Remote CSV (24h cache) + local overrides and offline mode

Pricing utilities

from openai_cost_calculator import (
  refresh_pricing, set_offline_mode,
  add_pricing_entry, add_pricing_entries, clear_local_pricing
)

# Force refresh (bypasses 24h cache)
refresh_pricing()

# Run fully offline (no network calls)
set_offline_mode(True)

# Teach custom prices (per 1M tokens)
add_pricing_entry(
  "ollama/qwen3:30b", "2025-08-01",
  input_price=0.20, output_price=0.60, cached_input_price=0.04
)

Remote CSV (auto-fetched, cached 24h):
https://raw.githubusercontent.com/orkunkinay/openai_cost_calculator/refs/heads/main/data/gpt_pricing_data.csv


Errors

Recoverable issues raise CostEstimateError with a clear message (missing pricing row, unexpected input shape, etc.).


Troubleshooting

  • “Pricing not found” → confirm row exists in the CSV; call refresh_pricing().
  • cached_tokens = 0 → ensure include_usage_details=True (classic) or stream_options={"include_usage": True} (streaming).
  • Model string has no date → the latest row with date ≤ today is used.

Links


License

MIT © 2025 Orkun Kınay & Murat Barkın Kınay

Metadata

Release files for openai-cost-calculator-with-lanchain 1.0.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 openai-cost-calculator-with-lanchain 1.0.0
File Size Uploaded
openai_cost_calculator_with_lanchain-1.0.0.tar.gz 15.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for openai-cost-calculator-with-lanchain 1.0.0
File Interpreter ABI Platform
openai_cost_calculator_with_lanchain-1.0.0-py3-none-any.whl Python 3 none any Details

Total release size: 27.8 kB

Release files / openai_cost_calculator_with_lanchain-1.0.0.tar.gz

Download URL openai_cost_calculator_with_lanchain-1.0.0.tar.gz
Size 15.2 kB
Tags Source
SHA-256 checksum
How to use checksums
3187209a37a9f332439fd084cda74233d9aaa95fd2fd9da9f2fd93a04bf56c36
BLAKE2b-256 checksum
How to use checksums
52d08c99649f10f4242b2a4dcc62bc497990626e9cdfa9dac1e72a60f469a312
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.0.1 CPython/3.12.8

Release files / openai_cost_calculator_with_lanchain-1.0.0-py3-none-any.whl

Download URL openai_cost_calculator_with_lanchain-1.0.0-py3-none-any.whl
Size 12.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
4d37e300a179fd5b8e53e2ca661f48807c5872f851cefb8e0c3a3186f26e405c
BLAKE2b-256 checksum
How to use checksums
0143dafb3a3403282573f5e90760a61ea544d84d9e24073c856d9a45dff31c22
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.0.1 CPython/3.12.8

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files

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