Skip to content

Commit 9491fe8

Browse files
Adding Ability for user to get deeper observability (#3541)
* feat(tracing): enhance first-time trace display and auto-open browser * avoinding line breaking * set tracing if user enables it * linted --------- Co-authored-by: lorenzejay <[email protected]>
1 parent 6f2ea01 commit 9491fe8

File tree

2 files changed

+71
-12
lines changed

2 files changed

+71
-12
lines changed

src/crewai/events/listeners/tracing/first_time_trace_handler.py

Lines changed: 58 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import logging
22
import uuid
3+
import webbrowser
4+
from pathlib import Path
35

46
from rich.console import Console
57
from rich.panel import Panel
@@ -14,6 +16,47 @@
1416
logger = logging.getLogger(__name__)
1517

1618

19+
def _update_or_create_env_file():
20+
"""Update or create .env file with CREWAI_TRACING_ENABLED=true."""
21+
env_path = Path(".env")
22+
env_content = ""
23+
variable_name = "CREWAI_TRACING_ENABLED"
24+
variable_value = "true"
25+
26+
# Read existing content if file exists
27+
if env_path.exists():
28+
with open(env_path, "r") as f:
29+
env_content = f.read()
30+
31+
# Check if CREWAI_TRACING_ENABLED is already set
32+
lines = env_content.splitlines()
33+
variable_exists = False
34+
updated_lines = []
35+
36+
for line in lines:
37+
if line.strip().startswith(f"{variable_name}="):
38+
# Update existing variable
39+
updated_lines.append(f"{variable_name}={variable_value}")
40+
variable_exists = True
41+
else:
42+
updated_lines.append(line)
43+
44+
# Add variable if it doesn't exist
45+
if not variable_exists:
46+
if updated_lines and not updated_lines[-1].strip():
47+
# If last line is empty, replace it
48+
updated_lines[-1] = f"{variable_name}={variable_value}"
49+
else:
50+
# Add new line and then the variable
51+
updated_lines.append(f"{variable_name}={variable_value}")
52+
53+
# Write updated content
54+
with open(env_path, "w") as f:
55+
f.write("\n".join(updated_lines))
56+
if updated_lines: # Add final newline if there's content
57+
f.write("\n")
58+
59+
1760
class FirstTimeTraceHandler:
1861
"""Handles the first-time user trace collection and display flow."""
1962

@@ -48,6 +91,12 @@ def handle_execution_completion(self):
4891
if user_wants_traces:
4992
self._initialize_backend_and_send_events()
5093

94+
# Enable tracing for future runs by updating .env file
95+
try:
96+
_update_or_create_env_file()
97+
except Exception: # noqa: S110
98+
pass
99+
51100
if self.ephemeral_url:
52101
self._display_ephemeral_trace_link()
53102

@@ -108,9 +157,14 @@ def _initialize_backend_and_send_events(self):
108157
self._gracefully_fail(f"Backend initialization failed: {e}")
109158

110159
def _display_ephemeral_trace_link(self):
111-
"""Display the ephemeral trace link to the user."""
160+
"""Display the ephemeral trace link to the user and automatically open browser."""
112161
console = Console()
113162

163+
try:
164+
webbrowser.open(self.ephemeral_url)
165+
except Exception: # noqa: S110
166+
pass
167+
114168
panel_content = f"""
115169
🎉 Your First CrewAI Execution Trace is Ready!
116170
@@ -123,7 +177,8 @@ def _display_ephemeral_trace_link(self):
123177
• Tool usage and results
124178
• LLM calls and responses
125179
126-
To use traces add tracing=True to your Crew(tracing=True) / Flow(tracing=True)
180+
✅ Tracing has been enabled for future runs! (CREWAI_TRACING_ENABLED=true added to .env)
181+
You can also add tracing=True to your Crew(tracing=True) / Flow(tracing=True) for more control.
127182
128183
📝 Note: This link will expire in 24 hours.
129184
""".strip()
@@ -158,8 +213,8 @@ def _show_local_trace_message(self):
158213
• Execution duration: {self.batch_manager.calculate_duration("execution")}ms
159214
• Batch ID: {self.batch_manager.trace_batch_id}
160215
216+
Tracing has been enabled for future runs! (CREWAI_TRACING_ENABLED=true added to .env)
161217
The traces include agent decisions, task execution, and tool usage.
162-
Try running with CREWAI_TRACING_ENABLED=true next time for persistent traces.
163218
""".strip()
164219

165220
panel = Panel(

src/crewai/events/listeners/tracing/trace_batch_manager.py

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -138,13 +138,6 @@ def _initialize_backend_batch(
138138
if not use_ephemeral
139139
else response_data["ephemeral_trace_id"]
140140
)
141-
console = Console()
142-
panel = Panel(
143-
f"✅ Trace batch initialized with session ID: {self.trace_batch_id}",
144-
title="Trace Batch Initialization",
145-
border_style="green",
146-
)
147-
console.print(panel)
148141
else:
149142
logger.warning(
150143
f"Trace batch initialization returned status {response.status_code}. Continuing without tracing."
@@ -258,12 +251,23 @@ def _finalize_backend_batch(self):
258251
if self.is_current_batch_ephemeral:
259252
self.ephemeral_trace_url = return_link
260253

254+
# Create a properly formatted message with URL on its own line
255+
message_parts = [
256+
f"✅ Trace batch finalized with session ID: {self.trace_batch_id}",
257+
"",
258+
f"🔗 View here: {return_link}",
259+
]
260+
261+
if access_code:
262+
message_parts.append(f"🔑 Access Code: {access_code}")
263+
261264
panel = Panel(
262-
f"✅ Trace batch finalized with session ID: {self.trace_batch_id}. View here: {return_link} {f', Access Code: {access_code}' if access_code else ''}",
265+
"\n".join(message_parts),
263266
title="Trace Batch Finalization",
264267
border_style="green",
265268
)
266-
console.print(panel)
269+
if not should_auto_collect_first_time_traces():
270+
console.print(panel)
267271

268272
else:
269273
logger.error(

0 commit comments

Comments
 (0)