-
Notifications
You must be signed in to change notification settings - Fork 5.3k
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
Implement custom console for MagenticOne CLI with enhanced message re… #4812
Draft
gagb
wants to merge
8
commits into
main
Choose a base branch
from
gagb-m1
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+95
−5
Draft
Changes from 7 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
f9ac86e
Implement custom console for MagenticOne CLI with enhanced message re…
gagb 5148966
Enhance CustomConsole output with Rich library for improved formatting
gagb 6600408
Refactor CustomConsole to use AutoGenConsole for MagenticOne CLI
gagb 59f00e6
Remove unused imports from MagenticOne CLI main execution block
gagb b3db06b
Replace AutoGenConsole with RichConsole for enhanced output formattin…
gagb 5cec7bb
Add primary color option to RichConsole and adjust output formatting
gagb 7284ae8
Refactor RichConsole to simplify image handling and improve output fo…
gagb 43a3808
Refactor RichConsole to streamline image handling and remove redundan…
gagb File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
117 changes: 117 additions & 0 deletions
117
python/packages/autogen-ext/src/autogen_ext/teams/rich_console.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,117 @@ | ||
import os | ||
import sys | ||
import time | ||
from typing import AsyncGenerator, List, Optional, TypeVar, cast | ||
|
||
from autogen_agentchat.base import Response, TaskResult | ||
from autogen_agentchat.messages import AgentEvent, ChatMessage, MultiModalMessage | ||
from autogen_core import Image | ||
from autogen_core.models import RequestUsage | ||
from rich.console import Console | ||
from rich.panel import Panel | ||
from rich.text import Text | ||
|
||
T = TypeVar("T", bound=TaskResult | Response) | ||
|
||
|
||
def _is_running_in_iterm() -> bool: | ||
return os.getenv("TERM_PROGRAM") == "iTerm.app" | ||
|
||
|
||
def _is_output_a_tty() -> bool: | ||
return sys.stdout.isatty() | ||
|
||
|
||
def _image_to_iterm(image: Image) -> str: | ||
image_data = image.to_base64() | ||
return f"\033]1337;File=inline=1:{image_data}\a\n" | ||
|
||
|
||
def _message_to_str(message: AgentEvent | ChatMessage, *, render_image_iterm: bool = False) -> str: | ||
if isinstance(message, MultiModalMessage): | ||
result: List[str] = [] | ||
for c in message.content: | ||
if isinstance(c, str): | ||
result.append(c) | ||
else: | ||
if render_image_iterm: | ||
result.append(_image_to_iterm(c)) | ||
else: | ||
result.append("<image>") | ||
return "\n".join(result) | ||
else: | ||
return f"{message.content}" | ||
|
||
|
||
async def RichConsole( | ||
stream: AsyncGenerator[AgentEvent | ChatMessage | T, None], | ||
*, | ||
no_inline_images: bool = False, | ||
primary_color: str = "magenta", | ||
) -> T: | ||
render_image_iterm = _is_running_in_iterm() and _is_output_a_tty() and not no_inline_images | ||
start_time = time.time() | ||
total_usage = RequestUsage(prompt_tokens=0, completion_tokens=0) | ||
|
||
last_processed: Optional[T] = None | ||
console = Console() | ||
|
||
async for message in stream: | ||
if isinstance(message, TaskResult): | ||
duration = time.time() - start_time | ||
output = ( | ||
f"Number of messages: {len(message.messages)}\n" | ||
f"Finish reason: {message.stop_reason}\n" | ||
f"Total prompt tokens: {total_usage.prompt_tokens}\n" | ||
f"Total completion tokens: {total_usage.completion_tokens}\n" | ||
f"Duration: {duration:.2f} seconds\n" | ||
) | ||
console.print(Panel(output, title="Summary")) | ||
last_processed = message # type: ignore | ||
|
||
elif isinstance(message, Response): | ||
duration = time.time() - start_time | ||
|
||
output = Text.from_markup(f"{_message_to_str(message.chat_message, render_image_iterm=render_image_iterm)}") | ||
if message.chat_message.models_usage: | ||
output.append( | ||
f"\n[Prompt tokens: {message.chat_message.models_usage.prompt_tokens}, Completion tokens: {message.chat_message.models_usage.completion_tokens}]" | ||
) | ||
total_usage.completion_tokens += message.chat_message.models_usage.completion_tokens | ||
total_usage.prompt_tokens += message.chat_message.models_usage.prompt_tokens | ||
console.print( | ||
Panel(output, title=f"[bold {primary_color}]{message.chat_message.source}[/bold {primary_color}]") | ||
) | ||
|
||
if message.inner_messages is not None: | ||
num_inner_messages = len(message.inner_messages) | ||
else: | ||
num_inner_messages = 0 | ||
output = ( | ||
f"Number of inner messages: {num_inner_messages}\n" | ||
f"Total prompt tokens: {total_usage.prompt_tokens}\n" | ||
f"Total completion tokens: {total_usage.completion_tokens}\n" | ||
f"Duration: {duration:.2f} seconds\n" | ||
) | ||
console.print(Panel(output, title="Summary")) | ||
last_processed = message # type: ignore | ||
|
||
else: | ||
message = cast(AgentEvent | ChatMessage, message) # type: ignore | ||
output = Text.from_markup(f"{_message_to_str(message, render_image_iterm=render_image_iterm)}") | ||
if message.models_usage: | ||
output.append( | ||
f"\n[Prompt tokens: {message.models_usage.prompt_tokens}, Completion tokens: {message.models_usage.completion_tokens}]" | ||
) | ||
total_usage.completion_tokens += message.models_usage.completion_tokens | ||
total_usage.prompt_tokens += message.models_usage.prompt_tokens | ||
console.print(Panel(output, title=f"[bold {primary_color}]{message.source}[/bold {primary_color}]")) | ||
if render_image_iterm and isinstance(message, MultiModalMessage): | ||
for c in message.content: | ||
if isinstance(c, Image): | ||
print(_image_to_iterm(c)) | ||
|
||
if last_processed is None: | ||
raise ValueError("No TaskResult or Response was processed.") | ||
|
||
return last_processed |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Perhaps put it inside
autogen_ext.ui.rich
to match the module layout in agentchat.