Skip to content

Python SDK for AI agent monitoring, LLM cost tracking, benchmarking, and more. Integrates with most LLMs and agent frameworks including CrewAI, Agno, OpenAI Agents SDK, Langchain, Autogen, AG2, and CamelAI

Add video embeds to docs (#1189)

Sri Laasya Nutheti5b40518c189c
diff --git a/docs/v2/examples/agno.mdx b/docs/v2/examples/agno.mdx
index b587721e..617ecf85 100644
--- a/docs/v2/examples/agno.mdx
+++ b/docs/v2/examples/agno.mdx
@@ -32,7 +32,7 @@ By using async operations, you can run multiple AI queries simultaneously instea
poetry add agentops agno python-dotenv
```
```bash uv
- uv add agentops agno python-dotenv
+ uv pip install agentops agno python-dotenv
```
</CodeGroup>
diff --git a/docs/v2/examples/anthropic.mdx b/docs/v2/examples/anthropic.mdx
index 02d1446b..89507429 100644
--- a/docs/v2/examples/anthropic.mdx
+++ b/docs/v2/examples/anthropic.mdx
@@ -21,7 +21,7 @@ To get started, we will import Agentops and Anthropic.
poetry add agentops anthropic python-dotenv
```
```bash uv
- uv add agentops anthropic python-dotenv
+ uv pip install agentops anthropic python-dotenv
```
</CodeGroup>
diff --git a/docs/v2/examples/autogen.mdx b/docs/v2/examples/autogen.mdx
index 7e5ba291..2d6b128b 100644
--- a/docs/v2/examples/autogen.mdx
+++ b/docs/v2/examples/autogen.mdx
@@ -23,7 +23,7 @@ First let's install the required packages
poetry add "autogen-ext[openai]" -U agentops autogen-agentchat python-dotenv
```
```bash uv
- uv add "autogen-ext[openai]" -U agentops autogen-agentchat python-dotenv
+ uv pip install "autogen-ext[openai]" -U agentops autogen-agentchat python-dotenv
```
</CodeGroup>
diff --git a/docs/v2/examples/crewai.mdx b/docs/v2/examples/crewai.mdx
index f84f77c3..0447f6ec 100644
--- a/docs/v2/examples/crewai.mdx
+++ b/docs/v2/examples/crewai.mdx
@@ -1,230 +1,402 @@
---
title: 'CrewAI Example'
-description: 'Using CrewAI with AgentOps to create a job posting'
+description: 'Build a job posting generator with CrewAI agents and AgentOps tracking'
---
{/* SOURCE_FILE: examples/crewai/job_posting.ipynb */}
_View Notebook on <a href={'https://github.com/AgentOps-AI/agentops/blob/main/examples/crewai/job_posting.ipynb'} target={'_blank'}>Github</a>_
-# CrewAI Job Posting Example
+# CrewAI Job Posting Generator with AgentOps
-This notebook demonstrates how to use CrewAI with AgentOps to automate the creation of a job posting.
+This example shows you how to build a complete job posting generator using CrewAI's official project structure with comprehensive tracking via AgentOps.
-First let's install the required packages.
+## What We're Building
+
+A **3-agent system** that collaborates to create job postings:
+- 🔍 **Research Agent**: Analyzes company culture and industry trends
+- ✍️ **Writer Agent**: Drafts compelling job descriptions
+- 📝 **Editor Agent**: Reviews and polishes the final posting
+
+**With AgentOps**, you'll get complete visibility into agent conversations, tool usage, costs, and performance.
+
+## Step-by-Step Implementation
+
+### Step 1: Install Dependencies
+
+Install CrewAI with tools support and AgentOps for tracking:
-## Installation
<CodeGroup>
```bash pip
- pip install -U 'crewai[tools]' agentops python-dotenv
+ pip install -U 'crewai[tools]' agentops
```
```bash poetry
- poetry add crewai agentops python-dotenv
- # For tools, you might need to add them or specific extras:
- # poetry add crewai --extras tools
- # or poetry add crewai[tools] depending on your poetry version
+ poetry add 'crewai[tools]' agentops
```
```bash uv
- uv add 'crewai[tools]' agentops python-dotenv
+ uv pip install 'crewai[tools]' agentops
```
</CodeGroup>
-## Setup
-Then import them.
-```python
-from crewai import Crew, Agent, Task
-from crewai_tools.tools import WebsiteSearchTool, SerperDevTool, FileReadTool # Corrected import in previous MDX version
-import agentops
-import os
-from dotenv import load_dotenv
-from textwrap import dedent # Added import
+**What AgentOps adds:**
+- 🔍 **Automatic tracking** of all LLM calls and agent interactions
+- 💰 **Cost monitoring** with token usage breakdown
+- 🛠️ **Tool usage analytics** for web searches and file operations
+- 📊 **Performance metrics** and execution timelines
+- 🐛 **Session replay** for debugging and optimization
+
+### Step 2: Create CrewAI Project
+
+Use CrewAI's CLI to create the proper project structure:
+
+```bash
+crewai create crew job_posting_agent
```
-Next, we'll set our API keys. There are several ways to do this, the code below is just the most foolproof way for the purposes of this notebook. It accounts for both users who use environment variables and those who just want to set the API Key here in this notebook.
+**Select your provider and model:**
+- Choose **1. openai**
+- Choose **1. gpt-4** (or your preferred model)
+- Enter your OpenAI API key when prompted
-[Get an AgentOps API key](https://agentops.ai/settings/projects)
+**This creates the complete project structure:**
+```
+job_posting_agent/
+├── .env # API keys
+├── .gitignore
+├── pyproject.toml # Dependencies
+├── README.md
+├── knowledge/
+│ └── user_preference.txt
+└── src/job_posting_agent/
+ ├── __init__.py
+ ├── main.py # Main execution
+ ├── crew.py # Crew definition
+ ├── config/
+ │ ├── agents.yaml # Agent configurations
+ │ └── tasks.yaml # Task definitions
+ └── tools/
+ ├── __init__.py
+ └── custom_tool.py # Custom tools
+```
-1. Create an environment variable in a `.env` file or other method. By default, the AgentOps `init()` function will look for an environment variable named `AGENTOPS_API_KEY`. Or...
+### Step 3: Add Additional API Keys
-2. Replace `<your_agentops_key>` below and pass in the optional `api_key` parameter to the AgentOps `init(api_key=...)` function. Remember not to commit your API key to a public repo!
+Edit the generated `.env` file to add AgentOps and Serper keys:
-```python
-load_dotenv()
-os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY", "your_agentops_api_key_here")
-os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY", "your_openai_api_key_here")
-os.environ["SERPER_API_KEY"] = os.getenv("SERPER_API_KEY", "your_serper_api_key_here")
+```bash
+# .env (already has OPENAI_API_KEY from crewai create)
+OPENAI_API_KEY=your_openai_key_here
+AGENTOPS_API_KEY=your_agentops_key_here
+SERPER_API_KEY=your_serper_key_here
```
-```python
-# Initialize AgentOps client
-agentops.init(auto_start_session=False)
+**Get your additional API keys:**
+- **AgentOps**: [Get one here](https://agentops.ai/settings/projects)
+- **Serper**: [Serper Dev](https://serper.dev/api-key) (for web search)
+
+### Step 4: Configure Agents
+
+Edit `src/job_posting_agent/config/agents.yaml` to define your 3 agents:
+
+```yaml
+researcher:
+ role: "Research Analyst"
+ goal: "Analyze the company website and provided description to extract insights on culture, values, and specific needs."
+ backstory: "Expert in analyzing company cultures and identifying key values and needs from various sources, including websites and brief descriptions."
+ verbose: true
+
+writer:
+ role: "Job Description Writer"
+ goal: "Use insights from the Research Analyst to create a detailed, engaging, and enticing job posting."
+ backstory: "Skilled in crafting compelling job descriptions that resonate with the company's values and attract the right candidates."
+ verbose: true
+
+editor:
+ role: "Review and Editing Specialist"
+ goal: "Review the job posting for clarity, engagement, grammatical accuracy, and alignment with company values and refine it to ensure perfection."
+ backstory: "A meticulous editor with an eye for detail, ensuring every piece of content is clear, engaging, and grammatically perfect."
+ verbose: true
```
-## Define Agents and Tasks
+### Step 5: Configure Tasks
+
+Edit `src/job_posting_agent/config/tasks.yaml` to define the workflow:
+
+```yaml
+research_company_culture:
+ description: >
+ Analyze the provided company website and description: "{company_description}"
+ at domain {company_domain}. Focus on understanding the company's culture,
+ values, and mission. Identify unique selling points and specific projects
+ or achievements highlighted on the site. Compile a report summarizing these
+ insights, specifically how they can be leveraged in a job posting to attract
+ the right candidates.
+ expected_output: >
+ A comprehensive report detailing the company's culture, values, and mission,
+ along with specific selling points relevant to the job role. Suggestions on
+ incorporating these insights into the job posting should be included.
+ agent: researcher
+
+research_role_requirements:
+ description: >
+ Based on the hiring manager's needs: "{hiring_needs}", identify the key skills,
+ experiences, and qualities the ideal candidate should possess for the role.
+ Consider the company's current projects, its competitive landscape, and industry
+ trends. Prepare a list of recommended job requirements and qualifications that
+ align with the company's needs and values.
+ expected_output: >
+ A list of recommended skills, experiences, and qualities for the ideal candidate,
+ aligned with the company's culture, ongoing projects, and the specific role's requirements.
+ agent: researcher
+
+draft_job_posting:
+ description: >
+ Draft a job posting for the role described by the hiring manager: "{hiring_needs}".
+ Use the insights on "{company_description}" to start with a compelling introduction,
+ followed by a detailed role description, responsibilities, and required skills and
+ qualifications. Ensure the tone aligns with the company's culture and incorporate
+ any unique benefits or opportunities offered by the company.
+ Specific benefits: "{specific_benefits}"
+ expected_output: >
+ A detailed, engaging job posting that includes an introduction, role description,
+ responsibilities, requirements, and unique company benefits. The tone should
+ resonate with the company's culture and values, aimed at attracting the right candidates.
+ agent: writer
+ context:
+ - research_company_culture
+ - research_role_requirements
+
+review_and_edit_job_posting:
+ description: >
+ Review the draft job posting for the role: "{hiring_needs}". Check for clarity,
+ engagement, grammatical accuracy, and alignment with the company's culture and
+ values. Edit and refine the content, ensuring it speaks directly to the desired
+ candidates and accurately reflects the role's unique benefits and opportunities.
+ Provide feedback for any necessary revisions.
+ expected_output: >
+ A polished, error-free job posting that is clear, engaging, and perfectly
+ aligned with the company's culture and values. Feedback on potential improvements
+ and final approval for publishing. Formatted in markdown.
+ agent: editor
+ context:
+ - draft_job_posting
+ output_file: "job_posting.md"
+```
+
+### Step 6: Update the Crew Definition
+
+Edit `src/job_posting_agent/crew.py` to add tools and AgentOps:
```python
-web_search_tool = WebsiteSearchTool()
-serper_dev_tool = SerperDevTool()
-file_read_tool = FileReadTool(
- file_path="job_description_example.md", # Ensure this file exists or handle appropriately
- description="A tool to read the job description example file.",
-)
+from crewai import Agent, Crew, Process, Task
+from crewai.project import CrewBase, agent, crew, task
+from crewai_tools import SerperDevTool, WebsiteSearchTool
+import agentops
+
+# Initialize AgentOps
+agentops.init()
+@CrewBase
+class JobPostingAgentCrew():
+ """JobPostingAgent crew"""
+
+ def __init__(self) -> None:
+ # Initialize tools
+ self.serper_tool = SerperDevTool()
+ self.website_tool = WebsiteSearchTool()
-class Agents:
- def research_agent(self):
+ @agent
+ def researcher(self) -> Agent:
return Agent(
- role="Research Analyst",
- goal="Analyze the company website and provided description to extract insights on culture, values, and specific needs.",
- tools=[web_search_tool, serper_dev_tool],
- backstory="Expert in analyzing company cultures and identifying key values and needs from various sources, including websites and brief descriptions.",
- verbose=True,
+ config=self.agents_config['researcher'],
+ tools=[self.serper_tool, self.website_tool]
)
- def writer_agent(self):
+ @agent
+ def writer(self) -> Agent:
return Agent(
- role="Job Description Writer",
- goal="Use insights from the Research Analyst to create a detailed, engaging, and enticing job posting.",
- tools=[web_search_tool, serper_dev_tool, file_read_tool],
- backstory="Skilled in crafting compelling job descriptions that resonate with the company's values and attract the right candidates.",
- verbose=True,
+ config=self.agents_config['writer'],
+ tools=[self.serper_tool, self.website_tool]
)
- def review_agent(self):
+ @agent
+ def editor(self) -> Agent:
return Agent(
- role="Review and Editing Specialist",
- goal="Review the job posting for clarity, engagement, grammatical accuracy, and alignment with company values and refine it to ensure perfection.",
- tools=[web_search_tool, serper_dev_tool, file_read_tool],
- backstory="A meticulous editor with an eye for detail, ensuring every piece of content is clear, engaging, and grammatically perfect.",
- verbose=True,
+ config=self.agents_config['editor']
)
-```
-```python
-class Tasks:
- def research_company_culture_task(self, agent, company_description, company_domain):
+ @task
+ def research_company_culture(self) -> Task:
return Task(
- description=dedent(
- f\"\"\"\\
- Analyze the provided company website and the hiring manager's company's domain {company_domain}, description: "{company_description}". Focus on understanding the company's culture, values, and mission. Identify unique selling points and specific projects or achievements highlighted on the site.
- Compile a report summarizing these insights, specifically how they can be leveraged in a job posting to attract the right candidates.\"\"\"
- ),
- expected_output=dedent(
- \"\"\"\\
- A comprehensive report detailing the company's culture, values, and mission, along with specific selling points relevant to the job role. Suggestions on incorporating these insights into the job posting should be included.\"\"\"
- ),
- agent=agent,
+ config=self.tasks_config['research_company_culture']
)
- def research_role_requirements_task(self, agent, hiring_needs):
+ @task
+ def research_role_requirements(self) -> Task:
return Task(
- description=dedent(
- f\"\"\"\\
- Based on the hiring manager's needs: "{hiring_needs}", identify the key skills, experiences, and qualities the ideal candidate should possess for the role. Consider the company's current projects, its competitive landscape, and industry trends. Prepare a list of recommended job requirements and qualifications that align with the company's needs and values.\"\"\"
- ),
- expected_output=dedent(
- \"\"\"\\
- A list of recommended skills, experiences, and qualities for the ideal candidate, aligned with the company's culture, ongoing projects, and the specific role's requirements.\"\"\"
- ),
- agent=agent,
+ config=self.tasks_config['research_role_requirements']
)
- def draft_job_posting_task(self, agent, company_description, hiring_needs, specific_benefits):
+ @task
+ def draft_job_posting(self) -> Task:
return Task(
- description=dedent(
- f\"\"\"\\
- Draft a job posting for the role described by the hiring manager: "{hiring_needs}". Use the insights on "{company_description}" to start with a compelling introduction, followed by a detailed role description, responsibilities, and required skills and qualifications. Ensure the tone aligns with the company's culture and incorporate any unique benefits or opportunities offered by the company.
- Specific benefits: "{specific_benefits}"\"\"\"
- ),
- expected_output=dedent(
- \"\"\"\\
- A detailed, engaging job posting that includes an introduction, role description, responsibilities, requirements, and unique company benefits. The tone should resonate with the company's culture and values, aimed at attracting the right candidates.\"\"\"
- ),
- agent=agent,
+ config=self.tasks_config['draft_job_posting']
)
- def review_and_edit_job_posting_task(self, agent, hiring_needs):
+ @task
+ def review_and_edit_job_posting(self) -> Task:
return Task(
- description=dedent(
- f\"\"\"\\
- Review the draft job posting for the role: "{hiring_needs}". Check for clarity, engagement, grammatical accuracy, and alignment with the company's culture and values. Edit and refine the content, ensuring it speaks directly to the desired candidates and accurately reflects the role's unique benefits and opportunities. Provide feedback for any necessary revisions.\"\"\"
- ),
- expected_output=dedent(
- \"\"\"\\
- A polished, error-free job posting that is clear, engaging, and perfectly aligned with the company's culture and values. Feedback on potential improvements and final approval for publishing. Formated in markdown.\"\"\"
- ),
- agent=agent,
- output_file="job_posting.md",
+ config=self.tasks_config['review_and_edit_job_posting']
)
- def industry_analysis_task(self, agent, company_domain, company_description):
- return Task(
- description=dedent(
- f\"\"\"\\
- Conduct an in-depth analysis of the industry related to the company's domain: "{company_domain}". Investigate current trends, challenges, and opportunities within the industry, utilizing market reports, recent developments, and expert opinions. Assess how these factors could impact the role being hired for and the overall attractiveness of the position to potential candidates.
- Consider how the company's position within this industry and its response to these trends could be leveraged to attract top talent. Include in your report how the role contributes to addressing industry challenges or seizing opportunities.\"\"\"
- ),
- expected_output=dedent(
- \"\"\"\\
- A detailed analysis report that identifies major industry trends, challenges, and opportunities relevant to the company's domain and the specific job role. This report should provide strategic insights on positioning the job role and the company as an attractive choice for potential candidates.\"\"\"
- ),
- agent=agent,
+ @crew
+ def crew(self) -> Crew:
+ """Creates the JobPostingAgent crew"""
+ return Crew(
+ agents=self.agents,
+ tasks=self.tasks,
+ process=Process.sequential,
+ verbose=True
)
```
-## Run the Crew
+### Step 7: Update the Main Execution File
+
+Edit `src/job_posting_agent/main.py` to add AgentOps session management:
```python
-tracer = agentops.start_trace(trace_name="CrewAI Job Posting", tags=["crew-job-posting-example", "agentops-example"])
-
-tasks = Tasks()
-agents = Agents()
-
-# Note: In a real scenario, you'd get these inputs dynamically.
-# For this MDX example, we'll use placeholders.
-company_description = "A fast-paced tech startup focused on AI-driven solutions for e-commerce."
-company_domain = "agentops.ai" # Example domain
-hiring_needs = "Senior Software Engineer with experience in Python, AI, and cloud platforms."
-specific_benefits = "Competitive salary, stock options, remote work flexibility, and a great team culture."
-
-# Create Agents
-researcher_agent = agents.research_agent()
-writer_agent = agents.writer_agent()
-review_agent = agents.review_agent()
-
-# Define Tasks for each agent
-research_company_culture_task = tasks.research_company_culture_task(
- researcher_agent, company_description, company_domain
-)
-industry_analysis_task = tasks.industry_analysis_task(researcher_agent, company_domain, company_description)
-research_role_requirements_task = tasks.research_role_requirements_task(researcher_agent, hiring_needs)
-draft_job_posting_task = tasks.draft_job_posting_task(
- writer_agent, company_description, hiring_needs, specific_benefits
-)
-review_and_edit_job_posting_task = tasks.review_and_edit_job_posting_task(review_agent, hiring_needs)
-
-# Instantiate the crew with a sequential process
-crew = Crew(
- agents=[researcher_agent, writer_agent, review_agent],
- tasks=[
- research_company_culture_task,
- industry_analysis_task,
- research_role_requirements_task,
- draft_job_posting_task,
- review_and_edit_job_posting_task,
- ],
-)
-
-
-result = crew.kickoff()
-print("Job Posting Creation Process Completed.")
-print("Final Job Posting:")
-print(result) # This will print the path to the output file job_posting.md
-
-agentops.end_trace(tracer, end_state="Success")
+#!/usr/bin/env python
+import sys
+import warnings
+from job_posting_agent.crew import JobPostingAgentCrew
+import agentops
+
+warnings.filterwarnings("ignore", category=SyntaxWarning, module="pysbd")
+
+def run():
+ """
+ Run the crew with AgentOps tracking.
+ """
+ # Start AgentOps session
+ session = agentops.start_session(tags=["crewai", "job-posting"])
+
+ try:
+ # 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():
+ """
+ Train the crew for a given number of iterations.
+ """
+ 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.'
+ }
+ try:
+ JobPostingAgentCrew().crew().train(n_iterations=int(sys.argv[1]), filename=sys.argv[2], inputs=inputs)
+ 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.
+ """
+ try:
+ JobPostingAgentCrew().crew().replay(task_id=sys.argv[1])
+ except Exception as e:
+ raise Exception(f"An error occurred while replaying the crew: {e}")
+
+def test():
+ """
+ Test the crew execution and returns the results.
+ """
+ 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.'
+ }
+ try:
+ JobPostingAgentCrew().crew().test(n_iterations=int(sys.argv[1]), openai_model_name=sys.argv[2], inputs=inputs)
+ except Exception as e:
+ raise Exception(f"An error occurred while testing the crew: {e}")
+```
+
+### Step 8: Run Your Job Posting Generator
+
+Navigate to your project and run:
+
+```bash
+cd job_posting_agent
+crewai run
```
-The `job_posting.md` file will be created in the same directory where this script/notebook is run.
-<script type="module" src="/scripts/github_stars.js"></script>
-<script type="module" src="/scripts/scroll-img-fadein-animation.js"></script>
-<script type="module" src="/scripts/button_heartbeat_animation.js"></script>
-<script type="module" src="/scripts/adjust_api_dynamically.js"></script>
+**What happens:**
+1. AgentOps session starts automatically
+2. Research agent analyzes the company and industry trends
+3. Writer agent drafts the job posting using research insights
+4. Editor agent reviews and polishes the final version
+5. A `job_posting.md` file is created with the result
+6. AgentOps captures all agent interactions, tool usage, and costs
+7. Session ends with success/failure status
+
+## View Results in AgentOps Dashboard
+
+After running your job posting generator, visit your [AgentOps Dashboard](https://app.agentops.ai) to see:
+
+1. **Session Overview**: Complete timeline of the 3-agent workflow
+2. **Agent Conversations**: Every LLM call with prompts and responses
+3. **Tool Execution**: Web searches and their results
+4. **Cost Breakdown**: Token usage and costs per agent and task
+5. **Performance Analytics**: Execution times and success rates
+6. **Session Replay**: Step-by-step playback for debugging
+
+## Key Files Modified
+
+**Configuration files you edited:**
+- `config/agents.yaml` - Agent definitions with roles and backstories
+- `config/tasks.yaml` - Task workflow with context dependencies
+- `crew.py` - Added tools and AgentOps initialization
+- `main.py` - Added session management
+- `.env` - Added AgentOps and Serper API keys
+
+**Generated output:**
+- `job_posting.md` - Final job posting created by the crew
+
+**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
+
+## 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
diff --git a/docs/v2/examples/google_adk.mdx b/docs/v2/examples/google_adk.mdx
index fd5ffb03..d598738f 100644
--- a/docs/v2/examples/google_adk.mdx
+++ b/docs/v2/examples/google_adk.mdx
@@ -1,43 +1,109 @@
---
title: 'Google ADK'
-description: 'Google ADK Example: Human Approval Workflow with AgentOps'
+description: 'Build a human approval workflow with Google ADK and AgentOps tracking'
---
{/* SOURCE_FILE: examples/google_adk/human_approval.ipynb */}
_View Notebook on <a href={'https://github.com/AgentOps-AI/agentops/blob/main/examples/google_adk/human_approval.ipynb'} target={'_blank'}>Github</a>_
-# Google ADK Example: Human Approval Workflow with AgentOps
+# Google ADK Human Approval Workflow with AgentOps
-This notebook demonstrates a complete human approval workflow using the Google ADK (Agent Development Kit), integrated with AgentOps for observability.
+This example shows you how to build a complete human approval workflow using Google's Agent Development Kit (ADK) with comprehensive tracking via AgentOps.
-**Key Features:**
-- **Sequential Agent Processing:** The workflow uses multiple agents chained together to handle different stages of the approval process.
-- **External Tool Integration:** An agent interacts with an external tool that simulates (or in this version, directly prompts for) human approval.
-- **Session State Management:** Information is passed between agents and persisted using session state.
-- **AgentOps Observability:** All agent actions, tool calls, and LLM interactions are traced and can be viewed in your AgentOps dashboard.
-- **Interactive Human Input:** The approval step now requires direct input from the user.
+## What We're Building
-## 1. Setup and Dependencies
+A **3-agent sequential workflow** for processing approval requests:
+- 🔍 **Prepare Agent**: Extracts and validates approval request details
+- 👤 **Approval Agent**: Handles human approval via external tool
+- ✅ **Decision Agent**: Processes approval decisions and provides final response
-First, let's install the necessary libraries if they are not already present and import them.
+**With AgentOps**, you'll get complete visibility into agent conversations, tool usage, costs, and performance.
+## Step-by-Step Implementation
-## Installation
+
+### Step 1: Install Dependencies
+
+Install Google ADK with required packages and AgentOps for tracking:
+
<CodeGroup>
```bash pip
- pip install agentops asyncio google-adk nest_asyncio python-dotenv
+ pip install google-adk agentops nest_asyncio python-dotenv
```
```bash poetry
- poetry add agentops asyncio google-adk nest_asyncio python-dotenv
+ poetry add google-adk agentops nest_asyncio python-dotenv
```
```bash uv
- uv add agentops asyncio google-adk nest_asyncio python-dotenv
+ uv pip install google-adk agentops nest_asyncio python-dotenv
```
</CodeGroup>
+**What AgentOps adds:**
+- 🔍 **Automatic tracking** of all LLM calls and agent interactions
+- 💰 **Cost monitoring** with token usage breakdown
+- 🛠️ **Tool usage analytics** for approval workflow steps
+- 📊 **Performance metrics** and execution timelines
+- 🐛 **Session replay** for debugging and optimization
+
+
+### Step 2: Create Google ADK Project
+
+Create the proper project structure for your approval workflow:
+
+```bash
+# Create project directory
+mkdir human_approval_workflow
+cd human_approval_workflow
+
+# Create agent module
+mkdir approval_agent
+touch approval_agent/__init__.py
+touch approval_agent/agent.py
+touch approval_agent/.env
+```
+
+**This creates the standard Google ADK structure:**
+```
+human_approval_workflow/
+└── approval_agent/
+ ├── __init__.py # Module initialization
+ ├── agent.py # Agent definitions
+ └── .env # API keys
+```
+
+### Step 3: Set Up Environment Variables
+
+Create the `.env` file in `approval_agent/` directory:
+
+```bash
+# approval_agent/.env
+GOOGLE_GENAI_USE_VERTEXAI=FALSE
+GOOGLE_API_KEY=your_google_api_key_here
+AGENTOPS_API_KEY=your_agentops_api_key_here
+```
+
+**Get your API keys:**
+- **Google API Key**: [Google AI Studio](https://aistudio.google.com/app/apikey)
+- **AgentOps API Key**: [AgentOps Settings](https://agentops.ai/settings/projects)
+
+**Note**: For Vertex AI, set `GOOGLE_GENAI_USE_VERTEXAI=TRUE` and run `gcloud auth application-default login`
+
+### Step 4: Create Module Initialization
+
+Edit `approval_agent/__init__.py`:
```python
+# approval_agent/__init__.py
+from . import agent
+```
+
+### Step 5: Define the Agent Workflow
+
+Edit `approval_agent/agent.py` to create your approval workflow:
+
+```python
+# approval_agent/agent.py
import json
import os
import asyncio
@@ -50,55 +116,31 @@ from pydantic import BaseModel, Field
import nest_asyncio
import agentops
from dotenv import load_dotenv
-```
-
-## 2. Configuration and Initialization
-
-Load environment variables (especially `AGENTOPS_API_KEY` and your Google API key for Gemini) and initialize AgentOps.
-
-```python
-# Load environment variables from .env file
+# Load environment and initialize AgentOps
load_dotenv()
nest_asyncio.apply()
-AGENTOPS_API_KEY = os.getenv("AGENTOPS_API_KEY") or "your_agentops_api_key_here"
-# Initialize AgentOps - Just 2 lines!
-agentops.init(AGENTOPS_API_KEY, trace_name="adk-human-approval-notebook", auto_start_session=False)
-```
+agentops.init(auto_start_session=False)
-Define some constants for our application.
+# Constants
+APP_NAME = "human_approval_workflow"
+USER_ID = "approval_user"
+MODEL_NAME = "gemini-2.0-flash"
-
-```python
-APP_NAME = "human_approval_app_notebook"
-USER_ID = "test_user_notebook_123"
-SESSION_ID = "approval_session_notebook_456"
-MODEL_NAME = "gemini-1.5-flash"
-agentops.start_trace(trace_name=APP_NAME, tags=["google_adk", "notebook"])
-```
-
-## 3. Define Schemas
-
-Pydantic models are used to define the structure of data for approval requests and decisions. This helps with validation and clarity.
-
-
-```python
+# Data models
class ApprovalRequest(BaseModel):
amount: float = Field(description="The amount requiring approval")
reason: str = Field(description="The reason for the request")
-
class ApprovalDecision(BaseModel):
decision: str = Field(description="The approval decision: 'approved' or 'rejected'")
comments: str = Field(description="Additional comments from the approver")
```
-## 4. External Approval Tool (with Human Interaction)
-
-This tool now directly prompts the user for an approval decision. In a real-world scenario, this might involve sending a notification to an approver and waiting for their response through a UI or API.
-
+Add the approval tool function:
```python
+# External approval tool with human interaction
async def external_approval_tool(amount: float, reason: str) -> str:
"""
Prompts for human approval and returns the decision as a JSON string.
@@ -116,18 +158,13 @@ async def external_approval_tool(amount: float, reason: str) -> str:
print(f" Comments: {comments if comments else 'N/A'}")
return json.dumps({"decision": decision, "comments": comments, "amount": amount, "reason": reason})
-
# Create the approval tool instance
approval_tool = FunctionTool(func=external_approval_tool)
```
-## 5. Define Agents
-
-We define three agents for our workflow:
-1. **`PrepareApprovalAgent`**: Extracts details from the user's request.
-2. **`RequestHumanApprovalAgent`**: Uses the `external_approval_tool` to get a decision.
-3. **`ProcessDecisionAgent`**: Processes the decision and formulates a final response.
+### Step 6: Define the Three-Agent Workflow
+Add the agent definitions to create your sequential workflow:
```python
# Agent 1: Prepare the approval request
@@ -182,104 +219,168 @@ process_decision = LlmAgent(
)
```
-## 6. Create Sequential Workflow
-
-Combine the agents into a sequential workflow. The `SequentialAgent` ensures that the sub-agents are executed in the specified order.
+### Step 7: Create the Sequential Workflow and Runner
+Combine agents into a workflow with session management:
```python
+# Create sequential workflow
approval_workflow = SequentialAgent(
- name="HumanApprovalWorkflowNotebook",
+ name="HumanApprovalWorkflow",
description="Complete workflow for processing approval requests with human oversight",
sub_agents=[prepare_request, request_approval, process_decision],
)
-```
-
-## 7. Session Management and Runner
-Set up an in-memory session service and the workflow runner.
-
-
-```python
+# Set up session service and runner
session_service = InMemorySessionService()
-# Create runner
workflow_runner = Runner(agent=approval_workflow, app_name=APP_NAME, session_service=session_service)
```
-## 8. Helper Function to Run Workflow
-
-This function encapsulates the logic to run the workflow for a given user request and session ID.
+### Step 8: Add the Main Execution Function
+Create the function to run the approval workflow with AgentOps tracking:
```python
-async def run_approval_workflow_notebook(user_request: str, session_id: str):
- """Run the complete approval workflow with a user request in the notebook environment"""
- 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,
- session_id=session_id,
- new_message=user_content,
- ):
- if event.author and event.content:
- step_count += 1
- 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
- session = 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.state.items():
- print(f" {key}: {value}")
- print(f"🎯 Final Response: {final_response}")
- return final_response
+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:
+ 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,
+ session_id=session_id,
+ new_message=user_content,
+ ):
+ if event.author and event.content:
+ step_count += 1
+ 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")
+ return final_response
+
+ except Exception as e:
+ print(f"Error occurred: {e}")
+ agentops.end_session("Failed", end_state_reason=str(e))
+ raise
```
-## 9. Main Execution Logic
-
-This cell contains the main logic to run the workflow with a few test cases. Each test case will run in its own session.
-
+Finally, add the main execution logic:
```python
-async def main_notebook():
+# Main execution function
+async def main():
test_requests = [
"I need approval for $750 for team lunch and celebrations",
"Please approve $3,000 for a conference ticket and travel expenses",
"I need $12,000 approved for critical software licenses renewal",
]
+
for i, request in enumerate(test_requests, 1):
- current_session_id = f"approval_session_notebook_{456 + i - 1}"
+ current_session_id = f"approval_session_{456 + i - 1}"
# Create the session before running the workflow
await session_service.create_session(app_name=APP_NAME, user_id=USER_ID, session_id=current_session_id)
print(f"Created session: {current_session_id}")
- await run_approval_workflow_notebook(request, current_session_id)
+ await run_approval_workflow(request, current_session_id)
+
+# Export the workflow for ADK
+root_agent = approval_workflow
+```
+### Step 9: Run Your Approval Workflow
-try:
- asyncio.run(main_notebook())
- agentops.end_trace(end_state="Success")
-except Exception as e:
- print(f"Error: {e}")
- agentops.end_trace(end_state="Error")
+Navigate to your project directory and run the workflow:
+
+**Option 1: Interactive Development UI**
+```bash
+cd human_approval_workflow
+adk web
+```
+Then open http://localhost:8000, select "approval_agent" from the dropdown, and interact with your workflow.
+
+**Option 2: Terminal Interface**
+```bash
+cd human_approval_workflow
+adk run approval_agent
```
+**Option 3: Run Programmatically**
+```python
+# Run this in a separate script or notebook
+import asyncio
+from approval_agent.agent import main
+
+if __name__ == "__main__":
+ try:
+ asyncio.run(main())
+ except Exception as e:
+ print(f"Error: {e}")
+```
-<script type="module" src="/scripts/github_stars.js"></script>
-<script type="module" src="/scripts/scroll-img-fadein-animation.js"></script>
-<script type="module" src="/scripts/button_heartbeat_animation.js"></script>
-<script type="module" src="/scripts/adjust_api_dynamically.js"></script>
\ No newline at end of file
+**What happens:**
+1. AgentOps session starts automatically
+2. Prepare agent extracts amount and reason from requests
+3. Approval agent prompts for human input via terminal
+4. Decision agent processes the approval and provides final response
+5. AgentOps captures all interactions, tool usage, and costs
+6. Session ends with success/failure status
+## View Results in AgentOps Dashboard
+
+After running your approval workflow, visit your [AgentOps Dashboard](https://app.agentops.ai) to see:
+
+1. **Session Overview**: Complete timeline of the 3-agent workflow
+2. **Agent Conversations**: Every LLM call with prompts and responses
+3. **Tool Execution**: Human approval interactions and decisions
+4. **Cost Breakdown**: Token usage and costs per agent and step
+5. **Performance Analytics**: Execution times and success rates
+6. **Session Replay**: Step-by-step playback for debugging
+
+## Key Files Created
+
+**Project structure you built:**
+- `approval_agent/__init__.py` - Module initialization with agent import
+- `approval_agent/agent.py` - Complete workflow with 3 agents and AgentOps integration
+- `approval_agent/.env` - API keys for Google AI and AgentOps
+
+**AgentOps Integration Points:**
+- `agentops.init()` - Enables automatic instrumentation
+- `agentops.start_session()` - Begins tracking each workflow run
+- `agentops.end_session()` - Completes the session with status
+
+## Next Steps
+
+- Customize approval thresholds and business logic
+- Add more sophisticated approval routing
+- Integrate with external approval systems (Slack, email, etc.)
+- Use Google ADK's web UI for better user experience
+- Use AgentOps analytics to optimize approval times
\ No newline at end of file
diff --git a/docs/v2/examples/google_genai.mdx b/docs/v2/examples/google_genai.mdx
index 6bd5770c..93f8938f 100644
--- a/docs/v2/examples/google_genai.mdx
+++ b/docs/v2/examples/google_genai.mdx
@@ -22,7 +22,7 @@ This notebook demonstrates how to use AgentOps with Google's Generative AI packa
poetry add agentops google-genai
```
```bash uv
- uv add agentops google-genai
+ uv pip install agentops google-genai
```
</CodeGroup>
diff --git a/docs/v2/examples/langchain.mdx b/docs/v2/examples/langchain.mdx
index da212b84..173c4caa 100644
--- a/docs/v2/examples/langchain.mdx
+++ b/docs/v2/examples/langchain.mdx
@@ -23,7 +23,7 @@ First let's install the required packages
poetry add agentops langchain langchain_openai python-dotenv
```
```bash uv
- uv add agentops langchain langchain_openai python-dotenv
+ uv pip install agentops langchain langchain_openai python-dotenv
```
</CodeGroup>
diff --git a/docs/v2/examples/langgraph.mdx b/docs/v2/examples/langgraph.mdx
index 4d2fae20..9a75c54d 100644
--- a/docs/v2/examples/langgraph.mdx
+++ b/docs/v2/examples/langgraph.mdx
@@ -1,254 +1,260 @@
---
title: 'Langgraph'
-description: 'LangGraph Integration with AgentOps'
+description: 'Build a basic chatbot with LangGraph and AgentOps tracking'
---
{/* SOURCE_FILE: examples/langgraph/langgraph_example.ipynb */}
_View Notebook on <a href={'https://github.com/AgentOps-AI/agentops/blob/main/examples/langgraph/langgraph_example.ipynb'} target={'_blank'}>Github</a>_
-# LangGraph Integration with AgentOps
+# LangGraph Basic Chatbot with AgentOps
-This example demonstrates how to use LangGraph with AgentOps for comprehensive observability of your graph-based agent workflows.
+This example shows you how to build a basic chatbot using LangGraph's StateGraph with comprehensive tracking via AgentOps.
-LangGraph is a framework for building stateful, multi-step applications with LLMs. AgentOps automatically instruments LangGraph to track:
-- Graph compilation and structure
-- Node executions and transitions
-- Tool usage within the graph
-- LLM calls made by agents
-- Complete execution flow with timing
+## What We're Building
+A **stateful chatbot** using LangGraph fundamentals:
+- 🗃️ **StateGraph**: Core LangGraph structure for managing conversation state
+- 💬 **Chat Model**: LLM integration for generating responses
+- 🔄 **State Management**: Automatic message history tracking with `add_messages`
+- 🎯 **Graph Flow**: START → chatbot node → END pattern
+**With AgentOps**, you'll get complete visibility into graph execution, state transitions, and LLM interactions.
+
+## Step-by-Step Implementation
+
+
+
+### Step 1: Install Dependencies
+
+Install LangGraph with your preferred chat model and AgentOps for tracking:
-## Installation
<CodeGroup>
```bash pip
- pip install agentops langchain-openai langgraph python-dotenv
+ pip install langgraph langchain agentops python-dotenv
```
```bash poetry
- poetry add agentops langchain-openai langgraph python-dotenv
+ poetry add langgraph langchain agentops python-dotenv
```
```bash uv
- uv add agentops langchain-openai langgraph python-dotenv
+ uv pip install langgraph langchain agentops python-dotenv
```
</CodeGroup>
-## Setup
+**What AgentOps adds:**
+- 📊 **Graph execution tracking** with node transitions and timing
+- 💰 **LLM cost monitoring** with token usage breakdown
+- 🔄 **State change visualization** showing message flow
+- 📈 **Performance metrics** for each graph execution
+- 🐛 **Execution replay** for debugging graph flows
-First, let's import the necessary libraries and initialize AgentOps:
+### Step 2: Create Your Project Structure
+Create a simple Python project for your chatbot:
-```python
-import os
-from typing import Annotated, Literal, TypedDict
-from langgraph.graph import StateGraph, END
-from langgraph.graph.message import add_messages
-from langchain_openai import ChatOpenAI
-from langchain_core.messages import HumanMessage, AIMessage, ToolMessage
-from langchain_core.tools import tool
-import agentops
-from dotenv import load_dotenv
+```bash
+# Create project directory
+mkdir langgraph_chatbot
+cd langgraph_chatbot
-# Load environment variables
-load_dotenv()
-
-# Initialize AgentOps - this enables automatic instrumentation
-agentops.init(os.getenv("AGENTOPS_API_KEY"), auto_start_session=False)
-trace = agentops.start_trace("langgraph_example")
+# Create main chatbot file
+touch chatbot.py
+touch .env
```
-## Define Tools
-
-Let's create some simple tools that our agent can use:
+**This creates the basic structure:**
+```
+langgraph_chatbot/
+├── chatbot.py # Main chatbot implementation
+└── .env # API keys
+```
+### Step 3: Set Up Environment Variables
-```python
-@tool
-def get_weather(location: str) -> str:
- """Get the weather for a given location."""
- # Simulated weather data
- weather_data = {
- "New York": "Sunny, 72°F",
- "London": "Cloudy, 60°F",
- "Tokyo": "Rainy, 65°F",
- "Paris": "Partly cloudy, 68°F",
- "Sydney": "Clear, 75°F"
- }
- return weather_data.get(location, f"Weather data not available for {location}")
-
-@tool
-def calculate(expression: str) -> str:
- """Evaluate a mathematical expression."""
- try:
- result = eval(expression)
- return f"The result is: {result}"
- except Exception as e:
- return f"Error calculating expression: {str(e)}"
+Create your `.env` file with the necessary API keys:
-# Collect tools for binding to the model
-tools = [get_weather, calculate]
+```bash
+# .env
+OPENAI_API_KEY=your_openai_api_key_here
+AGENTOPS_API_KEY=your_agentops_api_key_here
```
-## Define Agent State
+**Get your API keys:**
+- **OpenAI API Key**: [OpenAI Platform](https://platform.openai.com/api-keys)
+- **AgentOps API Key**: [AgentOps Settings](https://agentops.ai/settings/projects)
+
+**Note**: You can use any LangChain-compatible model (Anthropic, Google, etc.) by adjusting the imports and model initialization.
-In LangGraph, we need to define the state that will be passed between nodes:
+### Step 4: Build Your Basic Chatbot
+Edit `chatbot.py` to create your LangGraph chatbot:
```python
-class AgentState(TypedDict):
+# chatbot.py
+import os
+from typing import Annotated
+from typing_extensions import TypedDict
+
+from langchain.chat_models import init_chat_model
+from langgraph.graph import StateGraph, START, END
+from langgraph.graph.message import add_messages
+import agentops
+from dotenv import load_dotenv
+
+# Load environment variables and initialize AgentOps
+load_dotenv()
+agentops.init(auto_start_session=False)
+
+# Define the State schema
+class State(TypedDict):
+ # Messages have the type "list". The `add_messages` function
+ # in the annotation defines how this state key should be updated
+ # (in this case, it appends messages to the list, rather than overwriting them)
messages: Annotated[list, add_messages]
```
-## Create the Model and Node Functions
-
-We'll create a model with tool binding and define the functions that will be our graph nodes:
+### Step 5: Initialize the Chat Model and Create the Chatbot Node
+Add the model and node function:
```python
-# Create model with tool binding
-model = ChatOpenAI(temperature=0, model="gpt-4o-mini").bind_tools(tools)
+# Initialize the chat model (you can change to any provider)
+llm = init_chat_model("openai:gpt-4o-mini")
-def should_continue(state: AgentState) -> Literal["tools", "end"]:
- """Determine if we should continue to tools or end."""
- messages = state["messages"]
- last_message = messages[-1]
-
- # If the LLM wants to use tools, continue to the tools node
- if hasattr(last_message, "tool_calls") and last_message.tool_calls:
- return "tools"
- # Otherwise, we're done
- return "end"
-
-def call_model(state: AgentState):
- """Call the language model."""
- messages = state["messages"]
- response = model.invoke(messages)
- return {"messages": [response]}
-
-def call_tools(state: AgentState):
- """Execute the tool calls requested by the model."""
- messages = state["messages"]
- last_message = messages[-1]
-
- tool_messages = []
- for tool_call in last_message.tool_calls:
- tool_name = tool_call["name"]
- tool_args = tool_call["args"]
-
- # Find and execute the requested tool
- for tool in tools:
- if tool.name == tool_name:
- result = tool.invoke(tool_args)
- tool_messages.append(
- ToolMessage(
- content=str(result),
- tool_call_id=tool_call["id"]
- )
- )
- break
-
- return {"messages": tool_messages}
+# Create the chatbot node function
+def chatbot(state: State):
+ """Main chatbot function that processes messages and returns responses."""
+ return {"messages": [llm.invoke(state["messages"])]}
```
-## Build the Graph
-
-Now let's construct the LangGraph workflow:
+### Step 6: Build and Compile the StateGraph
+Construct your LangGraph workflow:
```python
-# Create the graph
-workflow = StateGraph(AgentState)
-
-# Add nodes
-workflow.add_node("agent", call_model)
-workflow.add_node("tools", call_tools)
+# Create the StateGraph
+graph_builder = StateGraph(State)
-# Set the entry point
-workflow.set_entry_point("agent")
+# Add the chatbot node
+# The first argument is the unique node name
+# The second argument is the function that will be called
+graph_builder.add_node("chatbot", chatbot)
-# Add conditional edges
-workflow.add_conditional_edges(
- "agent",
- should_continue,
- {
- "tools": "tools",
- "end": END
- }
-)
+# Add entry point (where to start)
+graph_builder.add_edge(START, "chatbot")
-# Add edge from tools back to agent
-workflow.add_edge("tools", "agent")
+# Add exit point (where to end)
+graph_builder.add_edge("chatbot", END)
# Compile the graph
-app = workflow.compile()
+graph = graph_builder.compile()
```
-## Run Examples
-
-Let's test our agent with different queries that require tool usage:
+### Step 7: Add the Streaming Chat Function
+Create the interactive chat interface with AgentOps tracking:
```python
-# Example 1: Weather query
-print("Example 1: Weather Query")
-print("=" * 50)
-
-messages = [HumanMessage(content="What's the weather in New York and Tokyo?")]
-result = app.invoke({"messages": messages})
+def stream_graph_updates(user_input: str):
+ """Stream graph updates for the given user input."""
+ for event in graph.stream({"messages": [{"role": "user", "content": user_input}]}):
+ for value in event.values():
+ print("Assistant:", value["messages"][-1].content)
+
+def run_chatbot():
+ """Main function to run the chatbot with AgentOps tracking."""
+ # Start AgentOps session
+ session = agentops.start_session(tags=["langgraph", "chatbot"])
+
+ try:
+ print("🤖 LangGraph Chatbot Started!")
+ print("Type 'quit', 'exit', or 'q' to stop.\n")
+
+ while True:
+ try:
+ user_input = input("User: ")
+ if user_input.lower() in ["quit", "exit", "q"]:
+ print("Goodbye!")
+ break
+ stream_graph_updates(user_input)
+ print() # Add blank line for readability
+ except KeyboardInterrupt:
+ print("\nGoodbye!")
+ break
+ 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
-final_message = result["messages"][-1]
-print(f"Response: {final_message.content}\n")
+# Main execution
+if __name__ == "__main__":
+ run_chatbot()
```
+### Step 8: Run Your Chatbot
-```python
-# Example 2: Math calculation
-print("Example 2: Math Calculation")
-print("=" * 50)
+Execute your chatbot:
-messages = [HumanMessage(content="Calculate 25 * 4 + 10")]
-result = app.invoke({"messages": messages})
-
-final_message = result["messages"][-1]
-print(f"Response: {final_message.content}\n")
+```bash
+cd langgraph_chatbot
+python chatbot.py
```
+**What happens:**
+1. AgentOps session starts automatically
+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'
-```python
-# Example 3: Combined query
-print("Example 3: Combined Query")
-print("=" * 50)
+**Example conversation:**
+```
+🤖 LangGraph Chatbot Started!
+Type 'quit', 'exit', or 'q' to stop.
-messages = [HumanMessage(content="What's the weather in Paris? Also calculate 100/5")]
-result = app.invoke({"messages": messages})
+User: Hello! What can you help me with?
+Assistant: Hello! I'm a helpful AI assistant. I can help you with a wide variety of tasks...
-final_message = result["messages"][-1]
-print(f"Response: {final_message.content}\n")
+User: Tell me a joke
+Assistant: Why don't scientists trust atoms? Because they make up everything!
+
+User: quit
+Goodbye!
```
-## View in AgentOps Dashboard
+## View Results in AgentOps Dashboard
-After running this notebook, you can view the traces in your AgentOps dashboard. You'll see:
+After running your chatbot, visit your [AgentOps Dashboard](https://app.agentops.ai) to see:
-1. **Graph Compilation**: The structure of your LangGraph with nodes and edges
-2. **Execution Flow**: How the graph executed, including:
- - Agent node calls
- - Tool node executions
- - State transitions
-3. **LLM Calls**: Each ChatGPT call with prompts and completions
-4. **Tool Usage**: Which tools were called and their results
-5. **Timing Information**: How long each step took
+1. **Graph Structure**: Visual representation of your StateGraph (START → chatbot → END)
+2. **State Transitions**: How messages flow through the graph
+3. **LLM Interactions**: Every conversation turn with prompts and responses
+4. **Execution Timing**: How long each node takes to process
+5. **Session Analytics**: Conversation length, token usage, and costs
+6. **Message History**: Complete conversation flow with state management
-The instrumentation captures the full context of your LangGraph application automatically!
+## Key Files Created
+**Project structure you built:**
+- `chatbot.py` - Complete LangGraph chatbot with AgentOps integration
+- `.env` - API keys for OpenAI and AgentOps
-```python
-print("✅ Check your AgentOps dashboard for comprehensive traces!")
-print("🔍 You'll see the graph structure, execution flow, and all LLM/tool calls.")
-agentops.end_trace(trace)
-```
+**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
+## Next Steps
-<script type="module" src="/scripts/github_stars.js"></script>
-<script type="module" src="/scripts/scroll-img-fadein-animation.js"></script>
-<script type="module" src="/scripts/button_heartbeat_animation.js"></script>
-<script type="module" src="/scripts/adjust_api_dynamically.js"></script>
\ No newline at end of file
+- Add tools to your chatbot (web search, calculators, etc.)
+- Implement more complex graph structures with conditional edges
+- Add memory persistence across sessions
+- Create multi-agent workflows with LangGraph
+- Use AgentOps analytics to optimize conversation flows
diff --git a/docs/v2/examples/litellm.mdx b/docs/v2/examples/litellm.mdx
index 224d82f1..46945aee 100644
--- a/docs/v2/examples/litellm.mdx
+++ b/docs/v2/examples/litellm.mdx
@@ -26,7 +26,7 @@ First let's install the required packages
poetry add -U agentops litellm python-dotenv
```
```bash uv
- uv add -U agentops litellm python-dotenv
+ uv pip install -U agentops litellm python-dotenv
```
</CodeGroup>
diff --git a/docs/v2/examples/mem0.mdx b/docs/v2/examples/mem0.mdx
index 0ce76d2d..0efe0f1c 100644
--- a/docs/v2/examples/mem0.mdx
+++ b/docs/v2/examples/mem0.mdx
@@ -34,7 +34,7 @@ By using async operations, you can perform multiple memory operations simultaneo
poetry add agentops mem0ai python-dotenv
```
```bash uv
- uv add agentops mem0ai python-dotenv
+ uv pip install agentops mem0ai python-dotenv
```
</CodeGroup>
diff --git a/docs/v2/examples/openai.mdx b/docs/v2/examples/openai.mdx
index 2114f213..45ec2c0a 100755
--- a/docs/v2/examples/openai.mdx
+++ b/docs/v2/examples/openai.mdx
@@ -1,6 +1,6 @@
---
title: 'OpenAI'
-description: 'Load the dataset (ensure you are logged in with huggingface-cli if needed)'
+description: 'Multi-tool orchestration with OpenAI and AgentOps instrumentation'
---
{/* SOURCE_FILE: examples/openai/multi_tool_orchestration.ipynb */}
@@ -23,7 +23,7 @@ This cookbook guides you through building dynamic, multi-tool workflows using Op
poetry add agentops datasets openai pandas pinecone python-dotenv tqdm
```
```bash uv
- uv add agentops datasets openai pandas pinecone python-dotenv tqdm
+ uv pip install agentops datasets openai pandas pinecone python-dotenv tqdm
```
</CodeGroup>
diff --git a/docs/v2/examples/openai_agents.mdx b/docs/v2/examples/openai_agents.mdx
index 8ca65468..2f2e6e2d 100644
--- a/docs/v2/examples/openai_agents.mdx
+++ b/docs/v2/examples/openai_agents.mdx
@@ -39,7 +39,7 @@ OPENAI_API_KEY=your_openai_api_key_here
poetry add -q agentops openai-agents pydotenv
```
```bash uv
- uv add -q agentops openai-agents pydotenv
+ uv pip install -q agentops openai-agents pydotenv
```
</CodeGroup>
diff --git a/docs/v2/examples/smolagents.mdx b/docs/v2/examples/smolagents.mdx
index f82f885d..51acfada 100644
--- a/docs/v2/examples/smolagents.mdx
+++ b/docs/v2/examples/smolagents.mdx
@@ -44,7 +44,7 @@ Run the line below to install the required dependencies:
poetry add agentops duckduckgo-search markdownify smolagents
```
```bash uv
- uv add agentops duckduckgo-search markdownify smolagents
+ uv pip install agentops duckduckgo-search markdownify smolagents
```
</CodeGroup>
diff --git a/docs/v2/examples/watsonx.mdx b/docs/v2/examples/watsonx.mdx
index d8bd2343..66f90fe6 100644
--- a/docs/v2/examples/watsonx.mdx
+++ b/docs/v2/examples/watsonx.mdx
@@ -20,7 +20,7 @@ Install the required packages:
poetry add agentops ibm-watsonx-ai python-dotenv
```
```bash uv
- uv add agentops ibm-watsonx-ai python-dotenv
+ uv pip install agentops ibm-watsonx-ai python-dotenv
```
</CodeGroup>
diff --git a/docs/v2/examples/xai.mdx b/docs/v2/examples/xai.mdx
index 3e690131..5bae5c09 100644
--- a/docs/v2/examples/xai.mdx
+++ b/docs/v2/examples/xai.mdx
@@ -24,7 +24,7 @@ First let's install the required packages
poetry add -U agentops openai
```
```bash uv
- uv add -U agentops openai
+ uv pip install -U agentops openai
```
</CodeGroup>
diff --git a/docs/v2/integrations/ag2.mdx b/docs/v2/integrations/ag2.mdx
index 0e78d3fe..6a7fd1ac 100755
--- a/docs/v2/integrations/ag2.mdx
+++ b/docs/v2/integrations/ag2.mdx
@@ -13,7 +13,7 @@ description: "Track and analyze your AG2 agents with AgentOps"
poetry add agentops pyautogen
```
```bash uv
- uv add agentops pyautogen
+ uv pip install agentops pyautogen
```
</CodeGroup>
diff --git a/docs/v2/integrations/agno.mdx b/docs/v2/integrations/agno.mdx
index 88c63f7f..5d6b8e9b 100644
--- a/docs/v2/integrations/agno.mdx
+++ b/docs/v2/integrations/agno.mdx
@@ -3,6 +3,18 @@ title: Agno
description: "Track your Agno agents, teams, and workflows with AgentOps"
---
+## Video Tutorial
+
+<iframe
+ width="560"
+ height="315"
+ src="https://www.youtube.com/embed/M4e1Ybkn_K0"
+ title="AgentOps + Agno Integration Tutorial"
+ frameborder="0"
+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
+ allowfullscreen
+></iframe>
+
[Agno](https://docs.agno.com) is a modern AI agent framework for building intelligent agents, teams, and workflows. AgentOps provides automatic instrumentation to track all Agno operations including agent interactions, team coordination, tool usage, and workflow execution.
## Installation
@@ -17,7 +29,7 @@ Install AgentOps and Agno:
poetry add agentops agno
```
```bash uv
- uv add agentops agno
+ uv pip install agentops agno
```
</CodeGroup>
diff --git a/docs/v2/integrations/anthropic.mdx b/docs/v2/integrations/anthropic.mdx
index 1fc08284..0680ddd7 100644
--- a/docs/v2/integrations/anthropic.mdx
+++ b/docs/v2/integrations/anthropic.mdx
@@ -17,7 +17,7 @@ AgentOps provides seamless integration with [Anthropic's Python SDK](https://git
poetry add agentops anthropic
```
```bash uv
- uv add agentops anthropic
+ uv pip install agentops anthropic
```
</CodeGroup>
diff --git a/docs/v2/integrations/autogen.mdx b/docs/v2/integrations/autogen.mdx
index c7fd16a6..9ca34629 100644
--- a/docs/v2/integrations/autogen.mdx
+++ b/docs/v2/integrations/autogen.mdx
@@ -15,7 +15,7 @@ pip install agentops autogen-core python-dotenv
poetry add agentops autogen-core python-dotenv
```
```bash uv
-uv add agentops autogen-core python-dotenv
+uv pip install agentops autogen-core python-dotenv
```
</CodeGroup>
diff --git a/docs/v2/integrations/crewai.mdx b/docs/v2/integrations/crewai.mdx
index 2f6ad1a7..00c5ad32 100644
--- a/docs/v2/integrations/crewai.mdx
+++ b/docs/v2/integrations/crewai.mdx
@@ -3,6 +3,18 @@ title: 'CrewAI'
description: 'AgentOps and CrewAI teamed up to make monitoring Crew agents dead simple.'
---
+## Video Tutorial
+
+<iframe
+ width="560"
+ height="315"
+ src="https://www.youtube.com/embed/t9YRRd2-wus"
+ title="AgentOps + CrewAI Integration Tutorial"
+ frameborder="0"
+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
+ allowfullscreen
+></iframe>
+
[CrewAI](https://www.crewai.com/) is a framework for easily building multi-agent applications. AgentOps integrates with CrewAI to provide observability into your agent workflows. Crew has comprehensive [documentation](https://docs.crewai.com) available as well as a great [quickstart](https://docs.crewai.com/how-to/Creating-a-Crew-and-kick-it-off/) guide.
## Installation
@@ -16,7 +28,7 @@ Install AgentOps and CrewAI, along with `python-dotenv` for managing API keys:
poetry add agentops crewai python-dotenv
```
```bash uv
- uv add agentops crewai python-dotenv
+ uv pip install agentops crewai python-dotenv
```
</CodeGroup>
diff --git a/docs/v2/integrations/google_adk.mdx b/docs/v2/integrations/google_adk.mdx
index 75366c53..5eeac225 100644
--- a/docs/v2/integrations/google_adk.mdx
+++ b/docs/v2/integrations/google_adk.mdx
@@ -15,7 +15,7 @@ pip install agentops google-adk
poetry add agentops google-adk
```
```bash uv
-uv add agentops google-adk
+uv pip install agentops google-adk
```
</CodeGroup>
diff --git a/docs/v2/integrations/google_generative_ai.mdx b/docs/v2/integrations/google_generative_ai.mdx
index c27686af..d04933dc 100644
--- a/docs/v2/integrations/google_generative_ai.mdx
+++ b/docs/v2/integrations/google_generative_ai.mdx
@@ -15,7 +15,7 @@ AgentOps provides seamless integration with [Google's Generative AI API](https:/
poetry add agentops google-genai
```
```bash uv
- uv add agentops google-genai
+ uv pip install agentops google-genai
```
</CodeGroup>
diff --git a/docs/v2/integrations/ibm_watsonx_ai.mdx b/docs/v2/integrations/ibm_watsonx_ai.mdx
index 04ce1687..cbcef99d 100644
--- a/docs/v2/integrations/ibm_watsonx_ai.mdx
+++ b/docs/v2/integrations/ibm_watsonx_ai.mdx
@@ -15,7 +15,7 @@ pip install agentops ibm-watsonx-ai
poetry add agentops ibm-watsonx-ai
```
```bash uv
-uv add agentops ibm-watsonx-ai
+uv pip install agentops ibm-watsonx-ai
```
</CodeGroup>
diff --git a/docs/v2/integrations/langchain.mdx b/docs/v2/integrations/langchain.mdx
index 6b28343a..7680c3be 100644
--- a/docs/v2/integrations/langchain.mdx
+++ b/docs/v2/integrations/langchain.mdx
@@ -17,7 +17,7 @@ Install AgentOps and the necessary LangChain dependencies:
poetry add agentops langchain langchain-community langchain-openai python-dotenv
```
```bash uv
- uv add agentops langchain langchain-community langchain-openai python-dotenv
+ uv pip install agentops langchain langchain-community langchain-openai python-dotenv
```
</CodeGroup>
diff --git a/docs/v2/integrations/langgraph.mdx b/docs/v2/integrations/langgraph.mdx
index 5cf86f14..ec7187af 100644
--- a/docs/v2/integrations/langgraph.mdx
+++ b/docs/v2/integrations/langgraph.mdx
@@ -26,7 +26,7 @@ Install AgentOps and LangGraph along with LangChain dependencies:
poetry add agentops langgraph langchain-openai python-dotenv
```
```bash uv
- uv add agentops langgraph langchain-openai python-dotenv
+ uv pip install agentops langgraph langchain-openai python-dotenv
```
</CodeGroup>
diff --git a/docs/v2/integrations/litellm.mdx b/docs/v2/integrations/litellm.mdx
index a03deeff..38acf39d 100644
--- a/docs/v2/integrations/litellm.mdx
+++ b/docs/v2/integrations/litellm.mdx
@@ -15,7 +15,7 @@ pip install agentops litellm
poetry add agentops litellm
```
```bash uv
-uv add agentops litellm
+uv pip install agentops litellm
```
</CodeGroup>
diff --git a/docs/v2/integrations/llamaindex.mdx b/docs/v2/integrations/llamaindex.mdx
index 79a149e6..5fd43f01 100644
--- a/docs/v2/integrations/llamaindex.mdx
+++ b/docs/v2/integrations/llamaindex.mdx
@@ -17,7 +17,7 @@ Install AgentOps and the LlamaIndex AgentOps instrumentation package:
poetry add agentops llama-index-instrumentation-agentops
```
```bash uv
- uv add agentops llama-index-instrumentation-agentops
+ uv pip install agentops llama-index-instrumentation-agentops
```
</CodeGroup>
diff --git a/docs/v2/integrations/mem0.mdx b/docs/v2/integrations/mem0.mdx
index 562ed3b4..8606438a 100644
--- a/docs/v2/integrations/mem0.mdx
+++ b/docs/v2/integrations/mem0.mdx
@@ -28,7 +28,7 @@ poetry add agentops mem0ai python-dotenv
```
```bash uv
-uv add agentops mem0ai python-dotenv
+uv pip install agentops mem0ai python-dotenv
```
</CodeGroup>
diff --git a/docs/v2/integrations/openai.mdx b/docs/v2/integrations/openai.mdx
index acd4c11f..3fa0f893 100644
--- a/docs/v2/integrations/openai.mdx
+++ b/docs/v2/integrations/openai.mdx
@@ -15,7 +15,7 @@ pip install agentops openai
poetry add agentops openai
```
```bash uv
-uv add agentops openai
+uv pip install agentops openai
```
</CodeGroup>
diff --git a/docs/v2/integrations/openai_agents_python.mdx b/docs/v2/integrations/openai_agents_python.mdx
index ce0db8eb..7a8ec681 100644
--- a/docs/v2/integrations/openai_agents_python.mdx
+++ b/docs/v2/integrations/openai_agents_python.mdx
@@ -3,6 +3,18 @@ title: OpenAI Agents SDK
description: 'AgentOps and OpenAI Agents SDK integration for powerful multi-agent workflow monitoring.'
---
+## Video Tutorial
+
+<iframe
+ width="560"
+ height="315"
+ src="https://www.youtube.com/embed/9FH-BYqYYrQ"
+ title="AgentOps + OpenAI Agents SDK Integration Tutorial"
+ frameborder="0"
+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
+ allowfullscreen
+></iframe>
+
[OpenAI Agents Python](https://github.com/openai/openai-agents-python) is a lightweight yet powerful SDK for building multi-agent workflows in Python. AgentOps seamlessly integrates to provide observability into these workflows.
- [OpenAI Agents Python documentation](https://openai.github.io/openai-agents-python/)
@@ -28,7 +40,7 @@ Install AgentOps, the OpenAI Agents SDK, and `python-dotenv` for managing API ke
poetry add agentops openai-agents python-dotenv
```
```bash uv
- uv add agentops openai-agents python-dotenv
+ uv pip install agentops openai-agents python-dotenv
```
</CodeGroup>
diff --git a/docs/v2/integrations/smolagents.mdx b/docs/v2/integrations/smolagents.mdx
index 639b36ed..d5f94b27 100644
--- a/docs/v2/integrations/smolagents.mdx
+++ b/docs/v2/integrations/smolagents.mdx
@@ -27,7 +27,7 @@ Install AgentOps and Smolagents, along with any additional dependencies:
poetry add agentops smolagents python-dotenv
```
```bash uv
- uv add agentops smolagents python-dotenv
+ uv pip install agentops smolagents python-dotenv
```
</CodeGroup>
diff --git a/docs/v2/integrations/xai.mdx b/docs/v2/integrations/xai.mdx
index 4711b4a3..449b546b 100644
--- a/docs/v2/integrations/xai.mdx
+++ b/docs/v2/integrations/xai.mdx
@@ -15,7 +15,7 @@ AgentOps can track Grok. Grok is this true?
poetry add agentops openai
``
```bash uv
- uv add agentops openai
+ uv pip install agentops openai
```
</CodeGroup>
diff --git a/docs/v2/quickstart.mdx b/docs/v2/quickstart.mdx
index f23b8cc5..73284fb0 100644
--- a/docs/v2/quickstart.mdx
+++ b/docs/v2/quickstart.mdx
@@ -22,7 +22,7 @@ First, install the AgentOps SDK. We recommend including `python-dotenv` for easy
poetry add agentops python-dotenv
```
```bash uv
- uv add agentops python-dotenv
+ uv pip install agentops python-dotenv
```
</CodeGroup>