-
Notifications
You must be signed in to change notification settings - Fork 0
/
prettyprint.py
248 lines (213 loc) · 9.85 KB
/
prettyprint.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
from typing import Union, Dict, Any, Optional
from rich.console import Console
from rich.panel import Panel
from rich.text import Text
from rich.rule import Rule
from rich.syntax import Syntax
from rich.theme import Theme
from rich.style import Style
import json
import logging
# Custom theme for different roles
custom_theme = Theme({
"supervisor": "bold magenta",
"valuation_analyst": "bold green",
"fundamental_analyst": "bold blue",
"price_analyst": "bold yellow",
"portfolio_manager": "bold red",
"error": "bold red",
"info": "bold cyan",
"warning": "bold yellow",
"success": "bold green"
})
# Define role-specific emojis and styles at module level
role_styles = {
"supervisor": ("🎯", "magenta"),
"valuation_analyst": ("📊", "green"),
"fundamental_analyst": ("💰", "blue"),
"price_analyst": ("📈", "yellow"),
"portfolio_manager": ("👔", "red"),
"user": ("❓", "bold white"),
"assistant": ("🤖", "bold blue"),
"system": ("⚙️", "dim"),
"tool": ("🔧", "yellow")
}
console = Console(theme=custom_theme)
# Custom logging handler using Rich
class RichLoggingHandler(logging.Handler):
def emit(self, record):
# Skip debug messages from httpx, httpcore, etc
if record.name.startswith(('httpx', 'httpcore', 'urllib3')):
return
# Create a styled message based on log level
level_name = record.levelname.lower()
message = record.getMessage()
if level_name == 'error':
console.print(f"[error]❌ {message}[/]")
elif level_name == 'warning':
console.print(f"[warning]⚠️ {message}[/]")
elif level_name == 'info':
console.print(f"[info]ℹ️ {message}[/]")
elif level_name == 'debug':
console.print(f"[dim]🔍 {message}[/]")
def format_json(data: Dict[str, Any]) -> str:
"""Format JSON data for pretty printing"""
return json.dumps(data, indent=2)
def format_code(code: str, language: str = "python") -> Syntax:
"""Format code blocks with syntax highlighting"""
return Syntax(code, language, theme="monokai", line_numbers=True)
def format_error(error: str) -> Text:
"""Format error messages"""
text = Text()
text.append("❌ Error: ", style="error")
text.append(error, style="red")
return text
def format_message_content(content: str) -> Union[str, Text]:
"""Format message content with appropriate styling"""
if not content:
return Text("")
try:
# Try to parse as JSON for structured data
data = json.loads(content)
formatted_json = json.dumps(data, indent=2)
text = Text(formatted_json)
# Highlight keys in JSON
text.highlight_regex(r'"[^"]+":(?=\s)', style="bold blue")
# Highlight numbers
text.highlight_regex(r'\b\d+\.?\d*\b', style="bold green")
return text
except json.JSONDecodeError:
# If not JSON, return as formatted text
text = Text(content)
# Add styling for different elements
# Numbers (including those with BRL prefix)
text.highlight_regex(r'BRL\s*\d+\.?\d*|\b\d+\.?\d*%?\b', style="bold green")
# Markdown-style headers
text.highlight_regex(r'#{1,6}\s+.*$', style="bold cyan", multiline=True)
# Markdown-style bold text
text.highlight_regex(r'\*\*.*?\*\*', style="bold")
# Important keywords
keywords = ['revenue', 'price', 'profit', 'earnings', 'ratio', 'analysis', 'recommendation']
for keyword in keywords:
text.highlight_regex(f'\\b{keyword}\\b', style="italic", ignore_case=True)
# Lists (bullet points)
text.highlight_regex(r'^\s*[-•]\s+.*$', style="yellow", multiline=True)
return text
def format_message(message: Dict[str, Any]) -> Panel:
"""Format a message as a Rich panel with role-specific styling"""
role = message.get("role", "unknown")
name = message.get("name", role)
content = message.get("content", "")
emoji, style = role_styles.get(name, ("💬", "bold white"))
# Format title based on message type
title = f"{emoji} {name.replace('_', ' ').title()}"
if "Routing" in str(content):
title = f"{emoji} Routing Decision"
# Handle tool calls
if "tool_calls" in message:
tool_calls = message.get("tool_calls", [])
content = "Tool Calls:\n" + "\n".join([
f"- {tool.get('function', {}).get('name')}: {tool.get('function', {}).get('arguments')}"
for tool in tool_calls
])
formatted_content = format_message_content(content)
# Add metadata if available
metadata = []
if "timestamp" in message:
metadata.append(f"Time: {message['timestamp']}")
if "tool_name" in message:
metadata.append(f"Tool: {message['tool_name']}")
subtitle = " | ".join(metadata) if metadata else None
return Panel(
formatted_content,
title=title,
subtitle=subtitle,
border_style=style,
padding=(1, 2),
highlight=True
)
def stream_agent_execution(graph, input_data: Dict[str, Any], config: Optional[Dict[str, Any]] = None):
"""Stream the execution of an agent graph with pretty printing"""
try:
# Configure root logger with Rich handler
root_logger = logging.getLogger()
root_logger.handlers = []
rich_handler = RichLoggingHandler()
root_logger.addHandler(rich_handler)
# Print initial separator and user query
console.print(Rule("🚀 Starting Analysis", style="bold cyan"))
if "messages" in input_data and input_data["messages"]:
user_message = input_data["messages"][0]
console.print(Panel(
user_message.content,
title="❓ User Query",
border_style="bold white",
padding=(1, 2)
))
# Track the current step for better visualization
current_step = 1
for output in graph.stream(input_data, config):
if isinstance(output, dict):
# Get the node name (key) and its output (value)
for node_name, node_output in output.items():
# Print supervisor routing
if node_name == "supervisor" and "selected_analysts" in node_output:
analysts = node_output.get("selected_analysts", [])
if analysts:
console.print("\n[bold magenta]🎯 Supervisor Decision:[/]")
console.print(" Routing query to:")
for analyst in analysts:
console.print(f" [magenta]→[/] [bold]{analyst}[/]")
console.print()
# Print analyst responses
elif node_name in ["valuation_analyst", "fundamental_analyst", "price_analyst"]:
if "messages" in node_output:
messages = node_output["messages"]
for message in messages:
# Handle different message types
if hasattr(message, 'name') and hasattr(message, 'content'):
name = message.name if hasattr(message, 'name') else node_name
if name == node_name and message.content:
title_emoji = {
"valuation_analyst": "📊",
"fundamental_analyst": "💰",
"price_analyst": "📈"
}.get(node_name, "🔍")
console.print(Panel(
message.content,
title=f"{title_emoji} {node_name.replace('_', ' ').title()} Analysis",
border_style=role_styles.get(node_name, "blue")[1],
padding=(1, 2)
))
console.print()
# Print final summary
elif node_name == "final_summary":
if "messages" in node_output:
final_message = next(
(msg for msg in node_output["messages"]
if hasattr(msg, 'name') and msg.name == "portfolio_manager"),
None
)
if final_message:
console.print("\n[bold cyan]📊 Final Analysis:[/]")
console.print(Panel(
final_message.content,
border_style="cyan",
padding=(1, 2)
))
console.print()
# Print any errors
if "error" in output:
console.print(Panel(
str(output["error"]),
title="❌ Error",
border_style="red",
padding=(1, 2)
))
except Exception as e:
console.print(format_error(f"Error in stream execution: {str(e)}"))
import traceback
console.print(f"[dim]{traceback.format_exc()}[/]")
finally:
# Print final separator
console.print(Rule("✨ Analysis Complete", style="bold cyan"))