diff --git a/backend/docs/CONFIGURATION.md b/backend/docs/CONFIGURATION.md index d6a8fefb0b..ea25b435a1 100644 --- a/backend/docs/CONFIGURATION.md +++ b/backend/docs/CONFIGURATION.md @@ -50,6 +50,22 @@ changing its configuration. Other memory backends do not consume these DeerMem-specific fields. Existing external memory templates remain the mechanism for complete template replacement; this feature adds no editing endpoint or UI. +## DeepSeek cache accounting + +Models configured with `langchain_deepseek:ChatDeepSeek` or +`deerflow.models.patched_deepseek:PatchedChatDeepSeek` retain DeepSeek's native +`usage.prompt_cache_hit_tokens` as `input_token_details.cache_read` when the +standard `prompt_tokens_details.cached_tokens` field is absent or null. An +explicit standard count, including zero, takes precedence. Invalid native +counts are ignored; they do not fail an otherwise successful response. + +This applies to synchronous, asynchronous and streaming calls. The existing +lead-agent journal and subagent usage handoff retain that count for per-model +cache-aware cost estimates. Cached tokens are a subset of input tokens, so +normalization never adds them or `prompt_cache_miss_tokens` to the input total. +Responses that already supply the standard field are unchanged. These are +provider-reported usage estimates, not a measurement of money saved by DeerFlow. + ## Model request admission For request-per-minute limits, opt into pacing on each relevant `models[]` diff --git a/backend/packages/harness/deerflow/models/factory.py b/backend/packages/harness/deerflow/models/factory.py index 446bcadec7..89a50f8d32 100644 --- a/backend/packages/harness/deerflow/models/factory.py +++ b/backend/packages/harness/deerflow/models/factory.py @@ -576,6 +576,13 @@ def create_chat_model(name: str | None = None, thinking_enabled: bool = False, * model_class = resolve_class(model_config.use, BaseChatModel) if model_config.use == "langchain_openai:ChatOpenAI" and model_class is ChatOpenAI: model_class = GuardedChatOpenAI + if model_config.use == "langchain_deepseek:ChatDeepSeek": + from langchain_deepseek import ChatDeepSeek + + from deerflow.models.patched_deepseek import GuardedChatDeepSeek + + if model_class is ChatDeepSeek: + model_class = GuardedChatDeepSeek model_settings_from_config = model_config.model_dump(exclude_none=True, exclude=set(_MODEL_METADATA_FIELDS)) if isinstance(model_config.reasoning, bool | str): # Before the capability contract, ``reasoning`` was an unrestricted diff --git a/backend/packages/harness/deerflow/models/patched_deepseek.py b/backend/packages/harness/deerflow/models/patched_deepseek.py index 1b8d532d04..6f690df193 100644 --- a/backend/packages/harness/deerflow/models/patched_deepseek.py +++ b/backend/packages/harness/deerflow/models/patched_deepseek.py @@ -79,8 +79,41 @@ def _restore_deepseek_assistant_payload( payload_msg["reasoning_content"] = "" +def _native_cache_read(usage: Any) -> int | None: + """Read DeepSeek's native cache count only when no standard count was sent.""" + if isinstance(usage, openai.BaseModel): + usage = usage.model_dump() + if not isinstance(usage, Mapping): + return None + details = usage.get("prompt_tokens_details") + if isinstance(details, Mapping) and details.get("cached_tokens") is not None: + return None + cached = usage.get("prompt_cache_hit_tokens") + prompt = usage.get("prompt_tokens") + if type(cached) is int and type(prompt) is int and 0 <= cached <= prompt: + return cached + return None + + class GuardedChatDeepSeek(OpenAIEmptyChoicesMixin, ChatDeepSeek): - """DeepSeek provider base with typed handling for empty response choices.""" + """DeepSeek response guards and native prompt-cache usage normalization.""" + + def _create_chat_result(self, response: dict | openai.BaseModel, generation_info: dict | None = None) -> ChatResult: + result = super()._create_chat_result(response, generation_info) + raw_usage = response.get("usage") if isinstance(response, dict) else getattr(response, "usage", None) + cached = _native_cache_read(raw_usage) + if cached is not None: + for generation in result.generations: + if usage := generation.message.usage_metadata: + usage.setdefault("input_token_details", {})["cache_read"] = cached + return result + + def _convert_chunk_to_generation_chunk(self, chunk: dict, default_chunk_class: type, base_generation_info: dict | None) -> ChatGenerationChunk | None: + result = super()._convert_chunk_to_generation_chunk(chunk, default_chunk_class, base_generation_info) + cached = _native_cache_read(chunk.get("usage")) + if result is not None and cached is not None and (usage := result.message.usage_metadata): + usage.setdefault("input_token_details", {})["cache_read"] = cached + return result class PatchedChatDeepSeek(GuardedChatDeepSeek): diff --git a/backend/tests/test_patched_deepseek.py b/backend/tests/test_patched_deepseek.py index c686d99ee8..bb2b607d2b 100644 --- a/backend/tests/test_patched_deepseek.py +++ b/backend/tests/test_patched_deepseek.py @@ -9,8 +9,12 @@ Covers: from __future__ import annotations +import json from unittest.mock import MagicMock, patch +import httpx +import pytest +import pytest_asyncio from langchain_core.messages import AIMessage, HumanMessage @@ -24,6 +28,117 @@ def _make_model(**kwargs): ) +@pytest_asyncio.fixture +async def cache_usage_model(): + """Exercise the real factory and SDK; supply only the provider HTTP response.""" + from deerflow.config.app_config import AppConfig + from deerflow.models.factory import create_chat_model + + clients = [] + async_clients = [] + + def build(usage, *, use="deerflow.models.patched_deepseek:PatchedChatDeepSeek"): + requests = [] + + def respond(request): + payload = json.loads(request.content) + requests.append(payload) + common = {"id": "cache-test", "created": 1, "model": "deepseek-chat"} + if not payload.get("stream"): + return httpx.Response(200, json={**common, "object": "chat.completion", "choices": [{"index": 0, "message": {"role": "assistant", "content": "done"}, "finish_reason": "stop"}], "usage": usage}) + chunks = [ + {**common, "object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {"role": "assistant", "content": "done"}, "finish_reason": None}]}, + {**common, "object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}, + {**common, "object": "chat.completion.chunk", "choices": [], "usage": usage}, + ] + body = "".join(f"data: {json.dumps(chunk)}\n\n" for chunk in chunks) + "data: [DONE]\n\n" + return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body) + + client = httpx.Client(transport=httpx.MockTransport(respond)) + async_client = httpx.AsyncClient(transport=httpx.MockTransport(respond)) + clients.append(client) + async_clients.append(async_client) + config = AppConfig.model_validate({"sandbox": {"use": "deerflow.sandbox.local:LocalSandboxProvider"}, "models": [{"name": "deepseek", "use": use, "model": "deepseek-chat", "api_key": "offline-test-key"}]}) + return create_chat_model("deepseek", app_config=config, attach_tracing=False, http_client=client, http_async_client=async_client), requests + + try: + yield build + finally: + for client in clients: + client.close() + for client in async_clients: + await client.aclose() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("mode", ["invoke", "ainvoke", "stream", "astream"]) +@pytest.mark.parametrize("use", ["langchain_deepseek:ChatDeepSeek", "deerflow.models.patched_deepseek:PatchedChatDeepSeek"]) +async def test_native_cache_usage_survives_sdk_and_agent_accounting(cache_usage_model, mode, use): + from deerflow.runtime.events.store.memory import MemoryRunEventStore + from deerflow.runtime.journal import RunJournal + from deerflow.subagents.token_collector import SubagentTokenCollector + + model, requests = cache_usage_model({"prompt_tokens": 100, "completion_tokens": 20, "total_tokens": 120, "prompt_cache_hit_tokens": 80, "prompt_cache_miss_tokens": 20}, use=use) + journal = RunJournal("lead-run", "thread", MemoryRunEventStore(), flush_threshold=100) + collector = SubagentTokenCollector("subagent:research") + config = {"callbacks": [journal, collector]} + if mode == "invoke": + message = model.invoke("Summarize the document", config=config) + elif mode == "ainvoke": + message = await model.ainvoke("Summarize the document", config=config) + else: + chunks = list(model.stream("Summarize the document", config=config)) if mode == "stream" else [chunk async for chunk in model.astream("Summarize the document", config=config)] + message = sum(chunks[1:], chunks[0]) + assert requests[0]["stream_options"]["include_usage"] is True + assert len(requests) == 1 + assert message.content == "done" + assert message.usage_metadata == {"input_tokens": 100, "output_tokens": 20, "total_tokens": 120, "input_token_details": {"cache_read": 80}, "output_token_details": {}} + expected = {"input_tokens": 100, "output_tokens": 20, "total_tokens": 120, "cache_read_tokens": 80} + assert journal.get_completion_data()["token_usage_by_model"] == {"deepseek-chat": expected} + parent = RunJournal("parent-run", "thread", MemoryRunEventStore(), flush_threshold=100) + records = collector.snapshot_records() + assert len(records) == 1 and records[0]["cache_read_tokens"] == 80 + parent.record_external_llm_usage_records(records) + parent.record_external_llm_usage_records(records) + completion = parent.get_completion_data() + assert completion["token_usage_by_model"] == {"deepseek-chat": expected} + assert completion["total_tokens"] == 120 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streaming", [False, True]) +@pytest.mark.parametrize( + "extra,expected", + [ + ({"prompt_cache_hit_tokens": 80, "prompt_tokens_details": {"cached_tokens": 0}}, 0), + ({"prompt_cache_hit_tokens": 80, "prompt_tokens_details": {"cached_tokens": 60, "cache_write_tokens": 10}}, 60), + ({"prompt_cache_hit_tokens": 0}, 0), + ({"prompt_cache_hit_tokens": 80, "prompt_tokens_details": {"cached_tokens": None}}, 80), + ({}, None), + ({"prompt_cache_hit_tokens": -1}, None), + ({"prompt_cache_hit_tokens": 101}, None), + ({"prompt_cache_hit_tokens": True}, None), + ({"prompt_cache_hit_tokens": "80"}, None), + ], +) +async def test_cache_usage_preserves_standard_fields_and_ignores_invalid_hints(cache_usage_model, streaming, extra, expected): + raw_usage = {"prompt_tokens": 100, "completion_tokens": 20, "total_tokens": 120, **extra} + original = json.dumps(raw_usage, sort_keys=True) + model, requests = cache_usage_model(raw_usage) + if streaming: + chunks = [chunk async for chunk in model.astream("Continue")] + message = sum(chunks[1:], chunks[0]) + else: + message = await model.ainvoke("Continue") + assert len(requests) == 1 and message.content == "done" + usage = message.usage_metadata + assert usage["input_tokens"] == 100 and usage["output_tokens"] == 20 and usage["total_tokens"] == 120 + assert usage.get("input_token_details", {}).get("cache_read") == expected + if "cache_write_tokens" in extra.get("prompt_tokens_details", {}): + assert usage["input_token_details"]["cache_creation"] == 10 + assert json.dumps(raw_usage, sort_keys=True) == original + + # --------------------------------------------------------------------------- # Serialization protocol # ---------------------------------------------------------------------------