Skip to content

Use class hierarchy to organize AgentChat message types and introduce StructuredMessage type #5998

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 32 commits into from
Mar 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
66c63a7
Introduce StructuredMessage type into ChatMessage
ekzhu Mar 19, 2025
7510a66
Merge branch 'main' into ekzhu-structured-message
ekzhu Mar 19, 2025
234226a
fix type
ekzhu Mar 19, 2025
491cf8f
fix doc
ekzhu Mar 19, 2025
8d7ab69
Merge branch 'main' into ekzhu-structured-message
ekzhu Mar 23, 2025
c80802b
refactor to use base class instead of union for agent chat messages
ekzhu Mar 23, 2025
5b8174b
wip: agentchat done
ekzhu Mar 24, 2025
a4cb79c
improve docs
ekzhu Mar 24, 2025
4660f1d
fix quote
ekzhu Mar 24, 2025
2af8c13
fix
ekzhu Mar 24, 2025
36d0cfb
Merge branch 'main' into ekzhu-structured-message
ekzhu Mar 24, 2025
17370d9
address comments
ekzhu Mar 25, 2025
4494757
Merge branch 'main' into ekzhu-structured-message
ekzhu Mar 25, 2025
b0c2ed1
use content methods instead of content itself
ekzhu Mar 25, 2025
c8f98cb
update
ekzhu Mar 25, 2025
d871cd9
lint
ekzhu Mar 25, 2025
de89005
swap union with base class
ekzhu Mar 25, 2025
864f75c
revert changes to agbench
ekzhu Mar 25, 2025
adc3350
revert changes to ags
ekzhu Mar 25, 2025
1af90db
revert changes
ekzhu Mar 25, 2025
dc0cd08
swap
ekzhu Mar 25, 2025
c87f583
revert
ekzhu Mar 25, 2025
c2d994e
clean up
ekzhu Mar 25, 2025
cb860ac
update
ekzhu Mar 25, 2025
74d6fcf
lint
ekzhu Mar 25, 2025
8813396
move content to concrete classes
ekzhu Mar 25, 2025
9510e09
fix notebook
ekzhu Mar 25, 2025
fe0f05b
lint
ekzhu Mar 25, 2025
2f843a3
rename
ekzhu Mar 25, 2025
79ee7a4
lint
ekzhu Mar 25, 2025
6dcb36a
Merge branch 'main' into ekzhu-structured-message
ekzhu Mar 26, 2025
6a1d51c
Merge branch 'main' into ekzhu-structured-message
ekzhu Mar 26, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
LLMMessage,
ModelFamily,
SystemMessage,
UserMessage,
)
from autogen_core.tools import BaseTool, FunctionTool
from pydantic import BaseModel
Expand Down Expand Up @@ -814,14 +813,13 @@ async def _add_messages_to_context(
messages: Sequence[ChatMessage],
) -> None:
"""
Add incoming user (and possibly handoff) messages to the model context.
Add incoming messages to the model context.
"""
for msg in messages:
if isinstance(msg, HandoffMessage):
# Add handoff context to the model context.
for context_msg in msg.context:
await model_context.add_message(context_msg)
await model_context.add_message(UserMessage(content=msg.content, source=msg.source))
for llm_msg in msg.context:
await model_context.add_message(llm_msg)
await model_context.add_message(msg.to_model_message())

@staticmethod
async def _update_model_context_with_memory(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
from ..base import ChatAgent, Response, TaskResult
from ..messages import (
AgentEvent,
BaseChatMessage,
ChatMessage,
ModelClientStreamingChunkEvent,
TextMessage,
Expand Down Expand Up @@ -121,15 +120,15 @@ async def run(
text_msg = TextMessage(content=task, source="user")
input_messages.append(text_msg)
output_messages.append(text_msg)
elif isinstance(task, BaseChatMessage):
elif isinstance(task, ChatMessage):
input_messages.append(task)
output_messages.append(task)
else:
if not task:
raise ValueError("Task list cannot be empty.")
# Task is a sequence of messages.
for msg in task:
if isinstance(msg, BaseChatMessage):
if isinstance(msg, ChatMessage):
input_messages.append(msg)
output_messages.append(msg)
else:
Expand Down Expand Up @@ -159,15 +158,15 @@ async def run_stream(
input_messages.append(text_msg)
output_messages.append(text_msg)
yield text_msg
elif isinstance(task, BaseChatMessage):
elif isinstance(task, ChatMessage):
input_messages.append(task)
output_messages.append(task)
yield task
else:
if not task:
raise ValueError("Task list cannot be empty.")
for msg in task:
if isinstance(msg, BaseChatMessage):
if isinstance(msg, ChatMessage):
input_messages.append(msg)
output_messages.append(msg)
yield msg
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ class CodeExecutorAgentConfig(BaseModel):


class CodeExecutorAgent(BaseChatAgent, Component[CodeExecutorAgentConfig]):
"""An agent that extracts and executes code snippets found in received messages and returns the output.
"""An agent that extracts and executes code snippets found in received
:class:`~autogen_agentchat.messages.TextMessage` messages and returns the output
of the code execution.

It is typically used within a team with another agent that generates code snippets to be executed.

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from typing import Any, AsyncGenerator, List, Mapping, Sequence

from autogen_core import CancellationToken, Component, ComponentModel
from autogen_core.models import ChatCompletionClient, LLMMessage, SystemMessage, UserMessage
from autogen_core.models import ChatCompletionClient, LLMMessage, SystemMessage
from pydantic import BaseModel
from typing_extensions import Self

Expand All @@ -11,7 +11,6 @@
from ..base import TaskResult, Team
from ..messages import (
AgentEvent,
BaseChatMessage,
ChatMessage,
ModelClientStreamingChunkEvent,
TextMessage,
Expand Down Expand Up @@ -167,13 +166,9 @@ async def on_messages_stream(
else:
# Generate a response using the model client.
llm_messages: List[LLMMessage] = [SystemMessage(content=self._instruction)]
llm_messages.extend(
[
UserMessage(content=message.content, source=message.source)
for message in inner_messages
if isinstance(message, BaseChatMessage)
]
)
for message in messages:
if isinstance(message, ChatMessage):
llm_messages.append(message.to_model_message())
llm_messages.append(SystemMessage(content=self._response_prompt))
completion = await self._model_client.create(messages=llm_messages, cancellation_token=cancellation_token)
assert isinstance(completion.content, str)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ async def simple_user_agent():
cancellation_token=CancellationToken(),
)
)
assert isinstance(response.chat_message, TextMessage)
print(f"Your name is {response.chat_message.content}")

Example:
Expand Down Expand Up @@ -117,6 +118,7 @@ async def cancellable_user_agent():
)
)
response = await agent_task
assert isinstance(response.chat_message, TextMessage)
print(f"Your name is {response.chat_message.content}")
except Exception as e:
print(f"Exception: {e}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
BaseChatMessage,
ChatMessage,
HandoffMessage,
MultiModalMessage,
StopMessage,
TextMessage,
ToolCallExecutionEvent,
Expand Down Expand Up @@ -137,18 +136,12 @@ async def __call__(self, messages: Sequence[AgentEvent | ChatMessage]) -> StopMe
if self._sources is not None and message.source not in self._sources:
continue

if isinstance(message.content, str) and self._termination_text in message.content:
content = message.to_text()
if self._termination_text in content:
self._terminated = True
return StopMessage(
content=f"Text '{self._termination_text}' mentioned", source="TextMentionTermination"
)
elif isinstance(message, MultiModalMessage):
for item in message.content:
if isinstance(item, str) and self._termination_text in item:
self._terminated = True
return StopMessage(
content=f"Text '{self._termination_text}' mentioned", source="TextMentionTermination"
)
return None

async def reset(self) -> None:
Expand Down
Loading
Loading