同步完整源码 - 2026-05-25

This commit is contained in:
xiaoxue
2026-05-25 01:45:55 +08:00
commit af7cdc0ffd
1581 changed files with 225877 additions and 0 deletions
+185
View File
@@ -0,0 +1,185 @@
---
title: 'AG2'
description: 'AG2 Async Agent Chat'
---
{/* SOURCE_FILE: examples/ag2/async_human_input.ipynb */}
_View Notebook on <a href={'https://github.com/AgentOps-AI/agentops/blob/main/examples/ag2/ag2_async_agent.ipynb'} target={'_blank'}>Github</a>_
# AG2 Async Agent Chat with Automated Responses
This notebook demonstrates how to leverage asynchronous programming with AG2 agents
to create automated conversations between AI agents, eliminating the need for human
input while maintaining full traceability.
# Overview
This notebook demonstrates a practical example of automated AI-to-AI communication where we:
1. Initialize AG2 agents with OpenAI's GPT-4o-mini model
2. Create custom async agents that simulate human-like responses and processing delays
3. Automate the entire conversation flow without requiring manual intervention
4. Track all interactions using AgentOps for monitoring and analysis
By using async operations and automated responses, you can create fully autonomous
agent conversations that simulate real-world scenarios. This is particularly useful
for testing, prototyping, and creating demos where you want to showcase agent
capabilities without manual input.
## Installation
<CodeGroup>
```bash pip
pip install ag2 agentops nest-asyncio
```
```bash poetry
poetry add ag2 agentops nest-asyncio
```
```bash uv
uv add ag2 agentops nest-asyncio
```
</CodeGroup>
```
import asyncio
from typing import Dict, Optional, Union
import os
from dotenv import load_dotenv
import nest_asyncio
import agentops
from autogen import AssistantAgent
from autogen.agentchat.user_proxy_agent import UserProxyAgent
```
```
# Load environment variables for API keys
load_dotenv()
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY", "your_api_key_here")
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY", "your_openai_api_key_here")
# Initialize AgentOps for tracking and monitoring
agentops.init(auto_start_session=False, trace_name="AG2 Async Demo")
tracer = agentops.start_trace(trace_name="AG2 Async Agent Demo", tags=["ag2-async-demo", "agentops-example"])
```
```
# Define an asynchronous function that simulates async processing
async def simulate_async_processing(task_name: str, delay: float = 1.0) -> str:
"""
Simulate some asynchronous processing (e.g., API calls, file operations, etc.)
"""
print(f"🔄 Starting async task: {task_name}")
await asyncio.sleep(delay) # Simulate async work
print(f"✅ Completed async task: {task_name}")
return f"Processed: {task_name}"
```
```
# Define a custom UserProxyAgent that simulates automated user responses
class AutomatedUserProxyAgent(UserProxyAgent):
def __init__(self, name: str, **kwargs):
super().__init__(name, **kwargs)
self.response_count = 0
self.predefined_responses = [
"Yes, please generate interview questions for these topics.",
"The questions look good. Can you make them more specific to senior-level positions?",
"Perfect! These questions are exactly what we need. Thank you!",
]
async def a_get_human_input(self, prompt: str) -> str:
# Simulate async processing before responding
await simulate_async_processing(f"Processing user input #{self.response_count + 1}")
if self.response_count < len(self.predefined_responses):
response = self.predefined_responses[self.response_count]
self.response_count += 1
print(f"👤 User: {response}")
return response
else:
print("👤 User: TERMINATE")
return "TERMINATE"
async def a_receive(
self,
message: Union[Dict, str],
sender,
request_reply: Optional[bool] = None,
silent: Optional[bool] = False,
):
await super().a_receive(message, sender, request_reply, silent)
```
```
# Define an AssistantAgent that simulates async processing before responding
class AsyncAssistantAgent(AssistantAgent):
async def a_receive(
self,
message: Union[Dict, str],
sender,
request_reply: Optional[bool] = None,
silent: Optional[bool] = False,
):
# Simulate async processing before responding
await simulate_async_processing("Analyzing request and preparing response", 0.5)
await super().a_receive(message, sender, request_reply, silent)
```
```
async def main():
print("🚀 Starting AG2 Async Demo")
# Create agents with automated behavior
user_proxy = AutomatedUserProxyAgent(
name="hiring_manager",
human_input_mode="NEVER", # No human input required
max_consecutive_auto_reply=3,
code_execution_config=False,
is_termination_msg=lambda msg: "TERMINATE" in str(msg.get("content", "")),
)
assistant = AsyncAssistantAgent(
name="interview_consultant",
system_message="""You are an expert interview consultant. When given interview topics,
you create thoughtful, relevant questions. You ask for feedback and incorporate it.
When the user is satisfied with the questions, end with 'TERMINATE'.""",
llm_config={"config_list": [{"model": "gpt-4o-mini", "api_key": os.environ.get("OPENAI_API_KEY")}]},
is_termination_msg=lambda msg: "TERMINATE" in str(msg.get("content", "")),
)
try:
print("🤖 Initiating automated conversation...")
# Start the automated chat between the user and assistant
await user_proxy.a_initiate_chat(
assistant,
message="""I need help creating interview questions for these topics:
- Resume Review
- Technical Skills Assessment
- Project Discussion
- Job Role Expectations
- Closing Remarks
Please create 2-3 questions for each topic.""",
max_turns=6,
)
except Exception as e:
print(f"\n❌ Error occurred: {e}")
finally:
agentops.end_trace(tracer, end_state="Success")
print("\n🎉 Demo completed successfully!")
```
```
# Run the main async demo
nest_asyncio.apply()
asyncio.run(main())
```
<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>
+120
View File
@@ -0,0 +1,120 @@
---
title: 'Agno'
description: 'Async Operations with Agno'
---
{/* SOURCE_FILE: examples/agno/agno_async_operations.ipynb */}
_View Notebook on <a href={'https://github.com/AgentOps-AI/agentops/blob/main/examples/agno/agno_async_operations.ipynb'} target={'_blank'}>Github</a>_
# Async Operations with Agno
This notebook demonstrates how to leverage asynchronous programming with Agno agents to execute multiple AI tasks concurrently, significantly improving performance and efficiency.
## Overview
This notebook demonstrates a practical example of concurrent AI operations where we:
1. **Initialize an Agno agent** with OpenAI's GPT-4o-mini model
2. **Create multiple async tasks** that query the AI about different programming languages
3. **Compare performance** between concurrent and sequential execution
By using async operations, you can run multiple AI queries simultaneously instead of waiting for each one to complete sequentially. This is particularly beneficial when dealing with I/O-bound operations like API calls to AI models.
## Installation
<CodeGroup>
```bash pip
pip install agentops agno python-dotenv
```
```bash poetry
poetry add agentops agno python-dotenv
```
```bash uv
uv pip install agentops agno python-dotenv
```
</CodeGroup>
```python
import os
import asyncio
from dotenv import load_dotenv
import agentops
from agno.agent import Agent
from agno.team import Team
from agno.models.openai import OpenAIChat
```
```python
load_dotenv()
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY", "your_openai_api_key_here")
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY", "your_agentops_api_key_here")
```
```python
agentops.init(auto_start_session=False, tags=["agno-example", "async-operation"])
```
```python
async def demonstrate_async_operations():
"""
Demonstrate concurrent execution of multiple AI agent tasks.
This function creates multiple async tasks that execute concurrently rather than sequentially.
Each task makes an independent API call to the AI model, and asyncio.gather()
waits for all tasks to complete before returning results.
Performance benefit: Instead of 3 sequential calls taking ~90 seconds total,
concurrent execution typically completes in ~30 seconds.
"""
tracer = agentops.start_trace(trace_name="Agno Async Operations Example",)
try:
# Initialize AI agent with specified model
agent = Agent(model=OpenAIChat(id="gpt-4o-mini"))
async def task1():
"""Query AI about Python programming language."""
response = await agent.arun("Explain Python programming language in one paragraph")
return f"Python: {response.content}"
async def task2():
"""Query AI about JavaScript programming language."""
response = await agent.arun("Explain JavaScript programming language in one paragraph")
return f"JavaScript: {response.content}"
async def task3():
"""Query AI for comparison between programming languages."""
response = await agent.arun("Compare Python and JavaScript briefly")
return f"Comparison: {response.content}"
# Execute all tasks concurrently using asyncio.gather()
results = await asyncio.gather(task1(), task2(), task3())
for i, result in enumerate(results, 1):
print(f"\nTask {i} Result:")
print(result)
print("-" * 50)
agentops.end_trace(tracer, end_state="Success")
except Exception as e:
print(f"An error occurred: {e}")
agentops.end_trace(tracer, end_state="Error")
```
```python
await demonstrate_async_operations()
```
<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>
+455
View File
@@ -0,0 +1,455 @@
---
title: 'Anthropic Tools Example'
description: 'Understanding and using tools with the Anthropic SDK and AgentOps'
---
{/* SOURCE_FILE: examples/anthropic/agentops-anthropic-understanding-tools.ipynb */}
_View Notebook on <a href={'https://github.com/AgentOps-AI/agentops/blob/main/examples/anthropic/agentops-anthropic-understanding-tools.ipynb'} target={'_blank'}>Github</a>_
# Anthropic Example for understanding Tools
Anthropic's tool returns are not as simple as getting a few strings! While this system is more complex than those before it, it's also simple enough to be used without problem once you understand how it works!
To get started, we will import Agentops and Anthropic.
## Installation
<CodeGroup>
```bash pip
pip install agentops anthropic python-dotenv
```
```bash poetry
poetry add agentops anthropic python-dotenv
```
```bash uv
uv pip install agentops anthropic python-dotenv
```
</CodeGroup>
## Setup
Setup our generic default statements:
```python
import agentops
from anthropic import Anthropic
from dotenv import load_dotenv
import os
import random
```
And set our API keys.
```python
load_dotenv()
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY", "your_agentops_api_key_here")
os.environ["ANTHROPIC_API_KEY"] = os.getenv("ANTHROPIC_API_KEY", "your_anthropic_api_key_here")
```
Now let's set the client as Anthropic and make an AgentOps trace.
```python
agentops.init(tags=["anthropic-example-tool-tutorials", "agentops-example"])
client = Anthropic()
```
## Creating a Dummy Tool
Now to create a simple dummy tool! We are going to make a tool that will tell us about the demon infestation levels for 3 areas. From there, we will have VEGA, our AI determine the best place for the Doom Slayer to attack.
```python
locations = [
{
"Name": "Super Gore Nest",
"Description": "A grotesque mass of demonic growth and organic structures infesting the ruins of an urban area on Earth. The Super Gore Nest serves as a massive, pulsating hive for Hell’s forces, complete with rivers of blood, twisted tendrils, and a dark, organic design that shows how deeply Hell has taken root in the city.",
},
{
"Name": "Exultia",
"Description": "An ancient, mystical world that holds the ruins of the Night Sentinels' kingdom, with gothic structures and arcane symbols throughout. This realm is filled with epic landscapes, medieval architecture, and hints of the powerful civilization that once defended against Hell’s forces.",
},
{
"Name": "Cultist Base",
"Description": "A grim fortress hidden within the icy mountains, where a fanatical cult worships demons. Filled with chilling sacrificial chambers, traps, and rituals, the Cultist Base is a hostile stronghold where Doom Slayer must confront the cult leaders aiding Hell's invasion of Earth.",
},
{
"Name": "Taras Nabad",
"Description": "A war-ravaged city on the homeworld of the Night Sentinels, showcasing grandiose, ancient architecture in the midst of destruction. Taras Nabad's sprawling structures and historical significance reveal glimpses into the Doom Slayer’s past and the once-thriving Sentinel civilization.",
},
{
"Name": "Nekravol",
"Description": "A hellish, industrial fortress where souls are processed into Argent energy. With conveyor belts moving the damned and a skyline dominated by fire and darkness, Nekravol is a nightmarish facility that powers Hell's armies and embodies the horrific machinery of Hell's cruelty.",
},
{
"Name": "Urdak",
"Description": "A surreal, high-tech realm that serves as the home of the angelic Maykrs. Urdak’s sleek, pristine architecture and ethereal ambiance sharply contrast with Hell’s brutal landscapes, yet this realm holds its own dark secrets and a critical role in Hell's invasion of Earth.",
},
{
"Name": "UAC Base",
"Description": "A futuristic military base on Earth controlled by the Union Aerospace Corporation (UAC), filled with high-tech weaponry and security systems. The UAC Base serves as a human foothold in the fight against Hell, though some within its ranks may have darker intentions.",
},
]
combat_casualties = ["Nonexistent", "Low", "Medium", "High", "Extinction"]
missions = [
"Locate and confront a key leader of Hell’s invasion forces.",
"Clear out demonic infestations to secure a strategic foothold.",
"Disrupt Hell's control over the area by eliminating critical targets.",
"Enter a critical demonic stronghold to disrupt enemy operations.",
"Locate and destroy the central power source to weaken enemy forces.",
"Collect essential resources before the area becomes unstable.",
]
```
Now that that's done, we can make a function! We will generate three random missions and pass it off to the AI.
```python
def generate_missions():
selectedmissions = []
loop = 0
while loop < 3:
location = random.choice(locations)
casualties = random.choice(combat_casualties)
mission = random.choice(missions)
final = (
f"LocationName: {location['Name']}, "
f"LocationInfo: {location['Description']}, "
f"HumanCombatCasualties: {casualties}, "
f"Mission: {mission}"
)
selectedmissions.append(final)
loop += 1
# Combine all mission strings into a single string with a separator (e.g., newline or comma)
# Notebook had 'missions_string = "\n".join(missions)', which is a bug.
# Using 'selectedmissions' as it's the correct variable.
missions_string = "\n".join(selectedmissions)
print(missions_string)
return missions_string
```
```python
generate_missions()
```
## Constructing the Message Stream
Now to the real core of this; making our message stream! We create this as a function we can call later! I create examples since the LLM's context size can handle it (and it's generally good practice)!
We are also going to take several steps here; we must create an example of the tool being used as context. Next, we must add the generated lines to the messages list once done being generated. Finally, we will parse the text for the format we want and request another line.
Now we make a message! This time around we will skip making an initial message that has too much context, unlike in the past!
```python
# We make our history a separate block to be easier to add to later on! This is essentially our history
initial_messages = [
{
"role": "user",
"content": "You are VEGA, the assistant to the DOOMGUY. Get three missions from the ship's API and tell me which mission is most to least important for quellng the forces of hell. ",
}
]
```
Now to construct a request!
```python
response = client.messages.create(
max_tokens=5000,
model="claude-3-7-sonnet-20250219", # Matched notebook
tools=[
{
"name": "generate_missions",
"description": "Retrieve three missions for the DoomSlayer",
"input_schema": {"type": "object", "properties": {}, "required": []},
}
],
messages=initial_messages,
)
print(response.content)
```
Having trouble understanding this? The first block given is always AI dialogue! You can use `response.content[0].text` to get the AI's text! Let's try it below.
```python
message = response.content[0].text
print(message)
```
The code below finds the tool used!
```python
gen_mission_result = ""
# Print response content to see the data
# print(response.content) # Already printed in the cell above in notebook
# Assuming ToolUseBlock is at index 1 (matches notebook's direct access)
tool_use_block = response.content[1]
# Get the tool name and input
tool_name = tool_use_block.name
tool_input = tool_use_block.input
# We don't need to look to extract any inputs since we don't use any
# Check if the tool name is "generate_missions"
if tool_name == "generate_missions":
# Call the function with the tool creator as an argument
gen_mission_result = generate_missions()
```
Now we add these as context to the LLM through `initial_messages`!
```python
# Matches notebook cell 25 logic
initial_messages.append({"role": "assistant", "content": gen_mission_result})
initial_messages.append(
{
"role": "user",
"content": "Based on these, which location should take priority and why?",
}
)
```
And now to get a response!
```python
response = client.messages.create(
max_tokens=5000,
model="claude-3-7-sonnet-20250219", # Matched notebook
tools=[
{
"name": "generate_missions",
"description": "Retrieve three missions for the DoomSlayer",
"input_schema": {"type": "object", "properties": {}, "required": []},
}
],
messages=initial_messages,
)
print(response)
```
Isolate again!
```python
message = response.content[0].text
print(message)
```
Hmmm, what if we wanted to include more tools and add inputs? Let's create two new functions to display this!
One will show the kind of demon we are facing, whereas another one will take our weapon input to determine what the best weapon chain to use is (You heard that right, we believe in quick weapon switches around these parts)
```python
demons = [
{
"Name": "Imp",
"Description": "A fast, agile demon that hurls fireballs and uses its claws to tear apart its prey. Imps are commonly found in Hell’s army, notorious for their quickness and ability to climb walls, making them dangerous adversaries in any environment.",
},
{
"Name": "Cacodemon",
"Description": "A floating, spherical demon with a large mouth full of teeth and an ability to launch explosive projectiles. Cacodemons are often encountered in open areas, where their aerial agility and relentless attacks pose a constant threat.",
},
{
"Name": "Hell Knight",
"Description": "A towering, brutish demon with immense strength and durability. The Hell Knight is capable of charging at the Doom Slayer and delivering devastating melee attacks. Its tough hide makes it resistant to most forms of damage.",
},
{
"Name": "Mancubus",
"Description": "A grotesque, overweight demon that releases powerful fireballs from its massive arm cannons. Mancubus demons are slow-moving but dangerous due to their firepower and the ability to overwhelm enemies with their fiery onslaughts.",
},
]
weapons = [
{
"Name": "Super Shotgun",
"Description": "A powerful, double-barreled shotgun that delivers devastating close-range damage. Known for its sheer stopping power, the Super Shotgun can tear through enemies with ease, especially when equipped with the Meat Hook attachment, allowing for rapid mobility and devastating hits.",
},
{
"Name": "Rocket Launcher",
"Description": "A high-powered weapon that fires explosive rockets capable of dealing massive area damage. The Rocket Launcher is invaluable for taking down groups of enemies or dealing significant damage to larger demons, especially when upgraded with the Lock-On Burst mod.",
},
{
"Name": "Chaingun",
"Description": "A rapid-fire weapon that can unleash a torrent of bullets at a high rate of speed. The Chaingun is perfect for mowing down enemies and can be equipped with the Heat Blast mod, allowing for explosive energy rounds that can clear multiple enemies at once.",
},
{
"Name": "BFG 9000",
"Description": "One of the most iconic weapons in the *Doom* franchise, the BFG 9000 fires a massive energy beam that obliterates anything in its path. With its massive damage potential, the BFG 9000 is a game-changer, especially in dealing with large groups of enemies or the toughest foes.",
},
{
"Name": "Ice Bomb",
"Description": "A special grenade that freezes enemies in a wide area, giving the Doom Slayer a chance to deal with multiple foes at once. The Ice Bomb is effective for crowd control, allowing for easy Glory Kills or creating distance from overwhelming enemies.",
},
]
```
Now we can keep the `initial_messages` from before actually! However let's change the context.
```python
# Matches notebook cell 33 (no conditional append of previous AI message)
initial_messages.append(
{
"role": "user",
"content": "The first priority mission was selected. At the same time, scan for enemies and check inventory to determine the best combat strategy. You should use both tools at once.",
}
)
```
And we of course make functions.
```python
def enemyscan(amount): # Matched notebook (no type hint)
enemiesonscene = []
loop = 0
while loop < amount + 1: # Matched notebook
scannedenemy = random.choice(demons)
# Append name and description separately (Matches notebook)
enemiesonscene.append(scannedenemy["Name"])
enemiesonscene.append(scannedenemy["Description"])
loop += 1
# Combine all mission strings into a single string with a separator (e.g., newline or comma)
enemies_string = "\n".join(enemiesonscene)
print(enemies_string)
return enemies_string
```
```python
enemyscan(5)
```
And now inventory.
```python
def inventoryscan():
weapons_at_hand = []
loop = 0
while loop < 5: # Matched notebook (loop < 5)
weapon = random.choice(weapons)
# Append name and description separately (Matches notebook)
weapons_at_hand.append(weapon["Name"])
weapons_at_hand.append(weapon["Description"])
loop += 1
# Combine all mission strings into a single string with a separator (e.g., newline or comma)
weapons_string = "\n".join(weapons_at_hand)
print(weapons_string)
return weapons_string
```
```python
inventoryscan()
```
With that, let's construct our new tools and run this!!
```python
response = client.messages.create(
max_tokens=5000,
model="claude-3-7-sonnet-20250219", # Matched notebook
tools=[
{
"name": "enemyscan_tool",
"description": "Retrieve a list of demons currently present in the area.",
"input_schema": {
"type": "object",
"properties": {
"amount": {
"type": "integer",
"description": "Number of enemies to scan.",
}
},
"required": ["amount"],
},
},
{
"name": "inventoryscan_tool",
"description": "Retrieve a list of weapons the Doom Slayer has at hand.",
"input_schema": {"type": "object", "properties": {}, "required": []},
},
],
messages=initial_messages,
)
print(response)
```
Display just the text.
```python
# Matches notebook cell 43
message = response.content[0].text
print(message)
```
```python
# Matches notebook cell 44
initial_messages.append({"role": "assistant", "content": f"{str(response.content[0].text)}"})
```
And now to get the information and put it all together! PLEASE read the comments!
```python
# Matches notebook cell 46 logic
inv_scan_res = ""
enemy_scan_res = ""
response_str = str(response) # As in notebook
tool_use_count = response_str.count(
"ToolUseBlock"
) # We know the ToolUseBlock will appear once for each tool request so we check how many time it appears
# You can use print(tool_use_count)to validate the ToolBlocks here if you wish
loop = 0
# We do this instead of a (foreach) because we need to skip the first block! This contains the message from the AI, not the tool! This way allows us to reference the item we want as easily as possible without complex logic needed!
while loop < tool_use_count: # We will get the tools now
tool_use_block = response.content[loop + 1] # We start at 1 since 0 holds the AI mesage
tool_name = tool_use_block.name
tool_input = tool_use_block.input
if tool_name == "inventoryscan_tool":
# Call the inventoryscan function for inventoryscan_tool
inv_scan_res = inventoryscan()
elif tool_name == "enemyscan_tool":
# Get the amount for enemyscan_tool
amount = tool_input["amount"] # Direct access as in notebook
# Call the enemyscan function with the amount
enemy_scan_res = enemyscan(amount)
loop = loop + 1 # Matches notebook
print(inv_scan_res)
print(enemy_scan_res)
```
And now we are basically done! We can give this to the AI and see what we get.
```python
# Matches notebook cell 48
initial_messages.append(
{
"role": "assistant", # Notebook uses assistant role here for tool results
"content": f"Weapons Inventory Scan Result: {inv_scan_res}\nEnemy Scans Result: {enemy_scan_res}",
}
)
initial_messages.append(
{
"role": "user",
"content": "What is the combat plan for killing these demons? Based on the last message, tell me which demons to kill first, in which order and using which weapons as well as any sweakpoints.", # Typo 'sweakpoints' from notebook
}
)
```
```python
# Matches notebook cell 49
response = client.messages.create(
max_tokens=5000,
model="claude-3-7-sonnet-20250219", # Matched notebook
tools=[
{
"name": "enemyscan_tool",
"description": "Retrieve a list of demons currently present in the area.",
"input_schema": {
"type": "object",
"properties": {
"amount": {
"type": "integer",
"description": "Number of enemies to scan.",
}
},
"required": ["amount"],
},
},
{
"name": "inventoryscan_tool",
"description": "Retrieve a list of weapons the Doom Slayer has at hand.",
"input_schema": {"type": "object", "properties": {}, "required": []},
},
],
messages=initial_messages,
)
message = response.content[0].text # Matches notebook
print(message)
```
<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>
+155
View File
@@ -0,0 +1,155 @@
---
title: 'AutoGen'
description: 'Microsoft Autogen Chat Example'
---
{/* SOURCE_FILE: examples/autogen/AgentChat.ipynb */}
_View Notebook on <a href={'https://github.com/AgentOps-AI/agentops/blob/main/examples/autogen/AgentChat.ipynb'} target={'_blank'}>Github</a>_
# Microsoft Autogen Chat Example
AgentOps automatically configures itself when it's initialized meaning your agent run data will be tracked and logged to your AgentOps dashboard right away.
First let's install the required packages
## Installation
<CodeGroup>
```bash pip
pip install "autogen-ext[openai]" -U agentops autogen-agentchat python-dotenv
```
```bash poetry
poetry add "autogen-ext[openai]" -U agentops autogen-agentchat python-dotenv
```
```bash uv
uv pip install "autogen-ext[openai]" -U agentops autogen-agentchat python-dotenv
```
</CodeGroup>
Then import them
```python
import os
from dotenv import load_dotenv
from IPython.core.error import (
StdinNotImplementedError,
)
import asyncio
import agentops
from autogen_agentchat.agents import AssistantAgent, UserProxyAgent
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_agentchat.conditions import MaxMessageTermination
from autogen_agentchat.ui import Console
```
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.
[Get an AgentOps API key](https://agentops.ai/settings/projects)
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...
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!
```python
load_dotenv()
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY", "your_api_key_here")
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY", "your_openai_api_key_here")
```
```python
# When initializing AgentOps, you can pass in optional tags to help filter sessions
agentops.init(auto_start_session=False)
tracer = agentops.start_trace(
trace_name="Microsoft Agent Chat Example", tags=["autogen-chat", "microsoft-autogen", "agentops-example"]
)
```
AutoGen will now start automatically tracking
* LLM prompts and completions
* Token usage and costs
* Agent names and actions
* Correspondence between agents
* Tool usage
* Errors
# Simple Chat Example
```python
# Define model and API key
model_name = "gpt-4-turbo" # Or "gpt-4o" / "gpt-4o-mini" as per migration guide examples
api_key = os.getenv("OPENAI_API_KEY")
# Create the model client
model_client = OpenAIChatCompletionClient(model=model_name, api_key=api_key)
# Create the agent that uses the LLM.
assistant = AssistantAgent(
name="assistant",
system_message="You are a helpful assistant.", # Added system message for clarity
model_client=model_client,
)
user_proxy_initiator = UserProxyAgent("user_initiator")
async def main():
termination = MaxMessageTermination(max_messages=2)
group_chat = RoundRobinGroupChat(
[user_proxy_initiator, assistant], # Corrected: agents as positional argument
termination_condition=termination,
)
chat_task = "How can I help you today?"
print(f"User Initiator: {chat_task}")
try:
stream = group_chat.run_stream(task=chat_task)
await Console().run(stream)
agentops.end_trace(tracer, end_state="Success")
except StdinNotImplementedError:
print("StdinNotImplementedError: This typically happens in non-interactive environments.")
print("Skipping interactive part of chat for automation.")
agentops.end_trace(tracer, end_state="Indeterminate")
except Exception as e:
print(f"An error occurred: {e}")
agentops.end_trace(tracer, end_state="Error")
finally:
await model_client.close()
if __name__ == "__main__":
try:
loop = asyncio.get_running_loop()
except RuntimeError:
loop = None
if loop and loop.is_running():
import nest_asyncio
nest_asyncio.apply()
asyncio.run(main())
else:
asyncio.run(main())
```
You can view data on this run at [app.agentops.ai](https://app.agentops.ai).
The dashboard will display LLM events for each message sent by each agent, including those made by the human user.
<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>
+402
View File
@@ -0,0 +1,402 @@
---
title: 'CrewAI Example'
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 Generator with AgentOps
This example shows you how to build a complete job posting generator using CrewAI's official project structure with comprehensive tracking via AgentOps.
## 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:
<CodeGroup>
```bash pip
pip install -U 'crewai[tools]' agentops
```
```bash poetry
poetry add 'crewai[tools]' agentops
```
```bash uv
uv pip install 'crewai[tools]' agentops
```
</CodeGroup>
**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
```
**Select your provider and model:**
- Choose **1. openai**
- Choose **1. gpt-4** (or your preferred model)
- Enter your OpenAI API key when prompted
**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
```
### Step 3: Add Additional API Keys
Edit the generated `.env` file to add AgentOps and Serper keys:
```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
```
**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
```
### 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
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()
@agent
def researcher(self) -> Agent:
return Agent(
config=self.agents_config['researcher'],
tools=[self.serper_tool, self.website_tool]
)
@agent
def writer(self) -> Agent:
return Agent(
config=self.agents_config['writer'],
tools=[self.serper_tool, self.website_tool]
)
@agent
def editor(self) -> Agent:
return Agent(
config=self.agents_config['editor']
)
@task
def research_company_culture(self) -> Task:
return Task(
config=self.tasks_config['research_company_culture']
)
@task
def research_role_requirements(self) -> Task:
return Task(
config=self.tasks_config['research_role_requirements']
)
@task
def draft_job_posting(self) -> Task:
return Task(
config=self.tasks_config['draft_job_posting']
)
@task
def review_and_edit_job_posting(self) -> Task:
return Task(
config=self.tasks_config['review_and_edit_job_posting']
)
@crew
def crew(self) -> Crew:
"""Creates the JobPostingAgent crew"""
return Crew(
agents=self.agents,
tasks=self.tasks,
process=Process.sequential,
verbose=True
)
```
### Step 7: Update the Main Execution File
Edit `src/job_posting_agent/main.py` to add AgentOps session management:
```python
#!/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
```
**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
+88
View File
@@ -0,0 +1,88 @@
---
title: 'Examples'
description: 'Examples of AgentOps with various integrations'
---
## Explore our examples to see AgentOps in action!
### LLM Integrations
<CardGroup cols={3}>
<Card title="Anthropic" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/anthropic/anthropic_icon_slate.png?raw=true" alt="Anthropic" />} iconType="image" href="/v2/examples/anthropic">
Claude integration with tool usage and advanced features
</Card>
<Card title="Google Generative AI" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/deepmind/gemini-logo.png?raw=true" alt="Gemini" />} iconType="image" href="/v2/examples/google_genai">
Google Gemini models and their examples
</Card>
<Card title="LiteLLM" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/litellm/litellm.png?raw=true" alt="LiteLLM" />} iconType="image" href="/v2/examples/litellm">
Unified LLM interface monitoring example
</Card>
<Card title="OpenAI" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/openai/openai-logomark.png?raw=true" alt="OpenAI" />} iconType="image" href="/v2/examples/openai">
Advanced multi-tool orchestration with GPT models
</Card>
<Card title="Watsonx" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/ibm/ibm-logo.svg?raw=true" alt="IBM" />} iconType="image" href="/v2/examples/watsonx">
Watsonx text chat integration example
</Card>
<Card title="x.AI" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/xai/xai-logo.png?raw=true" alt="x.AI" />} iconType="image" href="/v2/examples/xai">
Grok LLM basic usage patterns
</Card>
</CardGroup>
### Agent Integrations
<CardGroup>
<Card title="AG2" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/ag2/ag2-logo.svg?raw=true" alt="AG2" />} iconType="image" href="/v2/examples/ag2">
Multi-agent conversations with memory capabilities
</Card>
<Card title="Agno" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/agno/agno.png?raw=true" alt="Agno" />} iconType="image" href="/v2/examples/agno">
Modern AI agent framework with teams, workflows, and tool integration
</Card>
<Card title="Autogen" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/autogen/autogen-logo.svg?raw=true" alt="Autogen" />} iconType="image" href="/v2/examples/autogen">
AG2 multi-agent workflow demonstration
</Card>
<Card title="CrewAI" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/crewai/crewai-logo.png?raw=true" alt="CrewAI" />} iconType="image" href="/v2/examples/crewai">
CrewAI multi-agent framework example
</Card>
<Card title="Google ADK" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/google-adk/google-adk-logo.png?raw=true" alt="Google ADK" />} iconType="image" href="/v2/examples/google_adk">
Google Agent Development Kit integration
</Card>
<Card title="Haystack" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/haystack/haystack-logo.png?raw=true" alt="Haystack" />} iconType="image" href="/v2/integrations/haystack">
Monitor your Haystack agents with AgentOps
</Card>
<Card title="OpenAI Agents SDK" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/openai/openai-logomark.png?raw=true" alt="OpenAI Agents SDK" />} iconType="image" href="/v2/examples/openai_agents">
OpenAI Agents SDK workflow walkthrough
</Card>
<Card title="LangChain" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/langchain/langchain-logo.svg?raw=true" alt="LangChain" />} iconType="image" href="/v2/examples/langchain">
LangChain callback handler integration
</Card>
<Card title="Mem0" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/mem0/mem0.png?raw=true" alt="Mem0" />} iconType="image" href="/v2/examples/mem0">
Comprehensive memory operations with Mem0ai
</Card>
<Card title="smolagents" icon={<img src="https://github.com/AgentOps-AI/agentops/blob/main/docs/images/external/huggingface/hf-logo.png?raw=true" alt="smolagents" />} iconType="image" href="/v2/integrations/smolagents">
Track HuggingFace's smolagents with AgentOps seamlessly
</Card>
</CardGroup>
<script type="module" src="/scripts/github_stars.js" />
<script type="module" src="/scripts/scroll-img-fadein-animation.js" />
<script type="module" src="/scripts/button_heartbeat_animation.js" />
<script type="module" src="/scripts/adjust_api_dynamically.js" />
+386
View File
@@ -0,0 +1,386 @@
---
title: 'Google ADK'
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 Human Approval Workflow with AgentOps
This example shows you how to build a complete human approval workflow using Google's Agent Development Kit (ADK) with comprehensive tracking via AgentOps.
## What We're Building
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
**With AgentOps**, you'll get complete visibility into agent conversations, tool usage, costs, and performance.
## Step-by-Step Implementation
### Step 1: Install Dependencies
Install Google ADK with required packages and AgentOps for tracking:
<CodeGroup>
```bash pip
pip install google-adk agentops nest_asyncio python-dotenv
```
```bash poetry
poetry add google-adk agentops nest_asyncio python-dotenv
```
```bash uv
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
from google.adk.agents import LlmAgent, SequentialAgent
from google.adk.tools import FunctionTool
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
from pydantic import BaseModel, Field
import nest_asyncio
import agentops
from dotenv import load_dotenv
# Load environment and initialize AgentOps
load_dotenv()
nest_asyncio.apply()
agentops.init(auto_start_session=False)
# Constants
APP_NAME = "human_approval_workflow"
USER_ID = "approval_user"
MODEL_NAME = "gemini-2.0-flash"
# 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")
```
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.
"""
print("🔔 HUMAN APPROVAL REQUIRED:")
print(f" Amount: ${amount:,.2f}")
print(f" Reason: {reason}")
decision = ""
while decision.lower() not in ["approved", "rejected"]:
decision = input(" Enter decision (approved/rejected): ").strip().lower()
if decision.lower() not in ["approved", "rejected"]:
print(" Invalid input. Please enter 'approved' or 'rejected'.")
comments = input(" Enter comments (optional): ").strip()
print(f" Decision: {decision.upper()}")
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)
```
### Step 6: Define the Three-Agent Workflow
Add the agent definitions to create your sequential workflow:
```python
# Agent 1: Prepare the approval request
prepare_request = LlmAgent(
model=MODEL_NAME,
name="PrepareApprovalAgent",
description="Extracts and prepares approval request details from user input",
instruction="""You are an approval request preparation agent.
Your task:
1. Extract the amount and reason from the user's request
2. Store these values in the session state with keys 'approval_amount' and 'approval_reason'
3. Validate that both amount and reason are provided
4. Respond with a summary of what will be submitted for approval
If the user input is missing amount or reason, ask for clarification.
""",
output_key="request_prepared",
)
# Agent 2: Request human approval using the tool
request_approval = LlmAgent(
model=MODEL_NAME,
name="RequestHumanApprovalAgent",
description="Calls the external approval system with prepared request details",
instruction="""You are a human approval request agent.
Your task:
1. Get the 'approval_amount' and 'approval_reason' from the session state
2. Use the external_approval_tool with these values
3. Store the approval decision in session state with key 'human_decision'
4. Respond with the approval status
Always use the exact values from the session state for the tool call.
""",
tools=[approval_tool],
output_key="approval_requested",
)
# Agent 3: Process the approval decision
process_decision = LlmAgent(
model=MODEL_NAME,
name="ProcessDecisionAgent",
description="Processes the human approval decision and provides final response",
instruction="""You are a decision processing agent.
Your task:
1. Check the 'human_decision' from session state
2. Parse the approval decision JSON
3. If approved: congratulate and provide next steps
4. If rejected: explain the rejection and suggest alternatives
5. Provide a clear, helpful final response to the user
Be professional and helpful in your response.
""",
output_key="final_decision",
)
```
### Step 7: Create the Sequential Workflow and Runner
Combine agents into a workflow with session management:
```python
# Create sequential workflow
approval_workflow = SequentialAgent(
name="HumanApprovalWorkflow",
description="Complete workflow for processing approval requests with human oversight",
sub_agents=[prepare_request, request_approval, process_decision],
)
# Set up session service and runner
session_service = InMemorySessionService()
workflow_runner = Runner(agent=approval_workflow, app_name=APP_NAME, session_service=session_service)
```
### Step 8: Add the Main Execution Function
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:
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
```
Finally, add the main execution logic:
```python
# 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_{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(request, current_session_id)
# Export the workflow for ADK
root_agent = approval_workflow
```
### Step 9: Run Your Approval Workflow
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}")
```
**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
+93
View File
@@ -0,0 +1,93 @@
---
title: 'Google GenAI'
description: 'Google Generative AI Example with AgentOps'
---
{/* SOURCE_FILE: examples/google_genai/gemini_example.ipynb */}
_View Notebook on <a href={'https://github.com/AgentOps-AI/agentops/blob/main/examples/google_genai/gemini_example.ipynb'} target={'_blank'}>Github</a>_
# Google Generative AI Example with AgentOps
This notebook demonstrates how to use AgentOps with Google's Generative AI package for observing both synchronous and streaming text generation.
## Installation
<CodeGroup>
```bash pip
pip install agentops google-genai
```
```bash poetry
poetry add agentops google-genai
```
```bash uv
uv pip install agentops google-genai
```
</CodeGroup>
```python
from google import genai
import agentops
from dotenv import load_dotenv
import os
```
```python
load_dotenv()
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY", "your_api_key_here")
os.environ["GEMINI_API_KEY"] = os.getenv("GEMINI_API_KEY", "your_gemini_api_key_here")
```
```python
# Initialize AgentOps and Gemini client
agentops.init(tags=["gemini-example", "agentops-example"])
client = genai.Client()
```
```python
# Test synchronous generation
print("Testing synchronous generation:")
response = client.models.generate_content(model="gemini-1.5-flash", contents="What are the three laws of robotics?")
print(response.text)
```
```python
# Test streaming generation
print("\nTesting streaming generation:")
response_stream = client.models.generate_content_stream(
model="gemini-1.5-flash", contents="Explain the concept of machine learning in simple terms."
)
for chunk in response_stream:
print(chunk.text, end="")
print() # Add newline after streaming output
# Test another synchronous generation
print("\nTesting another synchronous generation:")
response = client.models.generate_content(
model="gemini-1.5-flash", contents="What is the difference between supervised and unsupervised learning?"
)
print(response.text)
```
```python
# Example of token counting
print("\nTesting token counting:")
token_response = client.models.count_tokens(
model="gemini-1.5-flash", contents="This is a test sentence to count tokens."
)
print(f"Token count: {token_response.total_tokens}")
```
<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>
+141
View File
@@ -0,0 +1,141 @@
---
title: 'LangChain'
description: 'AgentOps Langchain Agent Implementation'
---
{/* SOURCE_FILE: examples/langchain/langchain_examples.ipynb */}
_View Notebook on <a href={'https://github.com/AgentOps-AI/agentops/blob/main/examples/langchain/langchain_examples.ipynb'} target={'_blank'}>Github</a>_
# AgentOps Langchain Agent Implementation
Using AgentOps monitoring with Langchain is simple. We've created a LangchainCallbackHandler that will do all of the heavy lifting!
First let's install the required packages
## Installation
<CodeGroup>
```bash pip
pip install agentops langchain langchain_openai python-dotenv
```
```bash poetry
poetry add agentops langchain langchain_openai python-dotenv
```
```bash uv
uv pip install agentops langchain langchain_openai python-dotenv
```
</CodeGroup>
Then import them
```python
import os
from langchain_openai import ChatOpenAI
from langchain.agents import tool, AgentExecutor, create_openai_tools_agent
from dotenv import load_dotenv
from langchain_core.prompts import ChatPromptTemplate
```
The only difference with using AgentOps is that we'll also import this special Callback Handler
```python
from agentops.integration.callbacks.langchain import (
LangchainCallbackHandler as AgentOpsLangchainCallbackHandler,
)
```
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.
[Get an AgentOps API key](https://agentops.ai/settings/projects)
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...
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!
```python
load_dotenv()
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY", "your_api_key_here")
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY", "your_openai_api_key_here")
```
This is where AgentOps comes into play. Before creating our LLM instance via Langchain, first we'll create an instance of the AO LangchainCallbackHandler. After the handler is initialized, a session will be recorded automatically.
Pass in your API key, and optionally any tags to describe this session for easier lookup in the AO dashboard.
```python
agentops_handler = AgentOpsLangchainCallbackHandler(tags=["Langchain Example", "agentops-example"])
llm = ChatOpenAI(callbacks=[agentops_handler], model="gpt-3.5-turbo")
# You must pass in a callback handler to record your agent
llm.callbacks = [agentops_handler]
prompt = ChatPromptTemplate.from_messages(
[
("system", "You are a helpful assistant. Respond only in Spanish."),
("human", "{input}"),
# Placeholders fill up a **list** of messages
("placeholder", "{agent_scratchpad}"),
# ("tool_names", "find_movie")
]
)
```
Agents generally use tools. Let's define a simple tool here. Tool usage is also recorded.
```python
@tool
def find_movie(genre: str) -> str:
"""Find available movies"""
if genre == "drama":
return "Dune 2"
else:
return "Pineapple Express"
tools = [find_movie]
```
For each tool, you need to also add the callback handler
```python
for t in tools:
t.callbacks = [agentops_handler]
```
Add the tools to our LLM
```python
llm_with_tools = llm.bind_tools([find_movie])
```
Finally, let's create our agent! Pass in the callback handler to the agent, and all the actions will be recorded in the AO Dashboard
```python
agent = create_openai_tools_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools)
```
```python
agent_executor.invoke({"input": "What comedies are playing?"}, config={"callback": [agentops_handler]})
```
## Check your session
Finally, check your run on [AgentOps](https://app.agentops.ai). You will see a session recorded with the LLM calls and tool usage.
<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>
+260
View File
@@ -0,0 +1,260 @@
---
title: 'Langgraph'
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 Basic Chatbot with AgentOps
This example shows you how to build a basic chatbot using LangGraph's StateGraph with comprehensive tracking via AgentOps.
## 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:
<CodeGroup>
```bash pip
pip install langgraph langchain agentops python-dotenv
```
```bash poetry
poetry add langgraph langchain agentops python-dotenv
```
```bash uv
uv pip install langgraph langchain agentops python-dotenv
```
</CodeGroup>
**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
### Step 2: Create Your Project Structure
Create a simple Python project for your chatbot:
```bash
# Create project directory
mkdir langgraph_chatbot
cd langgraph_chatbot
# Create main chatbot file
touch chatbot.py
touch .env
```
**This creates the basic structure:**
```
langgraph_chatbot/
├── chatbot.py # Main chatbot implementation
└── .env # API keys
```
### Step 3: Set Up Environment Variables
Create your `.env` file with the necessary API keys:
```bash
# .env
OPENAI_API_KEY=your_openai_api_key_here
AGENTOPS_API_KEY=your_agentops_api_key_here
```
**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.
### Step 4: Build Your Basic Chatbot
Edit `chatbot.py` to create your LangGraph chatbot:
```python
# 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]
```
### Step 5: Initialize the Chat Model and Create the Chatbot Node
Add the model and node function:
```python
# Initialize the chat model (you can change to any provider)
llm = init_chat_model("openai:gpt-4o-mini")
# Create the chatbot node function
def chatbot(state: State):
"""Main chatbot function that processes messages and returns responses."""
return {"messages": [llm.invoke(state["messages"])]}
```
### Step 6: Build and Compile the StateGraph
Construct your LangGraph workflow:
```python
# Create the StateGraph
graph_builder = StateGraph(State)
# 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 entry point (where to start)
graph_builder.add_edge(START, "chatbot")
# Add exit point (where to end)
graph_builder.add_edge("chatbot", END)
# Compile the graph
graph = graph_builder.compile()
```
### Step 7: Add the Streaming Chat Function
Create the interactive chat interface with AgentOps tracking:
```python
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
# Main execution
if __name__ == "__main__":
run_chatbot()
```
### Step 8: Run Your Chatbot
Execute your chatbot:
```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'
**Example conversation:**
```
🤖 LangGraph Chatbot Started!
Type 'quit', 'exit', or 'q' to stop.
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...
User: Tell me a joke
Assistant: Why don't scientists trust atoms? Because they make up everything!
User: quit
Goodbye!
```
## View Results in AgentOps Dashboard
After running your chatbot, visit your [AgentOps Dashboard](https://app.agentops.ai) to see:
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
## Key Files Created
**Project structure you built:**
- `chatbot.py` - Complete LangGraph chatbot with AgentOps integration
- `.env` - API keys for OpenAI and 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
## Next Steps
- 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
+99
View File
@@ -0,0 +1,99 @@
---
title: 'LiteLLM'
description: 'AgentOps for observing LiteLLM'
---
{/* SOURCE_FILE: examples/litellm/litellm_example.ipynb */}
_View Notebook on <a href={'https://github.com/AgentOps-AI/agentops/blob/main/examples/litellm/litellm_example.ipynb'} target={'_blank'}>Github</a>_
# AgentOps for observing LiteLLM
We can use AgentOps to observe LiteLLM, a lightweight library for working with large language models. This integration allows you to monitor and log the performance of your LiteLLM applications, providing insights into their behavior and efficiency.
LiteLLM integration extends observability to the different agent libraries which rely on LiteLLM and hence make it possible to observe the agents built using these libraries.
[See our LiteLLM docs](https://docs.agentops.ai/v1/integrations/litellm)
First let's install the required packages
## Installation
<CodeGroup>
```bash pip
pip install -U agentops litellm python-dotenv
```
```bash poetry
poetry add -U agentops litellm python-dotenv
```
```bash uv
uv pip install -U agentops litellm python-dotenv
```
</CodeGroup>
Then import them
```python
import litellm
import agentops
import os
from dotenv import load_dotenv
```
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.
[Get an AgentOps API key](https://agentops.ai/settings/projects)
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...
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!
LiteLLM allows you to use several models including from OpenAI, Llama, Mistral, Claude, Gemini, Gemma, Dall-E, Whisper, and more all using the OpenAI format. To use a different model all you need to change are the API KEY and model (litellm.completion(model="...")).
```python
load_dotenv()
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY", "your_api_key_here")
os.environ["OPENAI_API_KEY"] = os.getenv(
"OPENAI_API_KEY", "your_openai_api_key_here"
) # or the provider of your choosing
```
```python
agentops.init(auto_start_session=False)
tracer = agentops.start_trace(trace_name="LiteLLM Example", tags=["litellm-example", "agentops-example"])
```
Note: AgentOps requires that you call LiteLLM completions differently than the LiteLLM's docs mention
Instead of doing this -
```python
from litellm import completion
completion()
```
You should do this -
```python
import litellm
litellm.completion()
```
```python
messages = [{"role": "user", "content": "Write a 12 word poem about secret agents."}]
response = litellm.completion(model="gpt-4", messages=messages) # or the model of your choosing
print(response.choices[0].message.content)
```
```python
agentops.end_trace(tracer, end_state="Success")
```
<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>
+136
View File
@@ -0,0 +1,136 @@
---
title: 'Llamaindex Examples Example'
description: 'LlamaIndex AgentOps Integration Example'
---
{/* SOURCE_FILE: examples/llamaindex_examples/llamaindex_example.ipynb */}
_View Notebook on <a href={'https://github.com/AgentOps-AI/agentops/blob/main/examples/llamaindex_examples/llamaindex_example.ipynb'} target={'_blank'}>Github</a>_
# LlamaIndex AgentOps Integration Example
This notebook demonstrates how to use AgentOps with LlamaIndex for observability and monitoring of your context-augmented generative AI applications.
## Setup
First, install the required packages:
```
# Install required packages
!pip install agentops llama-index-instrumentation-agentops llama-index-embeddings-huggingface llama-index-llms-huggingface python-dotenv
```
## Initialize AgentOps Handler
Set up the AgentOps handler for LlamaIndex instrumentation:
```
import os
from dotenv import load_dotenv
from llama_index.core import VectorStoreIndex, Document, Settings
from llama_index.instrumentation.agentops import AgentOpsHandler
# Initialize AgentOps handler
handler = AgentOpsHandler()
handler.init()
# Load environment variables
load_dotenv()
# Set API keys (replace with your actual keys)
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")
```
## Configure Local Models (Optional)
For this example, we'll use local HuggingFace models to avoid requiring external API keys:
```
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.llms.huggingface import HuggingFaceLLM
# Configure local embeddings and LLM
Settings.embed_model = HuggingFaceEmbedding(model_name="BAAI/bge-small-en-v1.5")
Settings.llm = HuggingFaceLLM(model_name="microsoft/DialoGPT-medium")
print("Using local HuggingFace embeddings and LLM")
```
## Create Sample Documents and Index
Create some sample documents and build a vector index:
```
print("🚀 Starting LlamaIndex AgentOps Integration Example")
print("=" * 50)
# Create sample documents
documents = [
Document(text="LlamaIndex is a framework for building context-augmented generative AI applications with LLMs."),
Document(text="AgentOps provides observability into your AI applications, tracking LLM calls, performance metrics, and more."),
Document(text="The integration between LlamaIndex and AgentOps allows you to monitor your RAG applications seamlessly."),
Document(text="Vector databases are used to store and retrieve embeddings for similarity search in RAG applications."),
Document(text="Context-augmented generation combines retrieval and generation to provide more accurate and relevant responses.")
]
print("📚 Creating vector index from sample documents...")
index = VectorStoreIndex.from_documents(documents)
print("✅ Vector index created successfully")
```
## Perform Queries
Now let's perform some queries to demonstrate the AgentOps integration:
```
# Create query engine
query_engine = index.as_query_engine()
print("🔍 Performing queries...")
# Sample queries
queries = [
"What is LlamaIndex?",
"How does AgentOps help with AI applications?",
"What are the benefits of using vector databases in RAG?"
]
for i, query in enumerate(queries, 1):
print(f"\n📝 Query {i}: {query}")
response = query_engine.query(query)
print(f"💬 Response: {response}")
```
## Results
After running this notebook, you should see:
1. **AgentOps Session Link**: A URL to view the session in your AgentOps dashboard
2. **Cost Tracking**: Information about the cost of LLM calls (if using paid APIs)
3. **Operation Tracking**: All LlamaIndex operations are automatically tracked
Check your AgentOps dashboard to see detailed information about:
- LLM calls and responses
- Performance metrics
- Cost analysis
- Session replay
The session link will be printed in the output above by AgentOps.
```
print("\n" + "=" * 50)
print("🎉 Example completed successfully!")
print("📊 Check your AgentOps dashboard to see the recorded session with LLM calls and operations.")
print("🔗 The session link should be printed above by AgentOps.")
```
<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>
+239
View File
@@ -0,0 +1,239 @@
---
title: 'Mem0'
description: 'Memory Operations with Mem0'
---
{/* SOURCE_FILE: examples/mem0/mem0_memory_example.ipynb */}
_View Notebook on <a href={'https://github.com/AgentOps-AI/agentops/blob/main/examples/mem0/mem0_memory_example.ipynb'} target={'_blank'}>Github</a>_
# Memory Operations with Mem0
This example demonstrates how to use Mem0's memory management capabilities with both synchronous and asynchronous operations to store, search, and manage conversational context and user preferences.
## Overview
This example showcases practical memory management operations where we:
1. **Initialize Mem0 Memory instances** for both sync and async operations
2. **Store conversation history** and user preferences with metadata
3. **Search memories** using natural language queries
4. **Compare performance** between synchronous and asynchronous memory operations
By using async operations, you can perform multiple memory operations simultaneously instead of waiting for each one to complete sequentially. This is particularly beneficial when dealing with multiple memory additions or searches.
## Setup and Imports
## Installation
<CodeGroup>
```bash pip
pip install agentops mem0ai python-dotenv
```
```bash poetry
poetry add agentops mem0ai python-dotenv
```
```bash uv
uv pip install agentops mem0ai python-dotenv
```
</CodeGroup>
Import the required libraries for local memory management with Mem0. We'll use both Memory and AsyncMemory classes to demonstrate different execution patterns for memory operations.
```python
from mem0 import Memory, AsyncMemory
import os
import asyncio
import logging
from dotenv import load_dotenv
import agentops
```
## Environment Configuration
Set up environment variables for API keys. These are essential for authenticating with AgentOps for tracing and OpenAI for the language model used in memory operations.
```python
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY")
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
```
## Configuration and Sample Data
Set up the configuration for local memory storage and define sample user data. The configuration specifies the LLM provider and model settings for processing memories.
```python
local_config = {
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4o-mini",
"temperature": 0.1,
"max_tokens": 2000,
},
}
}
user_id = "alice_demo"
agent_id = "assistant_demo"
run_id = "session_001"
sample_messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{
"role": "assistant",
"content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future.",
},
]
sample_preferences = [
"I prefer dark roast coffee over light roast",
"I exercise every morning at 6 AM",
"I'm vegetarian and avoid all meat products",
"I love reading science fiction novels",
"I work in software engineering",
]
```
## Synchronous Memory Operations
This function demonstrates sequential memory operations using the synchronous Memory class. While straightforward to implement, each operation must complete before the next begins, which can impact performance.
```python
def demonstrate_sync_memory(local_config, sample_messages, sample_preferences, user_id):
"""
Demonstrate synchronous Memory class operations.
"""
agentops.start_trace("mem0_memory_example", tags=["mem0_memory_example"])
try:
memory = Memory.from_config(local_config)
result = memory.add(
sample_messages, user_id=user_id, metadata={"category": "movie_preferences", "session": "demo"}
)
for i, preference in enumerate(sample_preferences):
result = memory.add(preference, user_id=user_id, metadata={"type": "preference", "index": i})
search_queries = [
"What movies does the user like?",
"What are the user's food preferences?",
"When does the user exercise?",
]
for query in search_queries:
results = memory.search(query, user_id=user_id)
if results and "results" in results:
for j, result in enumerate(results):
print(f"Result {j+1}: {result.get('memory', 'N/A')}")
else:
print("No results found")
all_memories = memory.get_all(user_id=user_id)
if all_memories and "results" in all_memories:
print(f"Total memories: {len(all_memories['results'])}")
delete_all_result = memory.delete_all(user_id=user_id)
print(f"Delete all result: {delete_all_result}")
agentops.end_trace(end_state="success")
except Exception as e:
agentops.end_trace(end_state="error")
```
## Asynchronous Memory Operations
This function showcases concurrent memory operations using AsyncMemory. By leveraging asyncio.gather(), multiple operations execute simultaneously, significantly reducing total execution time for I/O-bound tasks.
```python
async def demonstrate_async_memory(local_config, sample_messages, sample_preferences, user_id):
"""
Demonstrate asynchronous Memory class operations with concurrent execution.
"""
agentops.start_trace("mem0_memory_async_example", tags=["mem0_memory_async_example"])
try:
async_memory = await AsyncMemory.from_config(local_config)
result = await async_memory.add(
sample_messages, user_id=user_id, metadata={"category": "async_movie_preferences", "session": "async_demo"}
)
async def add_preference(preference, index):
"""Helper function to add a single preference asynchronously."""
return await async_memory.add(
preference, user_id=user_id, metadata={"type": "async_preference", "index": index}
)
tasks = [add_preference(pref, i) for i, pref in enumerate(sample_preferences)]
results = await asyncio.gather(*tasks)
for i, result in enumerate(results):
print(f"Added async preference {i+1}: {result}")
search_queries = [
"What movies does the user like?",
"What are the user's dietary restrictions?",
"What does the user do for work?",
]
async def search_memory(query):
"""Helper function to perform async memory search."""
return await async_memory.search(query, user_id=user_id), query
search_tasks = [search_memory(query) for query in search_queries]
search_results = await asyncio.gather(*search_tasks)
for result, query in search_results:
if result and "results" in result:
for j, res in enumerate(result["results"]):
print(f"Result {j+1}: {res.get('memory', 'N/A')}")
else:
print("No results found")
all_memories = await async_memory.get_all(user_id=user_id)
if all_memories and "results" in all_memories:
print(f"Total async memories: {len(all_memories['results'])}")
delete_all_result = await async_memory.delete_all(user_id=user_id)
print(f"Delete all result: {delete_all_result}")
agentops.end_trace(end_state="success")
except Exception as e:
agentops.end_trace(end_state="error")
```
## Execute Demonstrations
Run both synchronous and asynchronous demonstrations to compare their execution patterns and performance. The async version demonstrates the benefits of concurrent execution for multiple memory operations.
```python
# Execute both sync and async demonstrations
demonstrate_sync_memory(local_config, sample_messages, sample_preferences, user_id)
await demonstrate_async_memory(local_config, sample_messages, sample_preferences, user_id)
```
<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>
+436
View File
@@ -0,0 +1,436 @@
---
title: 'OpenAI'
description: 'Multi-tool orchestration with OpenAI and AgentOps instrumentation'
---
{/* SOURCE_FILE: examples/openai/multi_tool_orchestration.ipynb */}
_View Notebook on <a href={'https://github.com/AgentOps-AI/agentops/blob/main/examples/openai/multi_tool_orchestration.ipynb'} target={'_blank'}>Github</a>_
### Multi-Tool Orchestration with RAG approach using OpenAI's Responses API
This cookbook guides you through building dynamic, multi-tool workflows using OpenAI's Responses API. It demonstrates how to implement a Retrieval-Augmented Generation (RAG) approach that intelligently routes user queries to the appropriate in-built or external tools. Whether your query calls for general knowledge or requires accessing specific internal context from a vector database (like Pinecone), this guide shows you how to integrate function calls, web searches in-built tool, and leverage document retrieval to generate accurate, context-aware responses.
## Installation
<CodeGroup>
```bash pip
pip install agentops datasets openai pandas pinecone python-dotenv tqdm
```
```bash poetry
poetry add agentops datasets openai pandas pinecone python-dotenv tqdm
```
```bash uv
uv pip install agentops datasets openai pandas pinecone python-dotenv tqdm
```
</CodeGroup>
```python
import os
from dotenv import load_dotenv
import time
from tqdm.auto import tqdm
from pandas import DataFrame
from datasets import load_dataset
import random
import string
from openai import OpenAI
import agentops
from pinecone import Pinecone
from pinecone import ServerlessSpec
```
```python
load_dotenv()
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY", "your_api_key_here")
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY", "your_openai_api_key_here")
os.environ["PINECONE_API_KEY"] = os.getenv("PINECONE_API_KEY", "your_pinecone_api_key_here")
```
```python
agentops.init(auto_start_session=True)
tracer = agentops.start_trace(
trace_name="Multi-Tool Orchestration with RAG",
tags=["multi-tool-orchestration-rag-demo", "openai-responses", "agentops-example"],
)
client = OpenAI()
```
In this example we use a sample medical reasoning dataset from Hugging Face. We convert the dataset into a Pandas DataFrame and merge the “Question” and “Response” columns into a single string. This merged text is used for embedding and later stored as metadata.
```python
# Load the dataset (ensure you're logged in with huggingface-cli if needed)
ds = load_dataset("FreedomIntelligence/medical-o1-reasoning-SFT", "en", split="train[:100]", trust_remote_code=True)
ds_dataframe = DataFrame(ds)
# Merge the Question and Response columns into a single string.
ds_dataframe["merged"] = ds_dataframe.apply(
lambda row: f"Question: {row['Question']} Answer: {row['Response']}", axis=1
)
print("Example merged text:", ds_dataframe["merged"].iloc[0])
```
```python
ds_dataframe
```
### Create a Pinecone Index Based on the Dataset
Use the dataset itself to determine the embedding dimensionality. For example, compute one embedding from the merged column and then create the index accordingly.
```python
MODEL = "text-embedding-3-small" # Replace with your production embedding model if needed
# Compute an embedding for the first document to obtain the embedding dimension.
sample_embedding_resp = client.embeddings.create(input=[ds_dataframe["merged"].iloc[0]], model=MODEL)
embed_dim = len(sample_embedding_resp.data[0].embedding)
print(f"Embedding dimension: {embed_dim}")
```
```python
# Initialize Pinecone using your API key.
pc = Pinecone(api_key=os.environ["PINECONE_API_KEY"])
# Define the Pinecone serverless specification.
AWS_REGION = "us-east-1"
spec = ServerlessSpec(cloud="aws", region=AWS_REGION)
# Create a random index name with lower case alphanumeric characters and '-'
index_name = "pinecone-index-" + "".join(random.choices(string.ascii_lowercase + string.digits, k=10))
# Create the index if it doesn't already exist.
if index_name not in pc.list_indexes().names():
pc.create_index(index_name, dimension=embed_dim, metric="dotproduct", spec=spec)
# Connect to the index.
index = pc.Index(index_name)
time.sleep(1)
print("Index stats:", index.describe_index_stats())
```
#### Upsert the Dataset into Pinecone index
Process the dataset in batches, generate embeddings for each merged text, prepare metadata (including separate Question and Answer fields), and upsert each batch into the index. You may also update metadata for specific entries if needed.
```python
batch_size = 32
for i in tqdm(range(0, len(ds_dataframe["merged"]), batch_size), desc="Upserting to Pinecone"):
i_end = min(i + batch_size, len(ds_dataframe["merged"]))
lines_batch = ds_dataframe["merged"][i:i_end]
ids_batch = [str(n) for n in range(i, i_end)]
# Create embeddings for the current batch.
res = client.embeddings.create(input=[line for line in lines_batch], model=MODEL)
embeds = [record.embedding for record in res.data]
# Prepare metadata by extracting original Question and Answer.
meta = []
for record in ds_dataframe.iloc[i:i_end].to_dict("records"):
q_text = record["Question"]
a_text = record["Response"]
# Optionally update metadata for specific entries.
meta.append({"Question": q_text, "Answer": a_text})
# Upsert the batch into Pinecone.
vectors = list(zip(ids_batch, embeds, meta))
index.upsert(vectors=vectors)
```
### Query the Pinecone Index
Create a natural language query, compute its embedding, and perform a similarity search on the Pinecone index. The returned results include metadata that provides context for generating answers.
```python
def query_pinecone_index(client, index, model, query_text):
# Generate an embedding for the query.
query_embedding = client.embeddings.create(input=query_text, model=model).data[0].embedding
# Query the index and return top 5 matches.
res = index.query(vector=[query_embedding], top_k=5, include_metadata=True)
print("Query Results:")
for match in res["matches"]:
print(
f"{match['score']:.2f}: {match['metadata'].get('Question', 'N/A')} - {match['metadata'].get('Answer', 'N/A')}"
)
return res
```
```python
# Example usage with a different query from the train/test set
query = (
"A 45-year-old man with a history of alcohol use presents with symptoms including confusion, ataxia, and ophthalmoplegia. "
"What is the most likely diagnosis and the recommended treatment?"
)
query_pinecone_index(client, index, MODEL, query)
```
### Generate a Response Using the Retrieved Context
Select the best matching result from your query results and use the OpenAI Responses API to generate a final answer by combining the retrieved context with the original question.
```python
# Retrieve and concatenate top 3 match contexts.
matches = index.query(
vector=[client.embeddings.create(input=query, model=MODEL).data[0].embedding], top_k=3, include_metadata=True
)["matches"]
context = "\n\n".join(
f"Question: {m['metadata'].get('Question', '')}\nAnswer: {m['metadata'].get('Answer', '')}" for m in matches
)
# Use the context to generate a final answer.
response = client.responses.create(
model="gpt-4o",
input=f"Provide the answer based on the context: {context} and the question: {query} as per the internal knowledge base",
)
print("\nFinal Answer:")
print(response.output_text)
```
### Orchestrate Multi-Tool Calls
Now, we'll define the built-in function available through the Responses API, including the ability to invoke the external Vector Store - Pinecone as an example.
*Web Search Preview Tool*: Enables the model to perform live web searches and preview the results. This is ideal for retrieving real-time or up-to-date information from the internet.
*Pinecone Search Tool*: Allows the model to query a vector database using semantic search. This is especially useful for retrieving relevant documents—such as medical literature or other domain-specific content—that have been stored in a vectorized format.
```python
# Tools definition: The list of tools includes:
# - A web search preview tool.
# - A Pinecone search tool for retrieving medical documents.
# Define available tools.
tools = [
{
"type": "web_search_preview",
"user_location": {"type": "approximate", "country": "US", "region": "California", "city": "SF"},
"search_context_size": "medium",
},
{
"type": "function",
"name": "PineconeSearchDocuments",
"description": "Search for relevant documents based on the medical question asked by the user that is stored within the vector database using a semantic query.",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "The natural language query to search the vector database."},
"top_k": {"type": "integer", "description": "Number of top results to return.", "default": 3},
},
"required": ["query"],
"additionalProperties": False,
},
},
]
```
```python
# Example queries that the model should route appropriately.
queries = [
{"query": "Who won the cricket world cup in 1983?"},
{"query": "What is the most common cause of death in the United States according to the internet?"},
{
"query": (
"A 7-year-old boy with sickle cell disease is experiencing knee and hip pain, "
"has been admitted for pain crises in the past, and now walks with a limp. "
"His exam shows a normal, cool hip with decreased range of motion and pain with ambulation. "
"What is the most appropriate next step in management according to the internal knowledge base?"
)
},
]
```
```python
# Process each query dynamically.
for item in queries:
input_messages = [{"role": "user", "content": item["query"]}]
print("\n🌟--- Processing Query ---🌟")
print(f"🔍 **User Query:** {item['query']}")
# Call the Responses API with tools enabled and allow parallel tool calls.
response = client.responses.create(
model="gpt-4o",
input=[
{
"role": "system",
"content": "When prompted with a question, select the right tool to use based on the question.",
},
{"role": "user", "content": item["query"]},
],
tools=tools,
parallel_tool_calls=True,
)
print("\n✨ **Initial Response Output:**")
print(response.output)
# Determine if a tool call is needed and process accordingly.
if response.output:
tool_call = response.output[0]
if tool_call.type in ["web_search_preview", "function_call"]:
tool_name = tool_call.name if tool_call.type == "function_call" else "web_search_preview"
print(f"\n🔧 **Model triggered a tool call:** {tool_name}")
if tool_name == "PineconeSearchDocuments":
print("🔍 **Invoking PineconeSearchDocuments tool...**")
res = query_pinecone_index(client, index, MODEL, item["query"])
if res["matches"]:
best_match = res["matches"][0]["metadata"]
result = f"**Question:** {best_match.get('Question', 'N/A')}\n**Answer:** {best_match.get('Answer', 'N/A')}"
else:
result = "**No matching documents found in the index.**"
print("✅ **PineconeSearchDocuments tool invoked successfully.**")
else:
print("🔍 **Invoking simulated web search tool...**")
result = "**Simulated web search result.**"
print("✅ **Simulated web search tool invoked successfully.**")
# Append the tool call and its output back into the conversation.
input_messages.append(tool_call)
input_messages.append({"type": "function_call_output", "call_id": tool_call.call_id, "output": str(result)})
# Get the final answer incorporating the tool's result.
final_response = client.responses.create(
model="gpt-4o", input=input_messages, tools=tools, parallel_tool_calls=True
)
print("\n💡 **Final Answer:**")
print(final_response.output_text)
else:
# If no tool call is triggered, print the response directly.
print("💡 **Final Answer:**")
print(response.output_text)
```
As shown above, depending on the query, appropriate tool is invoked in order to determine the optimal response.
For instance, looking at the third example, when the model triggers the tool named "PineconeSearchDocuments", the code calls `query_pinecone_index` with the current query and then extracts the best match (or an appropriate context) as the result. For non health related inqueries or queries where explicit internet search is asked, the code calls the web_search_call function and for other queries, it may choose to not call any tool and rather provide a response based on the question under consideration.
Finally, the tool call and its output are appended to the conversation, and the final answer is generated by the Responses API.
### Multi-tool orchestration flow
Now let us try to modify the input query and the system instructions to the responses API in order to follow a tool calling sequence and generate the output.
```python
# Process one query as an example to understand the tool calls and function calls as part of the response output
item = "What is the most common cause of death in the United States"
# Initialize input messages with the user's query.
input_messages = [{"role": "user", "content": item}]
print("\n🌟--- Processing Query ---🌟")
print(f"🔍 **User Query:** {item}")
# Call the Responses API with tools enabled and allow parallel tool calls.
print("\n🔧 **Calling Responses API with Tools Enabled**")
print("\n🕵️‍♂️ **Step 1: Web Search Call**")
print(" - Initiating web search to gather initial information.")
print("\n📚 **Step 2: Pinecone Search Call**")
print(" - Querying Pinecone to find relevant examples from the internal knowledge base.")
response = client.responses.create(
model="gpt-4o",
input=[
{
"role": "system",
"content": "Every time it's prompted with a question, first call the web search tool for results, then call `PineconeSearchDocuments` to find real examples in the internal knowledge base.",
},
{"role": "user", "content": item},
],
tools=tools,
parallel_tool_calls=True,
)
# Print the initial response output.
print("input_messages", input_messages)
print("\n✨ **Initial Response Output:**")
print(response.output)
```
```python
# Understand the tool calls and function calls as part of the response output
import pandas as pd
# Create a list to store the tool call and function call details
tool_calls = []
# Iterate through the response output and collect the details
for i in response.output:
tool_calls.append(
{
"Type": i.type,
"Call ID": i.call_id if hasattr(i, "call_id") else i.id if hasattr(i, "id") else "N/A",
"Output": str(i.output) if hasattr(i, "output") else "N/A",
"Name": i.name if hasattr(i, "name") else "N/A",
}
)
# Convert the list to a DataFrame for tabular display
df_tool_calls = pd.DataFrame(tool_calls)
# Display the DataFrame
df_tool_calls
```
```python
tool_call_1 = response.output[0]
print(tool_call_1)
print(tool_call_1.id)
tool_call_2 = response.output[2]
print(tool_call_2)
print(tool_call_2.call_id)
```
```python
# append the tool call and its output back into the conversation.
input_messages.append(response.output[2])
input_messages.append({"type": "function_call_output", "call_id": tool_call_2.call_id, "output": str(result)})
print(input_messages)
```
```python
# Get the final answer incorporating the tool's result.
print("\n🔧 **Calling Responses API for Final Answer**")
response_2 = client.responses.create(
model="gpt-4o",
input=input_messages,
)
print(response_2)
```
```python
# print the final answer
print(response_2.output_text)
agentops.end_trace(tracer, end_state="Success")
```
Here, we have seen how to utilize OpenAI's Responses API to implement a Retrieval-Augmented Generation (RAG) approach with multi-tool calling capabilities. It showcases an example where the model selects the appropriate tool based on the input query: general questions may be handled by built-in tools such as web-search, while specific medical inquiries related to internal knowledge are addressed by retrieving context from a vector database (such as Pinecone) via function calls. Additonally, we have showcased how multiple tool calls can be sequentially combined to generate a final response based on our instructions provided to responses API. Happy coding!
<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>
+250
View File
@@ -0,0 +1,250 @@
---
title: 'OpenAI Agents'
description: 'Airline Customer Service Agent'
---
{/* SOURCE_FILE: examples/openai_agents/customer_service_agent.ipynb */}
_View Notebook on <a href={'https://github.com/AgentOps-AI/agentops/blob/main/examples/openai_agents/customer_service_agent.ipynb'} target={'_blank'}>Github</a>_
# Airline Customer Service Agent
This is a simple chatbot designed to assist airline customers with common queries. Here the agents are also used as tools to help the bot answer questions more effectively.
Using AgentOps we can track the flow of the conversation and the agents used. This is useful for debugging and understanding how the bot is performing.
## Prerequisites
Before running this notebook, you'll need:
1. **AgentOps Account**: Create a free account at [app.agentops.ai](https://app.agentops.ai)
2. **AgentOps API Key**: Obtain your API key from your AgentOps dashboard
3. **OpenAI API Key**: Get your API key from [platform.openai.com](https://platform.openai.com)
Make sure to set these as environment variables or create a `.env` file in your project root with:
```
AGENTOPS_API_KEY=your_agentops_api_key_here
OPENAI_API_KEY=your_openai_api_key_here
```
## Installation
<CodeGroup>
```bash pip
pip install -q agentops openai-agents pydotenv
```
```bash poetry
poetry add -q agentops openai-agents pydotenv
```
```bash uv
uv pip install -q agentops openai-agents pydotenv
```
</CodeGroup>
```python
# Set the API keys for your AgentOps and OpenAI accounts.
import os
from dotenv import load_dotenv
load_dotenv()
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY", "your_api_key_here")
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY", "your_openai_api_key_here")
```
```python
from __future__ import annotations as _annotations # noqa: F404
import random
import uuid
from pydantic import BaseModel
import agentops
from agents import ( # noqa: E402
Agent,
HandoffOutputItem,
ItemHelpers,
MessageOutputItem,
RunContextWrapper,
Runner,
ToolCallItem,
ToolCallOutputItem,
TResponseInputItem,
function_tool,
handoff,
trace,
)
from agents.extensions.handoff_prompt import RECOMMENDED_PROMPT_PREFIX # noqa: E402
```
```python
agentops.init(tags=["customer-service-agent", "openai-agents", "agentops-example"])
tracer = agentops.start_trace(trace_name="Customer Service Agent")
```
```python
# Context model for the airline agent
class AirlineAgentContext(BaseModel):
passenger_name: str | None = None
confirmation_number: str | None = None
seat_number: str | None = None
flight_number: str | None = None
```
```python
# Tools for the airline agent
@function_tool(name_override="faq_lookup_tool", description_override="Lookup frequently asked questions.")
async def faq_lookup_tool(question: str) -> str:
if "bag" in question or "baggage" in question:
return (
"You are allowed to bring one bag on the plane. "
"It must be under 50 pounds and 22 inches x 14 inches x 9 inches."
)
elif "seats" in question or "plane" in question:
return (
"There are 120 seats on the plane. "
"There are 22 business class seats and 98 economy seats. "
"Exit rows are rows 4 and 16. "
"Rows 5-8 are Economy Plus, with extra legroom. "
)
elif "wifi" in question:
return "We have free wifi on the plane, join Airline-Wifi"
return "I'm sorry, I don't know the answer to that question."
@function_tool
async def update_seat(context: RunContextWrapper[AirlineAgentContext], confirmation_number: str, new_seat: str) -> str:
"""
Update the seat for a given confirmation number.
Args:
confirmation_number: The confirmation number for the flight.
new_seat: The new seat to update to.
"""
# Update the context based on the customer's input
context.context.confirmation_number = confirmation_number
context.context.seat_number = new_seat
# Ensure that the flight number has been set by the incoming handoff
assert context.context.flight_number is not None, "Flight number is required"
return f"Updated seat to {new_seat} for confirmation number {confirmation_number}"
### HOOKS
async def on_seat_booking_handoff(context: RunContextWrapper[AirlineAgentContext]) -> None:
flight_number = f"FLT-{random.randint(100, 999)}"
context.context.flight_number = flight_number
### AGENTS
faq_agent = Agent[AirlineAgentContext](
name="FAQ Agent",
handoff_description="A helpful agent that can answer questions about the airline.",
instructions=f"""{RECOMMENDED_PROMPT_PREFIX}
You are an FAQ agent. If you are speaking to a customer, you probably were transferred to from the triage agent.
Use the following routine to support the customer.
# Routine
1. Identify the last question asked by the customer.
2. Use the faq lookup tool to answer the question. Do not rely on your own knowledge.
3. If you cannot answer the question, transfer back to the triage agent.""",
tools=[faq_lookup_tool],
)
seat_booking_agent = Agent[AirlineAgentContext](
name="Seat Booking Agent",
handoff_description="A helpful agent that can update a seat on a flight.",
instructions=f"""{RECOMMENDED_PROMPT_PREFIX}
You are a seat booking agent. If you are speaking to a customer, you probably were transferred to from the triage agent.
Use the following routine to support the customer.
# Routine
1. Ask for their confirmation number.
2. Ask the customer what their desired seat number is.
3. Use the update seat tool to update the seat on the flight.
If the customer asks a question that is not related to the routine, transfer back to the triage agent. """,
tools=[update_seat],
)
triage_agent = Agent[AirlineAgentContext](
name="Triage Agent",
handoff_description="A triage agent that can delegate a customer's request to the appropriate agent.",
instructions=(
f"{RECOMMENDED_PROMPT_PREFIX} "
"You are a helpful triaging agent. You can use your tools to delegate questions to other appropriate agents."
),
handoffs=[
faq_agent,
handoff(agent=seat_booking_agent, on_handoff=on_seat_booking_handoff),
],
)
```
```python
faq_agent.handoffs.append(triage_agent)
seat_booking_agent.handoffs.append(triage_agent)
```
```python
async def main():
current_agent: Agent[AirlineAgentContext] = triage_agent
input_items: list[TResponseInputItem] = []
context = AirlineAgentContext()
# Normally, each input from the user would be an API request to your app, and you can wrap the request in a trace()
# Here, we'll just use a random UUID for the conversation ID
conversation_id = uuid.uuid4().hex[:16]
while True:
user_input = input("Enter your message: ")
with trace("Customer service", group_id=conversation_id):
input_items.append({"content": user_input, "role": "user"})
result = await Runner.run(current_agent, input_items, context=context)
for new_item in result.new_items:
agent_name = new_item.agent.name
if isinstance(new_item, MessageOutputItem):
print(f"{agent_name}: {ItemHelpers.text_message_output(new_item)}")
elif isinstance(new_item, HandoffOutputItem):
print(f"Handed off from {new_item.source_agent.name} to {new_item.target_agent.name}")
elif isinstance(new_item, ToolCallItem):
print(f"{agent_name}: Calling a tool")
elif isinstance(new_item, ToolCallOutputItem):
print(f"{agent_name}: Tool call output: {new_item.output}")
else:
print(f"{agent_name}: Skipping item: {new_item.__class__.__name__}")
input_items = result.to_input_list()
current_agent = result.last_agent
```
```python
await main()
agentops.end_trace(tracer, end_state="Success")
```
## Conclusion
**AgentOps makes observability effortless** - simply import the library and all your interactions are automatically tracked, visualized, and analyzed. This enables you to:
- Monitor tool performance across different use cases
- Optimize costs by understanding tool usage patterns
- Debug tool integration issues quickly
- Scale your AI applications with confidence in tool reliability
Visit [app.agentops.ai](https://app.agentops.ai) to explore your tool usage sessions and gain deeper insights into your AI application's tool interactions.
<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>
+168
View File
@@ -0,0 +1,168 @@
---
title: 'Smolagents'
description: 'Orchestrate a Multi-Agent System'
---
{/* SOURCE_FILE: examples/smolagents/multi_smolagents_system.ipynb */}
_View Notebook on <a href={'https://github.com/AgentOps-AI/agentops/blob/main/examples/smolagents/multi_smolagents_system.ipynb'} target={'_blank'}>Github</a>_
# Orchestrate a Multi-Agent System
In this notebook, we will make a multi-agent web browser: an agentic system with several agents collaborating to solve problems using the web!
It will be a simple hierarchy, using a `ManagedAgent` object to wrap the managed web search agent:
```
+----------------+
| Manager agent |
+----------------+
|
_________|______________
| |
Code interpreter +--------------------------------+
tool | Managed agent |
| +------------------+ |
| | Web Search agent | |
| +------------------+ |
| | | |
| Web Search tool | |
| Visit webpage tool |
+--------------------------------+
```
Let’s set up this system.
Run the line below to install the required dependencies:
## Installation
<CodeGroup>
```bash pip
pip install agentops duckduckgo-search markdownify smolagents
```
```bash poetry
poetry add agentops duckduckgo-search markdownify smolagents
```
```bash uv
uv pip install agentops duckduckgo-search markdownify smolagents
```
</CodeGroup>
🖇️ Now we initialize the AgentOps client and load the environment variables to use the API keys.
```python
import agentops
from dotenv import load_dotenv
import os
import re
import requests
from markdownify import markdownify
from requests.exceptions import RequestException
from smolagents import LiteLLMModel, tool, CodeAgent, ToolCallingAgent, DuckDuckGoSearchTool
load_dotenv()
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY", "your_api_key_here")
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY", "your_openai_api_key_here")
```
⚡️ Our agent will be powered by `openai/gpt-4o-mini` using the `LiteLLMModel` class.
```python
from smolagents import LiteLLMModel, tool ,CodeAgent, ToolCallingAgent, DuckDuckGoSearchTool
agentops.init(auto_start_session=False)
tracer = agentops.start_trace(
trace_name="Orchestrate a Multi-Agent System", tags=["smolagents", "example", "multi-agent", "agentops-example"]
)
model = LiteLLMModel("openai/gpt-4o-mini")
```
## Create a Web Search Tool
For web browsing, we can already use our pre-existing `DuckDuckGoSearchTool`. However, we will also create a `VisitWebpageTool` from scratch using `markdownify`. Here’s how:
```python
@tool
def visit_webpage(url: str) -> str:
"""Visits a webpage at the given URL and returns its content as a markdown string.
Args:
url: The URL of the webpage to visit.
Returns:
The content of the webpage converted to Markdown, or an error message if the request fails.
"""
try:
# Send a GET request to the URL
response = requests.get(url)
response.raise_for_status() # Raise an exception for bad status codes
# Convert the HTML content to Markdown
markdown_content = markdownify(response.text).strip()
# Remove multiple line breaks
markdown_content = re.sub(r"\n{3,}", "\n\n", markdown_content)
return markdown_content
except RequestException as e:
return f"Error fetching the webpage: {str(e)}"
except Exception as e:
return f"An unexpected error occurred: {str(e)}"
```
Let’s test our tool:
```python
print(visit_webpage("https://en.wikipedia.org/wiki/Hugging_Face")[:500])
```
## Build Our Multi-Agent System
We will now use the tools `search` and `visit_webpage` to create the web agent.
```python
web_agent = ToolCallingAgent(
tools=[DuckDuckGoSearchTool(), visit_webpage],
model=model,
name="search",
description="Runs web searches for you. Give it your query as an argument.",
)
manager_agent = CodeAgent(
tools=[],
model=model,
managed_agents=[web_agent],
additional_authorized_imports=["time", "numpy", "pandas"],
)
```
Let’s run our system with the following query:
```python
answer = manager_agent.run(
"If LLM trainings continue to scale up at the current rhythm until 2030, what would be the electric power in GW required to power the biggest training runs by 2030? What does that correspond to, compared to some countries? Please provide a source for any number used."
)
print(answer)
```
Awesome! We've successfully run a multi-agent system. Let's end the agentops session with a "Success" state. You can also end the session with a "Failure" or "Indeterminate" state, which is set as default.
```python
agentops.end_trace(tracer, end_state="Success")
```
You can view the session in the [AgentOps dashboard](https://app.agentops.ai/sessions) by clicking the link provided after ending the session.
<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>
+137
View File
@@ -0,0 +1,137 @@
---
title: 'IBM Watsonx.ai Example'
description: 'Using IBM Watsonx.ai for text generation and chat with AgentOps'
---
{/* SOURCE_FILE: examples/watsonx/watsonx-text-chat.ipynb */}
_View Notebook on <a href={'https://github.com/AgentOps-AI/agentops/blob/main/examples/watsonx/watsonx-text-chat.ipynb'} target={'_blank'}>Github</a>_
# IBM Watsonx.ai Text Generation and Chat with AgentOps
This notebook demonstrates how to use IBM Watsonx.ai for basic text generation and chat completion tasks with AgentOps instrumentation.
## Installation
Install the required packages:
<CodeGroup>
```bash pip
pip install agentops ibm-watsonx-ai python-dotenv
```
```bash poetry
poetry add agentops ibm-watsonx-ai python-dotenv
```
```bash uv
uv pip install agentops ibm-watsonx-ai python-dotenv
```
</CodeGroup>
## Setup
First, let's import the necessary libraries and initialize AgentOps:
```python
import agentops
from ibm_watsonx_ai import Credentials
from ibm_watsonx_ai.foundation_models import ModelInference
from dotenv import load_dotenv
import os
# Load environment variables
load_dotenv()
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY", "your_agentops_api_key_here")
# Initialize AgentOps
agentops.init(tags=["watsonx-text-chat", "agentops-example"])
```
## Initialize IBM Watsonx.ai Credentials
To use IBM Watsonx.ai, you need to set up your credentials and project ID.
```python
# Initialize credentials - replace with your own API key
# Best practice: Store API keys in environment variables
# Ensure WATSONX_API_KEY, WATSONX_URL, and WATSONX_PROJECT_ID are set in your .env file or environment
os.environ["WATSONX_API_KEY"] = os.getenv("WATSONX_API_KEY", "your_watsonx_api_key_here")
os.environ["WATSONX_URL"] = os.getenv("WATSONX_URL", "https://eu-de.ml.cloud.ibm.com") # Example URL, ensure it's correct for your region
os.environ["WATSONX_PROJECT_ID"] = os.getenv("WATSONX_PROJECT_ID", "your-project-id-here")
credentials = Credentials(
url=os.environ["WATSONX_URL"],
api_key=os.environ["WATSONX_API_KEY"],
)
# Project ID for your IBM Watsonx project
project_id = os.environ["WATSONX_PROJECT_ID"]
```
## Text Generation
Let's use IBM Watsonx.ai to generate text based on a prompt:
```python
# Initialize text generation model
gen_model = ModelInference(model_id="google/flan-ul2", credentials=credentials, project_id=project_id)
# Generate text with a prompt
prompt = "Write a short poem about artificial intelligence:"
response = gen_model.generate_text(prompt)
print(f"Generated Text:\n{response}")
```
## Chat Completion
Now, let's use a different model for chat completion:
```python
# Initialize chat model
chat_model = ModelInference(
model_id="meta-llama/llama-3-8b-instruct", # Using the model ID from the MDX as it might be more current/available
credentials=credentials,
project_id=project_id
)
# Format messages for chat
messages = [
{"role": "system", "content": "You are a helpful AI assistant."},
{"role": "user", "content": "What are the three laws of robotics?"},
]
# Get chat response
chat_response = chat_model.chat(messages)
# Accessing response based on typical ibm-watsonx-ai SDK structure
print(f"Chat Response:\n{chat_response['results'][0]['generated_text']}")
```
## Another Chat Example
Let's try a different type of query:
```python
# New chat messages
messages = [
{"role": "system", "content": "You are an expert in machine learning."},
{"role": "user", "content": "Explain the difference between supervised and unsupervised learning in simple terms."},
]
# Get chat response
chat_response = chat_model.chat(messages)
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.
```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()
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
```
<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>
+142
View File
@@ -0,0 +1,142 @@
---
title: 'xAI'
description: 'XAI Example'
---
{/* SOURCE_FILE: examples/xai/grok_examples.ipynb */}
_View Notebook on <a href={'https://github.com/AgentOps-AI/agentops/blob/main/examples/xai/grok_examples.ipynb'} target={'_blank'}>Github</a>_
# XAI Example
This notebook demonstrates how to use XAI with AgentOps via the OpenAI python client.
We are going to use the latest Grok model from XAI to create a transliteration chatbot that can understand the major languages of the world and translate them to a user's native language! We will use AgentOps to track the chatbot's performance.
First let's install the required packages
## Installation
<CodeGroup>
```bash pip
pip install -U agentops openai
```
```bash poetry
poetry add -U agentops openai
```
```bash uv
uv pip install -U agentops openai
```
</CodeGroup>
Then import them
```python
from openai import OpenAI
import agentops
import os
from dotenv import load_dotenv
```
Next, we'll grab our API keys. You can use dotenv like below or however else you like to load environment variables
```python
load_dotenv()
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY", "your_api_key_here")
```
Next we initialize the AgentOps client.
```python
agentops.init(auto_start_session=False)
tracer = agentops.start_trace(trace_name="XAI Example", tags=["xai-example", "grok", "agentops-example"])
```
And we are all set! Note the session URL above. We will use it to track the chatbot.
Let's initialize the OpenAI client with the XAI API key and base url.
```python
client = OpenAI(
base_url="https://api.x.ai/v1",
api_key=os.getenv("XAI_API_KEY", "your_xai_api_key_here"),
)
```
Now we will set the system and instruction prompts for the chatbot. We will set the native language to Spanish and the user prompt to transliterate an excerpt from Haruki Murakami's "Kafka On The Shore".
```python
SYSTEM_PROMPT = """
You are a highly intelligent, multilingual assistant designed to understand user prompts in English and respond in the user's specified native language.
Your key responsibilities include:
1. Translating and generating meaningful, contextually appropriate responses in the user's native language.
2. Ensuring the output is accurate, coherent, and in Unicode format for proper display in the specified language.
3. Adhering to the nuances of the specified language's grammar, tone, and cultural context.
When asked to respond in a language, generate the response entirely in that language without using English unless explicitly requested.
If the specified language is unfamiliar or ambiguous, politely ask for clarification in English.
"""
```
```python
native_language = "Spanish"
USER_PROMPT = """
Sometimes fate is like a small sandstorm that keeps changing directions. You change direction but the sandstorm chases you.
You turn again, but the storm adjusts. Over and over you play this out, like some ominous dance with death just before dawn. Why?
Because this storm isn’t something that blew in from far away, something that has nothing to do with you. This storm is you.
Something inside of you. So all you can do is give in to it, step right inside the storm, closing your eyes and plugging up your ears so the sand doesn’t get in, and walk through it, step by step.
There’s no sun there, no moon, no direction, no sense of time. Just fine white sand swirling up into the sky like pulverized bones.
That’s the kind of sandstorm you need to imagine.
And you really will have to make it through that violent, metaphysical, symbolic storm.
No matter how metaphysical or symbolic it might be, make no mistake about it: it will cut through flesh like a thousand razor blades. People will bleed there, and you will bleed too.
Hot, red blood. You’ll catch that blood in your hands, your own blood and the blood of others.
And once the storm is over you won’t remember how you made it through, how you managed to survive. You won’t even be sure, in fact, whether the storm is really over.
But one thing is certain. When you come out of the storm you won’t be the same person who walked in. That’s what this storm’s all about.
"""
INSTRUCTION_PROMPT = f"""
You are a multilingual chatbot. Take the user's prompt: "{USER_PROMPT}" and respond naturally in {native_language}.
Ensure that the response is in Unicode characters appropriate for {native_language}.
"""
```
Now we will use the OpenAI client to generate the response by passing in the system and instruction prompts.
```python
response = client.chat.completions.create(
model="grok-3-mini",
messages=[{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": INSTRUCTION_PROMPT}],
)
```
```python
print(f"Original Prompt:\n{USER_PROMPT}")
generated_response = response.choices[0].message.content
print(f"Response in {native_language}:\n{generated_response}")
```
Awesome! We can now transliterate from English to any language! And all of this can be tracked with AgentOps by going to the session url above.
```python
agentops.end_trace(tracer, end_state="Success")
```
We end the session with a success state and a success reason. This is useful if you want to track the success or failure of the chatbot. In that case you can set the end state to failure and provide a reason. By default the session will have an indeterminate end state.
<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>
+38
View File
@@ -0,0 +1,38 @@
---
title: 'Xpander'
description: 'Xpander coding agent example with AgentOps'
---
{/* SOURCE_FILE: examples/xpander/coding_agent.py */}
_View Python Example on <a href={'https://github.com/AgentOps-AI/agentops/blob/main/examples/xpander/coding_agent.py'} target={'_blank'}>Github</a>_
This example demonstrates a complete Xpander coding agent implementation with AgentOps instrumentation using callback handlers. The example shows how to build a single-file agent that combines the MyAgent class and XpanderEventListener for comprehensive monitoring.
## Key Features
- **Single-file implementation** combining agent logic and event handling
- **Callback-based instrumentation** using XpanderEventListener
- **Async tool execution** with proper error handling and logging
- **AgentOps integration** with custom trace names and tags
## Running the Example
1. Set up your environment variables in a `.env` file or export them:
```bash
AGENTOPS_API_KEY=your_agentops_api_key
XPANDER_API_KEY=your_xpander_api_key
XPANDER_AGENT_ID=your_agent_id
OPENAI_API_KEY=your_openai_api_key
```
2. Run the agent:
```bash
python examples/xpander/coding_agent.py
```
The agent will start an interactive session where you can ask coding questions and see the results tracked in your AgentOps dashboard.
<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>