Skip to content

Commit 7d4e448

Browse files
cursoragentalex
andcommitted
Add AgentOps authentication fix for CrewAI with example and guide
Co-authored-by: alex <[email protected]>
1 parent e063acb commit 7d4e448

File tree

3 files changed

+288
-0
lines changed

3 files changed

+288
-0
lines changed

.env.example

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# AgentOps Configuration
2+
# Get your API key from: https://app.agentops.ai
3+
AGENTOPS_API_KEY=your_agentops_api_key_here
4+
5+
# Optional: OpenAI API Key (if using OpenAI models with CrewAI)
6+
# OPENAI_API_KEY=your_openai_api_key_here
7+
8+
# Optional: Custom AgentOps endpoint (defaults to https://api.agentops.ai)
9+
# AGENTOPS_ENDPOINT=https://api.agentops.ai
10+
11+
# Optional: Enable debug logging
12+
# AGENTOPS_DEBUG=true
Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
# AgentOps Authentication Fix Guide
2+
3+
## Problem Summary
4+
5+
The user encountered two main issues:
6+
1. **401 Unauthorized errors** when AgentOps tries to export telemetry data
7+
2. **Deprecation warning** about `end_session()` being replaced with `end_trace()`
8+
9+
## Root Causes
10+
11+
### 1. Authentication Error (401 Unauthorized)
12+
The error messages show:
13+
```
14+
Failed to export span batch code: 401, reason: Unauthorized
15+
Failed to export metrics batch code: 401, reason: Unauthorized
16+
```
17+
18+
This occurs when:
19+
- No API key is provided
20+
- An invalid or expired API key is used
21+
- The API key is not properly loaded from environment variables
22+
23+
### 2. Deprecation Warning
24+
```
25+
AgentOps: end_session() is deprecated and will be removed in v4 in the future.
26+
Use agentops.end_trace() instead.
27+
```
28+
29+
The `end_session()` method is being phased out in favor of the more flexible `end_trace()` method.
30+
31+
## Solution
32+
33+
### Step 1: Set Up Environment Variables
34+
35+
1. Create a `.env` file in your project root:
36+
```bash
37+
touch .env
38+
```
39+
40+
2. Add your AgentOps API key:
41+
```env
42+
AGENTOPS_API_KEY=your_actual_api_key_here
43+
```
44+
45+
3. Get your API key from [https://app.agentops.ai](https://app.agentops.ai)
46+
- Sign up or log in
47+
- Navigate to Settings or API Keys section
48+
- Copy your API key
49+
50+
### Step 2: Update Your Code
51+
52+
Replace the deprecated `end_session()` with `end_trace()`:
53+
54+
**Before (Deprecated):**
55+
```python
56+
agentops.end_session() # or
57+
agentops.end_session("Success")
58+
```
59+
60+
**After (Current):**
61+
```python
62+
agentops.end_trace(end_state="Success") # or
63+
agentops.end_trace() # defaults to "Success"
64+
```
65+
66+
### Step 3: Implement Proper Error Handling
67+
68+
Use the fixed script provided in `test_agentops_auth.py` which includes:
69+
- API key validation
70+
- Proper error handling
71+
- Clear error messages
72+
- Automatic session management
73+
74+
## Complete Working Example
75+
76+
```python
77+
import os
78+
from dotenv import load_dotenv
79+
import agentops
80+
from crewai import Agent, Task, Crew
81+
82+
# Load environment variables
83+
load_dotenv()
84+
85+
# Validate API key
86+
api_key = os.getenv("AGENTOPS_API_KEY")
87+
if not api_key:
88+
print("ERROR: Please set AGENTOPS_API_KEY in .env file")
89+
exit(1)
90+
91+
# Initialize AgentOps
92+
agentops.init(
93+
api_key=api_key,
94+
skip_auto_end_session=False # Let AgentOps handle cleanup
95+
)
96+
97+
# Your CrewAI code here
98+
agent = Agent(
99+
role="Math Assistant",
100+
goal="Solve simple math problems",
101+
backstory="You are a helpful assistant for quick calculations.",
102+
allow_delegation=False,
103+
verbose=True
104+
)
105+
106+
task = Task(
107+
description="Solve: What is 25 * 4?",
108+
expected_output="100",
109+
agent=agent
110+
)
111+
112+
crew = Crew(agents=[agent], tasks=[task], verbose=True)
113+
result = crew.kickoff()
114+
115+
print(f"Result: {result}")
116+
117+
# Optional: Manually end trace (not required with skip_auto_end_session=False)
118+
agentops.end_trace(end_state="Success")
119+
```
120+
121+
## Testing the Fix
122+
123+
1. Run the test script:
124+
```bash
125+
python examples/crewai/test_agentops_auth.py
126+
```
127+
128+
2. Expected output:
129+
```
130+
✅ AgentOps API key found: your_key_... (truncated for security)
131+
✅ AgentOps initialized successfully
132+
🚀 Starting CrewAI task...
133+
✅ Final Result: 25 multiplied by 4 equals 100.
134+
✅ AgentOps trace ended successfully
135+
```
136+
137+
3. Check your AgentOps dashboard at https://app.agentops.ai for the session data
138+
139+
## Additional Configuration Options
140+
141+
You can customize AgentOps behavior with these init parameters:
142+
143+
```python
144+
agentops.init(
145+
api_key=api_key,
146+
endpoint="https://api.agentops.ai", # Custom endpoint
147+
max_wait_time=30000, # Max wait time for API responses (ms)
148+
max_queue_size=100, # Max events to queue
149+
skip_auto_end_session=False, # Auto-end session on script exit
150+
)
151+
```
152+
153+
## Troubleshooting
154+
155+
### Still Getting 401 Errors?
156+
1. Verify your API key is correct
157+
2. Check if the key has expired
158+
3. Ensure the `.env` file is in the correct location
159+
4. Try regenerating your API key from the AgentOps dashboard
160+
161+
### Debug Mode
162+
Enable debug logging to see more details:
163+
```python
164+
import logging
165+
logging.basicConfig(level=logging.DEBUG)
166+
```
167+
168+
Or set in environment:
169+
```bash
170+
export AGENTOPS_DEBUG=true
171+
```
172+
173+
## References
174+
- [AgentOps Documentation](https://docs.agentops.ai)
175+
- [AgentOps API Keys](https://app.agentops.ai)
176+
- [CrewAI Integration Guide](https://docs.agentops.ai/integrations/crewai)
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Test script for AgentOps with CrewAI
4+
Fixes authentication issues and uses the updated API
5+
"""
6+
7+
import os
8+
import sys
9+
from dotenv import load_dotenv
10+
import agentops
11+
from crewai import Agent, Task, Crew
12+
13+
def main():
14+
# 1. Load environment variables
15+
load_dotenv()
16+
17+
# 2. Check for API key
18+
api_key = os.getenv("AGENTOPS_API_KEY")
19+
if not api_key:
20+
print("❌ ERROR: AGENTOPS_API_KEY not found in environment variables!")
21+
print("\nTo fix this issue:")
22+
print("1. Create a .env file in the project root")
23+
print("2. Add your AgentOps API key: AGENTOPS_API_KEY=your_api_key_here")
24+
print("3. Get your API key from: https://app.agentops.ai")
25+
sys.exit(1)
26+
27+
# Validate API key format (should be a UUID-like string)
28+
if len(api_key) < 20 or api_key == "your_api_key_here":
29+
print("❌ ERROR: Invalid AGENTOPS_API_KEY format!")
30+
print(f"Current key: {api_key[:10]}... (truncated for security)")
31+
print("\nPlease provide a valid API key from https://app.agentops.ai")
32+
sys.exit(1)
33+
34+
print(f"✅ AgentOps API key found: {api_key[:10]}... (truncated for security)")
35+
36+
# 3. Initialize AgentOps with explicit configuration
37+
try:
38+
agentops.init(
39+
api_key=api_key,
40+
# Optional: Add other configuration options
41+
# endpoint="https://api.agentops.ai", # Use default endpoint
42+
# max_wait_time=30000, # Max time to wait for API responses
43+
# max_queue_size=100, # Max number of events to queue
44+
skip_auto_end_session=False # Let AgentOps handle session ending automatically
45+
)
46+
print("✅ AgentOps initialized successfully")
47+
except Exception as e:
48+
print(f"❌ ERROR: Failed to initialize AgentOps: {e}")
49+
sys.exit(1)
50+
51+
# 4. Create a minimal CrewAI setup
52+
try:
53+
agent = Agent(
54+
role="Math Assistant",
55+
goal="Solve simple math problems",
56+
backstory="You are a helpful assistant for quick calculations.",
57+
allow_delegation=False,
58+
verbose=True
59+
)
60+
61+
task = Task(
62+
description="Solve: What is 25 * 4?",
63+
expected_output="100",
64+
agent=agent
65+
)
66+
67+
crew = Crew(
68+
agents=[agent],
69+
tasks=[task],
70+
verbose=True
71+
)
72+
73+
print("\n🚀 Starting CrewAI task...")
74+
75+
# 5. Run the crew
76+
result = crew.kickoff()
77+
78+
print(f"\n✅ Final Result: {result}")
79+
80+
# 6. Use the new end_trace() method instead of deprecated end_session()
81+
# Note: With skip_auto_end_session=False, AgentOps will handle this automatically
82+
# But if you need to manually end the trace:
83+
try:
84+
agentops.end_trace(end_state="Success")
85+
print("✅ AgentOps trace ended successfully")
86+
except Exception as e:
87+
print(f"⚠️ Warning: Could not end trace: {e}")
88+
# This is not critical as AgentOps will auto-end on script exit
89+
90+
except Exception as e:
91+
print(f"\n❌ ERROR during execution: {e}")
92+
# Try to end the trace with error state
93+
try:
94+
agentops.end_trace(end_state="Error")
95+
except:
96+
pass # Ignore errors during cleanup
97+
sys.exit(1)
98+
99+
if __name__ == "__main__":
100+
main()

0 commit comments

Comments
 (0)