Skip to content
Draft
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
20 changes: 11 additions & 9 deletions docs/v2/concepts/core-concepts.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ The [decorators](/v2/concepts/decorators) system allows you to add tracing to yo

AgentOps is built on [OpenTelemetry](https://opentelemetry.io/), a widely-adopted standard for observability instrumentation. This provides a robust and standardized approach to collecting, processing, and exporting telemetry data.

# Sessions
## Sessions

A [Session](/v2/concepts/sessions) represents a single user interaction with your agent. When you initialize AgentOps using the `init` function, a session is automatically created for you:

Expand All @@ -30,14 +30,16 @@ import agentops
agentops.init(api_key="YOUR_API_KEY")
```

By default, all events and API calls will be associated with this session. For more advanced use cases, you can control session creation manually:
By default, all events and API calls will be associated with this session. For workflows where you want explicit lifecycle control, prefer creating traces explicitly:

```python
# Initialize without auto-starting a session
# Initialize without starting a trace automatically
agentops.init(api_key="YOUR_API_KEY", auto_start_session=False)

# Later, manually start a session when needed
agentops.start_session(tags=["customer-query"])
# Later, wrap a workflow in a trace context manager
with agentops.start_trace(trace_name="Customer Workflow", tags=["customer-query", "high-priority"]):
# your workflow code
pass
```

# Span Hierarchy
Expand Down Expand Up @@ -109,14 +111,14 @@ response = client.chat.completions.create(

# Tags

[Tags](/v2/concepts/tags) help you organize and filter your sessions. You can add tags when initializing AgentOps or when starting a session:
[Tags](/v2/concepts/tags) help you organize and filter your sessions and traces. You can add tags when initializing AgentOps or when starting a trace:

```python
# Add tags when initializing
agentops.init(api_key="YOUR_API_KEY", tags=["production", "web-app"])
agentops.init(api_key="YOUR_API_KEY", default_tags=["production", "web-app"])

# Or when manually starting a session
agentops.start_session(tags=["customer-service", "tier-1"])
# Or when manually starting a trace
agentops.start_trace(trace_name="customer-service-workflow", tags=["customer-service", "tier-1"])
```

# Host Environment
Expand Down
4 changes: 2 additions & 2 deletions docs/v2/concepts/tags.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ description: 'Organize and filter your sessions with customizable tags'
---
## Adding Tags

You can add tags when initializing AgentOps, whicreh is the most common approach:
You can add tags when initializing AgentOps, which is the most common approach:

```python
import agentops
Expand All @@ -23,7 +23,7 @@ Alternatively, when using manual trace creation:
agentops.init(api_key="YOUR_API_KEY", auto_start_session=False)

# Later start a trace with specific tags (modern approach)
trace = agentops.start_trace(trace_name="test_workflow", default_tags=["development", "testing", "claude-3"])
trace = agentops.start_trace(trace_name="test_workflow", tags=["development", "testing", "claude-3"])
```

<Note>
Expand Down
5 changes: 3 additions & 2 deletions docs/v2/concepts/traces.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -48,14 +48,15 @@ You can use the `@trace` decorator to create a trace for a specific function:

```python
import agentops
from agentops.sdk.decorators import trace

@agentops.trace
@trace
def process_customer_data(customer_id):
# This entire function execution will be tracked as a trace
return analyze_data(customer_id)

# Or with custom parameters
@agentops.trace(name="data_processing", tags=["analytics"])
@trace(name="data_processing", tags=["analytics"])
def analyze_user_behavior(user_data):
return perform_analysis(user_data)
```
Expand Down
33 changes: 11 additions & 22 deletions docs/v2/examples/crewai.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ class JobPostingAgentCrew():

### Step 7: Update the Main Execution File

Edit `src/job_posting_agent/main.py` to add AgentOps session management:
Edit `src/job_posting_agent/main.py` to add AgentOps trace management:

```python
#!/usr/bin/env python
Expand All @@ -276,36 +276,28 @@ def run():
"""
Run the crew with AgentOps tracking.
"""
# Start AgentOps session
session = agentops.start_session(tags=["crewai", "job-posting"])

try:
# Start an AgentOps trace for this run
with agentops.start_trace(trace_name="CrewAI Job Posting", tags=["crewai", "job-posting"]):
# Define the inputs for the crew
inputs = {
'company_description': 'A fast-paced tech startup focused on AI-driven solutions for e-commerce.',
'company_domain': 'https://agentops.ai',
'hiring_needs': 'Senior Software Engineer with experience in Python, AI, and cloud platforms.',
'specific_benefits': 'Competitive salary, stock options, remote work flexibility, and great team culture.'
}

# Initialize and run the crew
crew = JobPostingAgentCrew().crew()
result = crew.kickoff(inputs=inputs)

print("\n" + "="*50)
print("Job Posting Creation Completed!")
print("Result:")
print(result)
print("\nCheck 'job_posting.md' for the generated job posting.")

# End session successfully
agentops.end_session("Success")

return result

except Exception as e:
print(f"An error occurred: {e}")
agentops.end_session("Failed", end_state_reason=str(e))
raise


def train():
"""
Expand All @@ -322,6 +314,7 @@ def train():
except Exception as e:
raise Exception(f"An error occurred while training the crew: {e}")


def replay():
"""
Replay the crew execution from a specific task.
Expand Down Expand Up @@ -390,13 +383,9 @@ After running your job posting generator, visit your [AgentOps Dashboard](https:

**AgentOps Integration Points:**
- `agentops.init()` in `crew.py` - Enables automatic instrumentation
- `agentops.start_session()` in `main.py` - Begins tracking
- `agentops.end_session()` in `main.py` - Completes the session
- `agentops.start_trace()` in `main.py` - Wraps execution with a trace
- Context manager automatically completes the trace on exit

## Next Steps

- Customize the input parameters in `main.py`
- Modify agent configurations in `agents.yaml`
- Add more tasks or change the workflow in `tasks.yaml`
- Add custom tools in the `tools/` directory
- Use AgentOps analytics to optimize agent performance
- Customize the input parameters in `
42 changes: 10 additions & 32 deletions docs/v2/examples/google_adk.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -243,20 +243,18 @@ Create the function to run the approval workflow with AgentOps tracking:
```python
async def run_approval_workflow(user_request: str, session_id: str):
"""Run the complete approval workflow with AgentOps tracking"""
# Start AgentOps session
session = agentops.start_session(tags=["google-adk", "approval-workflow"])

try:
# Start AgentOps trace
with agentops.start_trace(trace_name="Google ADK Approval Workflow", tags=["google-adk", "approval-workflow"]):
print(f"{'=' * 60}")
print(f" Starting Approval Workflow for Session: {session_id}")
print(f"{'=' * 60}")
print(f"User Request: {user_request}")

# Create user message
user_content = types.Content(role="user", parts=[types.Part(text=user_request)])
step_count = 0
final_response = "No response received"

# Run the workflow
async for event in workflow_runner.run_async(
user_id=USER_ID,
Expand All @@ -268,31 +266,12 @@ async def run_approval_workflow(user_request: str, session_id: str):
print(f"📋 Step {step_count} - {event.author}:")
if event.content.parts:
response_text = event.content.parts[0].text
print(f" {response_text}")
if event.is_final_response():
final_response = response_text

# Display session state
session_data = await session_service.get_session(
app_name=APP_NAME,
user_id=USER_ID,
session_id=session_id,
)
print(f"{'=' * 60}")
print(f"📊 Workflow Complete - Session State ({session_id}):")
print(f"{'=' * 60}")
for key, value in session_data.state.items():
print(f" {key}: {value}")
print(f"🎯 Final Response: {final_response}")

# End AgentOps session successfully
agentops.end_session("Success")
print(response_text)
final_response = response_text

print(f"\n✅ Workflow Completed in {step_count} steps")
print(f"Final Response: {final_response}")
return final_response

except Exception as e:
print(f"Error occurred: {e}")
agentops.end_session("Failed", end_state_reason=str(e))
raise
```

Finally, add the main execution logic:
Expand Down Expand Up @@ -374,8 +353,7 @@ After running your approval workflow, visit your [AgentOps Dashboard](https://ap

**AgentOps Integration Points:**
- `agentops.init()` - Enables automatic instrumentation
- `agentops.start_session()` - Begins tracking each workflow run
- `agentops.end_session()` - Completes the session with status
- `agentops.start_trace()` - Wraps each workflow run in a trace

## Next Steps

Expand Down
23 changes: 6 additions & 17 deletions docs/v2/examples/langgraph.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -162,13 +162,11 @@ def stream_graph_updates(user_input: str):

def run_chatbot():
"""Main function to run the chatbot with AgentOps tracking."""
# Start AgentOps session
session = agentops.start_session(tags=["langgraph", "chatbot"])

try:
# Start AgentOps trace for this chat session
with agentops.start_trace(trace_name="LangGraph Chatbot", tags=["langgraph", "chatbot"]):
print("🤖 LangGraph Chatbot Started!")
print("Type 'quit', 'exit', or 'q' to stop.\n")

while True:
try:
user_input = input("User: ")
Expand All @@ -183,14 +181,6 @@ def run_chatbot():
except Exception as e:
print(f"Error: {e}")
break

# End session successfully
agentops.end_session("Success")

except Exception as e:
print(f"Error occurred: {e}")
agentops.end_session("Failed", end_state_reason=str(e))
raise

# Main execution
if __name__ == "__main__":
Expand All @@ -207,12 +197,12 @@ python chatbot.py
```

**What happens:**
1. AgentOps session starts automatically
1. AgentOps trace starts
2. Interactive chat loop begins
3. Each user message flows through: START → chatbot node → END
4. LLM generates responses based on conversation history
5. AgentOps captures all state transitions and LLM interactions
6. Session ends when you type 'quit'
6. Trace ends when you type 'quit'

**Example conversation:**
```
Expand Down Expand Up @@ -248,8 +238,7 @@ After running your chatbot, visit your [AgentOps Dashboard](https://app.agentops

**AgentOps Integration Points:**
- `agentops.init()` - Enables automatic LangGraph instrumentation
- `agentops.start_session()` - Begins tracking each chat session
- `agentops.end_session()` - Completes the session with status
- `agentops.start_trace()` - Wraps each chat session in a trace

## Next Steps

Expand Down
14 changes: 6 additions & 8 deletions docs/v2/examples/watsonx.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -116,19 +116,17 @@ print(f"Chat Response:\n{chat_response['results'][0]['generated_text']}")

## Clean Up

Finally, let's close the persistent connection with the models if they were established and end the AgentOps session.
Finally, let's close the persistent connection with the models if they were established. The AgentOps trace will be closed automatically when the context ends.
```python
# Close connections if persistent connections were used.
# This is good practice if the SDK version/usage implies persistent connections.
try:
gen_model.close_persistent_connection()
chat_model.close_persistent_connection()
gen_model.close_persistent_connection()
chat_model.close_persistent_connection()
except AttributeError:
# Handle cases where this method might not exist (e.g. newer SDK versions or stateless calls)
print("Note: close_persistent_connection not available or needed for one or more models.")
pass

agentops.end_session("Success") # Manually end session
# Handle cases where this method might not exist (e.g. newer SDK versions or stateless calls)
print("Note: close_persistent_connection not available or needed for one or more models.")
pass
```

<script type="module" src="/scripts/github_stars.js"></script>
Expand Down