Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(embedding): report cache source for fully cached multi-batch merges (#2690)
ZxlDragonDoctor429352797fcb
diff --git a/src/agentscope/embedding/_embedding_base.py b/src/agentscope/embedding/_embedding_base.pyindex 966d4819d..94e5454a0 100644--- a/src/agentscope/embedding/_embedding_base.py+++ b/src/agentscope/embedding/_embedding_base.py@@ -6,7 +6,7 @@ import asyncioimport inspectfrom abc import abstractmethodfrom pathlib import Path-from typing import Any, Generic, TypeVar, Type, Union+from typing import Any, Generic, Literal, TypeVar, Type, Unionfrom pydantic import BaseModel, ConfigDict@@ -283,21 +283,29 @@ class EmbeddingModelBase(Generic[InputT]):all_embeddings: list = []total_tokens = 0total_time = 0.0+ sources: set[str] = set()for resp in responses:all_embeddings.extend(resp.embeddings)+ if resp.source:+ sources.add(resp.source)if resp.usage:total_time += resp.usage.timeif resp.usage.tokens:total_tokens += resp.usage.tokens+ # Mark the merged response as cached only if every batch is cached.+ merged_source: Literal["cache", "api"] = (+ "cache" if sources and sources == {"cache"} else "api"+ )+return EmbeddingResponse(embeddings=all_embeddings,usage=EmbeddingUsage(tokens=total_tokens,time=total_time,),- source="api",+ source=merged_source,)# ------------------------------------------------------------------diff --git a/tests/embedding_base_test.py b/tests/embedding_base_test.pynew file mode 100644index 000000000..640fdab0e--- /dev/null+++ b/tests/embedding_base_test.py@@ -0,0 +1,105 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access+"""Unit tests for EmbeddingModelBase."""+from dataclasses import asdict+from typing import Literal+from unittest import TestCase++from utils import AnyString++from agentscope.embedding import (+ EmbeddingModelBase,+ EmbeddingResponse,+ EmbeddingUsage,+)+++def _resp(+ source: Literal["cache", "api"],+ value: float,+ tokens: int = 0,+ time: float = 0.0,+) -> EmbeddingResponse:+ """Build a batch response with a distinct embedding and usage."""+ return EmbeddingResponse(+ embeddings=[[value]],+ usage=EmbeddingUsage(tokens=tokens, time=time),+ source=source,+ )+++class EmbeddingModelBaseTest(TestCase):+ """Test response merging across cached and API batches."""++ def test_merge_single_batch_preserves_cache_source(self) -> None:+ """Preserve the complete response for a single cached batch."""+ response = _resp("cache", 1.0)++ merged = EmbeddingModelBase._merge_responses([response])++ self.assertEqual(asdict(merged), asdict(response))+ self.assertIs(merged, response)++ def test_merge_all_cache_batches_reports_cache(self) -> None:+ """Merge cached vectors in order with zero API usage."""+ merged = EmbeddingModelBase._merge_responses(+ [+ _resp("cache", 1.0),+ _resp("cache", 2.0),+ _resp("cache", 3.0),+ ],+ )++ self.assertEqual(+ asdict(merged),+ {+ "embeddings": [[1.0], [2.0], [3.0]],+ "id": AnyString(),+ "created_at": AnyString(),+ "type": "embedding",+ "usage": {"tokens": 0, "time": 0.0, "type": "embedding"},+ "source": "cache",+ },+ )++ def test_merge_live_api_batches_reports_api(self) -> None:+ """Preserve vector order and sum tokens and time across API calls."""+ merged = EmbeddingModelBase._merge_responses(+ [+ _resp("api", 1.0, tokens=7, time=0.25),+ _resp("api", 2.0, tokens=5, time=0.5),+ ],+ )++ self.assertEqual(+ asdict(merged),+ {+ "embeddings": [[1.0], [2.0]],+ "id": AnyString(),+ "created_at": AnyString(),+ "type": "embedding",+ "usage": {"tokens": 12, "time": 0.75, "type": "embedding"},+ "source": "api",+ },+ )++ def test_merge_mixed_cache_and_api_reports_api(self) -> None:+ """Report API usage when cached and API batches are combined."""+ merged = EmbeddingModelBase._merge_responses(+ [+ _resp("cache", 1.0),+ _resp("api", 2.0, tokens=7, time=0.5),+ ],+ )++ self.assertEqual(+ asdict(merged),+ {+ "embeddings": [[1.0], [2.0]],+ "id": AnyString(),+ "created_at": AnyString(),+ "type": "embedding",+ "usage": {"tokens": 7, "time": 0.5, "type": "embedding"},+ "source": "api",+ },+ )