Skip to content

Commit 9645d33

Browse files
atty57Copilot
andauthored
Python: Fix Cosmos memory provider calling renamed add_cosmos toolkit API (microsoft#7635)
* Python: Fix Cosmos memory provider calling renamed add_cosmos toolkit API The Agent Memory Toolkit renamed AsyncCosmosMemoryClient.add_cosmos to upsert_memory with an identical signature. The provider declares azure-cosmos-agent-memory>=0.2.0b3 with no upper bound, so a resolved install can expose either name. after_run swallows write errors and only logs a warning, so on a post-rename toolkit the agent turn still looks successful while long-term memory silently stops receiving turns. Resolve the write method once per after_run, preferring upsert_memory and falling back to add_cosmos, so both ends of the declared range keep working. Same treatment for the emulator test's direct seed call. Fixes microsoft#7633 * Ponytail comment erased Co-authored-by: Copilot Autofix powered by AI <[email protected]> * Clarify TODO comment regarding memory method rename Updated TODO comment to include author and clarify context , to resolve linting error --------- Co-authored-by: Copilot Autofix powered by AI <[email protected]>
1 parent 9a06fa3 commit 9645d33

3 files changed

Lines changed: 39 additions & 14 deletions

File tree

‎python/packages/azure-cosmos-memory/agent_framework_azure_cosmos_memory/_context_provider.py‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -435,13 +435,17 @@ async def after_run(
435435
user_id = self._resolve_user_id(state, session)
436436
thread_id = state.get("thread_id") or session.session_id or "default"
437437

438+
# TODO(atty57): The toolkit renamed add_cosmos -> upsert_memory (same kwargs); accept either
439+
# until the declared azure-cosmos-agent-memory floor is past the rename, then inline it.
440+
write_turn = getattr(self.memory_client, "upsert_memory", None) or self.memory_client.add_cosmos
441+
438442
try:
439443
# Store input messages (skip empty/whitespace-only content to avoid junk turns)
440444
for msg in context.input_messages:
441445
if hasattr(msg, "role") and hasattr(msg, "text") and msg.text and msg.text.strip():
442446
role_value = getattr(msg.role, "value", None) or str(msg.role)
443447
if role_value in {"user", "assistant", "system"}:
444-
await self.memory_client.add_cosmos(
448+
await write_turn(
445449
user_id=user_id,
446450
thread_id=thread_id,
447451
role=self._ROLE_MAP.get(role_value, role_value),
@@ -454,15 +458,15 @@ async def after_run(
454458
if hasattr(msg, "role") and hasattr(msg, "text") and msg.text and msg.text.strip():
455459
role_value = getattr(msg.role, "value", None) or str(msg.role)
456460
if role_value in {"user", "assistant", "system"}:
457-
await self.memory_client.add_cosmos(
461+
await write_turn(
458462
user_id=user_id,
459463
thread_id=thread_id,
460464
role=self._ROLE_MAP.get(role_value, role_value),
461465
content=msg.text.strip(),
462466
)
463467

464468
# Auto-extraction and processing:
465-
# When auto_extract is True (default), add_cosmos() schedules cadence-aware background
469+
# When auto_extract is True (default), the turn write schedules cadence-aware background
466470
# processing (fact extraction, summaries, reconciliation) based on the configured
467471
# thresholds (FACT_EXTRACTION_EVERY_N, DEDUP_EVERY_N, etc.), so no explicit
468472
# process_now() call is needed. When auto_extract is False, those thresholds were

‎python/packages/azure-cosmos-memory/tests/test_context_provider.py‎

Lines changed: 30 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def mock_memory_client() -> AsyncMock:
5252
mock_client = AsyncMock()
5353
mock_client.search_cosmos = AsyncMock(return_value=[])
5454
mock_client.get_user_summary = AsyncMock(return_value=None)
55-
mock_client.add_cosmos = AsyncMock()
55+
mock_client.upsert_memory = AsyncMock()
5656
mock_client.create_memory_store = AsyncMock()
5757
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
5858
mock_client.__aexit__ = AsyncMock()
@@ -468,8 +468,8 @@ async def test_stores_input_and_response_messages(self, mock_memory_client: Asyn
468468
agent=_STUB_AGENT, session=session, context=ctx, state=session.state.setdefault(provider.source_id, {})
469469
)
470470

471-
assert mock_memory_client.add_cosmos.await_count == 2
472-
calls = mock_memory_client.add_cosmos.await_args_list
471+
assert mock_memory_client.upsert_memory.await_count == 2
472+
calls = mock_memory_client.upsert_memory.await_args_list
473473

474474
# Check input message stored
475475
assert calls[0].kwargs["role"] == "user"
@@ -499,7 +499,7 @@ async def test_assistant_role_mapped_to_agent(self, mock_memory_client: AsyncMoc
499499
agent=_STUB_AGENT, session=session, context=ctx, state=session.state.setdefault(provider.source_id, {})
500500
)
501501

502-
stored_roles = [c.kwargs["role"] for c in mock_memory_client.add_cosmos.await_args_list]
502+
stored_roles = [c.kwargs["role"] for c in mock_memory_client.upsert_memory.await_args_list]
503503
assert stored_roles == ["user", "agent"]
504504
# No raw "assistant" role should ever be sent to the toolkit.
505505
assert "assistant" not in stored_roles
@@ -520,7 +520,7 @@ async def test_uses_custom_user_and_thread_ids(self, mock_memory_client: AsyncMo
520520
agent=_STUB_AGENT, session=session, context=ctx, state=session.state.setdefault(provider.source_id, {})
521521
)
522522

523-
call_kwargs = mock_memory_client.add_cosmos.await_args_list[0].kwargs
523+
call_kwargs = mock_memory_client.upsert_memory.await_args_list[0].kwargs
524524
assert call_kwargs["user_id"] == "user-456"
525525
assert call_kwargs["thread_id"] == "thread-789"
526526

@@ -541,8 +541,8 @@ async def test_skips_empty_messages(self, mock_memory_client: AsyncMock) -> None
541541
)
542542

543543
# Only one message should be stored
544-
assert mock_memory_client.add_cosmos.await_count == 1
545-
call_kwargs = mock_memory_client.add_cosmos.await_args_list[0].kwargs
544+
assert mock_memory_client.upsert_memory.await_count == 1
545+
call_kwargs = mock_memory_client.upsert_memory.await_args_list[0].kwargs
546546
assert call_kwargs["content"] == "Valid message"
547547

548548
async def test_skips_whitespace_only_messages(self, mock_memory_client: AsyncMock) -> None:
@@ -563,15 +563,35 @@ async def test_skips_whitespace_only_messages(self, mock_memory_client: AsyncMoc
563563
)
564564

565565
# Whitespace-only input and the whitespace-only response are both skipped.
566-
assert mock_memory_client.add_cosmos.await_count == 1
567-
call_kwargs = mock_memory_client.add_cosmos.await_args_list[0].kwargs
566+
assert mock_memory_client.upsert_memory.await_count == 1
567+
call_kwargs = mock_memory_client.upsert_memory.await_args_list[0].kwargs
568568
assert call_kwargs["content"] == "Trimmed message"
569569

570+
async def test_falls_back_to_add_cosmos_on_older_toolkit(self) -> None:
571+
"""Toolkit versions predating the upsert_memory rename still receive turns.
572+
573+
The declared azure-cosmos-agent-memory range spans both names, so a resolved
574+
install can expose either one; picking neither would silently drop every turn.
575+
"""
576+
legacy_client = AsyncMock(spec=["add_cosmos", "search_cosmos", "get_user_summary"])
577+
legacy_client.add_cosmos = AsyncMock()
578+
579+
provider = CosmosMemoryContextProvider(memory_client=legacy_client)
580+
session = AgentSession(session_id="test-session")
581+
ctx = SessionContext(input_messages=[Message(role="user", contents=["Hello"])], session_id="s1")
582+
583+
await provider.after_run(
584+
agent=_STUB_AGENT, session=session, context=ctx, state=session.state.setdefault(provider.source_id, {})
585+
)
586+
587+
assert legacy_client.add_cosmos.await_count == 1
588+
assert legacy_client.add_cosmos.await_args_list[0].kwargs["content"] == "Hello"
589+
570590
async def test_storage_failure_logs_warning(
571591
self, mock_memory_client: AsyncMock, caplog: pytest.LogCaptureFixture
572592
) -> None:
573593
"""Storage failures are logged but don't raise."""
574-
mock_memory_client.add_cosmos.side_effect = Exception("Storage failed")
594+
mock_memory_client.upsert_memory.side_effect = Exception("Storage failed")
575595

576596
provider = CosmosMemoryContextProvider(memory_client=mock_memory_client)
577597
session = AgentSession(session_id="test-session")

‎python/packages/azure-cosmos-memory/tests/test_emulator.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,8 @@ async def test_before_run_retrieves_seeded_fact(self, emulator_provider: CosmosM
183183
# embeddings client). This lands in the memories container under the quantizedFlat
184184
# vector index, without needing LLM extraction.
185185
assert provider.memory_client is not None
186-
await provider.memory_client.add_cosmos(
186+
seed = getattr(provider.memory_client, "upsert_memory", None) or provider.memory_client.add_cosmos
187+
await seed(
187188
user_id=user_id,
188189
thread_id=thread_id,
189190
role="user",

0 commit comments

Comments
 (0)