mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
1e350ea22f
* 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
254 lines
9.8 KiB
Python
254 lines
9.8 KiB
Python
# Copyright (c) Microsoft. All rights reserved.
|
|
|
|
from collections.abc import AsyncIterable, Awaitable
|
|
from typing import Any
|
|
|
|
import pytest
|
|
from agent_framework import (
|
|
AgentExecutorResponse,
|
|
AgentResponse,
|
|
AgentResponseUpdate,
|
|
AgentSession,
|
|
BaseAgent,
|
|
Content,
|
|
Executor,
|
|
Message,
|
|
TypeCompatibilityError,
|
|
WorkflowContext,
|
|
WorkflowRunState,
|
|
handler,
|
|
)
|
|
from agent_framework._workflows._checkpoint import InMemoryCheckpointStorage
|
|
from agent_framework.orchestrations import SequentialBuilder
|
|
|
|
|
|
class _EchoAgent(BaseAgent):
|
|
"""Simple agent that appends a single assistant message with its name."""
|
|
|
|
def run( # type: ignore[override]
|
|
self,
|
|
messages: str | Message | list[str] | list[Message] | None = None,
|
|
*,
|
|
stream: bool = False,
|
|
session: AgentSession | None = None,
|
|
**kwargs: Any,
|
|
) -> Awaitable[AgentResponse] | AsyncIterable[AgentResponseUpdate]:
|
|
if stream:
|
|
return self._run_stream()
|
|
|
|
async def _run() -> AgentResponse:
|
|
return AgentResponse(messages=[Message("assistant", [f"{self.name} reply"])])
|
|
|
|
return _run()
|
|
|
|
async def _run_stream(self) -> AsyncIterable[AgentResponseUpdate]:
|
|
# Minimal async generator with one assistant update
|
|
yield AgentResponseUpdate(contents=[Content.from_text(text=f"{self.name} reply")])
|
|
|
|
|
|
class _SummarizerExec(Executor):
|
|
"""Custom executor that summarizes by appending a short assistant message."""
|
|
|
|
@handler
|
|
async def summarize(self, agent_response: AgentExecutorResponse, ctx: WorkflowContext[list[Message]]) -> None:
|
|
conversation = agent_response.full_conversation or []
|
|
user_texts = [m.text for m in conversation if m.role == "user"]
|
|
agents = [m.author_name or m.role for m in conversation if m.role == "assistant"]
|
|
summary = Message("assistant", [f"Summary of users:{len(user_texts)} agents:{len(agents)}"])
|
|
await ctx.send_message(list(conversation) + [summary])
|
|
|
|
|
|
class _InvalidExecutor(Executor):
|
|
"""Invalid executor that does not have a handler that accepts a list of chat messages"""
|
|
|
|
@handler
|
|
async def summarize(self, conversation: list[str], ctx: WorkflowContext[list[Message]]) -> None:
|
|
pass
|
|
|
|
|
|
def test_sequential_builder_rejects_empty_participants() -> None:
|
|
with pytest.raises(ValueError):
|
|
SequentialBuilder(participants=[])
|
|
|
|
|
|
def test_sequential_builder_validation_rejects_invalid_executor() -> None:
|
|
"""Test that adding an invalid executor to the builder raises an error."""
|
|
with pytest.raises(TypeCompatibilityError):
|
|
SequentialBuilder(participants=[_EchoAgent(id="agent1", name="A1"), _InvalidExecutor(id="invalid")]).build()
|
|
|
|
|
|
async def test_sequential_agents_append_to_context() -> None:
|
|
a1 = _EchoAgent(id="agent1", name="A1")
|
|
a2 = _EchoAgent(id="agent2", name="A2")
|
|
|
|
wf = SequentialBuilder(participants=[a1, a2]).build()
|
|
|
|
completed = False
|
|
output: list[Message] | None = None
|
|
async for ev in wf.run("hello sequential", stream=True):
|
|
if ev.type == "status" and ev.state == WorkflowRunState.IDLE:
|
|
completed = True
|
|
elif ev.type == "output":
|
|
output = ev.data # type: ignore[assignment]
|
|
if completed and output is not None:
|
|
break
|
|
|
|
assert completed
|
|
assert output is not None
|
|
assert isinstance(output, list)
|
|
msgs: list[Message] = output
|
|
assert len(msgs) == 3
|
|
assert msgs[0].role == "user" and "hello sequential" in msgs[0].text
|
|
assert msgs[1].role == "assistant" and (msgs[1].author_name == "A1" or True)
|
|
assert msgs[2].role == "assistant" and (msgs[2].author_name == "A2" or True)
|
|
assert "A1 reply" in msgs[1].text
|
|
assert "A2 reply" in msgs[2].text
|
|
|
|
|
|
async def test_sequential_with_custom_executor_summary() -> None:
|
|
a1 = _EchoAgent(id="agent1", name="A1")
|
|
summarizer = _SummarizerExec(id="summarizer")
|
|
|
|
wf = SequentialBuilder(participants=[a1, summarizer]).build()
|
|
|
|
completed = False
|
|
output: list[Message] | None = None
|
|
async for ev in wf.run("topic X", stream=True):
|
|
if ev.type == "status" and ev.state == WorkflowRunState.IDLE:
|
|
completed = True
|
|
elif ev.type == "output":
|
|
output = ev.data
|
|
if completed and output is not None:
|
|
break
|
|
|
|
assert completed
|
|
assert output is not None
|
|
msgs: list[Message] = output
|
|
# Expect: [user, A1 reply, summary]
|
|
assert len(msgs) == 3
|
|
assert msgs[0].role == "user"
|
|
assert msgs[1].role == "assistant" and "A1 reply" in msgs[1].text
|
|
assert msgs[2].role == "assistant" and msgs[2].text.startswith("Summary of users:")
|
|
|
|
|
|
async def test_sequential_checkpoint_resume_round_trip() -> None:
|
|
storage = InMemoryCheckpointStorage()
|
|
|
|
initial_agents = (_EchoAgent(id="agent1", name="A1"), _EchoAgent(id="agent2", name="A2"))
|
|
wf = SequentialBuilder(participants=list(initial_agents), checkpoint_storage=storage).build()
|
|
|
|
baseline_output: list[Message] | None = None
|
|
async for ev in wf.run("checkpoint sequential", stream=True):
|
|
if ev.type == "output":
|
|
baseline_output = ev.data # type: ignore[assignment]
|
|
if ev.type == "status" and ev.state == WorkflowRunState.IDLE:
|
|
break
|
|
|
|
assert baseline_output is not None
|
|
|
|
checkpoints = await storage.list_checkpoints(workflow_name=wf.name)
|
|
assert checkpoints
|
|
checkpoints.sort(key=lambda cp: cp.timestamp)
|
|
resume_checkpoint = checkpoints[0]
|
|
|
|
resumed_agents = (_EchoAgent(id="agent1", name="A1"), _EchoAgent(id="agent2", name="A2"))
|
|
wf_resume = SequentialBuilder(participants=list(resumed_agents), checkpoint_storage=storage).build()
|
|
|
|
resumed_output: list[Message] | None = None
|
|
async for ev in wf_resume.run(checkpoint_id=resume_checkpoint.checkpoint_id, stream=True):
|
|
if ev.type == "output":
|
|
resumed_output = ev.data # type: ignore[assignment]
|
|
if ev.type == "status" and ev.state in (
|
|
WorkflowRunState.IDLE,
|
|
WorkflowRunState.IDLE_WITH_PENDING_REQUESTS,
|
|
):
|
|
break
|
|
|
|
assert resumed_output is not None
|
|
assert [m.role for m in resumed_output] == [m.role for m in baseline_output]
|
|
assert [m.text for m in resumed_output] == [m.text for m in baseline_output]
|
|
|
|
|
|
async def test_sequential_checkpoint_runtime_only() -> None:
|
|
"""Test checkpointing configured ONLY at runtime, not at build time."""
|
|
storage = InMemoryCheckpointStorage()
|
|
|
|
agents = (_EchoAgent(id="agent1", name="A1"), _EchoAgent(id="agent2", name="A2"))
|
|
wf = SequentialBuilder(participants=list(agents)).build()
|
|
|
|
baseline_output: list[Message] | None = None
|
|
async for ev in wf.run("runtime checkpoint test", checkpoint_storage=storage, stream=True):
|
|
if ev.type == "output":
|
|
baseline_output = ev.data # type: ignore[assignment]
|
|
if ev.type == "status" and ev.state == WorkflowRunState.IDLE:
|
|
break
|
|
|
|
assert baseline_output is not None
|
|
|
|
checkpoints = await storage.list_checkpoints(workflow_name=wf.name)
|
|
assert checkpoints
|
|
checkpoints.sort(key=lambda cp: cp.timestamp)
|
|
resume_checkpoint = checkpoints[0]
|
|
|
|
resumed_agents = (_EchoAgent(id="agent1", name="A1"), _EchoAgent(id="agent2", name="A2"))
|
|
wf_resume = SequentialBuilder(participants=list(resumed_agents)).build()
|
|
|
|
resumed_output: list[Message] | None = None
|
|
async for ev in wf_resume.run(
|
|
checkpoint_id=resume_checkpoint.checkpoint_id, checkpoint_storage=storage, stream=True
|
|
):
|
|
if ev.type == "output":
|
|
resumed_output = ev.data # type: ignore[assignment]
|
|
if ev.type == "status" and ev.state in (
|
|
WorkflowRunState.IDLE,
|
|
WorkflowRunState.IDLE_WITH_PENDING_REQUESTS,
|
|
):
|
|
break
|
|
|
|
assert resumed_output is not None
|
|
assert [m.role for m in resumed_output] == [m.role for m in baseline_output]
|
|
assert [m.text for m in resumed_output] == [m.text for m in baseline_output]
|
|
|
|
|
|
async def test_sequential_checkpoint_runtime_overrides_buildtime() -> None:
|
|
"""Test that runtime checkpoint storage overrides build-time configuration."""
|
|
import tempfile
|
|
|
|
with tempfile.TemporaryDirectory() as temp_dir1, tempfile.TemporaryDirectory() as temp_dir2:
|
|
from agent_framework._workflows._checkpoint import FileCheckpointStorage
|
|
|
|
buildtime_storage = FileCheckpointStorage(temp_dir1)
|
|
runtime_storage = FileCheckpointStorage(temp_dir2)
|
|
|
|
agents = (_EchoAgent(id="agent1", name="A1"), _EchoAgent(id="agent2", name="A2"))
|
|
wf = SequentialBuilder(participants=list(agents), checkpoint_storage=buildtime_storage).build()
|
|
|
|
baseline_output: list[Message] | None = None
|
|
async for ev in wf.run("override test", checkpoint_storage=runtime_storage, stream=True):
|
|
if ev.type == "output":
|
|
baseline_output = ev.data # type: ignore[assignment]
|
|
if ev.type == "status" and ev.state == WorkflowRunState.IDLE:
|
|
break
|
|
|
|
assert baseline_output is not None
|
|
|
|
buildtime_checkpoints = await buildtime_storage.list_checkpoints(workflow_name=wf.name)
|
|
runtime_checkpoints = await runtime_storage.list_checkpoints(workflow_name=wf.name)
|
|
|
|
assert len(runtime_checkpoints) > 0, "Runtime storage should have checkpoints"
|
|
assert len(buildtime_checkpoints) == 0, "Build-time storage should have no checkpoints when overridden"
|
|
|
|
|
|
async def test_sequential_builder_reusable_after_build_with_participants() -> None:
|
|
"""Test that the builder can be reused to build multiple identical workflows with participants()."""
|
|
a1 = _EchoAgent(id="agent1", name="A1")
|
|
a2 = _EchoAgent(id="agent2", name="A2")
|
|
|
|
builder = SequentialBuilder(participants=[a1, a2])
|
|
|
|
# Build first workflow
|
|
builder.build()
|
|
|
|
assert builder._participants[0] is a1 # type: ignore
|
|
assert builder._participants[1] is a2 # type: ignore
|