How do I calculate the cost of a call in Python?
Every response has usage. Multiply by the model's prices per 1M tokens. That's exactly what's billed (rounded up to the next millionth of a dollar).
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.gateway.clatterlabs.xyz/v1",
api_key=os.environ["CLATTER_API_KEY"],
default_headers={"X-Clatter-Account": os.environ["CLATTER_ACCOUNT_ID"]},
)
PRICES = { # USD per 1M tokens (input, output)
"supercosmos-flash": (1.60, 3.40),
"supercosmos-max": (1.80, 3.80),
"supercosmos-heavy": (2.00, 4.40),
}
r = client.chat.completions.create(model="supercosmos-flash", messages=[{"role": "user", "content": "Hi!"}])
p_in, p_out = PRICES[r.model]
u = r.usage
if u.prompt_tokens > 262_000: # long-context input bills 1.5x
p_in *= 1.5
cost = u.prompt_tokens * p_in / 1e6 + u.completion_tokens * p_out / 1e6
print(f"${cost:.6f}")
prompt_tokens includes a short Clatter Labs instruction block added to every request. Check prices in GET /v1/models rather than hard-coding them if you want to stay in sync.
The client setup above (base URL, key and the X-Clatter-Account header) is the same in every Python example; see Set up the Python SDK. Full parameter list: Create a chat completion.
Still need help?#
- General support: support@clatterlabs.com or team@clatterlabs.xyz
- Infrastructure questions, or permanent deletion of your data (your whole account or one service): infrastructure@clatterlabs.xyz
We usually reply within the first hour, and always within 24 hours. A full support team is with you.
Related articles
- How do I set up the OpenAI Python SDK for the Model API?
- How do I count tokens before sending a request in Python?
- How do I read rate limit headers in Python?
- How do I estimate the cost of a call in JavaScript?
- What are cached tokens in /usage and /cost?Line CLI
- How can I estimate the cost of a request before sending it?SuperCosmos models
Still need help?
Tried the steps above and still stuck? Email us. We usually reply within the first hour, and always within 24 hours. A full support team is with you.