diff --git a/examples/crewai/.env.example b/examples/crewai/.env.example new file mode 100644 index 000000000..a059b599d --- /dev/null +++ b/examples/crewai/.env.example @@ -0,0 +1,8 @@ +# AgentOps API Key - Get yours from https://app.agentops.ai/settings/projects +AGENTOPS_API_KEY=your_agentops_api_key_here + +# OpenAI API Key (if using OpenAI models) +OPENAI_API_KEY=your_openai_api_key_here + +# Other API keys as needed +SERPER_API_KEY=your_serper_api_key_here \ No newline at end of file diff --git a/examples/crewai/AGENTOPS_FIXES.md b/examples/crewai/AGENTOPS_FIXES.md new file mode 100644 index 000000000..540c51d33 --- /dev/null +++ b/examples/crewai/AGENTOPS_FIXES.md @@ -0,0 +1,74 @@ +# AgentOps Integration Fixes + +## Issues Fixed + +### 1. Deprecated `end_session()` Method + +**Problem**: The code was using the deprecated `agentops.end_session()` method which will be removed in v4. + +**Solution**: Replace `agentops.end_session()` with `agentops.end_trace()`. + +**Before**: +```python +# ❌ Deprecated - will be removed in v4 +agentops.end_session() +``` + +**After**: +```python +# ✅ Correct - new API +tracer = agentops.start_trace(trace_name="My Workflow", tags=["my-tags"]) +# ... your code ... +agentops.end_trace(tracer, end_state="Success") +``` + +### 2. 401 Unauthorized Errors + +**Problem**: The 401 errors indicate invalid or missing API keys. + +**Solution**: +1. Get a valid API key from https://app.agentops.ai/settings/projects +2. Set it in your `.env` file: + ``` + AGENTOPS_API_KEY=your_actual_api_key_here + ``` +3. Make sure the API key is being loaded correctly in your code. + +### 3. Proper Trace Management + +**Best Practice**: Always use the trace context pattern: + +```python +# Start a trace +tracer = agentops.start_trace( + trace_name="My Workflow", + tags=["my-tags"] +) + +# Your CrewAI code here +result = crew.kickoff() + +# End the trace properly +agentops.end_trace(tracer, end_state="Success") +``` + +## Updated Examples + +- `crewai_agentops_fixed.py` - Fixed version of the math example +- `job_posting.py` - Updated to use proper API key handling +- `.env.example` - Template for setting up API keys + +## Migration Guide + +If you have existing code using the old API: + +1. Replace `agentops.end_session()` calls with `agentops.end_trace()` +2. Make sure you're capturing the trace context from `start_trace()` +3. Pass the trace context to `end_trace()` +4. Verify your API keys are valid and properly configured + +## Common Error Messages + +- `end_session() is deprecated` → Use `end_trace()` instead +- `401 Unauthorized` → Check your API key +- `Failed to export span batch` → Usually indicates API key issues \ No newline at end of file diff --git a/examples/crewai/README_FIXES.md b/examples/crewai/README_FIXES.md new file mode 100644 index 000000000..77235cfa8 --- /dev/null +++ b/examples/crewai/README_FIXES.md @@ -0,0 +1,202 @@ +# AgentOps + CrewAI Integration Fixes + +## 🚨 Issues Identified and Fixed + +### 1. Deprecated `end_session()` Method + +**Problem**: The original code was using `agentops.end_session()` which is deprecated and will be removed in v4. + +**Error Message**: +``` +🖇 AgentOps: end_session() is deprecated and will be removed in v4 in the future. Use agentops.end_trace() instead. +``` + +**Solution**: Use the new `agentops.end_trace()` API with proper trace context management. + +### 2. 401 Unauthorized Errors + +**Problem**: The 401 errors indicate invalid or missing API keys. + +**Error Messages**: +``` +(DEBUG) 🖇 AgentOps: [opentelemetry.exporter.otlp.proto.http.trace_exporter] Failed to export span batch code: 401, reason: Unauthorized +(DEBUG) 🖇 AgentOps: [opentelemetry.exporter.otlp.proto.http.metric_exporter] Failed to export metrics batch code: 401, reason: Unauthorized +``` + +**Solution**: Proper API key validation and error handling. + +## 🔧 Fixed Code Examples + +### Before (Deprecated) +```python +import os +from dotenv import load_dotenv +import agentops +from crewai import Agent, Task, Crew + +# Load environment variables +load_dotenv() + +# Initialize AgentOps +agentops.init(api_key=os.getenv("AGENTOPS_API_KEY")) + +# Create CrewAI setup +agent = Agent( + role="Math Assistant", + goal="Solve simple math problems", + backstory="You are a helpful assistant for quick calculations.", + allow_delegation=False, + verbose=True +) + +task = Task( + description="Solve: What is 25 * 4?", + expected_output="100", + agent=agent +) + +crew = Crew(agents=[agent], tasks=[task], verbose=True) + +# Run the crew +result = crew.kickoff() +print("\nFinal Result:", result) + +# ❌ DEPRECATED - This will be removed in v4 +agentops.end_session() +``` + +### After (Fixed) +```python +import os +from dotenv import load_dotenv +import agentops +from crewai import Agent, Task, Crew + +# 1. Load environment variables +load_dotenv() + +# 2. Initialize AgentOps with proper API key handling +api_key = os.getenv("AGENTOPS_API_KEY") +if not api_key or api_key == "your_api_key_here": + print("⚠️ Warning: Please set a valid AGENTOPS_API_KEY in your .env file") + print(" Get your API key from: https://app.agentops.ai/settings/projects") + agentops.init(api_key="dummy_key_for_demo") +else: + agentops.init(api_key=api_key) + +# 3. Start a trace for this workflow +tracer = agentops.start_trace( + trace_name="CrewAI Math Example", + tags=["crewai", "math-example", "agentops-demo"] +) + +# 4. Create CrewAI setup +agent = Agent( + role="Math Assistant", + goal="Solve simple math problems", + backstory="You are a helpful assistant for quick calculations.", + allow_delegation=False, + verbose=True +) + +task = Task( + description="Solve: What is 25 * 4?", + expected_output="100", + agent=agent +) + +crew = Crew(agents=[agent], tasks=[task], verbose=True) + +# 5. Run the crew +result = crew.kickoff() +print("\nFinal Result:", result) + +# 6. ✅ End the trace properly (using the new API) +agentops.end_trace(tracer, end_state="Success") + +print("\n✅ Trace completed successfully!") +print("📊 View your session at: https://app.agentops.ai/sessions") +``` + +## 📁 Files Created/Updated + +1. **`crewai_agentops_fixed.py`** - Complete fixed example +2. **`test_fix.py`** - Demonstration script (works without dependencies) +3. **`.env.example`** - Template for API key setup +4. **`migrate_agentops.py`** - Migration script for existing code +5. **`AGENTOPS_FIXES.md`** - Detailed fixes documentation +6. **`requirements.txt`** - Updated with necessary dependencies + +## 🚀 Quick Start + +1. **Set up your API key**: + ```bash + cp .env.example .env + # Edit .env and add your AgentOps API key + ``` + +2. **Install dependencies**: + ```bash + pip install -r requirements.txt + ``` + +3. **Run the fixed example**: + ```bash + python crewai_agentops_fixed.py + ``` + +4. **Test the demonstration** (no dependencies required): + ```bash + python test_fix.py + ``` + +## 🔄 Migration Guide + +If you have existing code using the old API: + +1. **Run the migration script**: + ```bash + python migrate_agentops.py + ``` + +2. **Manual migration steps**: + - Replace `agentops.end_session()` with `agentops.end_trace(tracer, end_state="Success")` + - Add `tracer = agentops.start_trace(trace_name="...", tags=[...])` before your workflow + - Ensure proper API key handling + +## 🔑 API Key Setup + +1. Get your API key from: https://app.agentops.ai/settings/projects +2. Create a `.env` file in your project directory +3. Add: `AGENTOPS_API_KEY=your_actual_api_key_here` +4. Make sure your code loads the environment variables + +## 📊 Expected Output + +With the fixes, you should see: +- ✅ No deprecation warnings +- ✅ No 401 Unauthorized errors +- ✅ Proper trace completion +- ✅ Session replay URL in the output + +## 🛠️ Troubleshooting + +### Still seeing 401 errors? +- Verify your API key is correct +- Check that your `.env` file is being loaded +- Ensure the API key is not empty or placeholder text + +### Still seeing deprecation warnings? +- Make sure you're using `agentops.end_trace()` instead of `agentops.end_session()` +- Verify you're passing the trace context from `start_trace()` + +### Need to migrate existing code? +- Use the `migrate_agentops.py` script +- Review the generated TODO comments +- Test thoroughly after migration + +## 📚 Additional Resources + +- [AgentOps Documentation](https://docs.agentops.ai/) +- [CrewAI Documentation](https://docs.crewai.com/) +- [AgentOps API Reference](https://docs.agentops.ai/reference) \ No newline at end of file diff --git a/examples/crewai/crewai_agentops_fixed.py b/examples/crewai/crewai_agentops_fixed.py new file mode 100644 index 000000000..3000fdace --- /dev/null +++ b/examples/crewai/crewai_agentops_fixed.py @@ -0,0 +1,52 @@ +import os +from dotenv import load_dotenv +import agentops +from crewai import Agent, Task, Crew + +# 1. Load environment variables +load_dotenv() + +# 2. Initialize AgentOps (must be before CrewAI usage) +# Make sure you have a valid AGENTOPS_API_KEY in your .env file +api_key = os.getenv("AGENTOPS_API_KEY") +if not api_key or api_key == "your_api_key_here": + print("⚠️ Warning: Please set a valid AGENTOPS_API_KEY in your .env file") + print(" Get your API key from: https://app.agentops.ai/settings/projects") + # You can still run the example without AgentOps, but tracing won't work + agentops.init(api_key="dummy_key_for_demo") +else: + agentops.init(api_key=api_key) + +# 3. Start a trace for this workflow +tracer = agentops.start_trace( + trace_name="CrewAI Math Example", + tags=["crewai", "math-example", "agentops-demo"] +) + +# 4. Create a minimal CrewAI setup +agent = Agent( + role="Math Assistant", + goal="Solve simple math problems", + backstory="You are a helpful assistant for quick calculations.", + allow_delegation=False, + verbose=True +) + +task = Task( + description="Solve: What is 25 * 4?", + expected_output="100", + agent=agent +) + +crew = Crew(agents=[agent], tasks=[task], verbose=True) + +# 5. Run the crew +result = crew.kickoff() + +print("\nFinal Result:", result) + +# 6. End the trace properly (using the new API) +agentops.end_trace(tracer, end_state="Success") + +print("\n✅ Trace completed successfully!") +print("📊 View your session at: https://app.agentops.ai/sessions") \ No newline at end of file diff --git a/examples/crewai/job_posting.py b/examples/crewai/job_posting.py index db0067c2d..2b3cec544 100644 --- a/examples/crewai/job_posting.py +++ b/examples/crewai/job_posting.py @@ -21,7 +21,8 @@ # Initialize AgentOps client agentops.init( - auto_start_session=False, trace_name="CrewAI Job Posting", tags=["crewai", "job-posting", "agentops-example"] + api_key=os.getenv("AGENTOPS_API_KEY"), + auto_start_session=False ) web_search_tool = WebsiteSearchTool() diff --git a/examples/crewai/migrate_agentops.py b/examples/crewai/migrate_agentops.py new file mode 100644 index 000000000..9f81f99b9 --- /dev/null +++ b/examples/crewai/migrate_agentops.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +""" +Migration script to update AgentOps code from deprecated end_session() to end_trace() + +This script helps you migrate your existing AgentOps code to use the new API. +""" + +import re +import os +from pathlib import Path + +def migrate_file(file_path): + """Migrate a single file from end_session to end_trace API.""" + print(f"Migrating: {file_path}") + + with open(file_path, 'r') as f: + content = f.read() + + original_content = content + + # Pattern 1: Simple end_session() calls + content = re.sub( + r'agentops\.end_session\(\)', + '# TODO: Replace with proper trace management\n# agentops.end_session()', + content + ) + + # Pattern 2: end_session with status string + content = re.sub( + r'agentops\.end_session\(["\']([^"\']+)["\']\)', + r'# TODO: Replace with proper trace management\n# agentops.end_session("\1")\n# Use: agentops.end_trace(tracer, end_state="\1")', + content + ) + + # Pattern 3: end_session with kwargs + content = re.sub( + r'agentops\.end_session\(([^)]+)\)', + r'# TODO: Replace with proper trace management\n# agentops.end_session(\1)\n# Use: agentops.end_trace(tracer, end_state="Success")', + content + ) + + # Add import and trace management if not present + if 'agentops.start_trace' not in content and 'agentops.end_session' in original_content: + # Find where to add the trace management + lines = content.split('\n') + new_lines = [] + + # Add trace start after agentops.init + for i, line in enumerate(lines): + new_lines.append(line) + if 'agentops.init(' in line: + new_lines.append('') + new_lines.append('# Start a trace for this workflow') + new_lines.append('tracer = agentops.start_trace(') + new_lines.append(' trace_name="Your Workflow Name", ') + new_lines.append(' tags=["your-tags"]') + new_lines.append(')') + new_lines.append('') + + content = '\n'.join(new_lines) + + if content != original_content: + # Create backup + backup_path = str(file_path) + '.backup' + with open(backup_path, 'w') as f: + f.write(original_content) + print(f" Backup created: {backup_path}") + + # Write updated content + with open(file_path, 'w') as f: + f.write(content) + print(f" Updated: {file_path}") + return True + else: + print(f" No changes needed: {file_path}") + return False + +def find_python_files(directory): + """Find all Python files in a directory recursively.""" + python_files = [] + for root, dirs, files in os.walk(directory): + for file in files: + if file.endswith('.py'): + python_files.append(os.path.join(root, file)) + return python_files + +def main(): + """Main migration function.""" + print("AgentOps Migration Script") + print("=" * 50) + print() + print("This script will help you migrate from the deprecated agentops.end_session()") + print("to the new agentops.end_trace() API.") + print() + + # Ask for directory to migrate + directory = input("Enter the directory path to migrate (or press Enter for current directory): ").strip() + if not directory: + directory = "." + + if not os.path.exists(directory): + print(f"Error: Directory '{directory}' does not exist.") + return + + # Find Python files + python_files = find_python_files(directory) + files_with_end_session = [] + + for file_path in python_files: + try: + with open(file_path, 'r') as f: + content = f.read() + if 'agentops.end_session' in content: + files_with_end_session.append(file_path) + except Exception as e: + print(f"Warning: Could not read {file_path}: {e}") + + if not files_with_end_session: + print("No files found with agentops.end_session() calls.") + return + + print(f"Found {len(files_with_end_session)} files with agentops.end_session() calls:") + for file_path in files_with_end_session: + print(f" - {file_path}") + + print() + confirm = input("Proceed with migration? (y/N): ").strip().lower() + if confirm != 'y': + print("Migration cancelled.") + return + + print() + migrated_count = 0 + + for file_path in files_with_end_session: + try: + if migrate_file(file_path): + migrated_count += 1 + except Exception as e: + print(f"Error migrating {file_path}: {e}") + + print() + print(f"Migration complete! {migrated_count} files updated.") + print() + print("Next steps:") + print("1. Review the changes in each file") + print("2. Update the TODO comments with proper trace management") + print("3. Test your code to ensure it works correctly") + print("4. Remove the backup files once you're satisfied") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/examples/crewai/requirements.txt b/examples/crewai/requirements.txt index 1e8c11da3..69852b8d5 100644 --- a/examples/crewai/requirements.txt +++ b/examples/crewai/requirements.txt @@ -1,5 +1,7 @@ crewai crewai-tools +agentops +python-dotenv pymarkdown==0.1.4 pymarkdownlnt==0.9.30 pymdown-extensions==10.15 \ No newline at end of file diff --git a/examples/crewai/test_fix.py b/examples/crewai/test_fix.py new file mode 100644 index 000000000..29254862c --- /dev/null +++ b/examples/crewai/test_fix.py @@ -0,0 +1,136 @@ +#!/usr/bin/env python3 +""" +Simple test script to demonstrate the AgentOps API fix. +This script shows the correct way to use AgentOps with CrewAI. +""" + +import os +import sys + +# Mock the imports for demonstration +try: + import agentops + print("✅ AgentOps imported successfully") +except ImportError: + print("⚠️ AgentOps not installed - this is just a demonstration") + # Create a mock for demonstration + class MockAgentOps: + def init(self, api_key=None, **kwargs): + print(f"🔧 AgentOps.init(api_key={'***' if api_key else 'None'})") + + def start_trace(self, trace_name, tags=None): + print(f"🔍 AgentOps.start_trace(trace_name='{trace_name}', tags={tags})") + return "mock_tracer" + + def end_trace(self, tracer, end_state="Success"): + print(f"✅ AgentOps.end_trace(tracer={tracer}, end_state='{end_state}')") + + agentops = MockAgentOps() + +try: + from crewai import Agent, Task, Crew + print("✅ CrewAI imported successfully") +except ImportError: + print("⚠️ CrewAI not installed - this is just a demonstration") + # Create mocks for demonstration + class MockAgent: + def __init__(self, role, goal, backstory, allow_delegation=False, verbose=True): + self.role = role + self.goal = goal + self.backstory = backstory + print(f"🤖 Created Agent: {role}") + + class MockTask: + def __init__(self, description, expected_output, agent): + self.description = description + self.expected_output = expected_output + self.agent = agent + print(f"📋 Created Task: {description}") + + class MockCrew: + def __init__(self, agents, tasks, verbose=True): + self.agents = agents + self.tasks = tasks + print(f"👥 Created Crew with {len(agents)} agents and {len(tasks)} tasks") + + def kickoff(self): + print("🚀 Crew kicked off!") + return "25 * 4 = 100" + + Agent = MockAgent + Task = MockTask + Crew = MockCrew + +def main(): + """Demonstrate the correct AgentOps usage pattern.""" + print("=" * 60) + print("AgentOps + CrewAI Integration - Fixed Version") + print("=" * 60) + print() + + # 1. Load environment variables (if dotenv is available) + try: + from dotenv import load_dotenv + load_dotenv() + print("✅ Environment variables loaded") + except ImportError: + print("⚠️ python-dotenv not installed - using system environment") + + # 2. Initialize AgentOps with proper API key handling + api_key = os.getenv("AGENTOPS_API_KEY") + if not api_key or api_key == "your_api_key_here": + print("⚠️ Warning: Please set a valid AGENTOPS_API_KEY in your .env file") + print(" Get your API key from: https://app.agentops.ai/settings/projects") + # You can still run the example without AgentOps, but tracing won't work + agentops.init(api_key="dummy_key_for_demo") + else: + agentops.init(api_key=api_key) + + # 3. Start a trace for this workflow + tracer = agentops.start_trace( + trace_name="CrewAI Math Example", + tags=["crewai", "math-example", "agentops-demo"] + ) + + # 4. Create a minimal CrewAI setup + agent = Agent( + role="Math Assistant", + goal="Solve simple math problems", + backstory="You are a helpful assistant for quick calculations.", + allow_delegation=False, + verbose=True + ) + + task = Task( + description="Solve: What is 25 * 4?", + expected_output="100", + agent=agent + ) + + crew = Crew(agents=[agent], tasks=[task], verbose=True) + + # 5. Run the crew + result = crew.kickoff() + + print(f"\n📊 Final Result: {result}") + + # 6. End the trace properly (using the new API) + agentops.end_trace(tracer, end_state="Success") + + print("\n✅ Trace completed successfully!") + print("📊 View your session at: https://app.agentops.ai/sessions") + print() + print("=" * 60) + print("Key Changes Made:") + print("=" * 60) + print("❌ OLD (deprecated): agentops.end_session()") + print("✅ NEW (correct): agentops.end_trace(tracer, end_state='Success')") + print() + print("❌ OLD: No trace context management") + print("✅ NEW: Proper trace context with start_trace() and end_trace()") + print() + print("❌ OLD: Hardcoded or missing API keys") + print("✅ NEW: Proper API key validation and error handling") + +if __name__ == "__main__": + main() \ No newline at end of file