Files
agent-framework/python/packages/devui/tests/devui/test_conversations.py
T
Eduard van Valkenburg 1e350ea22f Python: [BREAKING] PR2 — Wire context provider pipeline, remove old types, update all consumers (#3850)
* PR2: Wire context provider pipeline and update all internal consumers

- Replace AgentThread with AgentSession across all packages
- Replace ContextProvider with BaseContextProvider across all packages
- Replace context_provider param with context_providers (Sequence)
- Replace thread= with session= in run() signatures
- Replace get_new_thread() with create_session()
- Add get_session(service_session_id) to agent interface
- DurableAgentThread -> DurableAgentSession
- Remove _notify_thread_of_new_messages from WorkflowAgent
- Wire before_run/after_run context provider pipeline in RawAgent
- Auto-inject InMemoryHistoryProvider when no providers configured

* fix: update all tests for context provider pipeline, fix lazy-loaders, remove old test files

* refactor: update all sample files for context provider pipeline (AgentThread→AgentSession, ContextProvider→BaseContextProvider)

* fix: update remaining ag-ui references (client docstring, getting_started sample)

* fix: make get_session service_session_id keyword-only to avoid confusion with session_id

* refactor: rename _RunContext.thread_messages to session_messages

* refactor: remove _threads.py, _memory.py, and old provider files; migrate devui to use plain message lists

* rename: remove _new_ prefix from test files

* refactor: rewrite SlidingWindowChatMessageStore as SlidingWindowHistoryProvider(InMemoryHistoryProvider)

* fix: read full history from session state directly instead of reaching into provider internals

* fix: update stale .pyi stubs, sample imports, and README references for new provider types

* fix: remove stale message_store, _notify_thread_of_new_messages, and session_id.key references in samples

* refactor: merge context_providers and sessions sample folders into sessions, remove aggregate_context_provider

* refactor: UserInfoMemory stores state in session.state instead of instance attributes

* feat: add Pydantic BaseModel support to session state serialization

Pydantic models stored in session.state are now automatically serialized
via model_dump() and restored via model_validate() during to_dict()/from_dict()
round-trips. Models are auto-registered on first serialization; use
register_state_type() for cold-start deserialization.

Also export register_state_type as a public API.

* fix mem0

* Update sample README links and descriptions for session terminology

- Replace 'thread' with 'session' in sample descriptions across all READMEs
- Update file links for renamed samples (mem0_sessions, redis_sessions, etc.)
- Fix Threads section → Sessions section in main samples/README.md
- Update tools, middleware, workflows, durabletask, azure_functions READMEs
- Update architecture diagrams in concepts/tools/README.md
- Update migration guides (autogen, semantic-kernel)

* Fix broken Redis README link to renamed sample

* Fix Mem0 OSS client search: pass scoping params as direct kwargs

AsyncMemory (OSS) expects user_id/agent_id/run_id as direct kwargs,
while AsyncMemoryClient (Platform) expects them in a filters dict.
Adds tests for both client types.

Port of fix from #3844 to new Mem0ContextProvider.

* Fix rebase issues: restore missing _conversation_state.py and checkpoint decode logic

- Add back _conversation_state.py (encode/decode_chat_messages) lost in rebase
- Fix on_checkpoint_restore to decode cache/conversation with decode_chat_messages
- Fix on_checkpoint_restore to use decode_checkpoint_value for pending requests
- Add tests/workflow/__init__.py for relative import support
- Fix test_agent_executor checkpoint selection (checkpoints[1] not superstep)

* Add STORES_BY_DEFAULT ClassVar to skip redundant InMemoryHistoryProvider injection

Chat clients that store history server-side by default (OpenAI Responses API,
Azure AI Agent) now declare STORES_BY_DEFAULT = True. The agent checks this
during auto-injection and skips InMemoryHistoryProvider unless the user
explicitly sets store=False.

* Fix broken markdown links in azure_ai and redis READMEs

* Fix getting-started samples to use session API instead of removed thread/ContextProvider API

* updates to workflow as agent

* fix group chat import

* Rename Thread→Session throughout, fix service_session_id propagation, remove stale AGUIThread

- Fix: Propagate conversation_id from ChatResponse back to session.service_session_id
  in both streaming and non-streaming paths in _agents.py
- Rename AgentThreadException → AgentSessionException
- Remove stale AGUIThread from ag_ui lazy-loader
- Rename use_service_thread → use_service_session in ag-ui package
- Rename test functions from *_thread_* to *_session_*
- Rename sample files from *_thread* to *_session*
- Update docstrings and comments: thread → session
- Update _mcp.py kwargs filter: add 'session' alongside 'thread'
- Fix ContinuationToken docstring example: thread=thread → session=session
- Fix _clients.py docstring: 'Agent threads' → 'Agent sessions'

* Fix broken markdown links after thread→session file renames

* fix azure ai test
2026-02-12 21:00:32 +00:00

322 lines
11 KiB
Python

# Copyright (c) Microsoft. All rights reserved.
"""Tests for conversation store implementation."""
from typing import cast
import pytest
from openai.types.conversations import InputFileContent, InputImageContent, InputTextContent
from agent_framework_devui._conversations import InMemoryConversationStore
@pytest.mark.asyncio
async def test_create_conversation():
"""Test creating a conversation."""
store = InMemoryConversationStore()
conversation = store.create_conversation(metadata={"agent_id": "test_agent"})
assert conversation.id.startswith("conv_")
assert conversation.object == "conversation"
assert conversation.metadata == {"agent_id": "test_agent"}
@pytest.mark.asyncio
async def test_get_conversation():
"""Test retrieving a conversation."""
store = InMemoryConversationStore()
# Create conversation
created = store.create_conversation(metadata={"agent_id": "test_agent"})
# Retrieve it
retrieved = store.get_conversation(created.id)
assert retrieved is not None
assert retrieved.id == created.id
assert retrieved.metadata == {"agent_id": "test_agent"}
@pytest.mark.asyncio
async def test_get_conversation_not_found():
"""Test retrieving non-existent conversation."""
store = InMemoryConversationStore()
conversation = store.get_conversation("conv_nonexistent")
assert conversation is None
@pytest.mark.asyncio
async def test_update_conversation():
"""Test updating conversation metadata."""
store = InMemoryConversationStore()
# Create conversation
created = store.create_conversation(metadata={"agent_id": "test_agent"})
# Update metadata
updated = store.update_conversation(created.id, metadata={"agent_id": "new_agent", "session_id": "sess_123"})
assert updated.id == created.id
assert updated.metadata == {"agent_id": "new_agent", "session_id": "sess_123"}
@pytest.mark.asyncio
async def test_delete_conversation():
"""Test deleting a conversation."""
store = InMemoryConversationStore()
# Create conversation
created = store.create_conversation(metadata={"agent_id": "test_agent"})
# Delete it
result = store.delete_conversation(created.id)
assert result.id == created.id
assert result.deleted is True
assert result.object == "conversation.deleted"
# Verify it's gone
assert store.get_conversation(created.id) is None
@pytest.mark.asyncio
async def test_get_session():
"""Test getting AgentSession for execution."""
store = InMemoryConversationStore()
# Create conversation
conversation = store.create_conversation(metadata={"agent_id": "test_agent"})
# Get session
session = store.get_session(conversation.id)
assert session is not None
# AgentSession should have session_id
assert hasattr(session, "session_id")
@pytest.mark.asyncio
async def test_get_session_not_found():
"""Test getting session for non-existent conversation."""
store = InMemoryConversationStore()
session = store.get_session("conv_nonexistent")
assert session is None
@pytest.mark.asyncio
async def test_list_conversations_by_metadata():
"""Test filtering conversations by metadata."""
store = InMemoryConversationStore()
# Create multiple conversations
_conv1 = store.create_conversation(metadata={"agent_id": "agent1"})
_conv2 = store.create_conversation(metadata={"agent_id": "agent2"})
conv3 = store.create_conversation(metadata={"agent_id": "agent1", "session_id": "sess_1"})
# Filter by agent_id
results = await store.list_conversations_by_metadata({"agent_id": "agent1"})
assert len(results) == 2
assert all(cast(dict[str, str], c.metadata).get("agent_id") == "agent1" for c in results if c.metadata)
# Filter by agent_id and session_id
results = await store.list_conversations_by_metadata({"agent_id": "agent1", "session_id": "sess_1"})
assert len(results) == 1
assert results[0].id == conv3.id
@pytest.mark.asyncio
async def test_add_items():
"""Test adding items to conversation."""
store = InMemoryConversationStore()
# Create conversation
conversation = store.create_conversation(metadata={"agent_id": "test_agent"})
# Add items
items = [{"role": "user", "content": [{"type": "text", "text": "Hello"}]}]
conv_items = await store.add_items(conversation.id, items=items)
assert len(conv_items) == 1
# Message is a ConversationItem type - check standard OpenAI fields
assert conv_items[0].type == "message"
assert conv_items[0].role == "user"
assert conv_items[0].status == "completed"
assert len(conv_items[0].content) == 1
assert conv_items[0].content[0].type == "text"
text_content = cast(InputTextContent, conv_items[0].content[0])
assert text_content.text == "Hello"
@pytest.mark.asyncio
async def test_list_items():
"""Test listing conversation items."""
store = InMemoryConversationStore()
# Create conversation
conversation = store.create_conversation(metadata={"agent_id": "test_agent"})
# Add items
items = [
{"role": "user", "content": [{"type": "text", "text": "Hello"}]},
{"role": "assistant", "content": [{"type": "text", "text": "Hi there"}]},
]
await store.add_items(conversation.id, items=items)
# List items
retrieved_items, has_more = await store.list_items(conversation.id)
assert len(retrieved_items) >= 2 # At least the items we added
assert has_more is False
@pytest.mark.asyncio
async def test_list_items_pagination():
"""Test pagination when listing items."""
store = InMemoryConversationStore()
# Create conversation
conversation = store.create_conversation(metadata={"agent_id": "test_agent"})
# Add multiple items
items = [{"role": "user", "content": [{"type": "text", "text": f"Message {i}"}]} for i in range(5)]
await store.add_items(conversation.id, items=items)
# List with limit
retrieved_items, has_more = await store.list_items(conversation.id, limit=3)
assert len(retrieved_items) == 3
assert has_more is True
@pytest.mark.asyncio
async def test_list_items_converts_function_calls():
"""Test that list_items properly converts function calls to ResponseFunctionToolCallItem."""
from agent_framework import Message
store = InMemoryConversationStore()
# Create conversation
conversation = store.create_conversation(metadata={"agent_id": "test_agent"})
# Simulate messages from agent execution with function calls
messages = [
Message(role="user", contents=[{"type": "text", "text": "What's the weather in SF?"}]),
Message(
role="assistant",
contents=[
{
"type": "function_call",
"name": "get_weather",
"arguments": '{"city": "San Francisco"}',
"call_id": "call_test123",
}
],
),
Message(
role="tool",
contents=[
{
"type": "function_result",
"call_id": "call_test123",
"result": '{"temperature": 65, "condition": "sunny"}',
}
],
),
Message(role="assistant", contents=[{"type": "text", "text": "The weather is sunny, 65°F"}]),
]
# Add messages to internal storage
store._conversations[conversation.id]["messages"].extend(messages)
# List conversation items
items, has_more = await store.list_items(conversation.id)
# Verify we got the right number and types of items
assert len(items) == 4, f"Expected 4 items, got {len(items)}"
assert has_more is False
# Check item types
assert items[0].type == "message", "First item should be a message"
assert items[0].role == "user"
assert len(items[0].content) == 1
text_content_0 = cast(InputTextContent, items[0].content[0])
assert text_content_0.text == "What's the weather in SF?"
assert items[1].type == "function_call", "Second item should be a function_call"
assert items[1].call_id == "call_test123"
assert items[1].name == "get_weather"
assert items[1].arguments == '{"city": "San Francisco"}'
assert items[1].status == "completed"
assert items[2].type == "function_call_output", "Third item should be a function_call_output"
assert items[2].call_id == "call_test123"
assert items[2].output == '{"temperature": 65, "condition": "sunny"}'
assert items[2].status == "completed"
assert items[3].type == "message", "Fourth item should be a message"
assert items[3].role == "assistant"
assert len(items[3].content) == 1
text_content_3 = cast(InputTextContent, items[3].content[0])
assert text_content_3.text == "The weather is sunny, 65°F"
# CRITICAL: Ensure no empty message items
for item in items:
if item.type == "message":
assert len(item.content) > 0, f"Message item {item.id} has empty content!"
@pytest.mark.asyncio
async def test_list_items_handles_images_and_files():
"""Test that list_items properly converts data content (images/files) to OpenAI types."""
from agent_framework import Message
store = InMemoryConversationStore()
# Create conversation
conversation = store.create_conversation(metadata={"agent_id": "test_agent"})
# Simulate message with image and file
messages = [
Message(
role="user",
contents=[
{"type": "text", "text": "Check this image and PDF"},
{"type": "data", "uri": "data:image/png;base64,iVBORw0KGgo=", "media_type": "image/png"},
{"type": "data", "uri": "data:application/pdf;base64,JVBERi0=", "media_type": "application/pdf"},
],
),
]
# Add messages to internal storage
store._conversations[conversation.id]["messages"].extend(messages)
# List items
items, has_more = await store.list_items(conversation.id)
assert len(items) == 1
assert items[0].type == "message"
assert items[0].role == "user"
assert len(items[0].content) == 3
# Check content types
assert items[0].content[0].type == "text"
text_content = cast(InputTextContent, items[0].content[0])
assert text_content.text == "Check this image and PDF"
assert items[0].content[1].type == "input_image"
image_content = cast(InputImageContent, items[0].content[1])
assert image_content.image_url == "data:image/png;base64,iVBORw0KGgo="
assert image_content.detail == "auto"
assert items[0].content[2].type == "input_file"
file_content = cast(InputFileContent, items[0].content[2])
assert file_content.file_url == "data:application/pdf;base64,JVBERi0="