Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(ollama): prevent reused response ids from dropping spend logs (#39227)

devin-ai-integration[bot]67bfb7a14813
diff --git a/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py b/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py
index f32fba7c6ec..f3c60679c81 100644
--- a/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py
+++ b/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py
@@ -16,6 +16,7 @@ from litellm.litellm_core_utils.hidden_params import get_hidden_params
from litellm.litellm_core_utils.prompt_templates.common_utils import (
extract_reasoning_content,
)
+from litellm.llms.ollama.common_utils import OllamaResponseIdNormalizer
from litellm.types.llms.databricks import DatabricksTool
from litellm.types.llms.openai import (
ChatCompletionReasoningItem,
@@ -833,7 +834,9 @@ def convert_to_model_response_object(
if k not in _MODEL_RESPONSE_FIELDS:
setattr(model_response_object, k, v)
- return model_response_object
+ ollama_ids: Final = OllamaResponseIdNormalizer()
+ ollama_ids.observe(model_response_object)
+ return ollama_ids.apply(model_response_object)
elif response_type == "embedding" and (
model_response_object is None or isinstance(model_response_object, EmbeddingResponse)
):
diff --git a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py
index 6c18128a608..d505192184e 100644
--- a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py
+++ b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py
@@ -1,4 +1,5 @@
import base64
+import builtins
import time
from collections.abc import Callable, Iterator, Mapping, Sequence
from dataclasses import dataclass, replace
@@ -118,6 +119,7 @@ class _BaseChunk(TypedDict, total=False):
created: ReadOnly[int]
model: ReadOnly[str]
system_fingerprint: ReadOnly[str | None]
+ provider_specific_fields: ReadOnly[Mapping[str, builtins.object] | None]
service_tier: ReadOnly[str | None]
choices: ReadOnly[Required[Sequence[StreamingChoices]]]
_hidden_params: ReadOnly[_ChunkHiddenParams]
@@ -430,6 +432,11 @@ class ChunkProcessor:
"created": created,
"model": model,
"system_fingerprint": system_fingerprint,
+ **(
+ {"provider_specific_fields": chunks[0].get("provider_specific_fields")}
+ if system_fingerprint == "fp_ollama"
+ else {}
+ ),
**(
MappingProxyType({"service_tier": service_tier})
if service_tier is not None
diff --git a/litellm/litellm_core_utils/streaming_handler.py b/litellm/litellm_core_utils/streaming_handler.py
index 83511456d45..46ad1b70abe 100644
--- a/litellm/litellm_core_utils/streaming_handler.py
+++ b/litellm/litellm_core_utils/streaming_handler.py
@@ -14,6 +14,7 @@ from typing import Any, Final, NoReturn, Protocol, TypeVar, cast
import anyio
import httpx
+from openai.types.chat import ChatCompletionChunk
from pydantic import BaseModel, ValidationError
from typing_extensions import NotRequired, TypedDict
@@ -27,6 +28,7 @@ from litellm.litellm_core_utils.model_response_utils import (
)
from litellm.litellm_core_utils.redact_messages import LiteLLMLoggingObject
from litellm.litellm_core_utils.thread_pool_executor import executor
+from litellm.llms.ollama.common_utils import OllamaResponseIdNormalizer
from litellm.types.llms.base import LiteLLMBaseModel
from litellm.types.llms.openai import OpenAIChatCompletionChunk
from litellm.types.router import GenericLiteLLMParams
@@ -285,6 +287,7 @@ class CustomStreamWrapper:
self._response_headers = _response_headers
self.response_id: str | None = None
+ self._ollama_response_ids = OllamaResponseIdNormalizer()
self.received_model_id: str | None = None
self.logging_loop = None
self.rules = Rules()
@@ -824,7 +827,7 @@ class CustomStreamWrapper:
pass
else:
model_response.choices = [StreamingChoices(finish_reason=None)]
- return model_response
+ return self._ollama_response_ids.apply(model_response)
def is_delta_empty(self, delta: Delta) -> bool:
is_empty = True
@@ -1449,8 +1452,14 @@ class CustomStreamWrapper:
return _ProviderChunkParsed(response_obj)
def chunk_creator(self, chunk: Any):
+ if self.custom_llm_provider != "cached_response" and isinstance(
+ chunk, (ChatCompletionChunk, ModelResponseStream)
+ ):
+ self._ollama_response_ids.observe(chunk)
if hasattr(chunk, "id"):
self.response_id = chunk.id
+ if self._ollama_response_ids.response_id is not None:
+ self.response_id = self._ollama_response_ids.response_id
provider_response_model: Final = _provider_response_model(chunk)
if provider_response_model is not None:
self._provider_response_model = provider_response_model
diff --git a/litellm/llms/ollama/common_utils.py b/litellm/llms/ollama/common_utils.py
index af8d492316e..b5328b1ba4d 100644
--- a/litellm/llms/ollama/common_utils.py
+++ b/litellm/llms/ollama/common_utils.py
@@ -1,11 +1,56 @@
import base64
import io
-from typing import Final
+from typing import Final, overload
import httpx
+from openai.types.chat import ChatCompletionChunk
+from pydantic import BaseModel, TypeAdapter
from litellm import verbose_logger
+from litellm._uuid import uuid
from litellm.llms.base_llm.chat.transformation import BaseLLMException
+from litellm.types.utils import ModelResponse, ModelResponseStream
+
+_PROVIDER_FIELDS: Final = TypeAdapter(dict[str, object])
+
+
+class OllamaResponseIdNormalizer:
+ def __init__(self) -> None:
+ self.response_id: str | None = None
+ self.original_response_id: str | None = None
+
+ def observe(self, response: object) -> None:
+ if self.response_id is not None:
+ return
+ if not isinstance(response, (ModelResponse, ModelResponseStream, ChatCompletionChunk)):
+ return
+ if response.system_fingerprint != "fp_ollama":
+ return
+ fields: Final = _PROVIDER_FIELDS.validate_python(
+ BaseModel.model_dump(response).get("provider_specific_fields") or {}
+ )
+ original_id: Final = fields.get("original_response_id")
+ self.original_response_id = original_id if isinstance(original_id, str) else response.id
+ self.response_id = response.id if isinstance(original_id, str) else f"chatcmpl-{uuid.uuid4()}"
+
+ @overload
+ def apply(self, response: ModelResponse) -> ModelResponse: ...
+
+ @overload
+ def apply(self, response: ModelResponseStream) -> ModelResponseStream: ...
+
+ def apply(self, response: ModelResponse | ModelResponseStream) -> ModelResponse | ModelResponseStream:
+ if self.response_id is None:
+ return response
+ fields: Final = _PROVIDER_FIELDS.validate_python(
+ BaseModel.model_dump(response).get("provider_specific_fields") or {}
+ )
+ return response.model_copy(
+ update={
+ "id": self.response_id,
+ "provider_specific_fields": {**fields, "original_response_id": self.original_response_id},
+ }
+ )
class OllamaError(BaseLLMException):
diff --git a/litellm/llms/openai/chat/gpt_transformation.py b/litellm/llms/openai/chat/gpt_transformation.py
index 3b70732f3fb..4d7ef833181 100644
--- a/litellm/llms/openai/chat/gpt_transformation.py
+++ b/litellm/llms/openai/chat/gpt_transformation.py
@@ -958,9 +958,11 @@ class OpenAIChatCompletionStreamingHandler(BaseModelResponseIterator):
)
choices = chunk.get("choices", [])
choices = self._map_reasoning_to_reasoning_content(choices)
+ fingerprint: Final = _OBJECT_MAPPING.validate_python(chunk).get("system_fingerprint")
kwargs: Final[dict[str, Any]] = {
"id": chunk.get("id"),
+ "system_fingerprint": fingerprint,
"object": "chat.completion.chunk",
"created": chunk.get("created"),
"model": chunk.get("model"),
diff --git a/tests/integration/spend/test_spend_logs_metadata_fields.py b/tests/integration/spend/test_spend_logs_metadata_fields.py
index d7f1dbfd998..9941edf0f26 100644
--- a/tests/integration/spend/test_spend_logs_metadata_fields.py
+++ b/tests/integration/spend/test_spend_logs_metadata_fields.py
@@ -21,6 +21,98 @@ from pydantic import JsonValue
CACHED_PROMPT_TOKENS: Final = 4
+def _ollama_fixed_id_reply(request: Request) -> Reply:
+ body: Final = JSON_OBJECT.validate_json(request.body)
+ assert request.target == "/v1/chat/completions", request.target
+ assert body["model"] == "gpt-oss:20b", body
+ common: Final = {
+ "id": "chatcmpl-0",
+ "model": "gpt-oss:20b",
+ "created": 1,
+ "system_fingerprint": "fp_ollama",
+ }
+ usage: Final = {"prompt_tokens": 5, "completion_tokens": 1, "total_tokens": 6}
+ if body.get("stream") is True:
+ chunks: Final = (
+ {"choices": [{"index": 0, "delta": {"role": "assistant", "content": "h"}, "finish_reason": None}]},
+ {"choices": [{"index": 0, "delta": {"content": "i"}, "finish_reason": None}]},
+ {"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]},
+ {"choices": [], "usage": usage},
+ )
+ return Reply(
+ content_type="text/event-stream",
+ chunks=tuple(
+ ("data: " + json.dumps({**common, "object": "chat.completion.chunk", **chunk}) + "\n\n").encode()
+ for chunk in chunks
+ )
+ + (b"data: [DONE]\n\n",),
+ )
+ return Reply(
+ body=json.dumps(
+ {
+ **common,
+ "object": "chat.completion",
+ "usage": usage,
+ "choices": [{"index": 0, "message": {"role": "assistant", "content": "hi"}, "finish_reason": "stop"}],
+ }
+ ).encode()
+ )
+
+
[email protected]("stream", [False, True])
+def test_reused_ollama_response_ids_keep_every_spend_row(gateway: Gateway, stream: bool) -> None:
+ with wire_server(_ollama_fixed_id_reply) as wire, gateway.scenario() as scenario:
+ model: Final = scenario.model(
+ model="openai/gpt-oss:20b",
+ api_base=wire.url + "/v1",
+ api_key="synthetic-key",
+ input_cost_per_token=0.001,
+ output_cost_per_token=0.002,
+ )
+ key: Final = scenario.key(models=[model])
+ responses: Final = tuple(
+ gateway.request(
+ "POST",
+ "/v1/chat/completions",
+ {
+ "model": model,
+ "messages": [{"role": "user", "content": f"hi {index}"}],
+ "stream": stream,
+ **({"stream_options": {"include_usage": True}} if stream else {}),
+ },
+ key=key,
+ )
+ for index in range(3)
+ )
+ assert tuple(response.status_code for response in responses) == (200, 200, 200)
+ returned: Final = tuple(
+ tuple(
+ JSON_OBJECT.validate_json(line[6:])
+ for line in response.text.splitlines()
+ if line.startswith("data: ") and line != "data: [DONE]"
+ )
+ if stream
+ else (JSON_OBJECT.validate_json(response.content),)
+ for response in responses
+ )
+ ids: Final = tuple(string_value(chunks[0]["id"]) for chunks in returned)
+ for chunks, response_id in zip(returned, ids, strict=True):
+ assert {chunk["id"] for chunk in chunks} == {response_id}
+ assert object_value(chunks[0]["provider_specific_fields"])["original_response_id"] == "chatcmpl-0"
+ assert object_value(chunks[-1]["usage"])["total_tokens"] == 6
+ rows: Final = eventually(
+ lambda: read_rows(
+ 'SELECT request_id, spend FROM "LiteLLM_SpendLogs" WHERE api_key=%s',
+ (sha256(key.encode()).hexdigest(),),
+ ),
+ lambda values: len(values) == 3,
+ seconds=70,
+ )
+ assert len(set(ids)) == 3
+ assert {row["request_id"] for row in rows} == set(ids)
+ assert tuple(float(str(row["spend"])) for row in rows) == pytest.approx((0.007, 0.007, 0.007))
+
+
def _config(
tmp_path: Path,
spend_logs_metadata_fields: Mapping[str, JsonValue] | None,
diff --git a/tests/unit/integrations/gcs_bucket/test_gcs_bucket_base.py b/tests/unit/integrations/gcs_bucket/test_gcs_bucket_base.py
index 781b56cae14..07874bdbeb5 100644
--- a/tests/unit/integrations/gcs_bucket/test_gcs_bucket_base.py
+++ b/tests/unit/integrations/gcs_bucket/test_gcs_bucket_base.py
@@ -1,4 +1,5 @@
import os
+from typing import Final
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -7,6 +8,34 @@ from litellm.integrations.gcs_bucket.gcs_bucket import GCSBucketLogger
from litellm.integrations.gcs_bucket.gcs_bucket_base import GCSBucketBase
+def test_ollama_payload_key_matches_returned_response_id() -> None:
+ from datetime import datetime
+
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import convert_to_model_response_object
+ from litellm.proxy.spend_tracking.spend_tracking_utils import get_logging_payload
+ from litellm.types.utils import ModelResponse
+
+ logger: Final = object.__new__(GCSBucketLogger)
+ response: Final = convert_to_model_response_object(
+ response_object={
+ "id": "chatcmpl-0",
+ "system_fingerprint": "fp_ollama",
+ "choices": [{"index": 0, "message": {"role": "assistant", "content": "hi"}}],
+ },
+ model_response_object=ModelResponse(),
+ )
+ logged: Final = get_logging_payload(
+ kwargs={"call_type": "acompletion", "response_cost": 0.01},
+ response_obj=response,
+ start_time=datetime(2025, 1, 1),
+ end_time=datetime(2025, 1, 1),
+ )
+ object_name: Final = logger._get_object_name({}, {"error_str": None}, response)
+ assert response.id != "chatcmpl-0"
+ assert object_name.split("/", 1)[1] == response.id
+ assert logged["request_id"] == response.id
+
+
class TestGCSBucketBase:
def test_construct_request_headers_with_project_id(self, monkeypatch):
"""Test that construct_request_headers correctly uses project_id if passed from env"""
diff --git a/tests/unit/litellm_core_utils/llm_response_utils/test_convert_dict_to_response.py b/tests/unit/litellm_core_utils/llm_response_utils/test_convert_dict_to_response.py
index f918d4cb79e..0c601a6b2c8 100644
--- a/tests/unit/litellm_core_utils/llm_response_utils/test_convert_dict_to_response.py
+++ b/tests/unit/litellm_core_utils/llm_response_utils/test_convert_dict_to_response.py
@@ -14,6 +14,54 @@ from tests._vcr_conftest_common import install_live_call_probe, record_vcr_outco
FIXED_TIME: Final[datetime] = datetime(2025, 1, 1, 12, 0, 0)
+
+def test_reused_ollama_ids_have_distinct_response_and_spend_ids() -> None:
+ from litellm.proxy.spend_tracking.spend_tracking_utils import get_logging_payload
+
+ body: Final = {
+ "id": "chatcmpl-0",
+ "system_fingerprint": "fp_ollama",
+ "model": "gpt-oss:20b",
+ "choices": [{"index": 0, "message": {"role": "assistant", "content": "hi"}, "finish_reason": "stop"}],
+ "usage": {"prompt_tokens": 5, "completion_tokens": 1, "total_tokens": 6},
+ "provider_specific_fields": {"extra": "preserved"},
+ }
+ responses: Final = [
+ convert_to_model_response_object(response_object=body, model_response_object=ModelResponse()) for _ in range(2)
+ ]
+ assert len({response.id for response in responses}) == 2
+ for response in responses:
+ assert response.id != "chatcmpl-0"
+ assert response.provider_specific_fields == {"extra": "preserved", "original_response_id": "chatcmpl-0"}
+ logged: Final = get_logging_payload(
+ kwargs={"call_type": "acompletion", "litellm_call_id": "same-client-call-id", "response_cost": 0.01},
+ response_obj=response,
+ start_time=FIXED_TIME,
+ end_time=FIXED_TIME,
+ )
+ assert logged["request_id"] == response.id
+ reparsed: Final = convert_to_model_response_object(
+ response_object=response.model_dump(), model_response_object=ModelResponse()
+ )
+ assert reparsed.id == response.id
+ assert body["id"] == "chatcmpl-0"
+ assert body["provider_specific_fields"] == {"extra": "preserved"}
+
+
[email protected]("fingerprint", [None, "fp_openai", "fp_ollama_other"])
+def test_non_ollama_fingerprints_keep_provider_response_ids(fingerprint: str | None) -> None:
+ response: Final = convert_to_model_response_object(
+ response_object={
+ "id": "chatcmpl-0",
+ "system_fingerprint": fingerprint,
+ "choices": [{"index": 0, "message": {"role": "assistant", "content": "hi"}}],
+ },
+ model_response_object=ModelResponse(),
+ )
+ assert response.id == "chatcmpl-0"
+ assert response.model_dump().get("provider_specific_fields") is None
+
+
OPENAI_CUSTOM_TOOL_CALL_RESPONSE = {
"id": "chatcmpl-abc",
"created": 1784657740,
diff --git a/tests/unit/litellm_core_utils/test_streaming_handler.py b/tests/unit/litellm_core_utils/test_streaming_handler.py
index 07cdbc15baa..4347a6639bd 100644
--- a/tests/unit/litellm_core_utils/test_streaming_handler.py
+++ b/tests/unit/litellm_core_utils/test_streaming_handler.py
@@ -31,6 +31,94 @@ from litellm import completion
from typing import Tuple
[email protected]("async_stream", [False, True])
[email protected]("transport", ["sdk", "http_handler"])
[email protected]("fingerprint", ["fp_ollama", "fp_openai", None])
+async def test_ollama_stream_ids_match_usage_and_spend_logs(
+ async_stream: bool,
+ transport: str,
+ fingerprint: str | None,
+) -> None:
+ from datetime import datetime
+
+ from openai.types.chat import ChatCompletionChunk
+
+ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response import convert_to_model_response_object
+ from litellm.llms.openai.chat.gpt_transformation import OpenAIChatCompletionStreamingHandler
+ from litellm.proxy.spend_tracking.spend_tracking_utils import get_logging_payload
+
+ parser: Final = OpenAIChatCompletionStreamingHandler(streaming_response=None, sync_stream=True)
+ bodies: Final = [
+ {"choices": [{"index": 0, "delta": {"role": "assistant", "content": "h"}, "finish_reason": None}]},
+ {"choices": [{"index": 0, "delta": {"content": "i"}, "finish_reason": None}]},
+ {"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]},
+ {"choices": [], "usage": {"prompt_tokens": 5, "completion_tokens": 1, "total_tokens": 6}},
+ ]
+ raw_chunks: Final = [
+ {
+ "id": "chatcmpl-0",
+ "object": "chat.completion.chunk",
+ "model": "gpt-oss:20b",
+ "created": 1,
+ "system_fingerprint": fingerprint,
+ **body,
+ }
+ for body in bodies
+ ]
+ chunks: Final = [
+ ChatCompletionChunk(**body) if transport == "sdk" else parser.chunk_parser(body) for body in raw_chunks
+ ]
+ streams: Final = [
+ CustomStreamWrapper(
+ completion_stream=ModelResponseListIterator(model_responses=chunks),
+ model="gpt-oss:20b",
+ custom_llm_provider="openai",
+ stream_options={"include_usage": True},
+ logging_obj=Logging(
+ model="gpt-oss:20b",
+ messages=[{"role": "user", "content": "hi"}],
+ stream=True,
+ call_type="acompletion",
+ start_time=1.0,
+ litellm_call_id="same-client-call-id",
+ function_id="test",
+ ),
+ )
+ for _ in range(2)
+ ]
+ received_streams: Final = (
+ [chunk async for chunk in streams[0]] if async_stream else list(streams[0]),
+ [chunk async for chunk in streams[1]] if async_stream else list(streams[1]),
+ )
+ for received in received_streams:
+ assembled: Final = litellm.stream_chunk_builder(chunks=received)
+ assert assembled.choices[0].message.content == "hi"
+ assert assembled.usage.total_tokens == 6
+ assert len({chunk.id for chunk in received}) == 1
+ assert received[-1].usage.total_tokens == 6
+ assert assembled.id == received[0].id
+ reparsed: Final = convert_to_model_response_object(
+ response_object=assembled.model_dump(),
+ model_response_object=ModelResponse(),
+ )
+ assert reparsed.id == assembled.id
+ logged: Final = get_logging_payload(
+ kwargs={"call_type": "acompletion", "litellm_call_id": "same-client-call-id", "response_cost": 0.01},
+ response_obj=assembled,
+ start_time=datetime(2025, 1, 1),
+ end_time=datetime(2025, 1, 1),
+ )
+ assert logged["request_id"] == assembled.id
+ if fingerprint == "fp_ollama":
+ assert assembled.id != "chatcmpl-0"
+ assert received[0].provider_specific_fields == {"original_response_id": "chatcmpl-0"}
+ assert assembled.provider_specific_fields == {"original_response_id": "chatcmpl-0"}
+ else:
+ assert assembled.id == "chatcmpl-0"
+ assert len({chunks[0].id for chunks in received_streams}) == (2 if fingerprint == "fp_ollama" else 1)
+ assert all(chunk.id == "chatcmpl-0" for chunk in chunks)
+
+
@pytest.fixture
def initialized_custom_stream_wrapper() -> CustomStreamWrapper:
streaming_handler = CustomStreamWrapper(