diff --git a/src/crewai/events/listeners/tracing/trace_batch_manager.py b/src/crewai/events/listeners/tracing/trace_batch_manager.py index 826524d25..d2997a3db 100644 --- a/src/crewai/events/listeners/tracing/trace_batch_manager.py +++ b/src/crewai/events/listeners/tracing/trace_batch_manager.py @@ -51,9 +51,8 @@ class TraceBatchManager: 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 diff --git a/test_tracing_auth.py b/test_tracing_auth.py new file mode 100644 index 000000000..2f7ed979b --- /dev/null +++ b/test_tracing_auth.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +""" +Test script for issue #3559 - TraceBatchManager authentication handling +""" + +import sys +sys.path.insert(0, '/home/ubuntu/repos/crewAI/src') + +def test_tracing_auth_issue(): + """Test that tracing authentication issue is fixed""" + + try: + from crewai.events.listeners.tracing.trace_batch_manager import TraceBatchManager + from crewai.cli.authentication.token import AuthError + from unittest.mock import patch + + 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(f"✓ TraceBatchManager created successfully with empty API key: '{batch_manager.plus_api.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 Agent, Crew, Task, LLM + + 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("✓ Crew created successfully without authentication errors") + + 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") diff --git a/tests/tracing/test_tracing.py b/tests/tracing/test_tracing.py index 2ac07eb6d..30338b591 100644 --- a/tests/tracing/test_tracing.py +++ b/tests/tracing/test_tracing.py @@ -4,6 +4,7 @@ from unittest.mock import MagicMock, Mock, patch 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, ) @@ -657,3 +658,67 @@ class TestTraceListenerSetup: 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