Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(embedding): honor per-call api_key on the DashScope text path (#3465)
Wilson_Jiang0d44f9fa5633
diff --git a/src/agentscope/embedding/_dashscope/_model.py b/src/agentscope/embedding/_dashscope/_model.pyindex b80103175..7146b2bb4 100644--- a/src/agentscope/embedding/_dashscope/_model.py+++ b/src/agentscope/embedding/_dashscope/_model.py@@ -351,13 +351,20 @@ class DashScopeEmbeddingModel(EmbeddingModelBase[str | TextBlock | DataBlock]):api_kwargs: dict[str, Any] = {"input": texts,"model": self.model,+ "api_key": self.api_key,"dimension": self.dimensions,**kwargs,}+ # Exclude api_key from cache identifier to avoid persisting secrets+ # and to keep cache valid across key rotations.+ cache_identifier = {+ k: v for k, v in api_kwargs.items() if k != "api_key"+ }+if self.embedding_cache:cached = await self.embedding_cache.retrieve(- identifier=api_kwargs,+ identifier=cache_identifier,)if cached:return EmbeddingResponse(@@ -371,7 +378,6 @@ class DashScopeEmbeddingModel(EmbeddingModelBase[str | TextBlock | DataBlock]):start_time = datetime.now()response = await asyncio.to_thread(dashscope.embeddings.TextEmbedding.call,- api_key=self.api_key,**api_kwargs,)time = (datetime.now() - start_time).total_seconds()@@ -386,7 +392,7 @@ class DashScopeEmbeddingModel(EmbeddingModelBase[str | TextBlock | DataBlock]):]if self.embedding_cache:await self.embedding_cache.store(- identifier=api_kwargs,+ identifier=cache_identifier,embeddings=embeddings,)return EmbeddingResponse(diff --git a/tests/embedding_dashscope_test.py b/tests/embedding_dashscope_test.pyindex 2b3862ab8..eb50379a6 100644--- a/tests/embedding_dashscope_test.py+++ b/tests/embedding_dashscope_test.py@@ -192,6 +192,41 @@ class DashScopeTextCallTest(IsolatedAsyncioTestCase):},)+ @patch("dashscope.embeddings.TextEmbedding.call")+ async def test_text_api_key_override_with_cache(+ self,+ mock_api: Any,+ ) -> None:+ """Use the per-call key without including it in cache identifiers."""+ embeddings = [[0.1, 0.2]]+ mock_api.return_value = _text_resp(embeddings, 12)+ cache = MagicMock()+ cache.retrieve = AsyncMock(return_value=None)+ cache.store = AsyncMock()+ model = DashScopeEmbeddingModel(+ credential=_cred(),+ model="text-embedding-v4",+ dimensions=2,+ embedding_cache=cache,+ )++ await model(["hello"], api_key="sk-per-call")++ identifier = {+ "input": ["hello"],+ "model": "text-embedding-v4",+ "dimension": 2,+ }+ mock_api.assert_called_once_with(+ **identifier,+ api_key="sk-per-call",+ )+ cache.retrieve.assert_awaited_once_with(identifier=identifier)+ cache.store.assert_awaited_once_with(+ identifier=identifier,+ embeddings=embeddings,+ )+@patch("dashscope.embeddings.TextEmbedding.call")async def test_sdk_thread(self, mock_api: Any) -> None:"""The SDK executes on a worker instead of the event loop thread."""