Skip to content
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
* `ChatGoogle()` and `ChatVertex()` now count the tokens of content fetched by built-in tools (URL context, search, ...) as input tokens in `Turn.tokens` and the cost estimate. Gemini reports them as `tool_use_prompt_token_count`, separately from `prompt_token_count`, and they were left out.
* A tool that returns a `ContentToolResult` whose value is a `Content` object other than an image/PDF/document (e.g. `ContentToolResult(value=ContentText(...), model_format="as_is")`, as MCP client adapters produce) no longer poisons the conversation: the next API request failed with a 400 (e.g. Anthropic's "`tool_result` content must either be a string or a list of content blocks") because the raw `Content` object was serialized into the request. Turn preparation now unwraps any such value to a plain value -- `ContentText` becomes its text, `ContentJson` its underlying data, and a list of non-file content joins into a single string -- so no provider ever sees a raw `Content` object in a tool-result value. (#494)
* `.register_tool()` now keeps the description, parameters and `strict` setting of a `Tool` built with explicit `parameters=`, as `.set_tools()` does, instead of rebuilding them from the signature and docstring of `tool.func`. A `name=` override renames the tool without rebuilding it; passing `model=` still rebuilds the schema from that model. (#496)
* `ChatOpenAI()` and `ChatAzureOpenAI()` now count the tokens written to OpenAI's prompt cache in the turn's input tokens and cost at the cache-write rate (125% of the input rate for the default 30-minute lifetime, 250% for 12 hours). GPT-5.6 and later bill cache writes, but the cost was computed as if they were ordinary input.
* Streaming from `ChatOpenAICompletions()` (and the providers built on it, such as `ChatOpenRouter()` and `ChatGroq()`) no longer drops a chunk's text when the same chunk carries an empty `reasoning` or `reasoning_content` field, as some OpenAI-compatible servers send.
* `ChatOllama()` can now be created without a `model`, so `ChatOllama().list_models()` works. Sending a message without a model still raises an error that lists the available models. (#166)
* `ChatGoogle()` now reports `finish_reason == "content_filter"` for Gemini's `IMAGE_SAFETY`, `IMAGE_PROHIBITED_CONTENT`, `IMAGE_RECITATION` and `LANGUAGE` finish reasons, instead of passing the raw Gemini string through, and reports `"tool_use"` (rather than `"success"`) when a turn ends with a tool request, as `ChatOpenAI()` does. (#473)
Expand Down
40 changes: 38 additions & 2 deletions chatlas/_provider_openai.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from openai.types.responses.response_output_text_annotation_added_event import (
AnnotationURLCitation as StreamAnnotationURLCitation,
)
from openai.types.responses.response_usage import InputTokensDetails
from pydantic import BaseModel

from ._chat import Chat
Expand Down Expand Up @@ -54,6 +55,7 @@
from ._tools import Tool, ToolBuiltIn, basemodel_to_param_schema
from ._tools_builtin import ToolWebSearch
from ._turn import AssistantTurn, FinishReason, Turn, check_finish_reason
from ._typing_extensions import TypedDict

if TYPE_CHECKING:
import os
Expand Down Expand Up @@ -449,9 +451,20 @@ def value_tokens(self, completion):
usage = completion.usage
if usage is None:
return None
cached_tokens = usage.input_tokens_details.cached_tokens
details = usage.input_tokens_details
cached_tokens = details.cached_tokens

# `input_tokens` includes the tokens written to the prompt cache, which
# GPT-5.6 and later bill at 125% of the input rate for the default
# 30-minute lifetime and at 250% for the 12-hour one, so add the premium.
# Only the models that bill writes report the per-lifetime breakdown, so
# a response without it (earlier models: no write charge) adds nothing.
# https://developers.openai.com/api/docs/guides/prompt-caching
write_30m, write_12h = cache_write_tokens_by_lifetime(details)
write_premium = int(0.25 * write_30m + 1.5 * write_12h)

return (
usage.input_tokens - cached_tokens,
usage.input_tokens - cached_tokens + write_premium,
usage.output_tokens,
cached_tokens,
)
Expand Down Expand Up @@ -679,6 +692,29 @@ async def file_delete_async(self, id: str) -> None: # noqa: A002
await self._async_client.files.delete(id)


def cache_write_tokens_by_lifetime(details: InputTokensDetails) -> tuple[int, int]:
"""Prompt-cache write tokens, split by lifetime: (30-minute, 12-hour).

`openai` only typed `cache_write_tokens_details` in 3.45; older versions
keep it as an extra field holding a plain dict, which pydantic still
exposes as an attribute, so `getattr` reaches it either way.
"""
write = getattr(details, "cache_write_tokens_details", None)
if write is None:
return (0, 0)
if isinstance(write, dict):
write = cast(CacheWriteTokensDetailsDict, write)
return (write.get("ttl_30m_tokens") or 0, write.get("ttl_12h_tokens") or 0)
return (write.ttl_30m_tokens, write.ttl_12h_tokens)


class CacheWriteTokensDetailsDict(TypedDict, total=False):
"""The un-typed shape `openai` < 3.45 reports for `cache_write_tokens_details`."""

ttl_30m_tokens: int
ttl_12h_tokens: int


def openai_web_search_request(
item: "ResponseFunctionWebSearch",
) -> ContentToolRequestSearch | ContentToolRequestFetch:
Expand Down
93 changes: 92 additions & 1 deletion tests/test_provider_openai.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,15 @@
from chatlas.types import ContentCitation, ContentText, ContentToolRequestSearch
from openai.types.responses import (
Response,
ResponseOutputTextAnnotationAddedEvent,
ResponseOutputMessage,
ResponseOutputText,
ResponseOutputTextAnnotationAddedEvent,
ResponseUsage,
)
from openai.types.responses.response_output_text_annotation_added_event import (
AnnotationURLCitation,
)
from openai.types.responses.response_usage import InputTokensDetails

from .conftest import (
assert_data_extraction,
Expand Down Expand Up @@ -671,3 +673,92 @@ def test_openai_truncated_plain_text_still_returns_a_turn():

assert turn.text == '{"comments": [{"body": "trunc'
assert turn.finish_reason == "max_tokens"


def _usage_completion(**details):
usage = ResponseUsage.model_validate(
{
"input_tokens": 12000,
"output_tokens": 100,
"total_tokens": 12100,
"input_tokens_details": {"cache_write_tokens": 0, **details},
"output_tokens_details": {"reasoning_tokens": 0},
}
)
return Response.construct(
id="resp_1",
model="gpt-5.6-sol",
status="completed",
service_tier="default",
output=[],
usage=usage,
)


def test_openai_value_tokens_bills_cache_writes_above_the_input_rate():
provider = OpenAIProvider(model="gpt-5.6-sol", api_key="dummy")

# 12000 input tokens: 4000 read from the cache, 7000 written for 30 minutes,
# 1000 ordinary. Writes cost 125% of the input rate.
completion = _usage_completion(
cached_tokens=4000,
cache_write_tokens=7000,
cache_write_tokens_details={"ttl_30m_tokens": 7000, "ttl_12h_tokens": 0},
)

assert provider.value_tokens(completion) == (
12000 - 4000 + int(0.25 * 7000),
100,
4000,
)


def test_openai_value_tokens_bills_12h_cache_writes_at_250_percent():
provider = OpenAIProvider(model="gpt-5.6-sol", api_key="dummy")

completion = _usage_completion(
cached_tokens=4000,
cache_write_tokens=7000,
cache_write_tokens_details={"ttl_30m_tokens": 3000, "ttl_12h_tokens": 4000},
)

assert provider.value_tokens(completion) == (
12000 - 4000 + int(0.25 * 3000 + 1.5 * 4000),
100,
4000,
)


def test_openai_value_tokens_without_cache_writes_is_unchanged():
provider = OpenAIProvider(model="gpt-5.6-sol", api_key="dummy")

assert provider.value_tokens(_usage_completion(cached_tokens=4000)) == (
8000,
100,
4000,
)

# Writes reported without the per-lifetime breakdown are not billed above the
# input rate (models before GPT-5.6), so no premium is added.
completion = _usage_completion(cached_tokens=4000, cache_write_tokens=7000)
assert provider.value_tokens(completion) == (8000, 100, 4000)


def test_openai_value_tokens_cache_write_breakdown_from_untyped_sdk():
provider = OpenAIProvider(model="gpt-5.6-sol", api_key="dummy")

# `openai` < 3.45 doesn't type `cache_write_tokens_details`, so it arrives
# as a plain dict. Simulate that by skipping validation for the field.
completion = _usage_completion(cached_tokens=4000)
assert completion.usage is not None
completion.usage.input_tokens_details = InputTokensDetails.construct(
cached_tokens=4000,
cache_write_tokens=7000,
cache_write_tokens_details={"ttl_30m_tokens": 7000, "ttl_12h_tokens": 0},
)

assert provider.value_tokens(completion) == (
12000 - 4000 + int(0.25 * 7000),
100,
4000,
)
Loading