Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
5 changes: 2 additions & 3 deletions src/crewai/events/listeners/tracing/trace_batch_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,8 @@ def __init__(self):
self.backend_initialized: bool = False
self.ephemeral_trace_url: str | None = None
try:
self.plus_api = PlusAPI(
api_key=get_auth_token(),
)
api_key = get_auth_token()
self.plus_api = PlusAPI(api_key=api_key)
except AuthError:
self.plus_api = PlusAPI(api_key="")
self.ephemeral_trace_url = None
Expand Down
89 changes: 89 additions & 0 deletions test_tracing_auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
#!/usr/bin/env python3
"""
Test script for issue #3559 - TraceBatchManager authentication handling
"""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))

def test_tracing_auth_issue():
"""Test that tracing authentication issue is fixed"""

try:
from unittest.mock import patch

from crewai.cli.authentication.token import AuthError
from crewai.events.listeners.tracing.trace_batch_manager import (
TraceBatchManager,
)

print("Test 1: TraceBatchManager creation without authentication")

with patch(
"crewai.events.listeners.tracing.trace_batch_manager.get_auth_token",
side_effect=AuthError("No token found, make sure you are logged in")
):
batch_manager = TraceBatchManager()
print("✓ TraceBatchManager created successfully with empty API key")

batch = batch_manager.initialize_batch({"user_id": "test"}, {"crew_name": "test"})
if batch is not None:
print(f"✓ Batch initialized successfully: {batch.batch_id}")
else:
print("✗ Batch initialization returned None")
return False

except Exception as e:
print(f"✗ TraceBatchManager test failed: {e}")
import traceback
traceback.print_exc()
return False

try:
from crewai import LLM, Agent, Crew, Task

print("\nTest 2: Crew creation without authentication")

with patch(
"crewai.events.listeners.tracing.trace_batch_manager.get_auth_token",
side_effect=AuthError("No token found, make sure you are logged in")
):
agent = Agent(
role="Test Agent",
goal="Complete a simple task",
backstory="A test agent for reproducing the bug",
llm=LLM(model="gpt-4o-mini", api_key="fake-key")
)

task = Task(
description="Say hello world",
expected_output="A greeting message",
agent=agent
)

crew = Crew(
agents=[agent],
tasks=[task],
verbose=False
)

print(f"✓ Crew created successfully without authentication errors: {len(crew.agents)} agents, {len(crew.tasks)} tasks")

except Exception as e:
print(f"✗ Crew creation test failed: {e}")
import traceback
traceback.print_exc()
return False

return True

if __name__ == "__main__":
print("Testing TraceBatchManager authentication handling...")
success = test_tracing_auth_issue()
if not success:
print("\nFAILED: Issue #3559 still exists")
exit(1)
else:
print("\nPASSED: Issue #3559 appears to be fixed")
65 changes: 65 additions & 0 deletions tests/tracing/test_tracing.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import pytest

from crewai import Agent, Crew, Task
from crewai.cli.authentication.token import AuthError
from crewai.events.listeners.tracing.first_time_trace_handler import (
FirstTimeTraceHandler,
)
Expand Down Expand Up @@ -657,3 +658,67 @@ def test_first_time_handler_graceful_error_handling(self):
handler.handle_execution_completion()

mock_mark_completed.assert_called_once()

def test_trace_batch_manager_handles_missing_auth_gracefully(self):
"""Test that TraceBatchManager handles missing authentication gracefully"""

with (
patch(
"crewai.events.listeners.tracing.trace_batch_manager.get_auth_token",
side_effect=AuthError("No token found, make sure you are logged in")
),
patch(
"crewai.events.listeners.tracing.trace_batch_manager.should_auto_collect_first_time_traces",
return_value=False
),
patch.object(TraceBatchManager, "_initialize_backend_batch") as mock_backend_init,
):
batch_manager = TraceBatchManager()

# Verify that the manager was created with empty API key due to auth error
assert batch_manager.plus_api.api_key == ""

user_context = {"user_id": "test"}
execution_metadata = {"crew_name": "test_crew"}

batch = batch_manager.initialize_batch(user_context, execution_metadata)

# Verify the batch was created successfully
assert batch is not None
assert batch_manager.is_batch_initialized()
assert batch.user_context == user_context
assert batch.execution_metadata == execution_metadata
assert isinstance(batch.batch_id, str)
assert len(batch.batch_id) > 0

# Verify that backend initialization was attempted but handled gracefully
mock_backend_init.assert_called_once()

@pytest.mark.vcr(filter_headers=["authorization"])
def test_crew_works_without_authentication(self):
"""Test that crews work properly when no authentication token is present"""

with (
patch(
"crewai.events.listeners.tracing.trace_batch_manager.get_auth_token",
side_effect=AuthError("No token found, make sure you are logged in")
),
patch.dict(os.environ, {"CREWAI_TRACING_ENABLED": "false"}),
):
agent = Agent(
role="Test Agent",
goal="Test goal",
backstory="Test backstory",
llm="gpt-4o-mini",
)
task = Task(
description="Say hello to the world",
expected_output="hello world",
agent=agent,
)

crew = Crew(agents=[agent], tasks=[task], verbose=True)

assert crew is not None
assert len(crew.agents) == 1
assert len(crew.tasks) == 1
Loading