Skip to content

A programming framework for agentic AI

add simple chainlit integration (#3999)

Mohammad Mazraeh4023454c5840
diff --git a/python/packages/autogen-core/docs/src/user-guide/core-user-guide/framework/distributed-agent-runtime.ipynb b/python/packages/autogen-core/docs/src/user-guide/core-user-guide/framework/distributed-agent-runtime.ipynb
index 290341123..833799c20 100644
--- a/python/packages/autogen-core/docs/src/user-guide/core-user-guide/framework/distributed-agent-runtime.ipynb
+++ b/python/packages/autogen-core/docs/src/user-guide/core-user-guide/framework/distributed-agent-runtime.ipynb
@@ -188,7 +188,7 @@
"\n",
"- [Distributed Workers](https://github.com/microsoft/autogen/tree/main/python/packages/autogen-core/samples/worker) \n",
"- [Distributed Semantic Router](https://github.com/microsoft/autogen/tree/main/python/packages/autogen-core/samples/semantic_router) \n",
- "- [Distributed Group Chat](https://github.com/microsoft/autogen/tree/main/python/packages/autogen-core/samples/distributed_group_chat) \n"
+ "- [Distributed Group Chat](https://github.com/microsoft/autogen/tree/main/python/packages/autogen-core/samples/distributed-group-chat) \n"
]
}
],
diff --git a/python/packages/autogen-core/samples/distributed-group-chat/.gitattributes b/python/packages/autogen-core/samples/distributed-group-chat/.gitattributes
deleted file mode 100644
index 6884bd468..000000000
--- a/python/packages/autogen-core/samples/distributed-group-chat/.gitattributes
+++ /dev/null
@@ -1 +0,0 @@
-distributed_group_chat.gif filter=lfs diff=lfs merge=lfs -text
diff --git a/python/packages/autogen-core/samples/distributed-group-chat/.gitignore b/python/packages/autogen-core/samples/distributed-group-chat/.gitignore
new file mode 100644
index 000000000..2121b2589
--- /dev/null
+++ b/python/packages/autogen-core/samples/distributed-group-chat/.gitignore
@@ -0,0 +1 @@
+.chainlit
diff --git a/python/packages/autogen-core/samples/distributed-group-chat/README.md b/python/packages/autogen-core/samples/distributed-group-chat/README.md
index b62085ae9..43d17ee0e 100644
--- a/python/packages/autogen-core/samples/distributed-group-chat/README.md
+++ b/python/packages/autogen-core/samples/distributed-group-chat/README.md
@@ -8,7 +8,8 @@ This example runs a gRPC server using [WorkerAgentRuntimeHost](../../src/autogen
### Setup Python Environment
-You should run this project using the same virtual environment created for it. Instructions are provided in the [README](../../../../../../../../README.md).
+1. Create a virtual environment as instructed in [README](../../../../../../../../README.md).
+2. Run `uv pip install chainlit` in the same virtual environment
### General Configuration
@@ -30,7 +31,7 @@ The [run.sh](./run.sh) file provides commands to run the host and agents using [
Here is a screen recording of the execution:
-![Distributed Group Chat Sample Run](./distributed_group_chat.gif)
+[![Distributed Group Chat Demo with Simple UI Integration](https://img.youtube.com/vi/kLTzI-3VgPQ/0.jpg)](https://youtu.be/kLTzI-3VgPQ)
**Note**: Some `asyncio.sleep` commands have been added to the example code to make the `./run.sh` execution look sequential and visually easy to follow. In practice, these lines are not necessary.
@@ -39,21 +40,21 @@ Here is a screen recording of the execution:
If you prefer to run Python files individually, follow these steps. Note that each step must be run in a different terminal process, and the virtual environment should be activated using `source .venv/bin/activate`.
1. `python run_host.py`: Starts the host and listens for agent connections.
-2. `python run_editor.py`: Starts the editor agent and connects it to the host.
-3. `python run_writer.py`: Starts the writer agent and connects it to the host.
-4. `python run_group_chat_manager.py`: Starts the group chat manager and sends a message to initiate the writer agent.
+2. `python run_editor.py`: Starts the <img src="./public/avatars/editor.png" width="20" height="20" style="vertical-align:middle"> editor agent and connects it to the host.
+3. `python run_writer.py`: Starts the <img src="./public/avatars/writer.png" width="20" height="20" style="vertical-align:middle"> writer agent and connects it to the host.
+4. `chainlit run run_group_chat_manager.py --port 8001`: Run chainlit app which starts <img src="./public/avatars/group_chat_manager.png" width="20" height="20" style="vertical-align:middle"> group chat manager agent and sends the initial message to start the conversation. We're using port 8001 as the default port 8000 is used to run host (assuming using same machine to run all of the agents)
## What's Going On?
The general flow of this example is as follows:
-1. The Group Chat Manager sends a `RequestToSpeak` request to the `writer_agent`.
-2. The `writer_agent` writes a short sentence into the group chat topic.
-3. The `editor_agent` receives the message in the group chat topic and updates its memory.
-4. The Group Chat Manager receives the message sent by the writer into the group chat simultaneously and sends the next participant, the `editor_agent`, a `RequestToSpeak` message.
-5. The `editor_agent` sends its feedback to the group chat topic.
-6. The `writer_agent` receives the feedback and updates its memory.
-7. The Group Chat Manager receives the message simultaneously and repeats the loop from step 1.
+1. The <img src="./public/avatars/group_chat_manager.png" width="20" height="20" style="vertical-align:middle"> Group Chat Manager, on behalf of <img src="./public/avatars/user.png" width="20" height="20" style="vertical-align:middle"> `User`, sends a `RequestToSpeak` request to the <img src="./public/avatars/writer.png" width="20" height="20" style="vertical-align:middle"> `writer_agent`.
+2. The <img src="./public/avatars/writer.png" width="20" height="20" style="vertical-align:middle"> `writer_agent` writes a short sentence into the group chat topic.
+3. The <img src="./public/avatars/editor.png" width="20" height="20" style="vertical-align:middle"> `editor_agent` receives the message in the group chat topic and updates its memory.
+4. The <img src="./public/avatars/group_chat_manager.png" width="20" height="20" style="vertical-align:middle"> Group Chat Manager receives the message sent by the writer into the group chat simultaneously and sends the next participant, the <img src="./public/avatars/editor.png" width="20" height="20" style="vertical-align:middle"> `editor_agent`, a `RequestToSpeak` message.
+5. The <img src="./public/avatars/editor.png" width="20" height="20" style="vertical-align:middle"> `editor_agent` sends its feedback to the group chat topic.
+6. The <img src="./public/avatars/writer.png" width="20" height="20" style="vertical-align:middle"> `writer_agent` receives the feedback and updates its memory.
+7. The <img src="./public/avatars/group_chat_manager.png" width="20" height="20" style="vertical-align:middle"> Group Chat Manager receives the message simultaneously and repeats the loop from step 1.
Here is an illustration of the system developed in this example:
@@ -67,21 +68,21 @@ graph TD;
end
subgraph Distributed Writer Runtime
- writer_agent[Writer Agent] --> A1
+ writer_agent[<img src="./public/avatars/writer.png" width="50"/> Writer Agent] --> A1
wt -.->|2 - Subscription| writer_agent
gct -.->|4 - Subscription| writer_agent
writer_agent -.->|3 - Publish: Group Chat Message| gct
end
subgraph Distributed Editor Runtime
- editor_agent[Editor Agent] --> A1
+ editor_agent[<img src="./public/avatars/editor.png" width="50"/> Editor Agent] --> A1
et -.->|6 - Subscription| editor_agent
gct -.->|4 - Subscription| editor_agent
editor_agent -.->|7 - Publish: Group Chat Message| gct
end
subgraph Distributed Group Chat Manager Runtime
- group_chat_manager[Group Chat Manager Agent] --> A1
+ group_chat_manager[<img src="./public/avatars/group_chat_manager.png" width="50"/> Group Chat Manager Agent] --> A1
gct -.->|4 - Subscription| group_chat_manager
group_chat_manager -.->|1 - Request To Speak| wt
group_chat_manager -.->|5 - Request To Speak| et
@@ -93,4 +94,11 @@ graph TD;
style writer_agent fill:#b7c4d7,color:#000
style editor_agent fill:#b7c4d7,color:#000
style group_chat_manager fill:#b7c4d7,color:#000
+
```
+
+## TODO:
+
+- [ ] Properly handle chat restarts. It complains about group chat manager being already registered
+- [ ] Send Chainlit messages within each agent (Currently the manager can just sends messages in the group chat topic)
+- [ ] Add streaming to the UI like [this example](https://docs.chainlit.io/advanced-features/streaming) but Autogen's Open AI Client [does not supporting streaming yet](https://github.com/microsoft/autogen/blob/0f4dd0cc6dd3eea303ad3d2063979b4b9a1aacfc/python/packages/autogen-ext/src/autogen_ext/models/_openai/_openai_client.py#L81)
diff --git a/python/packages/autogen-core/samples/distributed-group-chat/_agents.py b/python/packages/autogen-core/samples/distributed-group-chat/_agents.py
index 968fd3b66..89ac74555 100644
--- a/python/packages/autogen-core/samples/distributed-group-chat/_agents.py
+++ b/python/packages/autogen-core/samples/distributed-group-chat/_agents.py
@@ -1,4 +1,4 @@
-from typing import List
+from typing import Awaitable, Callable, List
from _types import GroupChatMessage, RequestToSpeak
from autogen_core.base import MessageContext
@@ -61,6 +61,7 @@ class GroupChatManager(RoutedAgent):
model_client: ChatCompletionClient,
participant_topic_types: List[str],
participant_descriptions: List[str],
+ on_message_func: Callable[[str, str], Awaitable[None]],
max_rounds: int = 3,
) -> None:
super().__init__("Group chat manager")
@@ -70,14 +71,15 @@ class GroupChatManager(RoutedAgent):
self._chat_history: List[GroupChatMessage] = []
self._max_rounds = max_rounds
self.console = Console()
+ self._on_message_func = on_message_func
self._participant_descriptions = participant_descriptions
self._previous_participant_topic_type: str | None = None
@message_handler
async def handle_message(self, message: GroupChatMessage, ctx: MessageContext) -> None:
assert isinstance(message.body, UserMessage)
-
- self._chat_history.append(message.body) # type: ignore[reportargumenttype]
+ await self._on_message_func(message.body.content, message.body.source) # type: ignore[arg-type]
+ self._chat_history.append(message.body) # type: ignore[reportargumenttype,arg-type]
# Format message history.
messages: List[str] = []
@@ -118,11 +120,9 @@ Read the above conversation. Then select the next role from {participants} to pl
assert isinstance(completion.content, str)
if completion.content.upper() == "FINISH":
- self.console.print(
- Markdown(
- f"\n{'-'*80}\n Manager ({id(self)}): I think it's enough iterations on the story! Thanks for collaborating!"
- )
- )
+ manager_message = f"\n{'-'*80}\n Manager ({id(self)}): I think it's enough iterations on the story! Thanks for collaborating!"
+ await self._on_message_func(manager_message, "group_chat_manager")
+ self.console.print(Markdown(manager_message))
return
selected_topic_type: str
diff --git a/python/packages/autogen-core/samples/distributed-group-chat/_utils.py b/python/packages/autogen-core/samples/distributed-group-chat/_utils.py
index 737bb8bda..2c4b768e4 100644
--- a/python/packages/autogen-core/samples/distributed-group-chat/_utils.py
+++ b/python/packages/autogen-core/samples/distributed-group-chat/_utils.py
@@ -1,3 +1,4 @@
+import logging
import os
from typing import Any, Iterable, Type
@@ -32,3 +33,11 @@ def get_serializers(types: Iterable[Type[Any]]) -> list[MessageSerializer[Any]]:
for type in types:
serializers.extend(try_get_known_serializers_for_type(type)) # type: ignore
return serializers # type: ignore [reportUnknownVariableType]
+
+
+# TODO: This is a helper function to get rid of a lot of logs until we find exact loggers to properly set log levels ...
+def set_all_log_levels(log_leve: int):
+ # Iterate through all existing loggers and set their levels
+ for _, logger in logging.root.manager.loggerDict.items():
+ if isinstance(logger, logging.Logger): # Ensure it's actually a Logger object
+ logger.setLevel(log_leve) # Adjust to DEBUG or another level as needed
diff --git a/python/packages/autogen-core/samples/distributed-group-chat/public/avatars/editor.png b/python/packages/autogen-core/samples/distributed-group-chat/public/avatars/editor.png
new file mode 100644
index 000000000..196310477
--- /dev/null
+++ b/python/packages/autogen-core/samples/distributed-group-chat/public/avatars/editor.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:ca081360cdb35adbc43e282675757a8f94a6b59cba38224c36a6ca2a80a4dce5
+size 5675
diff --git a/python/packages/autogen-core/samples/distributed-group-chat/public/avatars/group_chat_manager.png b/python/packages/autogen-core/samples/distributed-group-chat/public/avatars/group_chat_manager.png
new file mode 100644
index 000000000..08a537646
--- /dev/null
+++ b/python/packages/autogen-core/samples/distributed-group-chat/public/avatars/group_chat_manager.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:7e8370f35865293d3126f7f282e6ffef8052a266d205ce2acbee5d211c531a18
+size 6026
diff --git a/python/packages/autogen-core/samples/distributed-group-chat/public/avatars/user.png b/python/packages/autogen-core/samples/distributed-group-chat/public/avatars/user.png
new file mode 100644
index 000000000..8e67f65f3
--- /dev/null
+++ b/python/packages/autogen-core/samples/distributed-group-chat/public/avatars/user.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:52e3e0154e49f6a09b2a16d6671acb98c32ab53490ff080f0674e83163c640e8
+size 5215
diff --git a/python/packages/autogen-core/samples/distributed-group-chat/public/avatars/writer.png b/python/packages/autogen-core/samples/distributed-group-chat/public/avatars/writer.png
new file mode 100644
index 000000000..eacb0bfa1
--- /dev/null
+++ b/python/packages/autogen-core/samples/distributed-group-chat/public/avatars/writer.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:bd82203ec3fa337ea5b61de36c3e4223c175871e40e34ee6b36c3281130979b4
+size 5426
diff --git a/python/packages/autogen-core/samples/distributed-group-chat/public/favicon.png b/python/packages/autogen-core/samples/distributed-group-chat/public/favicon.png
new file mode 100644
index 000000000..27e52d184
--- /dev/null
+++ b/python/packages/autogen-core/samples/distributed-group-chat/public/favicon.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:a60b36ba9e366a244eb641ca59588b6734839c360a42405a369d7af77e7613fc
+size 3700
diff --git a/python/packages/autogen-core/samples/distributed-group-chat/public/logo.png b/python/packages/autogen-core/samples/distributed-group-chat/public/logo.png
new file mode 100644
index 000000000..27e52d184
--- /dev/null
+++ b/python/packages/autogen-core/samples/distributed-group-chat/public/logo.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:a60b36ba9e366a244eb641ca59588b6734839c360a42405a369d7af77e7613fc
+size 3700
diff --git a/python/packages/autogen-core/samples/distributed-group-chat/run.sh b/python/packages/autogen-core/samples/distributed-group-chat/run.sh
index 615ca0189..859096e94 100755
--- a/python/packages/autogen-core/samples/distributed-group-chat/run.sh
+++ b/python/packages/autogen-core/samples/distributed-group-chat/run.sh
@@ -20,7 +20,7 @@ tmux select-pane -t distributed_group_chat:0.0
tmux send-keys -t distributed_group_chat:0.0 "python run_host.py" C-m
tmux send-keys -t distributed_group_chat:0.2 "python run_writer_agent.py" C-m
tmux send-keys -t distributed_group_chat:0.3 "python run_editor_agent.py" C-m
-tmux send-keys -t distributed_group_chat:0.1 "python run_group_chat_manager.py" C-m
+tmux send-keys -t distributed_group_chat:0.1 "chainlit run run_group_chat_manager.py --port 8001" C-m
# # Attach to the session
tmux attach-session -t distributed_group_chat
diff --git a/python/packages/autogen-core/samples/distributed-group-chat/run_editor_agent.py b/python/packages/autogen-core/samples/distributed-group-chat/run_editor_agent.py
index 8d72b631d..a452db6b9 100644
--- a/python/packages/autogen-core/samples/distributed-group-chat/run_editor_agent.py
+++ b/python/packages/autogen-core/samples/distributed-group-chat/run_editor_agent.py
@@ -1,9 +1,10 @@
import asyncio
+import logging
import warnings
from _agents import BaseGroupChatAgent
from _types import AppConfig, GroupChatMessage, RequestToSpeak
-from _utils import get_serializers, load_config
+from _utils import get_serializers, load_config, set_all_log_levels
from autogen_core.application import WorkerAgentRuntime
from autogen_core.components import (
TypeSubscription,
@@ -14,12 +15,12 @@ from rich.markdown import Markdown
async def main(config: AppConfig):
+ set_all_log_levels(logging.ERROR)
editor_agent_runtime = WorkerAgentRuntime(host_address=config.host.address)
editor_agent_runtime.add_message_serializer(get_serializers([RequestToSpeak, GroupChatMessage])) # type: ignore[arg-type]
await asyncio.sleep(4)
Console().print(Markdown("Starting **`Editor Agent`**"))
editor_agent_runtime.start()
-
editor_agent_type = await BaseGroupChatAgent.register(
editor_agent_runtime,
config.editor_agent.topic_type,
@@ -41,5 +42,6 @@ async def main(config: AppConfig):
if __name__ == "__main__":
+ set_all_log_levels(logging.ERROR)
warnings.filterwarnings("ignore", category=UserWarning, message="Resolved model mismatch.*")
asyncio.run(main(load_config()))
diff --git a/python/packages/autogen-core/samples/distributed-group-chat/run_group_chat_manager.py b/python/packages/autogen-core/samples/distributed-group-chat/run_group_chat_manager.py
index 41f5a91a0..5af446ab1 100644
--- a/python/packages/autogen-core/samples/distributed-group-chat/run_group_chat_manager.py
+++ b/python/packages/autogen-core/samples/distributed-group-chat/run_group_chat_manager.py
@@ -1,14 +1,16 @@
import asyncio
+import logging
import warnings
+import chainlit as cl # type: ignore [reportUnknownMemberType] # This dependency is installed through instructions
from _agents import GroupChatManager
from _types import AppConfig, GroupChatMessage, RequestToSpeak
-from _utils import get_serializers, load_config
+from _utils import get_serializers, load_config, set_all_log_levels
from autogen_core.application import WorkerAgentRuntime
from autogen_core.components import (
+ DefaultTopicId,
TypeSubscription,
)
-from autogen_core.components._default_topic import DefaultTopicId
from autogen_core.components.models import (
UserMessage,
)
@@ -16,16 +18,25 @@ from autogen_ext.models import AzureOpenAIChatCompletionClient
from rich.console import Console
from rich.markdown import Markdown
+set_all_log_levels(logging.ERROR)
+
+
+# TODO: This is the simple hack to send messages to the UI, needs to be improved once we get some help in https://github.com/Chainlit/chainlit/issues/1491
+async def send_cl(msg: str, author: str) -> None:
+ await cl.Message(content=msg, author=author).send() # type: ignore [reportAttributeAccessIssue,reportUnknownMemberType]
+
async def main(config: AppConfig):
- # Add group chat manager runtime
+ set_all_log_levels(logging.ERROR)
group_chat_manager_runtime = WorkerAgentRuntime(host_address=config.host.address)
+ # Add group chat manager runtime
+
group_chat_manager_runtime.add_message_serializer(get_serializers([RequestToSpeak, GroupChatMessage])) # type: ignore[arg-type]
await asyncio.sleep(1)
Console().print(Markdown("Starting **`Group Chat Manager`**"))
group_chat_manager_runtime.start()
-
+ set_all_log_levels(logging.ERROR)
group_chat_manager_type = await GroupChatManager.register(
group_chat_manager_runtime,
"group_chat_manager",
@@ -34,6 +45,7 @@ async def main(config: AppConfig):
participant_topic_types=[config.writer_agent.topic_type, config.editor_agent.topic_type],
participant_descriptions=[config.writer_agent.description, config.editor_agent.description],
max_rounds=config.group_chat_manager.max_rounds,
+ on_message_func=send_cl,
),
)
@@ -59,6 +71,18 @@ async def main(config: AppConfig):
Console().print("Manager left the chat!")
-if __name__ == "__main__":
[email protected]_chat_start # type: ignore
+async def start_chat():
+ set_all_log_levels(logging.ERROR)
warnings.filterwarnings("ignore", category=UserWarning, message="Resolved model mismatch.*")
asyncio.run(main(load_config()))
+
+
+# This can be used for debugging, you can run this file using python
+# if __name__ == "__main__":
+# from chainlit.cli import run_chainlit
+
+# set_all_log_levels(logging.ERROR)
+# run_chainlit(
+# __file__,
+# )
diff --git a/python/packages/autogen-core/samples/distributed-group-chat/run_host.py b/python/packages/autogen-core/samples/distributed-group-chat/run_host.py
index 726d7022e..6f1d1f646 100644
--- a/python/packages/autogen-core/samples/distributed-group-chat/run_host.py
+++ b/python/packages/autogen-core/samples/distributed-group-chat/run_host.py
@@ -7,7 +7,6 @@ from rich.console import Console
from rich.markdown import Markdown
-# TODO: Use config.yaml
async def main(host_config: HostConfig):
host = WorkerAgentRuntimeHost(address=host_config.address)
host.start()
diff --git a/python/packages/autogen-core/samples/distributed-group-chat/run_writer_agent.py b/python/packages/autogen-core/samples/distributed-group-chat/run_writer_agent.py
index 041fe5728..1c6935de3 100644
--- a/python/packages/autogen-core/samples/distributed-group-chat/run_writer_agent.py
+++ b/python/packages/autogen-core/samples/distributed-group-chat/run_writer_agent.py
@@ -1,9 +1,10 @@
import asyncio
+import logging
import warnings
from _agents import BaseGroupChatAgent
from _types import AppConfig, GroupChatMessage, RequestToSpeak
-from _utils import get_serializers, load_config
+from _utils import get_serializers, load_config, set_all_log_levels
from autogen_core.application import WorkerAgentRuntime
from autogen_core.components import (
TypeSubscription,
@@ -14,6 +15,7 @@ from rich.markdown import Markdown
async def main(config: AppConfig) -> None:
+ set_all_log_levels(logging.ERROR)
writer_agent_runtime = WorkerAgentRuntime(host_address=config.host.address)
writer_agent_runtime.add_message_serializer(get_serializers([RequestToSpeak, GroupChatMessage])) # type: ignore[arg-type]
await asyncio.sleep(3)
@@ -41,5 +43,6 @@ async def main(config: AppConfig) -> None:
if __name__ == "__main__":
+ set_all_log_levels(logging.ERROR)
warnings.filterwarnings("ignore", category=UserWarning, message="Resolved model mismatch.*")
asyncio.run(main(load_config()))