同步完整源码 - 2026-05-25
This commit is contained in:
@@ -0,0 +1,115 @@
|
||||
# AgentOps Examples
|
||||
|
||||
This directory contains comprehensive examples demonstrating how to integrate AgentOps with various AI/ML frameworks, libraries, and providers. Each example is provided as a Jupyter notebook and a Python script with detailed explanations and code samples.
|
||||
|
||||
## 📁 Directory Structure
|
||||
|
||||
- **[`ag2/`](./ag2/)** - Examples for AG2 (AutoGen 2.0) multi-agent conversations
|
||||
- `agentchat_with_memory` - Agent chat with persistent memory
|
||||
- `async_human_input` - Asynchronous human input handling
|
||||
- `tools_wikipedia_search` - Wikipedia search tool integration
|
||||
|
||||
- **[`anthropic/`](./anthropic/)** - Anthropic Claude API integration examples
|
||||
- `agentops-anthropic-understanding-tools` - Deep dive into tool usage
|
||||
- `anthropic-example-async` - Asynchronous API calls
|
||||
- `anthropic-example-sync` - Synchronous API calls
|
||||
- `antrophic-example-tool` - Tool calling examples
|
||||
- `README.md` - Detailed Anthropic integration guide
|
||||
|
||||
- **[`autogen/`](./autogen/)** - Microsoft AutoGen framework examples
|
||||
- `AgentChat` - Basic agent chat functionality
|
||||
- `MathAgent` - Mathematical problem-solving agent
|
||||
|
||||
- **[`crewai/`](./crewai/)** - CrewAI multi-agent framework examples
|
||||
- `job_posting` - Job posting automation workflow
|
||||
- `markdown_validator` - Markdown validation agent
|
||||
|
||||
- **[`gemini/`](./gemini/)** - Google Gemini API integration
|
||||
- `gemini_example` - Basic Gemini API usage with AgentOps
|
||||
|
||||
- **[`google_adk/`](./google_adk/)** - Google AI Development Kit examples
|
||||
- `human_approval` - Human-in-the-loop approval workflows
|
||||
|
||||
- **[`langchain/`](./langchain/)** - LangChain framework integration
|
||||
- `langchain_examples` - Comprehensive LangChain usage examples
|
||||
|
||||
- **[`litellm/`](./litellm/)** - LiteLLM proxy integration
|
||||
- `litellm_example` - Multi-provider LLM access through LiteLLM
|
||||
|
||||
- **[`openai/`](./openai/)** - OpenAI API integration examples
|
||||
- `multi_tool_orchestration` - Complex tool orchestration
|
||||
- `openai_example_async` - Asynchronous OpenAI API calls
|
||||
- `openai_example_sync` - Synchronous OpenAI API calls
|
||||
- `web_search` - Web search functionality
|
||||
|
||||
- **[`openai_agents/`](./openai_agents/)** - OpenAI Agents SDK examples
|
||||
- `agent_patterns` - Common agent design patterns
|
||||
- `agents_tools` - Agent tool integration
|
||||
- `customer_service_agent` - Customer service automation
|
||||
|
||||
- **[`smolagents/`](./smolagents/)** - SmolAgents framework examples
|
||||
- `multi_smolagents_system` - Multi-agent system coordination
|
||||
- `text_to_sql` - Natural language to SQL conversion
|
||||
|
||||
- **[`watsonx/`](./watsonx/)** - IBM Watsonx AI integration
|
||||
- `watsonx-streaming` - Streaming text generation
|
||||
- `watsonx-text-chat` - Text generation and chat completion
|
||||
- `watsonx-tokeniation-model` - Tokenization and model details
|
||||
- `README.md` - Detailed Watsonx integration guide
|
||||
|
||||
- **[`xai/`](./xai/)** - xAI (Grok) API integration
|
||||
- `grok_examples` - Basic Grok API usage
|
||||
- `grok_vision_examples` - Vision capabilities with Grok
|
||||
|
||||
### Utility Scripts
|
||||
|
||||
- **[`generate_documentation.py`](./generate_documentation.py)** - Script to convert Jupyter notebooks to MDX documentation files
|
||||
- Converts notebooks from `examples/` to `docs/v2/examples/`
|
||||
- Handles frontmatter, GitHub links, and installation sections
|
||||
- Transforms `%pip install` commands to CodeGroup format
|
||||
|
||||
## 📓 Prerequisites
|
||||
|
||||
1. **AgentOps Account**: Sign up at [agentops.ai](https://agentops.ai)
|
||||
2. **Python Environment**: Python 3.10+ recommended
|
||||
3. **API Keys**: Obtain API keys for the services you want to use
|
||||
|
||||
## 📖 Documentation Generation
|
||||
|
||||
The `generate_documentation.py` script automatically converts these Jupyter notebook examples into documentation for the AgentOps website. It:
|
||||
|
||||
- Extracts notebook content and converts to Markdown
|
||||
- Adds proper frontmatter and metadata
|
||||
- Transforms installation commands into user-friendly format
|
||||
- Generates GitHub links for source notebooks
|
||||
- Creates MDX files in `docs/v2/examples/`
|
||||
|
||||
### Usage
|
||||
```bash
|
||||
python examples/generate_documentation.py examples/langchain/langchain_examples.ipynb
|
||||
```
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
When adding new examples:
|
||||
|
||||
1. Create a new subdirectory for the framework/provider
|
||||
2. Include comprehensive Jupyter notebooks with explanations
|
||||
3. Add a README.md if the integration is complex
|
||||
4. Ensure examples are self-contained and runnable
|
||||
5. Follow the existing naming conventions
|
||||
6. Use the `generate_documentation.py` script to create documentation files
|
||||
7. Add the example notebook to the main `README.md` for visibility
|
||||
8. Add the generated documentation to the `docs/v2/examples/` directory for website visibility
|
||||
9. Submit a pull request with a clear description of your changes
|
||||
|
||||
## 📚 Additional Resources
|
||||
|
||||
- [AgentOps Documentation](https://docs.agentops.ai)
|
||||
- [AgentOps Dashboard](https://app.agentops.ai)
|
||||
- [GitHub Repository](https://github.com/AgentOps-AI/agentops)
|
||||
- [Community Discord](https://discord.gg/agentops)
|
||||
|
||||
## 📄 License
|
||||
|
||||
These examples are provided under the same license as the AgentOps project. See the main repository for license details.
|
||||
@@ -0,0 +1,103 @@
|
||||
# AgentOps Examples Integration Testing
|
||||
|
||||
This directory contains example scripts demonstrating how to use AgentOps with various LLM providers and frameworks. Each example includes automatic validation to ensure that LLM spans are properly tracked by AgentOps.
|
||||
|
||||
## What's Being Tested
|
||||
|
||||
Each example script now includes automated span validation that:
|
||||
|
||||
1. **Runs the example** - Executes the normal example code
|
||||
2. **Validates span tracking** - Uses the AgentOps integrated validation to verify that:
|
||||
- Spans were successfully sent to AgentOps
|
||||
- LLM calls were properly instrumented and tracked
|
||||
- Token counts and costs were recorded
|
||||
|
||||
## How It Works
|
||||
|
||||
### 1. Integrated Validation
|
||||
|
||||
AgentOps now includes built-in validation functionality (`agentops.validate_trace_spans`) that:
|
||||
- Exchanges API keys for JWT tokens using the public API
|
||||
- Queries the AgentOps API for trace and span data
|
||||
- Validates that expected spans are present
|
||||
- Retrieves metrics like token usage and costs
|
||||
|
||||
### 2. Example Structure
|
||||
|
||||
Each example follows this pattern:
|
||||
|
||||
```python
|
||||
import agentops
|
||||
|
||||
# Initialize AgentOps
|
||||
agentops.init()
|
||||
|
||||
# Start a trace
|
||||
tracer = agentops.start_trace("example-name")
|
||||
|
||||
# ... perform operations with LLMs ...
|
||||
|
||||
# End the trace
|
||||
agentops.end_trace(tracer, end_state="Success")
|
||||
|
||||
# Validate spans were tracked
|
||||
try:
|
||||
result = agentops.validate_trace_spans(trace_context=tracer)
|
||||
agentops.print_validation_summary(result)
|
||||
except agentops.ValidationError as e:
|
||||
print(f"❌ Error validating spans: {e}")
|
||||
raise
|
||||
```
|
||||
|
||||
### 3. CI/CD Integration
|
||||
|
||||
The GitHub Actions workflow (`examples-integration-test.yml`) runs all examples automatically on:
|
||||
- Push to main/develop branches
|
||||
- Pull requests
|
||||
- Manual workflow dispatch
|
||||
|
||||
Each example is run in isolation with proper error handling and reporting.
|
||||
|
||||
## Running Tests Locally
|
||||
|
||||
To run a specific example with validation:
|
||||
|
||||
```bash
|
||||
cd examples/openai
|
||||
python openai_example_sync.py
|
||||
```
|
||||
|
||||
To run all examples:
|
||||
|
||||
```bash
|
||||
# From the examples directory
|
||||
for script in $(find . -name "*.py" -type f | grep -v "__pycache__"); do
|
||||
echo "Running $script..."
|
||||
python "$script"
|
||||
done
|
||||
```
|
||||
|
||||
## Adding New Examples
|
||||
|
||||
When adding a new example:
|
||||
|
||||
1. Include the standard validation at the end:
|
||||
```python
|
||||
# Validate spans were tracked
|
||||
try:
|
||||
result = agentops.validate_trace_spans(trace_context=tracer)
|
||||
agentops.print_validation_summary(result)
|
||||
except agentops.ValidationError as e:
|
||||
print(f"❌ Error validating spans: {e}")
|
||||
raise
|
||||
```
|
||||
|
||||
2. Add the example to the GitHub Actions matrix in `.github/workflows/examples-integration-test.yml`
|
||||
|
||||
3. Ensure the example has proper error handling
|
||||
|
||||
## Requirements
|
||||
|
||||
- Valid `AGENTOPS_API_KEY` environment variable
|
||||
- API keys for the specific LLM provider being tested
|
||||
- Python 3.12+ with required dependencies
|
||||
@@ -0,0 +1,33 @@
|
||||
# AG2 Examples with AgentOps
|
||||
|
||||
This directory contains examples of using AG2 (AutoGen 2.0) with AgentOps instrumentation for various multi-agent conversation tasks.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Python >= 3.10 < 3.13
|
||||
- Install required dependencies:
|
||||
```
|
||||
pip install agentops ag2
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### 1. Asynchronous Human Input
|
||||
|
||||
Example: `async_human_input`
|
||||
|
||||
This example demonstrates:
|
||||
- Asynchronous human input handling
|
||||
|
||||
### 2. Wikipedia Search Tool
|
||||
|
||||
Example: `tools_wikipedia_search`
|
||||
|
||||
This example demonstrates:
|
||||
- Wikipedia search tool integration
|
||||
|
||||
## AgentOps Integration
|
||||
|
||||
These examples show how to use AgentOps to monitor and analyze your AI applications. AgentOps automatically instruments your AG2 calls to provide insights into performance, usage patterns, and model behavior.
|
||||
|
||||
To learn more about AgentOps, visit [https://www.agentops.ai](https://www.agentops.ai)
|
||||
@@ -0,0 +1,236 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "1ad612e0",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"AG2 Async Agent Chat with Automated Responses\n",
|
||||
"\n",
|
||||
"This notebook demonstrates how to leverage asynchronous programming with AG2 agents \n",
|
||||
"to create automated conversations between AI agents, eliminating the need for human \n",
|
||||
"input while maintaining full traceability.\n",
|
||||
"\n",
|
||||
"Overview\n",
|
||||
"This notebook demonstrates a practical example of automated AI-to-AI communication where we:\n",
|
||||
"\n",
|
||||
"1. Initialize AG2 agents with OpenAI's GPT-4o-mini model\n",
|
||||
"2. Create custom async agents that simulate human-like responses and processing delays\n",
|
||||
"3. Automate the entire conversation flow without requiring manual intervention\n",
|
||||
"4. Track all interactions using AgentOps for monitoring and analysis\n",
|
||||
"\n",
|
||||
"By using async operations and automated responses, you can create fully autonomous \n",
|
||||
"agent conversations that simulate real-world scenarios. This is particularly useful \n",
|
||||
"for testing, prototyping, and creating demos where you want to showcase agent \n",
|
||||
"capabilities without manual input."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "361b3cf5",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%pip install agentops\n",
|
||||
"%pip install ag2\n",
|
||||
"%pip install nest-asyncio"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "9962270b",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import asyncio\n",
|
||||
"from typing import Dict, Optional, Union\n",
|
||||
"import os\n",
|
||||
"from dotenv import load_dotenv\n",
|
||||
"import nest_asyncio\n",
|
||||
"import agentops\n",
|
||||
"from autogen import AssistantAgent\n",
|
||||
"from autogen.agentchat.user_proxy_agent import UserProxyAgent"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "60e84ffb",
|
||||
"metadata": {
|
||||
"lines_to_next_cell": 1
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Load environment variables for API keys\n",
|
||||
"load_dotenv()\n",
|
||||
"os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\", \"your_api_key_here\")\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\", \"your_openai_api_key_here\")\n",
|
||||
"# Initialize AgentOps for tracking and monitoring\n",
|
||||
"agentops.init(auto_start_session=False, trace_name=\"AG2 Async Demo\")\n",
|
||||
"tracer = agentops.start_trace(trace_name=\"AG2 Async Agent Demo\", tags=[\"ag2-async-demo\", \"agentops-example\"])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "8c1dc105",
|
||||
"metadata": {
|
||||
"lines_to_next_cell": 1
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Define an asynchronous function that simulates async processing\n",
|
||||
"async def simulate_async_processing(task_name: str, delay: float = 1.0) -> str:\n",
|
||||
" \"\"\"\n",
|
||||
" Simulate some asynchronous processing (e.g., API calls, file operations, etc.)\n",
|
||||
" \"\"\"\n",
|
||||
" print(f\"🔄 Starting async task: {task_name}\")\n",
|
||||
" await asyncio.sleep(delay) # Simulate async work\n",
|
||||
" print(f\"✅ Completed async task: {task_name}\")\n",
|
||||
" return f\"Processed: {task_name}\""
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "0d683b3d",
|
||||
"metadata": {
|
||||
"lines_to_next_cell": 1
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Define a custom UserProxyAgent that simulates automated user responses\n",
|
||||
"class AutomatedUserProxyAgent(UserProxyAgent):\n",
|
||||
" def __init__(self, name: str, **kwargs):\n",
|
||||
" super().__init__(name, **kwargs)\n",
|
||||
" self.response_count = 0\n",
|
||||
" self.predefined_responses = [\n",
|
||||
" \"Yes, please generate interview questions for these topics.\",\n",
|
||||
" \"The questions look good. Can you make them more specific to senior-level positions?\",\n",
|
||||
" \"Perfect! These questions are exactly what we need. Thank you!\",\n",
|
||||
" ]\n",
|
||||
"\n",
|
||||
" async def a_get_human_input(self, prompt: str) -> str:\n",
|
||||
" # Simulate async processing before responding\n",
|
||||
" await simulate_async_processing(f\"Processing user input #{self.response_count + 1}\")\n",
|
||||
"\n",
|
||||
" if self.response_count < len(self.predefined_responses):\n",
|
||||
" response = self.predefined_responses[self.response_count]\n",
|
||||
" self.response_count += 1\n",
|
||||
" print(f\"👤 User: {response}\")\n",
|
||||
" return response\n",
|
||||
" else:\n",
|
||||
" print(\"👤 User: TERMINATE\")\n",
|
||||
" return \"TERMINATE\"\n",
|
||||
"\n",
|
||||
" async def a_receive(\n",
|
||||
" self,\n",
|
||||
" message: Union[Dict, str],\n",
|
||||
" sender,\n",
|
||||
" request_reply: Optional[bool] = None,\n",
|
||||
" silent: Optional[bool] = False,\n",
|
||||
" ):\n",
|
||||
" await super().a_receive(message, sender, request_reply, silent)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "b792d207",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Define an AssistantAgent that simulates async processing before responding\n",
|
||||
"class AsyncAssistantAgent(AssistantAgent):\n",
|
||||
" async def a_receive(\n",
|
||||
" self,\n",
|
||||
" message: Union[Dict, str],\n",
|
||||
" sender,\n",
|
||||
" request_reply: Optional[bool] = None,\n",
|
||||
" silent: Optional[bool] = False,\n",
|
||||
" ):\n",
|
||||
" # Simulate async processing before responding\n",
|
||||
" await simulate_async_processing(\"Analyzing request and preparing response\", 0.5)\n",
|
||||
" await super().a_receive(message, sender, request_reply, silent)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "7f8c6c50",
|
||||
"metadata": {
|
||||
"lines_to_next_cell": 1
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"async def main():\n",
|
||||
" print(\"🚀 Starting AG2 Async Demo\")\n",
|
||||
"\n",
|
||||
" # Create agents with automated behavior\n",
|
||||
" user_proxy = AutomatedUserProxyAgent(\n",
|
||||
" name=\"hiring_manager\",\n",
|
||||
" human_input_mode=\"NEVER\", # No human input required\n",
|
||||
" max_consecutive_auto_reply=3,\n",
|
||||
" code_execution_config=False,\n",
|
||||
" is_termination_msg=lambda msg: \"TERMINATE\" in str(msg.get(\"content\", \"\")),\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" assistant = AsyncAssistantAgent(\n",
|
||||
" name=\"interview_consultant\",\n",
|
||||
" system_message=\"\"\"You are an expert interview consultant. When given interview topics, \n",
|
||||
" you create thoughtful, relevant questions. You ask for feedback and incorporate it.\n",
|
||||
" When the user is satisfied with the questions, end with 'TERMINATE'.\"\"\",\n",
|
||||
" llm_config={\"config_list\": [{\"model\": \"gpt-4o-mini\", \"api_key\": os.environ.get(\"OPENAI_API_KEY\")}]},\n",
|
||||
" is_termination_msg=lambda msg: \"TERMINATE\" in str(msg.get(\"content\", \"\")),\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" try:\n",
|
||||
" print(\"🤖 Initiating automated conversation...\")\n",
|
||||
" # Start the automated chat between the user and assistant\n",
|
||||
" await user_proxy.a_initiate_chat(\n",
|
||||
" assistant,\n",
|
||||
" message=\"\"\"I need help creating interview questions for these topics:\n",
|
||||
" - Resume Review\n",
|
||||
" - Technical Skills Assessment \n",
|
||||
" - Project Discussion\n",
|
||||
" - Job Role Expectations\n",
|
||||
" - Closing Remarks\n",
|
||||
" \n",
|
||||
" Please create 2-3 questions for each topic.\"\"\",\n",
|
||||
" max_turns=6,\n",
|
||||
" )\n",
|
||||
" except Exception as e:\n",
|
||||
" print(f\"\\n❌ Error occurred: {e}\")\n",
|
||||
" finally:\n",
|
||||
" agentops.end_trace(tracer, end_state=\"Success\")\n",
|
||||
"\n",
|
||||
" print(\"\\n🎉 Demo completed successfully!\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "e4520d6f",
|
||||
"metadata": {
|
||||
"lines_to_next_cell": 2
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Run the main async demo\n",
|
||||
"nest_asyncio.apply()\n",
|
||||
"asyncio.run(main())"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"jupytext": {
|
||||
"cell_metadata_filter": "-all",
|
||||
"main_language": "python",
|
||||
"notebook_metadata_filter": "-all"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
# 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.
|
||||
|
||||
# %pip install agentops
|
||||
# %pip install ag2
|
||||
# %pip install nest-asyncio
|
||||
|
||||
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,
|
||||
)
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
agentops.validate_trace_spans(trace_context=tracer)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
|
||||
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())
|
||||
@@ -0,0 +1,159 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "cdf47b93",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"AG2 Multi-Agent Group Chat Example with AgentOps Integration\n",
|
||||
"\n",
|
||||
"This script demonstrates how to orchestrate a group of specialized AI agents collaborating on a task using AG2 and AgentOps.\n",
|
||||
"\n",
|
||||
"Overview\n",
|
||||
"This example shows how to:\n",
|
||||
"1. Initialize multiple AG2 agents with different roles (researcher, coder, critic, and user proxy)\n",
|
||||
"2. Set up a group chat where agents interact and collaborate to solve a problem\n",
|
||||
"3. Simulate a human participant using a user proxy agent\n",
|
||||
"4. Limit the number of chat rounds and user turns for controlled execution\n",
|
||||
"5. Track and monitor all agent interactions and LLM calls using AgentOps for full traceability\n",
|
||||
"\n",
|
||||
"By using group chat and specialized agents, you can model real-world collaborative workflows, automate complex problem solving, and analyze agent behavior in detail."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "49497415",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%pip install agentops\n",
|
||||
"%pip install ag2\n",
|
||||
"%pip install nest-asyncio"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "5e8f3321",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"import agentops\n",
|
||||
"import autogen"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "017dd674",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Initialize AgentOps for tracing and monitoring\n",
|
||||
"agentops.init(auto_start_session=False, trace_name=\"AG2 Group Chat\")\n",
|
||||
"tracer = agentops.start_trace(trace_name=\"AG2 Group Chat\", tags=[\"ag2-group-chat\", \"agentops-example\"])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "d23930de",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Configure your AG2 agents with model and API key\n",
|
||||
"config_list = [\n",
|
||||
" {\n",
|
||||
" \"model\": \"gpt-4\",\n",
|
||||
" \"api_key\": os.getenv(\"OPENAI_API_KEY\"),\n",
|
||||
" }\n",
|
||||
"]\n",
|
||||
"llm_config = {\n",
|
||||
" \"config_list\": config_list,\n",
|
||||
" \"timeout\": 60,\n",
|
||||
"}"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "eeee05a1",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Create a team of agents with specialized roles\n",
|
||||
"researcher = autogen.AssistantAgent(\n",
|
||||
" name=\"researcher\",\n",
|
||||
" llm_config=llm_config,\n",
|
||||
" system_message=\"You are a researcher who specializes in finding accurate information.\",\n",
|
||||
")\n",
|
||||
"coder = autogen.AssistantAgent(\n",
|
||||
" name=\"coder\", llm_config=llm_config, system_message=\"You are an expert programmer who writes clean, efficient code.\"\n",
|
||||
")\n",
|
||||
"critic = autogen.AssistantAgent(\n",
|
||||
" name=\"critic\", llm_config=llm_config, system_message=\"You review solutions and provide constructive feedback.\"\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "abd6720b",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# The user proxy agent simulates a human participant in the chat\n",
|
||||
"user_proxy = autogen.UserProxyAgent(\n",
|
||||
" name=\"user_proxy\",\n",
|
||||
" human_input_mode=\"TERMINATE\", # Stops when a message ends with 'TERMINATE'\n",
|
||||
" max_consecutive_auto_reply=10, # Limits auto-replies before requiring termination\n",
|
||||
" is_termination_msg=lambda x: x.get(\"content\", \"\").rstrip().endswith(\"TERMINATE\"),\n",
|
||||
" code_execution_config={\"last_n_messages\": 3, \"work_dir\": \"coding\"},\n",
|
||||
")\n",
|
||||
"# Create a group chat with all agents and set a maximum number of rounds\n",
|
||||
"groupchat = autogen.GroupChat(\n",
|
||||
" agents=[user_proxy, researcher, coder, critic],\n",
|
||||
" messages=[],\n",
|
||||
" max_round=4, # Limits the total number of chat rounds\n",
|
||||
")\n",
|
||||
"# The manager coordinates the group chat and LLM configuration\n",
|
||||
"manager = autogen.GroupChatManager(groupchat=groupchat, llm_config=llm_config)\n",
|
||||
"# Start the group chat with an initial task and a maximum number of user turns\n",
|
||||
"user_proxy.initiate_chat(\n",
|
||||
" manager,\n",
|
||||
" message=\"Create a Python program to analyze sentiment from Twitter data.\",\n",
|
||||
" max_turns=2, # Limits the number of user turns\n",
|
||||
")\n",
|
||||
"agentops.end_trace(tracer, end_state=\"Success\")"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"jupytext": {
|
||||
"cell_metadata_filter": "-all",
|
||||
"main_language": "python",
|
||||
"notebook_metadata_filter": "-all"
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": ".venv",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.13"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
# AG2 Multi-Agent Group Chat Example with AgentOps Integration
|
||||
#
|
||||
# This script demonstrates how to orchestrate a group of specialized AI agents collaborating on a task using AG2 and AgentOps.
|
||||
#
|
||||
# Overview
|
||||
# This example shows how to:
|
||||
# 1. Initialize multiple AG2 agents with different roles (researcher, coder, critic, and user proxy)
|
||||
# 2. Set up a group chat where agents interact and collaborate to solve a problem
|
||||
# 3. Simulate a human participant using a user proxy agent
|
||||
# 4. Limit the number of chat rounds and user turns for controlled execution
|
||||
# 5. Track and monitor all agent interactions and LLM calls using AgentOps for full traceability
|
||||
#
|
||||
# By using group chat and specialized agents, you can model real-world collaborative workflows, automate complex problem solving, and analyze agent behavior in detail.
|
||||
|
||||
# %pip install agentops
|
||||
# %pip install ag2
|
||||
# %pip install nest-asyncio
|
||||
|
||||
import os
|
||||
import agentops
|
||||
import autogen
|
||||
|
||||
# Initialize AgentOps for tracing and monitoring
|
||||
agentops.init(auto_start_session=False, trace_name="AG2 Group Chat")
|
||||
tracer = agentops.start_trace(trace_name="AG2 Group Chat", tags=["ag2-group-chat", "agentops-example"])
|
||||
|
||||
# Configure your AG2 agents with model and API key
|
||||
config_list = [
|
||||
{
|
||||
"model": "gpt-4",
|
||||
"api_key": os.getenv("OPENAI_API_KEY"),
|
||||
}
|
||||
]
|
||||
llm_config = {
|
||||
"config_list": config_list,
|
||||
"timeout": 60,
|
||||
}
|
||||
|
||||
# Create a team of agents with specialized roles
|
||||
researcher = autogen.AssistantAgent(
|
||||
name="researcher",
|
||||
llm_config=llm_config,
|
||||
system_message="You are a researcher who specializes in finding accurate information.",
|
||||
)
|
||||
coder = autogen.AssistantAgent(
|
||||
name="coder", llm_config=llm_config, system_message="You are an expert programmer who writes clean, efficient code."
|
||||
)
|
||||
critic = autogen.AssistantAgent(
|
||||
name="critic", llm_config=llm_config, system_message="You review solutions and provide constructive feedback."
|
||||
)
|
||||
|
||||
# The user proxy agent simulates a human participant in the chat
|
||||
user_proxy = autogen.UserProxyAgent(
|
||||
name="user_proxy",
|
||||
human_input_mode="TERMINATE", # Stops when a message ends with 'TERMINATE'
|
||||
max_consecutive_auto_reply=10, # Limits auto-replies before requiring termination
|
||||
is_termination_msg=lambda x: x.get("content", "").rstrip().endswith("TERMINATE"),
|
||||
code_execution_config={"last_n_messages": 3, "work_dir": "coding"},
|
||||
)
|
||||
# Create a group chat with all agents and set a maximum number of rounds
|
||||
groupchat = autogen.GroupChat(
|
||||
agents=[user_proxy, researcher, coder, critic],
|
||||
messages=[],
|
||||
max_round=4, # Limits the total number of chat rounds
|
||||
)
|
||||
# The manager coordinates the group chat and LLM configuration
|
||||
manager = autogen.GroupChatManager(groupchat=groupchat, llm_config=llm_config)
|
||||
# Start the group chat with an initial task and a maximum number of user turns
|
||||
user_proxy.initiate_chat(
|
||||
manager,
|
||||
message="Create a Python program to analyze sentiment from Twitter data.",
|
||||
max_turns=2, # Limits the number of user turns
|
||||
)
|
||||
agentops.end_trace(tracer, end_state="Success")
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
agentops.validate_trace_spans(trace_context=tracer)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
@@ -0,0 +1,4 @@
|
||||
ag2
|
||||
nest-asyncio
|
||||
wikipedia-api
|
||||
ag2[openai]
|
||||
@@ -0,0 +1,207 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# AG2 Wikipedia Search Tools\n",
|
||||
"\n",
|
||||
"AG2's Wikipedia search integration allows agents to perform searches in Wikipedia and retrieve the relevant pages. Follow these steps to integrate Wikipedia Search Tools with AG2 Agents.\n",
|
||||
"\n",
|
||||
"Two tools are available for your AG2 agents:\n",
|
||||
"- `WikipediaQueryRunTool` executes Wikipedia queries and returning summarized page results\n",
|
||||
"- `WikipediaPageLoadTool` loads the contents of a Wikipedia page together with its metadata (for detailed data extraction)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Install required dependencies\n",
|
||||
"%pip install agentops\n",
|
||||
"%pip install \"ag2[wikipedia, openai]\""
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Imports"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"from dotenv import load_dotenv\n",
|
||||
"import agentops\n",
|
||||
"from autogen import AssistantAgent, LLMConfig, UserProxyAgent\n",
|
||||
"from autogen.tools.experimental import WikipediaPageLoadTool, WikipediaQueryRunTool"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"load_dotenv()\n",
|
||||
"os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\", \"your_api_key_here\")\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\", \"your_openai_api_key_here\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Agent Configuration\n",
|
||||
"\n",
|
||||
"Configure an assistant agent and user proxy to be used for LLM recommendation and execution respectively.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"agentops.init(auto_start_session=False)\n",
|
||||
"tracer = agentops.start_trace(\n",
|
||||
" trace_name=\"AG2 Wikipedia Search Tools\", tags=[\"ag2-wikipedia-search-tools\", \"agentops-example\"]\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"config_list = LLMConfig(api_type=\"openai\", model=\"gpt-4o-mini\")\n",
|
||||
"\n",
|
||||
"assistant = AssistantAgent(\n",
|
||||
" name=\"assistant\",\n",
|
||||
" llm_config=config_list,\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"user_proxy = UserProxyAgent(name=\"user_proxy\", human_input_mode=\"NEVER\", code_execution_config=False)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Query Tool Setup"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"wikipedia_query_tool = WikipediaQueryRunTool()\n",
|
||||
"\n",
|
||||
"# Register the tool for LLM recommendation (assistant agent) and execution (user_proxy agent).\n",
|
||||
"wikipedia_query_tool.register_for_llm(assistant)\n",
|
||||
"wikipedia_query_tool.register_for_execution(user_proxy)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Start the Conversation\n",
|
||||
"\n",
|
||||
"With the setup complete, you can now use the assistant to search Wikipedia."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"response = user_proxy.initiate_chat(\n",
|
||||
" recipient=assistant,\n",
|
||||
" message=\"Who is the father of AI?\",\n",
|
||||
" max_turns=2,\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Page Load Tool Setup"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Start by removing the Query tool so we ensure our agent uses the Page Load tool\n",
|
||||
"assistant.remove_tool_for_llm(wikipedia_query_tool)\n",
|
||||
"\n",
|
||||
"# Create the Page Load tool\n",
|
||||
"wikipedia_page_load_tool = WikipediaPageLoadTool()\n",
|
||||
"\n",
|
||||
"# Register the tool for LLM recommendation (assistant agent) and execution (user_proxy agent).\n",
|
||||
"wikipedia_page_load_tool.register_for_llm(assistant)\n",
|
||||
"wikipedia_page_load_tool.register_for_execution(user_proxy)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"response = user_proxy.initiate_chat(\n",
|
||||
" recipient=assistant,\n",
|
||||
" message=\"What's the population of Australia?\",\n",
|
||||
" max_turns=2,\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"agentops.end_trace(tracer, end_state=\"Success\")"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"front_matter": {
|
||||
"description": "Perplexity Search Integration with AG2",
|
||||
"tags": [
|
||||
"tools",
|
||||
"perplexity",
|
||||
"web-search",
|
||||
"search"
|
||||
]
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "agentops (3.11.11)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.11"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 2
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
# AG2 Wikipedia Search Tools
|
||||
#
|
||||
# AG2's Wikipedia search integration allows agents to perform searches in Wikipedia and retrieve the relevant pages. Follow these steps to integrate Wikipedia Search Tools with AG2 Agents.
|
||||
#
|
||||
# Two tools are available for your AG2 agents:
|
||||
# - `WikipediaQueryRunTool` executes Wikipedia queries and returning summarized page results
|
||||
# - `WikipediaPageLoadTool` loads the contents of a Wikipedia page together with its metadata (for detailed data extraction)
|
||||
# # Install required dependencies
|
||||
# %pip install agentops
|
||||
# %pip install "ag2[wikipedia, openai]"
|
||||
# ### Imports
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
import agentops
|
||||
from autogen import AssistantAgent, LLMConfig, UserProxyAgent
|
||||
from autogen.tools.experimental import WikipediaPageLoadTool, WikipediaQueryRunTool
|
||||
|
||||
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")
|
||||
|
||||
# ### Agent Configuration
|
||||
#
|
||||
# Configure an assistant agent and user proxy to be used for LLM recommendation and execution respectively.
|
||||
agentops.init(auto_start_session=False, trace_name="AG2 Wikipedia Search Tools")
|
||||
tracer = agentops.start_trace(
|
||||
trace_name="AG2 Wikipedia Search Tools", tags=["ag2-wikipedia-search-tools", "agentops-example"]
|
||||
)
|
||||
|
||||
config_list = LLMConfig(api_type="openai", model="gpt-4o-mini")
|
||||
|
||||
assistant = AssistantAgent(
|
||||
name="assistant",
|
||||
llm_config=config_list,
|
||||
)
|
||||
|
||||
user_proxy = UserProxyAgent(name="user_proxy", human_input_mode="NEVER", code_execution_config=False)
|
||||
|
||||
# ### Query Tool Setup
|
||||
wikipedia_query_tool = WikipediaQueryRunTool()
|
||||
|
||||
# Register the tool for LLM recommendation (assistant agent) and execution (user_proxy agent).
|
||||
wikipedia_query_tool.register_for_llm(assistant)
|
||||
wikipedia_query_tool.register_for_execution(user_proxy)
|
||||
|
||||
# ### Start the Conversation
|
||||
#
|
||||
# With the setup complete, you can now use the assistant to search Wikipedia.
|
||||
response = user_proxy.initiate_chat(
|
||||
recipient=assistant,
|
||||
message="Who is the father of AI?",
|
||||
max_turns=2,
|
||||
)
|
||||
|
||||
# ## Page Load Tool Setup
|
||||
# Start by removing the Query tool so we ensure our agent uses the Page Load tool
|
||||
assistant.remove_tool_for_llm(wikipedia_query_tool)
|
||||
|
||||
# Create the Page Load tool
|
||||
wikipedia_page_load_tool = WikipediaPageLoadTool()
|
||||
|
||||
# Register the tool for LLM recommendation (assistant agent) and execution (user_proxy agent).
|
||||
wikipedia_page_load_tool.register_for_llm(assistant)
|
||||
wikipedia_page_load_tool.register_for_execution(user_proxy)
|
||||
|
||||
response = user_proxy.initiate_chat(
|
||||
recipient=assistant,
|
||||
message="What's the population of Australia?",
|
||||
max_turns=2,
|
||||
)
|
||||
|
||||
agentops.end_trace(tracer, end_state="Success")
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
agentops.validate_trace_spans(trace_context=tracer)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
@@ -0,0 +1,167 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "a35d851b",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"\n",
|
||||
"# Async Operations with Agno\n",
|
||||
"\n",
|
||||
"This notebook demonstrates how to leverage asynchronous programming with Agno agents to execute multiple AI tasks concurrently, significantly improving performance and efficiency.\n",
|
||||
"\n",
|
||||
"## Overview\n",
|
||||
"This notebook demonstrates a practical example of concurrent AI operations where we:\n",
|
||||
"\n",
|
||||
"1. **Initialize an Agno agent** with OpenAI's GPT-4o-mini model\n",
|
||||
"2. **Create multiple async tasks** that query the AI about different programming languages\n",
|
||||
"3. **Compare performance** between concurrent and sequential execution\n",
|
||||
"\n",
|
||||
"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.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "75767381",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Install the required dependencies:\n",
|
||||
"%pip install agentops\n",
|
||||
"%pip install agno\n",
|
||||
"%pip install python-dotenv"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "fe7d8b83",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"import asyncio\n",
|
||||
"from dotenv import load_dotenv\n",
|
||||
"\n",
|
||||
"import agentops\n",
|
||||
"from agno.agent import Agent\n",
|
||||
"from agno.models.openai import OpenAIChat"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "c6653555",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"load_dotenv()\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\", \"your_openai_api_key_here\")\n",
|
||||
"os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\", \"your_agentops_api_key_here\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "ac01eb8a",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"agentops.init(auto_start_session=False, tags=[\"agno-example\", \"async-operation\"])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "ca0f1a8a",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"async def demonstrate_async_operations():\n",
|
||||
" \"\"\"\n",
|
||||
" Demonstrate concurrent execution of multiple AI agent tasks.\n",
|
||||
"\n",
|
||||
" This function creates multiple async tasks that execute concurrently rather than sequentially.\n",
|
||||
" Each task makes an independent API call to the AI model, and asyncio.gather()\n",
|
||||
" waits for all tasks to complete before returning results.\n",
|
||||
"\n",
|
||||
" Performance benefit: Instead of 3 sequential calls taking ~90 seconds total,\n",
|
||||
" concurrent execution typically completes in ~30 seconds.\n",
|
||||
" \"\"\"\n",
|
||||
" tracer = agentops.start_trace(\n",
|
||||
" trace_name=\"Agno Async Operations Example\",\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" try:\n",
|
||||
" # Initialize AI agent with specified model\n",
|
||||
" agent = Agent(model=OpenAIChat(id=\"gpt-4o-mini\"))\n",
|
||||
"\n",
|
||||
" async def task1():\n",
|
||||
" \"\"\"Query AI about Python programming language.\"\"\"\n",
|
||||
" response = await agent.arun(\"Explain Python programming language in one paragraph\")\n",
|
||||
" return f\"Python: {response.content}\"\n",
|
||||
"\n",
|
||||
" async def task2():\n",
|
||||
" \"\"\"Query AI about JavaScript programming language.\"\"\"\n",
|
||||
" response = await agent.arun(\"Explain JavaScript programming language in one paragraph\")\n",
|
||||
" return f\"JavaScript: {response.content}\"\n",
|
||||
"\n",
|
||||
" async def task3():\n",
|
||||
" \"\"\"Query AI for comparison between programming languages.\"\"\"\n",
|
||||
" response = await agent.arun(\"Compare Python and JavaScript briefly\")\n",
|
||||
" return f\"Comparison: {response.content}\"\n",
|
||||
"\n",
|
||||
" # Execute all tasks concurrently using asyncio.gather()\n",
|
||||
" results = await asyncio.gather(task1(), task2(), task3())\n",
|
||||
"\n",
|
||||
" for i, result in enumerate(results, 1):\n",
|
||||
" print(f\"\\nTask {i} Result:\")\n",
|
||||
" print(result)\n",
|
||||
" print(\"-\" * 50)\n",
|
||||
"\n",
|
||||
" agentops.end_trace(tracer, end_state=\"Success\")\n",
|
||||
"\n",
|
||||
" except Exception as e:\n",
|
||||
" print(f\"An error occurred: {e}\")\n",
|
||||
" agentops.end_trace(tracer, end_state=\"Error\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "0aa21331",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"await demonstrate_async_operations()"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"jupytext": {
|
||||
"cell_metadata_filter": "-all",
|
||||
"main_language": "python",
|
||||
"notebook_metadata_filter": "-all"
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "agentops (3.11.11)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.11"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
"""
|
||||
# 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.
|
||||
"""
|
||||
|
||||
import os
|
||||
import asyncio
|
||||
from dotenv import load_dotenv
|
||||
import agentops
|
||||
from agno.agent import Agent
|
||||
from agno.models.openai import OpenAIChat
|
||||
|
||||
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")
|
||||
|
||||
agentops.init(auto_start_session=False, trace_name="Agno Async Operations", tags=["agno-example", "async-operation"])
|
||||
|
||||
|
||||
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")
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
agentops.validate_trace_spans(trace_context=tracer)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(demonstrate_async_operations())
|
||||
@@ -0,0 +1,216 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "8b2111ae",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Basic Agents and Teams with Agno\n",
|
||||
"\n",
|
||||
"This example demonstrates the fundamentals of creating AI agents and organizing them into collaborative teams using the Agno framework.\n",
|
||||
"\n",
|
||||
"## Overview\n",
|
||||
"\n",
|
||||
"In this example, you'll learn how to:\n",
|
||||
"- **Create specialized AI agents** with specific roles and expertise\n",
|
||||
"- **Organize agents into teams** for collaborative problem-solving\n",
|
||||
"- **Use coordination modes** for effective agent communication\n",
|
||||
"- **Monitor agent interactions** with AgentOps integration\n",
|
||||
"\n",
|
||||
"## Key Concepts\n",
|
||||
"\n",
|
||||
"### Agents\n",
|
||||
"Individual AI entities with specific roles and capabilities. Each agent can be assigned a particular area of expertise, making them specialists in their domain.\n",
|
||||
"\n",
|
||||
"### Teams\n",
|
||||
"Collections of agents that work together to solve complex tasks. Teams can coordinate their responses, share information, and delegate tasks based on each agent's expertise.\n",
|
||||
"\n",
|
||||
"### Coordination Modes\n",
|
||||
"Different strategies for how agents within a team interact and collaborate. The \"coordinate\" mode enables intelligent task routing and information sharing."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "d087e416",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Install the required dependencies\n",
|
||||
"%pip install agentops\n",
|
||||
"%pip install agno\n",
|
||||
"%pip install python-dotenv"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "39ad00cb",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"from dotenv import load_dotenv\n",
|
||||
"\n",
|
||||
"import agentops\n",
|
||||
"from agno.agent import Agent\n",
|
||||
"from agno.team import Team\n",
|
||||
"from agno.models.openai import OpenAIChat"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "f733e281",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"load_dotenv()\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\", \"your_openai_api_key_here\")\n",
|
||||
"os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\", \"your_agentops_api_key_here\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "fb37819a",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"agentops.init(auto_start_session=False, tags=[\"agno-example\", \"basics\", \"agents-and-teams\"])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "e954b898",
|
||||
"metadata": {
|
||||
"vscode": {
|
||||
"languageId": "raw"
|
||||
}
|
||||
},
|
||||
"source": [
|
||||
"## Creating Agents and Teams\n",
|
||||
"\n",
|
||||
"Now let's create our specialized agents and organize them into a collaborative team:\n",
|
||||
"\n",
|
||||
"### Step 1: Create Individual Agents\n",
|
||||
"We'll create two agents with different specializations:\n",
|
||||
"- **News Agent**: Specializes in gathering and analyzing news\n",
|
||||
"- **Weather Agent**: Specializes in weather forecasting and analysis\n",
|
||||
"\n",
|
||||
"### Step 2: Form a Team\n",
|
||||
"We'll combine these agents into a team using the \"coordinate\" mode, which enables:\n",
|
||||
"- Intelligent task routing based on agent expertise\n",
|
||||
"- Information sharing between agents\n",
|
||||
"- Collaborative problem-solving\n",
|
||||
"\n",
|
||||
"### Step 3: Execute Tasks\n",
|
||||
"The team will automatically delegate tasks to the most appropriate agent(s) based on the query.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "c12702d0",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Here's the code to implement this:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "f872be2e",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def demonstrate_basic_agents():\n",
|
||||
" \"\"\"\n",
|
||||
" Demonstrate basic agent creation and team coordination.\n",
|
||||
"\n",
|
||||
" This function shows how to:\n",
|
||||
" 1. Create specialized agents with specific roles\n",
|
||||
" 2. Organize agents into a team\n",
|
||||
" 3. Use the team to solve tasks that require multiple perspectives\n",
|
||||
" \"\"\"\n",
|
||||
" tracer = agentops.start_trace(\n",
|
||||
" trace_name=\"Agno Basic Agents and Teams Demonstration\",\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" try:\n",
|
||||
" # Create individual agents with specific roles\n",
|
||||
" # Each agent has a name and a role that defines its expertise\n",
|
||||
"\n",
|
||||
" # News Agent: Specializes in gathering and analyzing news information\n",
|
||||
" news_agent = Agent(\n",
|
||||
" name=\"News Agent\", role=\"Get the latest news and provide news analysis\", model=OpenAIChat(id=\"gpt-4o-mini\")\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" # Weather Agent: Specializes in weather forecasting and analysis\n",
|
||||
" weather_agent = Agent(\n",
|
||||
" name=\"Weather Agent\",\n",
|
||||
" role=\"Get weather forecasts and provide weather analysis\",\n",
|
||||
" model=OpenAIChat(id=\"gpt-4o-mini\"),\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" # Create a team with coordination mode\n",
|
||||
" # The \"coordinate\" mode allows agents to work together and share information\n",
|
||||
" team = Team(\n",
|
||||
" name=\"News and Weather Team\",\n",
|
||||
" mode=\"coordinate\", # Agents will coordinate their responses\n",
|
||||
" members=[news_agent, weather_agent],\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" # Run a task that requires team coordination\n",
|
||||
" # The team will automatically determine which agent(s) should respond\n",
|
||||
" response = team.run(\"What is the weather in Tokyo?\")\n",
|
||||
"\n",
|
||||
" print(\"\\nTeam Response:\")\n",
|
||||
" print(\"-\" * 60)\n",
|
||||
" print(f\"{response.content}\")\n",
|
||||
" print(\"-\" * 60)\n",
|
||||
"\n",
|
||||
" agentops.end_trace(tracer, end_state=\"Success\")\n",
|
||||
"\n",
|
||||
" except Exception as e:\n",
|
||||
" print(f\"An error occurred: {e}\")\n",
|
||||
" agentops.end_trace(tracer, end_state=\"Error\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "ca13c9b0",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"demonstrate_basic_agents()"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"jupytext": {
|
||||
"cell_metadata_filter": "-all",
|
||||
"main_language": "python",
|
||||
"notebook_metadata_filter": "-all"
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "agentops (3.11.11)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.11"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
"""
|
||||
# Basic Agents and Teams with Agno
|
||||
|
||||
This example demonstrates the fundamentals of creating AI agents and organizing them into collaborative teams using the Agno framework.
|
||||
|
||||
## Overview
|
||||
|
||||
In this example, you'll learn how to:
|
||||
- **Create specialized AI agents** with specific roles and expertise
|
||||
- **Organize agents into teams** for collaborative problem-solving
|
||||
- **Use coordination modes** for effective agent communication
|
||||
- **Monitor agent interactions** with AgentOps integration
|
||||
|
||||
## Key Concepts
|
||||
|
||||
### Agents
|
||||
Individual AI entities with specific roles and capabilities. Each agent can be assigned a particular area of expertise, making them specialists in their domain.
|
||||
|
||||
### Teams
|
||||
Collections of agents that work together to solve complex tasks. Teams can coordinate their responses, share information, and delegate tasks based on each agent's expertise.
|
||||
|
||||
### Coordination Modes
|
||||
Different strategies for how agents within a team interact and collaborate. The "coordinate" mode enables intelligent task routing and information sharing.
|
||||
"""
|
||||
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
import agentops
|
||||
from agno.agent import Agent
|
||||
from agno.team import Team
|
||||
from agno.models.openai import OpenAIChat
|
||||
|
||||
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")
|
||||
|
||||
agentops.init(
|
||||
auto_start_session=False, trace_name="Agno Basic Agents", tags=["agno-example", "basics", "agents-and-teams"]
|
||||
)
|
||||
|
||||
|
||||
def demonstrate_basic_agents():
|
||||
"""
|
||||
Demonstrate basic agent creation and team coordination.
|
||||
|
||||
This function shows how to:
|
||||
1. Create specialized agents with specific roles
|
||||
2. Organize agents into a team
|
||||
3. Use the team to solve tasks that require multiple perspectives
|
||||
"""
|
||||
tracer = agentops.start_trace(trace_name="Agno Basic Agents and Teams Demonstration")
|
||||
|
||||
try:
|
||||
# Create individual agents with specific roles
|
||||
# Each agent has a name and a role that defines its expertise
|
||||
|
||||
# News Agent: Specializes in gathering and analyzing news information
|
||||
news_agent = Agent(
|
||||
name="News Agent", role="Get the latest news and provide news analysis", model=OpenAIChat(id="gpt-4o-mini")
|
||||
)
|
||||
|
||||
# Weather Agent: Specializes in weather forecasting and analysis
|
||||
weather_agent = Agent(
|
||||
name="Weather Agent",
|
||||
role="Get weather forecasts and provide weather analysis",
|
||||
model=OpenAIChat(id="gpt-4o-mini"),
|
||||
)
|
||||
|
||||
# Create a team with coordination mode
|
||||
# The "coordinate" mode allows agents to work together and share information
|
||||
team = Team(
|
||||
name="News and Weather Team",
|
||||
mode="coordinate", # Agents will coordinate their responses
|
||||
members=[news_agent, weather_agent],
|
||||
)
|
||||
|
||||
# Run a task that requires team coordination
|
||||
# The team will automatically determine which agent(s) should respond
|
||||
response = team.run("What is the weather in Tokyo?")
|
||||
|
||||
print("\nTeam Response:")
|
||||
print("-" * 60)
|
||||
print(f"{response.content}")
|
||||
print("-" * 60)
|
||||
|
||||
agentops.end_trace(tracer, end_state="Success")
|
||||
|
||||
except Exception as e:
|
||||
print(f"An error occurred: {e}")
|
||||
agentops.end_trace(tracer, end_state="Error")
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
agentops.validate_trace_spans(trace_context=tracer)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
demonstrate_basic_agents()
|
||||
@@ -0,0 +1,302 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "e78c48e2",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"\n",
|
||||
"Collaborative Research Team with Agno\n",
|
||||
"--------------------------------------\n",
|
||||
"\n",
|
||||
"This example demonstrates how to create a sophisticated research team with multiple specialized agents,\n",
|
||||
"each equipped with different tools and expertise. The team collaborates to research topics from\n",
|
||||
"multiple perspectives, providing comprehensive insights.\n",
|
||||
"\n",
|
||||
"**Overview:**\n",
|
||||
"\n",
|
||||
"This example creates a research team consisting of four specialized agents:\n",
|
||||
"\n",
|
||||
"1. **Reddit Researcher**\n",
|
||||
" - Focus: Community discussions and user experiences\n",
|
||||
" - Tools: Google Search (to find Reddit discussions)\n",
|
||||
" - Expertise: Analyzing user opinions, practical advice, and real-world experiences\n",
|
||||
" - Role: Provides insights from community perspectives\n",
|
||||
"\n",
|
||||
"2. **HackerNews Researcher**\n",
|
||||
" - Focus: Technical discussions and industry trends\n",
|
||||
" - Tools: HackerNews API\n",
|
||||
" - Expertise: Technical analysis and industry insights\n",
|
||||
" - Role: Provides technical and startup ecosystem perspectives\n",
|
||||
"\n",
|
||||
"3. **Academic Paper Researcher**\n",
|
||||
" - Focus: Scholarly research and evidence-based findings\n",
|
||||
" - Tools: Google Search + Arxiv API\n",
|
||||
" - Expertise: Academic literature and research methodology\n",
|
||||
" - Role: Provides evidence-based academic insights\n",
|
||||
"\n",
|
||||
"4. **Twitter Researcher**\n",
|
||||
" - Focus: Real-time trends and public sentiment\n",
|
||||
" - Tools: DuckDuckGo Search\n",
|
||||
" - Expertise: Current events and public opinion\n",
|
||||
" - Role: Provides real-time social media insights\n",
|
||||
"\n",
|
||||
"**Team Collaboration:**\n",
|
||||
"\n",
|
||||
"- Mode: Collaborative discussion\n",
|
||||
"- Coordination: Team uses GPT-4 for discussion management\n",
|
||||
"- Process: \n",
|
||||
" 1. Each agent researches independently using their tools\n",
|
||||
" 2. Agents share findings and discuss implications\n",
|
||||
" 3. Team works towards consensus through structured discussion\n",
|
||||
" 4. Discussion continues until comprehensive understanding is reached\n",
|
||||
"\n",
|
||||
"**Features Demonstrated:**\n",
|
||||
"\n",
|
||||
"- Creating specialized agents with specific research tools\n",
|
||||
"- Building collaborative teams that discuss and reach consensus\n",
|
||||
"- Using various research tools (Google Search, HackerNews, Arxiv, DuckDuckGo)\n",
|
||||
"- Enabling real-time streaming of agent discussions\n",
|
||||
"- Tracking agent interactions with AgentOps\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "c9f7fb8d",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Install the required dependencies:\n",
|
||||
"%pip install agentops\n",
|
||||
"%pip install agno\n",
|
||||
"%pip install python-dotenv"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "08978603",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"from textwrap import dedent\n",
|
||||
"\n",
|
||||
"import agentops\n",
|
||||
"from agno.agent import Agent\n",
|
||||
"from agno.team import Team\n",
|
||||
"from agno.tools.googlesearch import GoogleSearchTools\n",
|
||||
"from agno.tools.hackernews import HackerNewsTools\n",
|
||||
"from agno.tools.arxiv import ArxivTools\n",
|
||||
"from agno.tools.duckduckgo import DuckDuckGoTools\n",
|
||||
"from agno.models.openai import OpenAIChat\n",
|
||||
"from dotenv import load_dotenv"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "143be722",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Load environment variables\n",
|
||||
"load_dotenv()\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\", \"your_openai_api_key_here\")\n",
|
||||
"os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\", \"your_agentops_api_key_here\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "2e071b24",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Initialize AgentOps for monitoring and analytics\n",
|
||||
"agentops.init(auto_start_session=False, tags=[\"agno-example\", \"research-team\"])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 5,
|
||||
"id": "8eb6fbe2",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def demonstrate_research_team():\n",
|
||||
" \"\"\"\n",
|
||||
" Demonstrate a collaborative research team with multiple specialized agents.\n",
|
||||
"\n",
|
||||
" This function creates a team of researchers, each with:\n",
|
||||
" - Specific expertise and research focus\n",
|
||||
" - Specialized tools for their domain\n",
|
||||
" - Custom instructions for their research approach\n",
|
||||
"\n",
|
||||
" The team collaborates to provide comprehensive research insights.\n",
|
||||
" \"\"\"\n",
|
||||
" tracer = agentops.start_trace(trace_name=\"Agno Research Team Demonstration\")\n",
|
||||
"\n",
|
||||
" try:\n",
|
||||
" print(\"\\n1. Creating specialized research agents...\")\n",
|
||||
"\n",
|
||||
" # Reddit Researcher: Focuses on community discussions and user experiences\n",
|
||||
" reddit_researcher = Agent(\n",
|
||||
" name=\"Reddit Researcher\",\n",
|
||||
" role=\"Research a topic on Reddit\",\n",
|
||||
" model=OpenAIChat(id=\"gpt-4o\"),\n",
|
||||
" tools=[GoogleSearchTools()],\n",
|
||||
" add_name_to_instructions=True,\n",
|
||||
" instructions=dedent(\n",
|
||||
" \"\"\"\n",
|
||||
" You are a Reddit researcher specializing in community insights.\n",
|
||||
" You will be given a topic to research on Reddit.\n",
|
||||
" Your tasks:\n",
|
||||
" - Find the most relevant and popular Reddit posts\n",
|
||||
" - Identify common opinions and experiences from users\n",
|
||||
" - Highlight both positive and negative perspectives\n",
|
||||
" - Focus on practical advice and real-world experiences\n",
|
||||
" \"\"\"\n",
|
||||
" ),\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" # HackerNews Researcher: Focuses on technical discussions and industry trends\n",
|
||||
" hackernews_researcher = Agent(\n",
|
||||
" name=\"HackerNews Researcher\",\n",
|
||||
" model=OpenAIChat(\"gpt-4o\"),\n",
|
||||
" role=\"Research a topic on HackerNews.\",\n",
|
||||
" tools=[HackerNewsTools()],\n",
|
||||
" add_name_to_instructions=True,\n",
|
||||
" instructions=dedent(\n",
|
||||
" \"\"\"\n",
|
||||
" You are a HackerNews researcher specializing in technical insights.\n",
|
||||
" You will be given a topic to research on HackerNews.\n",
|
||||
" Your tasks:\n",
|
||||
" - Find the most relevant technical discussions\n",
|
||||
" - Identify industry trends and expert opinions\n",
|
||||
" - Focus on technical depth and innovation\n",
|
||||
" - Highlight startup and technology perspectives\n",
|
||||
" \"\"\"\n",
|
||||
" ),\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" # Academic Paper Researcher: Focuses on scholarly research and evidence\n",
|
||||
" academic_paper_researcher = Agent(\n",
|
||||
" name=\"Academic Paper Researcher\",\n",
|
||||
" model=OpenAIChat(\"gpt-4o\"),\n",
|
||||
" role=\"Research academic papers and scholarly content\",\n",
|
||||
" tools=[GoogleSearchTools(), ArxivTools()],\n",
|
||||
" add_name_to_instructions=True,\n",
|
||||
" instructions=dedent(\n",
|
||||
" \"\"\"\n",
|
||||
" You are an academic paper researcher specializing in scholarly content.\n",
|
||||
" You will be given a topic to research in academic literature.\n",
|
||||
" Your tasks:\n",
|
||||
" - Find relevant scholarly articles, papers, and academic discussions\n",
|
||||
" - Focus on peer-reviewed content and citations from reputable sources\n",
|
||||
" - Provide brief summaries of key findings and methodologies\n",
|
||||
" - Highlight evidence-based conclusions and research gaps\n",
|
||||
" \"\"\"\n",
|
||||
" ),\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" # Twitter Researcher: Focuses on real-time trends and public sentiment\n",
|
||||
" twitter_researcher = Agent(\n",
|
||||
" name=\"Twitter Researcher\",\n",
|
||||
" model=OpenAIChat(\"gpt-4o\"),\n",
|
||||
" role=\"Research trending discussions and real-time updates\",\n",
|
||||
" tools=[DuckDuckGoTools()],\n",
|
||||
" add_name_to_instructions=True,\n",
|
||||
" instructions=dedent(\n",
|
||||
" \"\"\"\n",
|
||||
" You are a Twitter/X researcher specializing in real-time insights.\n",
|
||||
" You will be given a topic to research on Twitter/X.\n",
|
||||
" Your tasks:\n",
|
||||
" - Find trending discussions and influential voices\n",
|
||||
" - Track real-time updates and breaking news\n",
|
||||
" - Focus on verified accounts and credible sources\n",
|
||||
" - Identify relevant hashtags and ongoing conversations\n",
|
||||
" - Capture public sentiment and viral content\n",
|
||||
" \"\"\"\n",
|
||||
" ),\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" # Create collaborative team with advanced features\n",
|
||||
" agent_team = Team(\n",
|
||||
" name=\"Discussion Team\",\n",
|
||||
" mode=\"collaborate\",\n",
|
||||
" model=OpenAIChat(\"gpt-4o\"),\n",
|
||||
" members=[\n",
|
||||
" reddit_researcher,\n",
|
||||
" hackernews_researcher,\n",
|
||||
" academic_paper_researcher,\n",
|
||||
" twitter_researcher,\n",
|
||||
" ],\n",
|
||||
" instructions=[\n",
|
||||
" \"You are a discussion master coordinating a research team.\",\n",
|
||||
" \"Facilitate productive discussion between all researchers.\",\n",
|
||||
" \"Ensure each researcher contributes their unique perspective.\",\n",
|
||||
" \"Guide the team towards a comprehensive understanding of the topic.\",\n",
|
||||
" \"You have to stop the discussion when you think the team has reached a consensus.\",\n",
|
||||
" ],\n",
|
||||
" success_criteria=\"The team has reached a consensus with insights from all perspectives.\",\n",
|
||||
" enable_agentic_context=True,\n",
|
||||
" add_context=True,\n",
|
||||
" show_tool_calls=True,\n",
|
||||
" markdown=True,\n",
|
||||
" debug_mode=True,\n",
|
||||
" show_members_responses=True,\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" # Stream the team discussion in real-time\n",
|
||||
" agent_team.print_response(\n",
|
||||
" message=\"Start the discussion on the topic: 'What is the best way to learn to code?'\",\n",
|
||||
" stream=True,\n",
|
||||
" stream_intermediate_steps=True,\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" agentops.end_trace(tracer, end_state=\"Success\")\n",
|
||||
"\n",
|
||||
" except Exception:\n",
|
||||
" agentops.end_trace(tracer, end_state=\"Error\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "754f75be",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"demonstrate_research_team()"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"jupytext": {
|
||||
"cell_metadata_filter": "-all",
|
||||
"main_language": "python",
|
||||
"notebook_metadata_filter": "-all"
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "venv",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.9"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
"""
|
||||
Collaborative Research Team with Agno
|
||||
|
||||
This example demonstrates how to create a sophisticated research team with multiple specialized agents,
|
||||
each equipped with different tools and expertise. The team collaborates to research topics from
|
||||
multiple perspectives, providing comprehensive insights.
|
||||
|
||||
Overview:
|
||||
---------
|
||||
This example creates a research team consisting of four specialized agents:
|
||||
|
||||
1. Reddit Researcher
|
||||
- Focus: Community discussions and user experiences
|
||||
- Tools: Google Search (to find Reddit discussions)
|
||||
- Expertise: Analyzing user opinions, practical advice, and real-world experiences
|
||||
- Role: Provides insights from community perspectives
|
||||
|
||||
2. HackerNews Researcher
|
||||
- Focus: Technical discussions and industry trends
|
||||
- Tools: HackerNews API
|
||||
- Expertise: Technical analysis and industry insights
|
||||
- Role: Provides technical and startup ecosystem perspectives
|
||||
|
||||
3. Academic Paper Researcher
|
||||
- Focus: Scholarly research and evidence-based findings
|
||||
- Tools: Google Search + Arxiv API
|
||||
- Expertise: Academic literature and research methodology
|
||||
- Role: Provides evidence-based academic insights
|
||||
|
||||
4. Twitter Researcher
|
||||
- Focus: Real-time trends and public sentiment
|
||||
- Tools: DuckDuckGo Search
|
||||
- Expertise: Current events and public opinion
|
||||
- Role: Provides real-time social media insights
|
||||
|
||||
Team Collaboration:
|
||||
------------------
|
||||
- Mode: Collaborative discussion
|
||||
- Coordination: Team uses GPT-4 for discussion management
|
||||
- Process:
|
||||
1. Each agent researches independently using their tools
|
||||
2. Agents share findings and discuss implications
|
||||
3. Team works towards consensus through structured discussion
|
||||
4. Discussion continues until comprehensive understanding is reached
|
||||
|
||||
Features Demonstrated:
|
||||
---------------------
|
||||
- Creating specialized agents with specific research tools
|
||||
- Building collaborative teams that discuss and reach consensus
|
||||
- Using various research tools (Google Search, HackerNews, Arxiv, DuckDuckGo)
|
||||
- Enabling real-time streaming of agent discussions
|
||||
- Tracking agent interactions with AgentOps
|
||||
"""
|
||||
|
||||
from textwrap import dedent
|
||||
from agno.agent import Agent
|
||||
from agno.team import Team
|
||||
from agno.tools.googlesearch import GoogleSearchTools
|
||||
from agno.tools.hackernews import HackerNewsTools
|
||||
from agno.tools.arxiv import ArxivTools
|
||||
from agno.tools.duckduckgo import DuckDuckGoTools
|
||||
from agno.models.openai import OpenAIChat
|
||||
import agentops
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables
|
||||
load_dotenv()
|
||||
|
||||
# Initialize AgentOps for monitoring and analytics
|
||||
agentops.init(auto_start_session=False, trace_name="Agno Research Team", tags=["agno-example", "research-team"])
|
||||
|
||||
|
||||
def demonstrate_research_team():
|
||||
"""
|
||||
Demonstrate a collaborative research team with multiple specialized agents.
|
||||
|
||||
This function creates a team of researchers, each with:
|
||||
- Specific expertise and research focus
|
||||
- Specialized tools for their domain
|
||||
- Custom instructions for their research approach
|
||||
|
||||
The team collaborates to provide comprehensive research insights.
|
||||
"""
|
||||
tracer = agentops.start_trace(trace_name="Agno Research Team Demonstration")
|
||||
|
||||
try:
|
||||
# Reddit Researcher: Focuses on community discussions and user experiences
|
||||
reddit_researcher = Agent(
|
||||
name="Reddit Researcher",
|
||||
role="Research a topic on Reddit",
|
||||
model=OpenAIChat(id="gpt-4o"),
|
||||
tools=[GoogleSearchTools()],
|
||||
add_name_to_instructions=True,
|
||||
instructions=dedent(
|
||||
"""
|
||||
You are a Reddit researcher specializing in community insights.
|
||||
You will be given a topic to research on Reddit.
|
||||
Your tasks:
|
||||
- Find the most relevant and popular Reddit posts
|
||||
- Identify common opinions and experiences from users
|
||||
- Highlight both positive and negative perspectives
|
||||
- Focus on practical advice and real-world experiences
|
||||
"""
|
||||
),
|
||||
)
|
||||
|
||||
# HackerNews Researcher: Focuses on technical discussions and industry trends
|
||||
hackernews_researcher = Agent(
|
||||
name="HackerNews Researcher",
|
||||
model=OpenAIChat("gpt-4o"),
|
||||
role="Research a topic on HackerNews.",
|
||||
tools=[HackerNewsTools()],
|
||||
add_name_to_instructions=True,
|
||||
instructions=dedent(
|
||||
"""
|
||||
You are a HackerNews researcher specializing in technical insights.
|
||||
You will be given a topic to research on HackerNews.
|
||||
Your tasks:
|
||||
- Find the most relevant technical discussions
|
||||
- Identify industry trends and expert opinions
|
||||
- Focus on technical depth and innovation
|
||||
- Highlight startup and technology perspectives
|
||||
"""
|
||||
),
|
||||
)
|
||||
|
||||
# Academic Paper Researcher: Focuses on scholarly research and evidence
|
||||
academic_paper_researcher = Agent(
|
||||
name="Academic Paper Researcher",
|
||||
model=OpenAIChat("gpt-4o"),
|
||||
role="Research academic papers and scholarly content",
|
||||
tools=[GoogleSearchTools(), ArxivTools()],
|
||||
add_name_to_instructions=True,
|
||||
instructions=dedent(
|
||||
"""
|
||||
You are an academic paper researcher specializing in scholarly content.
|
||||
You will be given a topic to research in academic literature.
|
||||
Your tasks:
|
||||
- Find relevant scholarly articles, papers, and academic discussions
|
||||
- Focus on peer-reviewed content and citations from reputable sources
|
||||
- Provide brief summaries of key findings and methodologies
|
||||
- Highlight evidence-based conclusions and research gaps
|
||||
"""
|
||||
),
|
||||
)
|
||||
|
||||
# Twitter Researcher: Focuses on real-time trends and public sentiment
|
||||
twitter_researcher = Agent(
|
||||
name="Twitter Researcher",
|
||||
model=OpenAIChat("gpt-4o"),
|
||||
role="Research trending discussions and real-time updates",
|
||||
tools=[DuckDuckGoTools()],
|
||||
add_name_to_instructions=True,
|
||||
instructions=dedent(
|
||||
"""
|
||||
You are a Twitter/X researcher specializing in real-time insights.
|
||||
You will be given a topic to research on Twitter/X.
|
||||
Your tasks:
|
||||
- Find trending discussions and influential voices
|
||||
- Track real-time updates and breaking news
|
||||
- Focus on verified accounts and credible sources
|
||||
- Identify relevant hashtags and ongoing conversations
|
||||
- Capture public sentiment and viral content
|
||||
"""
|
||||
),
|
||||
)
|
||||
|
||||
# Create collaborative team with advanced features
|
||||
agent_team = Team(
|
||||
name="Discussion Team",
|
||||
mode="collaborate",
|
||||
model=OpenAIChat("gpt-4o"),
|
||||
members=[
|
||||
reddit_researcher,
|
||||
hackernews_researcher,
|
||||
academic_paper_researcher,
|
||||
twitter_researcher,
|
||||
],
|
||||
instructions=[
|
||||
"You are a discussion master coordinating a research team.",
|
||||
"Facilitate productive discussion between all researchers.",
|
||||
"Ensure each researcher contributes their unique perspective.",
|
||||
"Guide the team towards a comprehensive understanding of the topic.",
|
||||
"You have to stop the discussion when you think the team has reached a consensus.",
|
||||
],
|
||||
success_criteria="The team has reached a consensus with insights from all perspectives.",
|
||||
enable_agentic_context=True,
|
||||
add_context=True,
|
||||
show_tool_calls=True,
|
||||
markdown=True,
|
||||
debug_mode=True,
|
||||
show_members_responses=True,
|
||||
)
|
||||
|
||||
# Stream the team discussion in real-time
|
||||
agent_team.print_response(
|
||||
message="Start the discussion on the topic: 'What is the best way to learn to code?'",
|
||||
stream=True,
|
||||
stream_intermediate_steps=True,
|
||||
)
|
||||
|
||||
agentops.end_trace(tracer, end_state="Success")
|
||||
|
||||
except Exception:
|
||||
agentops.end_trace(tracer, end_state="Error")
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
agentops.validate_trace_spans(trace_context=tracer)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
|
||||
|
||||
demonstrate_research_team()
|
||||
@@ -0,0 +1,246 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "intro-cell",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Tool Integration Example with Agno\n",
|
||||
"\n",
|
||||
"This example demonstrates how to integrate and use various tools with Agno agents,\n",
|
||||
"showing how AgentOps automatically tracks tool usage and agent interactions.\n",
|
||||
"\n",
|
||||
"## Overview\n",
|
||||
"This example demonstrates:\n",
|
||||
"\n",
|
||||
"1. **Using built-in Agno tools** like GoogleSearch, DuckDuckGo, and Arxiv\n",
|
||||
"2. **Creating agents with tools** and seeing how they use them\n",
|
||||
"3. **Tool execution tracking** with AgentOps\n",
|
||||
"4. **Combining multiple tools** for comprehensive research\n",
|
||||
"\n",
|
||||
"This example uses actual Agno components to show real tool integration patterns."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "setup-cell",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Install the required dependencies:\n",
|
||||
"%pip install agentops\n",
|
||||
"%pip install \"agno[tools]\"\n",
|
||||
"%pip install python-dotenv"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "imports-cell",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"from dotenv import load_dotenv\n",
|
||||
"import agentops\n",
|
||||
"from agno.agent import Agent\n",
|
||||
"from agno.models.openai import OpenAIChat\n",
|
||||
"from agno.tools.googlesearch import GoogleSearchTools\n",
|
||||
"from agno.tools.duckduckgo import DuckDuckGoTools\n",
|
||||
"from agno.tools.arxiv import ArxivTools"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "config-cell",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Load environment variables\n",
|
||||
"load_dotenv()\n",
|
||||
"\n",
|
||||
"# Set environment variables if not already set\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\", \"your_openai_api_key_here\")\n",
|
||||
"os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\", \"your_agentops_api_key_here\")\n",
|
||||
"\n",
|
||||
"# Initialize AgentOps\n",
|
||||
"agentops.init(\n",
|
||||
" auto_start_session=False, trace_name=\"Agno Tool Integrations\", tags=[\"agno-tools\", \"tool-integration\", \"demo\"]\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "demo-function",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def demonstrate_tool_integration():\n",
|
||||
" \"\"\"Demonstrate tool integration with Agno agents.\"\"\"\n",
|
||||
" print(\"🚀 Agno Tool Integration Demonstration\")\n",
|
||||
" print(\"=\" * 60)\n",
|
||||
"\n",
|
||||
" # Start AgentOps trace\n",
|
||||
" tracer = agentops.start_trace(trace_name=\"Agno Tool Integration Demo\")\n",
|
||||
"\n",
|
||||
" try:\n",
|
||||
" # Example 1: Single Tool Agent\n",
|
||||
" print(\"\\n📌 Example 1: Agent with Google Search Tool\")\n",
|
||||
" print(\"-\" * 40)\n",
|
||||
"\n",
|
||||
" search_agent = Agent(\n",
|
||||
" name=\"Search Agent\",\n",
|
||||
" role=\"Research information using Google Search\",\n",
|
||||
" model=OpenAIChat(id=\"gpt-4o-mini\"),\n",
|
||||
" tools=[GoogleSearchTools()],\n",
|
||||
" instructions=\"You are a research assistant. Use Google Search to find accurate, up-to-date information.\",\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" response = search_agent.run(\"What are the latest developments in AI agents?\")\n",
|
||||
" print(f\"Search Agent Response:\\n{response.content}\")\n",
|
||||
"\n",
|
||||
" # Example 2: Multi-Tool Agent\n",
|
||||
" print(\"\\n\\n📌 Example 2: Agent with Multiple Tools\")\n",
|
||||
" print(\"-\" * 40)\n",
|
||||
"\n",
|
||||
" research_agent = Agent(\n",
|
||||
" name=\"Research Agent\",\n",
|
||||
" role=\"Comprehensive research using multiple tools\",\n",
|
||||
" model=OpenAIChat(id=\"gpt-4o-mini\"),\n",
|
||||
" tools=[GoogleSearchTools(), ArxivTools(), DuckDuckGoTools()],\n",
|
||||
" instructions=\"\"\"You are a comprehensive research assistant. \n",
|
||||
" Use Google Search for general information, Arxiv for academic papers, \n",
|
||||
" and DuckDuckGo as an alternative search engine. \n",
|
||||
" Provide well-researched, balanced information from multiple sources.\"\"\",\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" response = research_agent.run(\n",
|
||||
" \"Find information about recent advances in tool-use for AI agents. \"\n",
|
||||
" \"Include both academic research and practical implementations.\"\n",
|
||||
" )\n",
|
||||
" print(f\"Research Agent Response:\\n{response.content}\")\n",
|
||||
"\n",
|
||||
" # Example 3: Specialized Tool Usage\n",
|
||||
" print(\"\\n\\n📌 Example 3: Academic Research with Arxiv\")\n",
|
||||
" print(\"-\" * 40)\n",
|
||||
"\n",
|
||||
" academic_agent = Agent(\n",
|
||||
" name=\"Academic Agent\",\n",
|
||||
" role=\"Find and summarize academic papers\",\n",
|
||||
" model=OpenAIChat(id=\"gpt-4o-mini\"),\n",
|
||||
" tools=[ArxivTools()],\n",
|
||||
" instructions=\"You are an academic research assistant. Use Arxiv to find relevant papers and provide concise summaries.\",\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" response = academic_agent.run(\"Find recent papers about tool augmented language models\")\n",
|
||||
" print(f\"Academic Agent Response:\\n{response.content}\")\n",
|
||||
"\n",
|
||||
" # Example 4: Comparing Search Tools\n",
|
||||
" print(\"\\n\\n📌 Example 4: Comparing Different Search Tools\")\n",
|
||||
" print(\"-\" * 40)\n",
|
||||
"\n",
|
||||
" comparison_agent = Agent(\n",
|
||||
" name=\"Comparison Agent\",\n",
|
||||
" role=\"Compare results from different search engines\",\n",
|
||||
" model=OpenAIChat(id=\"gpt-4o-mini\"),\n",
|
||||
" tools=[GoogleSearchTools(), DuckDuckGoTools()],\n",
|
||||
" instructions=\"\"\"Compare search results from Google and DuckDuckGo. \n",
|
||||
" Note any differences in results, ranking, or information quality.\n",
|
||||
" Be objective in your comparison.\"\"\",\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" response = comparison_agent.run(\n",
|
||||
" \"Search for 'AgentOps observability platform' on both search engines and compare the results\"\n",
|
||||
" )\n",
|
||||
" print(f\"Comparison Agent Response:\\n{response.content}\")\n",
|
||||
"\n",
|
||||
" print(\"\\n\\n✨ Demonstration Complete!\")\n",
|
||||
" print(\"\\nKey Takeaways:\")\n",
|
||||
" print(\"- Agno agents can use multiple tools seamlessly\")\n",
|
||||
" print(\"- Tools are automatically invoked based on the agent's task\")\n",
|
||||
" print(\"- AgentOps tracks all tool executions automatically\")\n",
|
||||
" print(\"- Different tools serve different purposes (web search, academic search, etc.)\")\n",
|
||||
" print(\"- Agents can compare and synthesize information from multiple tools\")\n",
|
||||
"\n",
|
||||
" # End the AgentOps trace successfully\n",
|
||||
" print(\"\\n📊 View your tool execution traces in AgentOps:\")\n",
|
||||
" print(\" Visit https://app.agentops.ai/ to see detailed analytics\")\n",
|
||||
" agentops.end_trace(tracer, end_state=\"Success\")\n",
|
||||
"\n",
|
||||
" except Exception as e:\n",
|
||||
" print(f\"\\n❌ An error occurred: {e}\")\n",
|
||||
" agentops.end_trace(tracer, end_state=\"Error\")\n",
|
||||
" raise\n",
|
||||
"\n",
|
||||
" # Let's check programmatically that spans were recorded in AgentOps\n",
|
||||
" print(\"\\n\" + \"=\" * 50)\n",
|
||||
" print(\"Now let's verify that our LLM calls were tracked properly...\")\n",
|
||||
" try:\n",
|
||||
" agentops.validate_trace_spans(trace_context=tracer)\n",
|
||||
" print(\"\\n✅ Success! All LLM spans were properly recorded in AgentOps.\")\n",
|
||||
" except agentops.ValidationError as e:\n",
|
||||
" print(f\"\\n❌ Error validating spans: {e}\")\n",
|
||||
" raise"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "run-demo",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"demonstrate_tool_integration()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "summary-cell",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Summary\n",
|
||||
"\n",
|
||||
"This notebook demonstrated how to:\n",
|
||||
"\n",
|
||||
"- Set up Agno agents with various tools (Google Search, DuckDuckGo, Arxiv)\n",
|
||||
"- Create single-tool and multi-tool agents\n",
|
||||
"- Track tool usage with AgentOps\n",
|
||||
"- Compare results from different search engines\n",
|
||||
"- Validate that all operations are properly traced\n",
|
||||
"\n",
|
||||
"## Next Steps\n",
|
||||
"\n",
|
||||
"Visit the AgentOps dashboard to explore:\n",
|
||||
"- Detailed tool execution metrics\n",
|
||||
"- Agent performance analytics \n",
|
||||
"- Error tracking and debugging information\n",
|
||||
"\n",
|
||||
"Each trace URL printed during execution provides direct access to that specific session's details."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.9.0"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
"""
|
||||
# Tool Integration Example with Agno
|
||||
|
||||
This example demonstrates how to integrate and use various tools with Agno agents,
|
||||
showing how AgentOps automatically tracks tool usage and agent interactions.
|
||||
|
||||
## Overview
|
||||
This example demonstrates:
|
||||
|
||||
1. **Using built-in Agno tools** like GoogleSearch, DuckDuckGo, and Arxiv
|
||||
2. **Creating agents with tools** and seeing how they use them
|
||||
3. **Tool execution tracking** with AgentOps
|
||||
4. **Combining multiple tools** for comprehensive research
|
||||
|
||||
This example uses actual Agno components to show real tool integration patterns.
|
||||
"""
|
||||
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
import agentops
|
||||
from agno.agent import Agent
|
||||
from agno.models.openai import OpenAIChat
|
||||
from agno.tools.googlesearch import GoogleSearchTools
|
||||
from agno.tools.duckduckgo import DuckDuckGoTools
|
||||
from agno.tools.arxiv import ArxivTools
|
||||
|
||||
# Load environment variables
|
||||
load_dotenv()
|
||||
|
||||
# Set environment variables if not already set
|
||||
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")
|
||||
|
||||
# Initialize AgentOps
|
||||
agentops.init(
|
||||
auto_start_session=False, trace_name="Agno Tool Integrations", tags=["agno-tools", "tool-integration", "demo"]
|
||||
)
|
||||
|
||||
|
||||
def demonstrate_tool_integration():
|
||||
"""Demonstrate tool integration with Agno agents."""
|
||||
print("🚀 Agno Tool Integration Demonstration")
|
||||
print("=" * 60)
|
||||
|
||||
# Start AgentOps trace
|
||||
tracer = agentops.start_trace(trace_name="Agno Tool Integration Demo")
|
||||
|
||||
try:
|
||||
# Example 1: Single Tool Agent
|
||||
print("\n📌 Example 1: Agent with Google Search Tool")
|
||||
print("-" * 40)
|
||||
|
||||
search_agent = Agent(
|
||||
name="Search Agent",
|
||||
role="Research information using Google Search",
|
||||
model=OpenAIChat(id="gpt-4o-mini"),
|
||||
tools=[GoogleSearchTools()],
|
||||
instructions="You are a research assistant. Use Google Search to find accurate, up-to-date information.",
|
||||
)
|
||||
|
||||
response = search_agent.run("What are the latest developments in AI agents?")
|
||||
print(f"Search Agent Response:\n{response.content}")
|
||||
|
||||
# Example 2: Multi-Tool Agent
|
||||
print("\n\n📌 Example 2: Agent with Multiple Tools")
|
||||
print("-" * 40)
|
||||
|
||||
research_agent = Agent(
|
||||
name="Research Agent",
|
||||
role="Comprehensive research using multiple tools",
|
||||
model=OpenAIChat(id="gpt-4o-mini"),
|
||||
tools=[GoogleSearchTools(), ArxivTools(), DuckDuckGoTools()],
|
||||
instructions="""You are a comprehensive research assistant.
|
||||
Use Google Search for general information, Arxiv for academic papers,
|
||||
and DuckDuckGo as an alternative search engine.
|
||||
Provide well-researched, balanced information from multiple sources.""",
|
||||
)
|
||||
|
||||
response = research_agent.run(
|
||||
"Find information about recent advances in tool-use for AI agents. "
|
||||
"Include both academic research and practical implementations."
|
||||
)
|
||||
print(f"Research Agent Response:\n{response.content}")
|
||||
|
||||
# Example 3: Specialized Tool Usage
|
||||
print("\n\n📌 Example 3: Academic Research with Arxiv")
|
||||
print("-" * 40)
|
||||
|
||||
academic_agent = Agent(
|
||||
name="Academic Agent",
|
||||
role="Find and summarize academic papers",
|
||||
model=OpenAIChat(id="gpt-4o-mini"),
|
||||
tools=[ArxivTools()],
|
||||
instructions="You are an academic research assistant. Use Arxiv to find relevant papers and provide concise summaries.",
|
||||
)
|
||||
|
||||
response = academic_agent.run("Find recent papers about tool augmented language models")
|
||||
print(f"Academic Agent Response:\n{response.content}")
|
||||
|
||||
# Example 4: Comparing Search Tools
|
||||
print("\n\n📌 Example 4: Comparing Different Search Tools")
|
||||
print("-" * 40)
|
||||
|
||||
comparison_agent = Agent(
|
||||
name="Comparison Agent",
|
||||
role="Compare results from different search engines",
|
||||
model=OpenAIChat(id="gpt-4o-mini"),
|
||||
tools=[GoogleSearchTools(), DuckDuckGoTools()],
|
||||
instructions="""Compare search results from Google and DuckDuckGo.
|
||||
Note any differences in results, ranking, or information quality.
|
||||
Be objective in your comparison.""",
|
||||
)
|
||||
|
||||
response = comparison_agent.run(
|
||||
"Search for 'AgentOps observability platform' on both search engines and compare the results"
|
||||
)
|
||||
print(f"Comparison Agent Response:\n{response.content}")
|
||||
|
||||
print("\n\n✨ Demonstration Complete!")
|
||||
print("\nKey Takeaways:")
|
||||
print("- Agno agents can use multiple tools seamlessly")
|
||||
print("- Tools are automatically invoked based on the agent's task")
|
||||
print("- AgentOps tracks all tool executions automatically")
|
||||
print("- Different tools serve different purposes (web search, academic search, etc.)")
|
||||
print("- Agents can compare and synthesize information from multiple tools")
|
||||
|
||||
# End the AgentOps trace successfully
|
||||
print("\n📊 View your tool execution traces in AgentOps:")
|
||||
print(" Visit https://app.agentops.ai/ to see detailed analytics")
|
||||
agentops.end_trace(tracer, end_state="Success")
|
||||
|
||||
except Exception as e:
|
||||
print(f"\n❌ An error occurred: {e}")
|
||||
agentops.end_trace(tracer, end_state="Error")
|
||||
raise
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
agentops.validate_trace_spans(trace_context=tracer)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
demonstrate_tool_integration()
|
||||
@@ -0,0 +1,217 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "2ac8b4d4",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"\n",
|
||||
"# Workflow Setup with Caching in Agno\n",
|
||||
"\n",
|
||||
"This example demonstrates how to create efficient, stateful workflows in Agno that orchestrate complex agent interactions while maintaining performance through caching and state management.\n",
|
||||
"\n",
|
||||
"## Overview\n",
|
||||
"This example shows how to build reusable agent workflows where we:\n",
|
||||
"\n",
|
||||
"1. **Design workflow architecture** with custom logic and agent orchestration\n",
|
||||
"2. **Implement caching mechanisms** to store and reuse expensive computations\n",
|
||||
"3. **Manage session state** to maintain context across multiple interactions\n",
|
||||
"4. **Set up response streaming** for real-time output handling\n",
|
||||
"\n",
|
||||
"By using workflows, you can create sophisticated agent pipelines that are both performant and maintainable, with built-in optimizations for repeated operations and long-running sessions.\n",
|
||||
"\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "40bf672a",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Install the required dependencies:\n",
|
||||
"%pip install agentops\n",
|
||||
"%pip install agno\n",
|
||||
"%pip install python-dotenv"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "ee482533",
|
||||
"metadata": {
|
||||
"lines_to_next_cell": 2
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"from dotenv import load_dotenv\n",
|
||||
"\n",
|
||||
"import agentops\n",
|
||||
"from agno.agent import Agent, RunResponse\n",
|
||||
"from agno.workflow import Workflow\n",
|
||||
"from agno.utils.pprint import pprint_run_response\n",
|
||||
"from agno.models.openai import OpenAIChat\n",
|
||||
"from agno.utils.log import logger\n",
|
||||
"from typing import Iterator"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "eddbb872",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Load environment variables\n",
|
||||
"load_dotenv()\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\", \"your_openai_api_key_here\")\n",
|
||||
"os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\", \"your_agentops_api_key_here\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "6f234791",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"agentops.init(auto_start_session=False, tags=[\"agno-example\", \"workflow-setup\"])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 18,
|
||||
"id": "ff36679e",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"class CacheWorkflow(Workflow):\n",
|
||||
" \"\"\"\n",
|
||||
" A workflow that demonstrates intelligent caching capabilities.\n",
|
||||
"\n",
|
||||
" This workflow:\n",
|
||||
" - Caches agent responses to avoid redundant API calls\n",
|
||||
" - Maintains session state across multiple invocations\n",
|
||||
" - Provides instant responses for repeated queries\n",
|
||||
" - Reduces costs and improves performance\n",
|
||||
"\n",
|
||||
" Use cases:\n",
|
||||
" - FAQ systems where questions repeat frequently\n",
|
||||
" - Development/testing to avoid repeated API calls\n",
|
||||
" - Systems with predictable query patterns\n",
|
||||
" \"\"\"\n",
|
||||
"\n",
|
||||
" # Workflow metadata (descriptive, not functional)\n",
|
||||
" description: str = \"A workflow that caches previous outputs for efficiency\"\n",
|
||||
"\n",
|
||||
" # Initialize agents as workflow attributes\n",
|
||||
" # This agent will be used to generate responses when cache misses occur\n",
|
||||
" agent = Agent(model=OpenAIChat(id=\"gpt-4o-mini\"), description=\"General purpose agent for generating responses\")\n",
|
||||
"\n",
|
||||
" def run(self, message: str) -> Iterator[RunResponse]:\n",
|
||||
" \"\"\"\n",
|
||||
" Execute the workflow with caching logic.\n",
|
||||
"\n",
|
||||
" This method:\n",
|
||||
" 1. Checks if the response is already cached\n",
|
||||
" 2. Returns cached response immediately if found\n",
|
||||
" 3. Generates new response if not cached\n",
|
||||
" 4. Caches the new response for future use\n",
|
||||
"\n",
|
||||
" Args:\n",
|
||||
" message: The input query to process\n",
|
||||
"\n",
|
||||
" Yields:\n",
|
||||
" RunResponse: Streamed response chunks\n",
|
||||
" \"\"\"\n",
|
||||
" logger.info(f\"Checking cache for '{message}'\")\n",
|
||||
"\n",
|
||||
" if self.session_state.get(message):\n",
|
||||
" logger.info(f\"Cache hit for '{message}'\")\n",
|
||||
" # Return cached response immediately (no API call needed)\n",
|
||||
" yield RunResponse(run_id=self.run_id, content=self.session_state.get(message))\n",
|
||||
" return\n",
|
||||
"\n",
|
||||
" logger.info(f\"Cache miss for '{message}'\")\n",
|
||||
"\n",
|
||||
" yield from self.agent.run(message, stream=True)\n",
|
||||
"\n",
|
||||
" self.session_state[message] = self.agent.run_response.content\n",
|
||||
" logger.info(\"Cached response for future use\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 19,
|
||||
"id": "b1e9e06c",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def demonstrate_workflows():\n",
|
||||
" \"\"\"\n",
|
||||
" Demonstrate workflow capabilities with caching.\n",
|
||||
"\n",
|
||||
" This function shows:\n",
|
||||
" - How to create and use custom workflows\n",
|
||||
" - The performance benefits of caching\n",
|
||||
" - Session state persistence\n",
|
||||
" - Response streaming\n",
|
||||
" \"\"\"\n",
|
||||
"\n",
|
||||
" tracer = agentops.start_trace(trace_name=\"Agno Workflow Setup Demonstration\")\n",
|
||||
" try:\n",
|
||||
" workflow = CacheWorkflow()\n",
|
||||
"\n",
|
||||
" response: Iterator[RunResponse] = workflow.run(message=\"Tell me a joke.\")\n",
|
||||
"\n",
|
||||
" pprint_run_response(response, markdown=True, show_time=True)\n",
|
||||
"\n",
|
||||
" response: Iterator[RunResponse] = workflow.run(message=\"Tell me a joke.\")\n",
|
||||
"\n",
|
||||
" pprint_run_response(response, markdown=True, show_time=True)\n",
|
||||
"\n",
|
||||
" agentops.end_trace(tracer, end_state=\"Success\")\n",
|
||||
"\n",
|
||||
" except Exception:\n",
|
||||
" agentops.end_trace(tracer, end_state=\"Error\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "d09d8f70",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"demonstrate_workflows()"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"jupytext": {
|
||||
"cell_metadata_filter": "-all",
|
||||
"main_language": "python",
|
||||
"notebook_metadata_filter": "-all"
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "venv",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.9"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
"""
|
||||
# Workflow Setup with Caching in Agno
|
||||
|
||||
This example demonstrates how to create efficient, stateful workflows in Agno that orchestrate complex agent interactions while maintaining performance through caching and state management.
|
||||
|
||||
## Overview
|
||||
This example shows how to build reusable agent workflows where we:
|
||||
|
||||
1. **Design workflow architecture** with custom logic and agent orchestration
|
||||
2. **Implement caching mechanisms** to store and reuse expensive computations
|
||||
3. **Manage session state** to maintain context across multiple interactions
|
||||
4. **Set up response streaming** for real-time output handling
|
||||
|
||||
By using workflows, you can create sophisticated agent pipelines that are both performant and maintainable, with built-in optimizations for repeated operations and long-running sessions.
|
||||
|
||||
"""
|
||||
|
||||
from agno.agent import Agent, RunResponse
|
||||
import agentops
|
||||
from dotenv import load_dotenv
|
||||
from agno.workflow import Workflow
|
||||
from agno.utils.pprint import pprint_run_response
|
||||
from agno.models.openai import OpenAIChat
|
||||
from agno.utils.log import logger
|
||||
from typing import Iterator
|
||||
|
||||
|
||||
load_dotenv()
|
||||
agentops.init(auto_start_session=False, trace_name="Agno Workflow Setup", tags=["agno-example", "workflow-setup"])
|
||||
|
||||
|
||||
class CacheWorkflow(Workflow):
|
||||
"""
|
||||
A workflow that demonstrates intelligent caching capabilities.
|
||||
|
||||
This workflow:
|
||||
- Caches agent responses to avoid redundant API calls
|
||||
- Maintains session state across multiple invocations
|
||||
- Provides instant responses for repeated queries
|
||||
- Reduces costs and improves performance
|
||||
|
||||
Use cases:
|
||||
- FAQ systems where questions repeat frequently
|
||||
- Development/testing to avoid repeated API calls
|
||||
- Systems with predictable query patterns
|
||||
"""
|
||||
|
||||
# Workflow metadata (descriptive, not functional)
|
||||
description: str = "A workflow that caches previous outputs for efficiency"
|
||||
|
||||
# Initialize agents as workflow attributes
|
||||
# This agent will be used to generate responses when cache misses occur
|
||||
agent = Agent(model=OpenAIChat(id="gpt-4o-mini"), description="General purpose agent for generating responses")
|
||||
|
||||
def run(self, message: str) -> Iterator[RunResponse]:
|
||||
"""
|
||||
Execute the workflow with caching logic.
|
||||
|
||||
This method:
|
||||
1. Checks if the response is already cached
|
||||
2. Returns cached response immediately if found
|
||||
3. Generates new response if not cached
|
||||
4. Caches the new response for future use
|
||||
|
||||
Args:
|
||||
message: The input query to process
|
||||
|
||||
Yields:
|
||||
RunResponse: Streamed response chunks
|
||||
"""
|
||||
logger.info(f"Checking cache for '{message}'")
|
||||
|
||||
if self.session_state.get(message):
|
||||
logger.info(f"Cache hit for '{message}'")
|
||||
# Return cached response immediately (no API call needed)
|
||||
yield RunResponse(run_id=self.run_id, content=self.session_state.get(message))
|
||||
return
|
||||
|
||||
logger.info(f"Cache miss for '{message}'")
|
||||
|
||||
yield from self.agent.run(message, stream=True)
|
||||
|
||||
self.session_state[message] = self.agent.run_response.content
|
||||
logger.info("Cached response for future use")
|
||||
|
||||
|
||||
def demonstrate_workflows():
|
||||
"""
|
||||
Demonstrate workflow capabilities with caching.
|
||||
|
||||
This function shows:
|
||||
- How to create and use custom workflows
|
||||
- The performance benefits of caching
|
||||
- Session state persistence
|
||||
- Response streaming
|
||||
"""
|
||||
|
||||
tracer = agentops.start_trace(trace_name="Agno Workflow Setup Demonstration")
|
||||
try:
|
||||
workflow = CacheWorkflow()
|
||||
|
||||
response: Iterator[RunResponse] = workflow.run(message="Tell me a joke.")
|
||||
|
||||
pprint_run_response(response, markdown=True, show_time=True)
|
||||
|
||||
response: Iterator[RunResponse] = workflow.run(message="Tell me a joke.")
|
||||
|
||||
pprint_run_response(response, markdown=True, show_time=True)
|
||||
|
||||
agentops.end_trace(tracer, end_state="Success")
|
||||
|
||||
except Exception:
|
||||
agentops.end_trace(tracer, end_state="Error")
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
agentops.validate_trace_spans(trace_context=tracer)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
|
||||
|
||||
demonstrate_workflows()
|
||||
@@ -0,0 +1,8 @@
|
||||
agno
|
||||
aiohttp
|
||||
openai
|
||||
googlesearch-python
|
||||
pycountry
|
||||
arxiv
|
||||
pypdf
|
||||
duckduckgo-search
|
||||
@@ -0,0 +1,655 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Anthropic Example for understanding Tools\n",
|
||||
"\n",
|
||||
"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! "
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"To get started, we will import Agentops and Anthropic"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%pip install agentops\n",
|
||||
"%pip install anthropic"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Setup our generic default statements"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import agentops\n",
|
||||
"from anthropic import Anthropic\n",
|
||||
"from dotenv import load_dotenv\n",
|
||||
"import os\n",
|
||||
"import random"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"And set our API keys."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"load_dotenv()\n",
|
||||
"os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\", \"your_api_key_here\")\n",
|
||||
"os.environ[\"ANTHROPIC_API_KEY\"] = os.getenv(\"ANTHROPIC_API_KEY\", \"your_anthropic_api_key_here\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"\n",
|
||||
"Now let's set the client as Anthropic and make an AgentOps trace"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"agentops.init(tags=[\"anthropic-example-tool-tutorials\", \"agentops-example\"])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"client = Anthropic()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"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."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"locations = [\n",
|
||||
" {\n",
|
||||
" \"Name\": \"Super Gore Nest\",\n",
|
||||
" \"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.\",\n",
|
||||
" },\n",
|
||||
" {\n",
|
||||
" \"Name\": \"Exultia\",\n",
|
||||
" \"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.\",\n",
|
||||
" },\n",
|
||||
" {\n",
|
||||
" \"Name\": \"Cultist Base\",\n",
|
||||
" \"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.\",\n",
|
||||
" },\n",
|
||||
" {\n",
|
||||
" \"Name\": \"Taras Nabad\",\n",
|
||||
" \"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.\",\n",
|
||||
" },\n",
|
||||
" {\n",
|
||||
" \"Name\": \"Nekravol\",\n",
|
||||
" \"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.\",\n",
|
||||
" },\n",
|
||||
" {\n",
|
||||
" \"Name\": \"Urdak\",\n",
|
||||
" \"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.\",\n",
|
||||
" },\n",
|
||||
" {\n",
|
||||
" \"Name\": \"UAC Base\",\n",
|
||||
" \"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.\",\n",
|
||||
" },\n",
|
||||
"]\n",
|
||||
"\n",
|
||||
"combat_casualties = [\"Nonexistent\", \"Low\", \"Medium\", \"High\", \"Extinction\"]\n",
|
||||
"\n",
|
||||
"missions = [\n",
|
||||
" \"Locate and confront a key leader of Hell’s invasion forces.\",\n",
|
||||
" \"Clear out demonic infestations to secure a strategic foothold.\",\n",
|
||||
" \"Disrupt Hell's control over the area by eliminating critical targets.\",\n",
|
||||
" \"Enter a critical demonic stronghold to disrupt enemy operations.\",\n",
|
||||
" \"Locate and destroy the central power source to weaken enemy forces.\",\n",
|
||||
" \"Collect essential resources before the area becomes unstable.\",\n",
|
||||
"]"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Now that that's done, we can make a function! We will generate three random missions and pass it off to the AI."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def generate_missions():\n",
|
||||
" selectedmissions = []\n",
|
||||
" loop = 0\n",
|
||||
"\n",
|
||||
" while loop < 3:\n",
|
||||
" location = random.choice(locations)\n",
|
||||
" casualties = random.choice(combat_casualties)\n",
|
||||
" mission = random.choice(missions)\n",
|
||||
" final = (\n",
|
||||
" f\"LocationName: {location['Name']}, \"\n",
|
||||
" f\"LocationInfo: {location['Description']}, \"\n",
|
||||
" f\"HumanCombatCasualties: {casualties}, \"\n",
|
||||
" f\"Mission: {mission}\"\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" selectedmissions.append(final)\n",
|
||||
" loop += 1\n",
|
||||
"\n",
|
||||
" # Combine all mission strings into a single string with a separator (e.g., newline or comma)\n",
|
||||
" missions_string = \"\\n\".join(missions) # Or \", \".join(missions) for a comma-separated string\n",
|
||||
" print(missions_string)\n",
|
||||
" return missions_string"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"generate_missions()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"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)!\n",
|
||||
"\n",
|
||||
"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"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Now we make a message! This time around we will skip making an initial message that has too much context, unlike in the past!"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# We make our history a separate block to be easier to add to later on! This is essentially our history\n",
|
||||
"initial_messages = [\n",
|
||||
" {\n",
|
||||
" \"role\": \"user\",\n",
|
||||
" \"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. \",\n",
|
||||
" }\n",
|
||||
"]"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Now to construct a request!"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": "response = client.messages.create(\n max_tokens=5000,\n model=\"claude-3-7-sonnet-20250219\",\n tools=[\n {\n \"name\": \"generate_missions\",\n \"description\": \"Retrieve three missions for the DoomSlayer\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {}, \"required\": []},\n }\n ],\n messages=initial_messages,\n)\n\nprint(response.content)"
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Having trouble understanding this? The first block given is always Ai dialouge! You can use response.content[0].text to get the AI's text! Let's try it below."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"message = response.content[0].text\n",
|
||||
"print(message)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"The code below finds the tool used!"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"gen_mission_result = \"\"\n",
|
||||
"\n",
|
||||
"# Print response content to see the data\n",
|
||||
"print(response.content)\n",
|
||||
"\n",
|
||||
"# Assuming ToolUseBlock is at index 1\n",
|
||||
"tool_use_block = response.content[1]\n",
|
||||
"\n",
|
||||
"# Get the tool name and input\n",
|
||||
"tool_name = tool_use_block.name\n",
|
||||
"tool_input = tool_use_block.input\n",
|
||||
"\n",
|
||||
"# We don't need to look to extract any inputs since we don't use any\n",
|
||||
"\n",
|
||||
"# Check if the tool name is \"generate_missions\"\n",
|
||||
"if tool_name == \"generate_missions\":\n",
|
||||
" # Call the function with the tool creator as an argument\n",
|
||||
" gen_mission_result = generate_missions()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Now we add these as context to the LLM through initial messages!"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"initial_messages.append({\"role\": \"assistant\", \"content\": gen_mission_result})\n",
|
||||
"\n",
|
||||
"initial_messages.append(\n",
|
||||
" {\n",
|
||||
" \"role\": \"user\",\n",
|
||||
" \"content\": \"Based on these, which location should take priority and why?\",\n",
|
||||
" }\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"And now to get a response!"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": "response = client.messages.create(\n max_tokens=5000,\n model=\"claude-3-7-sonnet-20250219\",\n tools=[\n {\n \"name\": \"generate_missions\",\n \"description\": \"Retrieve three missions for the DoomSlayer\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {}, \"required\": []},\n }\n ],\n messages=initial_messages,\n)\n\nprint(response)"
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Isolate again!"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"message = response.content[0].text\n",
|
||||
"print(message)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Hmmm, what if we wanted to include more tools and add inputs? Let's create two new functions to display this!\n",
|
||||
"\n",
|
||||
"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)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"demons = [\n",
|
||||
" {\n",
|
||||
" \"Name\": \"Imp\",\n",
|
||||
" \"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.\",\n",
|
||||
" },\n",
|
||||
" {\n",
|
||||
" \"Name\": \"Cacodemon\",\n",
|
||||
" \"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.\",\n",
|
||||
" },\n",
|
||||
" {\n",
|
||||
" \"Name\": \"Hell Knight\",\n",
|
||||
" \"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.\",\n",
|
||||
" },\n",
|
||||
" {\n",
|
||||
" \"Name\": \"Mancubus\",\n",
|
||||
" \"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.\",\n",
|
||||
" },\n",
|
||||
"]\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"weapons = [\n",
|
||||
" {\n",
|
||||
" \"Name\": \"Super Shotgun\",\n",
|
||||
" \"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.\",\n",
|
||||
" },\n",
|
||||
" {\n",
|
||||
" \"Name\": \"Rocket Launcher\",\n",
|
||||
" \"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.\",\n",
|
||||
" },\n",
|
||||
" {\n",
|
||||
" \"Name\": \"Chaingun\",\n",
|
||||
" \"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.\",\n",
|
||||
" },\n",
|
||||
" {\n",
|
||||
" \"Name\": \"BFG 9000\",\n",
|
||||
" \"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.\",\n",
|
||||
" },\n",
|
||||
" {\n",
|
||||
" \"Name\": \"Ice Bomb\",\n",
|
||||
" \"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.\",\n",
|
||||
" },\n",
|
||||
"]"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Now we can keep the initialmessages from before actually! However let's change the context"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"initial_messages.append(\n",
|
||||
" {\n",
|
||||
" \"role\": \"user\",\n",
|
||||
" \"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.\",\n",
|
||||
" }\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"And we of course make functions"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def enemyscan(amount):\n",
|
||||
" enemiesonscene = []\n",
|
||||
" loop = 0\n",
|
||||
"\n",
|
||||
" while loop < amount + 1:\n",
|
||||
" scannedenemy = random.choice(demons)\n",
|
||||
"\n",
|
||||
" # Append just the name of the demon to the list\n",
|
||||
" enemiesonscene.append(scannedenemy[\"Name\"])\n",
|
||||
" enemiesonscene.append(scannedenemy[\"Description\"])\n",
|
||||
" loop += 1\n",
|
||||
"\n",
|
||||
" # Combine all mission strings into a single string with a separator (e.g., newline or comma)\n",
|
||||
" enemies_string = \"\\n\".join(enemiesonscene)\n",
|
||||
" print(enemies_string)\n",
|
||||
" return enemies_string"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"enemyscan(5)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"And now inventory"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def inventoryscan():\n",
|
||||
" weapons_at_hand = []\n",
|
||||
" loop = 0\n",
|
||||
"\n",
|
||||
" while loop < 5:\n",
|
||||
" weapon = random.choice(weapons)\n",
|
||||
"\n",
|
||||
" # Append just the name of the demon to the list\n",
|
||||
" weapons_at_hand.append(weapon[\"Name\"])\n",
|
||||
" weapons_at_hand.append(weapon[\"Description\"])\n",
|
||||
" loop += 1\n",
|
||||
"\n",
|
||||
" # Combine all mission strings into a single string with a separator (e.g., newline or comma)\n",
|
||||
" weapons_string = \"\\n\".join(weapons_at_hand)\n",
|
||||
" print(weapons_string)\n",
|
||||
" return weapons_string"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"inventoryscan()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"With that, let's construct our new tools and run this!!"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": "response = client.messages.create(\n max_tokens=5000,\n model=\"claude-3-7-sonnet-20250219\",\n tools=[\n {\n \"name\": \"enemyscan_tool\",\n \"description\": \"Retrieve a list of demons currently present in the area.\",\n \"input_schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"amount\": {\n \"type\": \"integer\",\n \"description\": \"Number of enemies to scan.\",\n }\n },\n \"required\": [\"amount\"],\n },\n },\n {\n \"name\": \"inventoryscan_tool\",\n \"description\": \"Retrieve a list of weapons the Doom Slayer has at hand.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {}, \"required\": []},\n },\n ],\n messages=initial_messages,\n)\n\nprint(response)"
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Display just the text"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"message = response.content[0].text\n",
|
||||
"print(message)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"initial_messages.append({\"role\": \"assistant\", \"content\": f\"{str(response.content[0].text)}\"})"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"And now to get the information and put it all together! PLEASE read the comments!"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"inv_scan_res = \"\"\n",
|
||||
"enemy_scan_res = \"\"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"response_str = str(response)\n",
|
||||
"tool_use_count = response_str.count(\n",
|
||||
" \"ToolUseBlock\"\n",
|
||||
") # We know the ToolUseBlock will appear once for each tool request so we check how many time it appears\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# You can use print(tool_use_count)to validate the ToolBlocks here if you wish\n",
|
||||
"\n",
|
||||
"loop = 0\n",
|
||||
"\n",
|
||||
"# 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!\n",
|
||||
"\n",
|
||||
"while loop < tool_use_count: # We will get the tools now\n",
|
||||
" tool_use_block = response.content[loop + 1] # We start at 1 since 0 holds the AI mesage\n",
|
||||
" tool_name = tool_use_block.name\n",
|
||||
" tool_input = tool_use_block.input\n",
|
||||
"\n",
|
||||
" if tool_name == \"inventoryscan_tool\":\n",
|
||||
" # Call the inventoryscan function for inventoryscan_tool\n",
|
||||
" inv_scan_res = inventoryscan()\n",
|
||||
" elif tool_name == \"enemyscan_tool\":\n",
|
||||
" # Get the amount for enemyscan_tool\n",
|
||||
" amount = tool_input[\"amount\"]\n",
|
||||
" # Call the enemyscan function with the amount\n",
|
||||
" enemy_scan_res = enemyscan(amount)\n",
|
||||
"\n",
|
||||
" loop = loop + 1\n",
|
||||
"print(inv_scan_res)\n",
|
||||
"print(enemy_scan_res)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"And now we are basically done! We can give this to th AI and see what we get"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"initial_messages.append(\n",
|
||||
" {\n",
|
||||
" \"role\": \"assistant\",\n",
|
||||
" \"content\": f\"Weapons Inventory Scan Result: {inv_scan_res}\\nEnemy Scans Result: {enemy_scan_res}\",\n",
|
||||
" }\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"initial_messages.append(\n",
|
||||
" {\n",
|
||||
" \"role\": \"user\",\n",
|
||||
" \"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.\",\n",
|
||||
" }\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": "response = client.messages.create(\n max_tokens=5000,\n model=\"claude-3-7-sonnet-20250219\",\n tools=[\n {\n \"name\": \"enemyscan_tool\",\n \"description\": \"Retrieve a list of demons currently present in the area.\",\n \"input_schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"amount\": {\n \"type\": \"integer\",\n \"description\": \"Number of enemies to scan.\",\n }\n },\n \"required\": [\"amount\"],\n },\n },\n {\n \"name\": \"inventoryscan_tool\",\n \"description\": \"Retrieve a list of weapons the Doom Slayer has at hand.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {}, \"required\": []},\n },\n ],\n messages=initial_messages,\n)\n\nmessage = response.content[0].text\nprint(message)"
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kaggle": {
|
||||
"accelerator": "none",
|
||||
"dataSources": [],
|
||||
"dockerImageVersionId": 30787,
|
||||
"isGpuEnabled": false,
|
||||
"isInternetEnabled": true,
|
||||
"language": "python",
|
||||
"sourceType": "notebook"
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "agentops (3.11.11)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.11"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 4
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
# # 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
|
||||
# %pip install agentops
|
||||
# %pip install anthropic
|
||||
# Setup our generic default statements
|
||||
import agentops
|
||||
from anthropic import Anthropic
|
||||
from dotenv import load_dotenv
|
||||
import os
|
||||
import random
|
||||
|
||||
# And set our API keys.
|
||||
load_dotenv()
|
||||
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY", "your_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
|
||||
agentops.init(trace_name="Anthropic Understanding Tools", tags=["anthropic-example-tool-tutorials", "agentops-example"])
|
||||
client = Anthropic()
|
||||
# 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.
|
||||
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.
|
||||
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)
|
||||
missions_string = "\\n".join(missions) # Or \", \".join(missions) for a comma-separated string
|
||||
print(missions_string)
|
||||
return missions_string
|
||||
|
||||
|
||||
generate_missions()
|
||||
# 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!
|
||||
# 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!
|
||||
response = client.messages.create(
|
||||
max_tokens=5000,
|
||||
model="claude-3-7-sonnet-20250219",
|
||||
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 dialouge! You can use response.content[0].text to get the AI's text! Let's try it below.
|
||||
message = response.content[0].text
|
||||
print(message)
|
||||
# The code below finds the tool used!
|
||||
gen_mission_result = ""
|
||||
|
||||
# Print response content to see the data
|
||||
print(response.content)
|
||||
|
||||
# Assuming ToolUseBlock is at index 1
|
||||
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!
|
||||
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!
|
||||
response = client.messages.create(
|
||||
max_tokens=5000,
|
||||
model="claude-3-7-sonnet-20250219",
|
||||
tools=[
|
||||
{
|
||||
"name": "generate_missions",
|
||||
"description": "Retrieve three missions for the DoomSlayer",
|
||||
"input_schema": {"type": "object", "properties": {}, "required": []},
|
||||
}
|
||||
],
|
||||
messages=initial_messages,
|
||||
)
|
||||
|
||||
print(response)
|
||||
# Isolate again!
|
||||
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)
|
||||
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 initialmessages from before actually! However let's change the context
|
||||
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
|
||||
def enemyscan(amount):
|
||||
enemiesonscene = []
|
||||
loop = 0
|
||||
|
||||
while loop < amount + 1:
|
||||
scannedenemy = random.choice(demons)
|
||||
|
||||
# Append just the name of the demon to the list
|
||||
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
|
||||
|
||||
|
||||
enemyscan(5)
|
||||
|
||||
|
||||
# And now inventory
|
||||
def inventoryscan():
|
||||
weapons_at_hand = []
|
||||
loop = 0
|
||||
|
||||
while loop < 5:
|
||||
weapon = random.choice(weapons)
|
||||
|
||||
# Append just the name of the demon to the list
|
||||
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
|
||||
|
||||
|
||||
inventoryscan()
|
||||
# With that, let's construct our new tools and run this!!
|
||||
response = client.messages.create(
|
||||
max_tokens=5000,
|
||||
model="claude-3-7-sonnet-20250219",
|
||||
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
|
||||
message = response.content[0].text
|
||||
print(message)
|
||||
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!
|
||||
inv_scan_res = ""
|
||||
enemy_scan_res = ""
|
||||
|
||||
|
||||
response_str = str(response)
|
||||
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"]
|
||||
# Call the enemyscan function with the amount
|
||||
enemy_scan_res = enemyscan(amount)
|
||||
|
||||
loop = loop + 1
|
||||
print(inv_scan_res)
|
||||
print(enemy_scan_res)
|
||||
# And now we are basically done! We can give this to th AI and see what we get
|
||||
initial_messages.append(
|
||||
{
|
||||
"role": "assistant",
|
||||
"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.",
|
||||
}
|
||||
)
|
||||
response = client.messages.create(
|
||||
max_tokens=5000,
|
||||
model="claude-3-7-sonnet-20250219",
|
||||
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
|
||||
print(message)
|
||||
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
agentops.validate_trace_spans(trace_context=None)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
@@ -0,0 +1,298 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Anthropic Async Example\n",
|
||||
"\n",
|
||||
"Anthropic supports both sync and async! This is great because we can wait for functions to finish before we use them! \n",
|
||||
"\n",
|
||||
"In this example, we will make a program called \"Titan Support Protocol.\" In this example, we will assign our mech a personality type and have a message generated based on our Titan's health (Which we randomly choose). We also send four generated UUIDs which are generated while the LLM runs"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"First, we start by importing Agentops and Anthropic"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"execution": {
|
||||
"iopub.execute_input": "2024-11-09T19:24:21.051231Z",
|
||||
"iopub.status.busy": "2024-11-09T19:24:21.050842Z",
|
||||
"iopub.status.idle": "2024-11-09T19:24:46.728962Z",
|
||||
"shell.execute_reply": "2024-11-09T19:24:46.727711Z",
|
||||
"shell.execute_reply.started": "2024-11-09T19:24:21.051179Z"
|
||||
},
|
||||
"trusted": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%pip install agentops\n",
|
||||
"%pip install anthropic"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Setup our generic default statements"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"execution": {
|
||||
"iopub.execute_input": "2024-11-09T19:24:46.731735Z",
|
||||
"iopub.status.busy": "2024-11-09T19:24:46.731341Z",
|
||||
"iopub.status.idle": "2024-11-09T19:24:47.550169Z",
|
||||
"shell.execute_reply": "2024-11-09T19:24:47.549415Z",
|
||||
"shell.execute_reply.started": "2024-11-09T19:24:46.731687Z"
|
||||
},
|
||||
"trusted": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from anthropic import Anthropic\n",
|
||||
"import agentops\n",
|
||||
"from dotenv import load_dotenv\n",
|
||||
"import os\n",
|
||||
"import random\n",
|
||||
"import asyncio\n",
|
||||
"import uuid"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"And set our API keys."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"execution": {
|
||||
"iopub.execute_input": "2024-11-09T19:48:37.019670Z",
|
||||
"iopub.status.busy": "2024-11-09T19:48:37.018784Z",
|
||||
"iopub.status.idle": "2024-11-09T19:48:37.024482Z",
|
||||
"shell.execute_reply": "2024-11-09T19:48:37.023495Z",
|
||||
"shell.execute_reply.started": "2024-11-09T19:48:37.019626Z"
|
||||
},
|
||||
"trusted": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"load_dotenv()\n",
|
||||
"os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\", \"your_api_key_here\")\n",
|
||||
"os.environ[\"ANTHROPIC_API_KEY\"] = os.getenv(\"ANTHROPIC_API_KEY\", \"your_anthropic_api_key_here\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"\n",
|
||||
"Now let's set the client as Anthropic and open an agentops trace!"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"execution": {
|
||||
"iopub.execute_input": "2024-11-09T19:48:26.615366Z",
|
||||
"iopub.status.busy": "2024-11-09T19:48:26.614702Z",
|
||||
"iopub.status.idle": "2024-11-09T19:48:26.630956Z",
|
||||
"shell.execute_reply": "2024-11-09T19:48:26.630026Z",
|
||||
"shell.execute_reply.started": "2024-11-09T19:48:26.615326Z"
|
||||
},
|
||||
"trusted": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"client = Anthropic()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"trusted": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"agentops.init(tags=[\"anthropic-async\", \"agentops-example\"])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Now we create three personality presets; \n",
|
||||
"\n",
|
||||
"Legion is a relentless and heavy-hitting Titan that embodies brute strength and defensive firepower, Northstar is a precise and agile sniper that excels in long-range combat and flight, while Ronin is a swift and aggressive melee specialist who thrives on close-quarters hit-and-run tactics."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"execution": {
|
||||
"iopub.execute_input": "2024-11-09T19:48:45.831654Z",
|
||||
"iopub.status.busy": "2024-11-09T19:48:45.830897Z",
|
||||
"iopub.status.idle": "2024-11-09T19:48:45.835837Z",
|
||||
"shell.execute_reply": "2024-11-09T19:48:45.835037Z",
|
||||
"shell.execute_reply.started": "2024-11-09T19:48:45.831616Z"
|
||||
},
|
||||
"trusted": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"TitanPersonality = [\n",
|
||||
" \"Legion is a relentless and heavy-hitting Titan that embodies brute strength and defensive firepower. He speaks bluntly.,\",\n",
|
||||
" \"Northstar is a precise and agile sniper that excels in long-range combat and flight. He speaks with an edge of coolness to him\",\n",
|
||||
" \"Ronin is a swift and aggressive melee specialist who thrives on close-quarters hit-and-run tactics. He talks like a Samurai might.\",\n",
|
||||
"]"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"And our comabt log generator! We select from four health presets!"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"execution": {
|
||||
"iopub.execute_input": "2024-11-09T19:48:47.703344Z",
|
||||
"iopub.status.busy": "2024-11-09T19:48:47.702974Z",
|
||||
"iopub.status.idle": "2024-11-09T19:48:47.707915Z",
|
||||
"shell.execute_reply": "2024-11-09T19:48:47.706767Z",
|
||||
"shell.execute_reply.started": "2024-11-09T19:48:47.703308Z"
|
||||
},
|
||||
"trusted": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"TitanHealth = [\n",
|
||||
" \"Fully functional\",\n",
|
||||
" \"Slightly Damaged\",\n",
|
||||
" \"Moderate Damage\",\n",
|
||||
" \"Considerable Damage\",\n",
|
||||
" \"Near Destruction\",\n",
|
||||
"]"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"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!"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {
|
||||
"execution": {
|
||||
"iopub.execute_input": "2024-11-09T19:49:04.543561Z",
|
||||
"iopub.status.busy": "2024-11-09T19:49:04.543172Z",
|
||||
"iopub.status.idle": "2024-11-09T19:49:04.552542Z",
|
||||
"shell.execute_reply": "2024-11-09T19:49:04.551542Z",
|
||||
"shell.execute_reply.started": "2024-11-09T19:49:04.543522Z"
|
||||
},
|
||||
"trusted": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": "Personality = {random.choice(TitanPersonality)}\nHealth = {random.choice(TitanHealth)}\n\n\nasync def req():\n # Start a streaming message request\n stream = client.messages.create(\n max_tokens=1024,\n model=\"claude-3-7-sonnet-20250219\",\n messages=[\n {\n \"role\": \"user\",\n \"content\": \"You are a Titan; a mech from Titanfall 2. Based on your titan's personality and status, generate a message for your pilot. If Near Destruction, make an all caps death message such as AVENGE ME or UNTIL NEXT TIME.\",\n },\n {\n \"role\": \"assistant\",\n \"content\": \"Personality: Legion is a relentless and heavy-hitting Titan that embodies brute strength and defensive firepower. He speaks bluntly. Status: Considerable Damage\",\n },\n {\n \"role\": \"assistant\",\n \"content\": \"Heavy damage detected. Reinforcements would be appreciated, but I can still fight.\",\n },\n {\n \"role\": \"user\",\n \"content\": \"You are a Titan; a mech from Titanfall 2. Based on your titan's personality and status, generate a message for your pilot. If Near Destruction, make an all caps death message such as AVENGE ME or UNTIL NEXT TIME.\",\n },\n {\n \"role\": \"assistant\",\n \"content\": f\"Personality: {Personality}. Status: {Health}\",\n },\n ],\n stream=True,\n )\n\n response = \"\"\n for event in stream:\n if event.type == \"content_block_delta\":\n response += event.delta.text\n elif event.type == \"message_stop\":\n break # Exit the loop when the message completes\n\n return response\n\n\nasync def generate_uuids():\n uuids = [str(uuid.uuid4()) for _ in range(4)]\n return uuids"
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Now we wrap it all in a nice main function! Run this for the magic to happen! Go to your AgentOps dashboard and you should see this trace reflected!\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"execution": {
|
||||
"iopub.execute_input": "2024-11-09T19:49:06.598601Z",
|
||||
"iopub.status.busy": "2024-11-09T19:49:06.597657Z",
|
||||
"iopub.status.idle": "2024-11-09T19:49:07.565561Z",
|
||||
"shell.execute_reply": "2024-11-09T19:49:07.564647Z",
|
||||
"shell.execute_reply.started": "2024-11-09T19:49:06.598561Z"
|
||||
},
|
||||
"trusted": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"async def main():\n",
|
||||
" # Start both tasks concurrently\n",
|
||||
" uuids, message = await asyncio.gather(generate_uuids(), req())\n",
|
||||
"\n",
|
||||
" print(\"Personality:\", Personality)\n",
|
||||
" print(\"Health Status:\", Health)\n",
|
||||
" print(\"Combat log incoming from encrypted area\")\n",
|
||||
"\n",
|
||||
" print(\"Verification matrix activated.:\")\n",
|
||||
" for u in uuids:\n",
|
||||
" print(u)\n",
|
||||
"\n",
|
||||
" print(\". Titan Message: \", message)\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Run the main function\n",
|
||||
"await main()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"We can observe the trace in the AgentOps dashboard by going to the trace URL provided above."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kaggle": {
|
||||
"accelerator": "gpu",
|
||||
"dataSources": [],
|
||||
"dockerImageVersionId": 30786,
|
||||
"isGpuEnabled": true,
|
||||
"isInternetEnabled": true,
|
||||
"language": "python",
|
||||
"sourceType": "notebook"
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "agentops (3.11.11)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.11"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 4
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
# # Anthropic Async Example
|
||||
#
|
||||
# Anthropic supports both sync and async! This is great because we can wait for functions to finish before we use them!
|
||||
#
|
||||
# In this example, we will make a program called "Titan Support Protocol." In this example, we will assign our mech a personality type and have a message generated based on our Titan's health (Which we randomly choose). We also send four generated UUIDs which are generated while the LLM runs
|
||||
# First, we start by importing Agentops and Anthropic
|
||||
# %pip install agentops
|
||||
# %pip install anthropic
|
||||
# Setup our generic default statements
|
||||
from anthropic import Anthropic
|
||||
import agentops
|
||||
from dotenv import load_dotenv
|
||||
import os
|
||||
import random
|
||||
import asyncio
|
||||
import uuid
|
||||
|
||||
# And set our API keys.
|
||||
load_dotenv()
|
||||
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY", "your_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 open an agentops trace!
|
||||
client = Anthropic()
|
||||
agentops.init(trace_name="Anthropic Async Example", tags=["anthropic-async", "agentops-example"])
|
||||
# Now we create three personality presets;
|
||||
#
|
||||
# Legion is a relentless and heavy-hitting Titan that embodies brute strength and defensive firepower, Northstar is a precise and agile sniper that excels in long-range combat and flight, while Ronin is a swift and aggressive melee specialist who thrives on close-quarters hit-and-run tactics.
|
||||
TitanPersonality = [
|
||||
"Legion is a relentless and heavy-hitting Titan that embodies brute strength and defensive firepower. He speaks bluntly.,",
|
||||
"Northstar is a precise and agile sniper that excels in long-range combat and flight. He speaks with an edge of coolness to him",
|
||||
"Ronin is a swift and aggressive melee specialist who thrives on close-quarters hit-and-run tactics. He talks like a Samurai might.",
|
||||
]
|
||||
# And our comabt log generator! We select from four health presets!
|
||||
TitanHealth = [
|
||||
"Fully functional",
|
||||
"Slightly Damaged",
|
||||
"Moderate Damage",
|
||||
"Considerable Damage",
|
||||
"Near Destruction",
|
||||
]
|
||||
# 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!
|
||||
Personality = {random.choice(TitanPersonality)}
|
||||
Health = {random.choice(TitanHealth)}
|
||||
|
||||
|
||||
async def req():
|
||||
# Start a streaming message request
|
||||
stream = client.messages.create(
|
||||
max_tokens=1024,
|
||||
model="claude-3-7-sonnet-20250219",
|
||||
messages=[
|
||||
{
|
||||
"role": "user",
|
||||
"content": "You are a Titan; a mech from Titanfall 2. Based on your titan's personality and status, generate a message for your pilot. If Near Destruction, make an all caps death message such as AVENGE ME or UNTIL NEXT TIME.",
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "Personality: Legion is a relentless and heavy-hitting Titan that embodies brute strength and defensive firepower. He speaks bluntly. Status: Considerable Damage",
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "Heavy damage detected. Reinforcements would be appreciated, but I can still fight.",
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "You are a Titan; a mech from Titanfall 2. Based on your titan's personality and status, generate a message for your pilot. If Near Destruction, make an all caps death message such as AVENGE ME or UNTIL NEXT TIME.",
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": f"Personality: {Personality}. Status: {Health}",
|
||||
},
|
||||
],
|
||||
stream=True,
|
||||
)
|
||||
|
||||
response = ""
|
||||
for event in stream:
|
||||
if event.type == "content_block_delta":
|
||||
response += event.delta.text
|
||||
elif event.type == "message_stop":
|
||||
break # Exit the loop when the message completes
|
||||
|
||||
return response
|
||||
|
||||
|
||||
async def generate_uuids():
|
||||
uuids = [str(uuid.uuid4()) for _ in range(4)]
|
||||
return uuids
|
||||
|
||||
|
||||
# Now we wrap it all in a nice main function! Run this for the magic to happen! Go to your AgentOps dashboard and you should see this trace reflected!
|
||||
async def main():
|
||||
# Start both tasks concurrently
|
||||
uuids, message = await asyncio.gather(generate_uuids(), req())
|
||||
|
||||
print("Personality:", Personality)
|
||||
print("Health Status:", Health)
|
||||
print("Combat log incoming from encrypted area")
|
||||
|
||||
print("Verification matrix activated.:")
|
||||
for u in uuids:
|
||||
print(u)
|
||||
|
||||
print(". Titan Message: ", message)
|
||||
|
||||
|
||||
# Run the main function
|
||||
asyncio.run(main())
|
||||
# We can observe the trace in the AgentOps dashboard by going to the trace URL provided above.
|
||||
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
agentops.validate_trace_spans(trace_context=None)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
@@ -0,0 +1,344 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Anthropic Sync Example\n",
|
||||
"\n",
|
||||
"We are going to create a program called \"Nier Storyteller\". In short, it uses a message system similar to Nier Automata's to generate a one sentence summary before creating a short story.\n",
|
||||
"\n",
|
||||
"Example:\n",
|
||||
"\n",
|
||||
"{A foolish doll} {died in a world} {of ended dreams.} turns into \"In a forgotten land where sunlight barely touched the ground, a little doll wandered through the remains of shattered dreams. Its porcelain face, cracked and wea...\""
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"First, we start by importing Agentops and Anthropic"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"execution": {
|
||||
"iopub.execute_input": "2024-11-09T19:19:24.428838Z",
|
||||
"iopub.status.busy": "2024-11-09T19:19:24.428366Z",
|
||||
"iopub.status.idle": "2024-11-09T19:19:58.542271Z",
|
||||
"shell.execute_reply": "2024-11-09T19:19:58.540331Z",
|
||||
"shell.execute_reply.started": "2024-11-09T19:19:24.428796Z"
|
||||
},
|
||||
"trusted": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%pip install agentops\n",
|
||||
"%pip install anthropic"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Setup our generic default statements"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"execution": {
|
||||
"iopub.execute_input": "2024-11-09T19:20:59.991361Z",
|
||||
"iopub.status.busy": "2024-11-09T19:20:59.990855Z",
|
||||
"iopub.status.idle": "2024-11-09T19:21:00.999929Z",
|
||||
"shell.execute_reply": "2024-11-09T19:21:00.998751Z",
|
||||
"shell.execute_reply.started": "2024-11-09T19:20:59.991315Z"
|
||||
},
|
||||
"trusted": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from anthropic import Anthropic\n",
|
||||
"import agentops\n",
|
||||
"from dotenv import load_dotenv\n",
|
||||
"import os\n",
|
||||
"import random"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"And set our API keys."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"execution": {
|
||||
"iopub.execute_input": "2024-11-09T19:21:23.838837Z",
|
||||
"iopub.status.busy": "2024-11-09T19:21:23.838379Z",
|
||||
"iopub.status.idle": "2024-11-09T19:21:23.845690Z",
|
||||
"shell.execute_reply": "2024-11-09T19:21:23.844372Z",
|
||||
"shell.execute_reply.started": "2024-11-09T19:21:23.838785Z"
|
||||
},
|
||||
"trusted": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"load_dotenv()\n",
|
||||
"os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\", \"your_api_key_here\")\n",
|
||||
"os.environ[\"ANTHROPIC_API_KEY\"] = os.getenv(\"ANTHROPIC_API_KEY\", \"your_anthropic_api_key_here\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Now let's set the client as Anthropic and an AgentOps session!"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"execution": {
|
||||
"iopub.execute_input": "2024-11-09T19:21:25.808135Z",
|
||||
"iopub.status.busy": "2024-11-09T19:21:25.807585Z",
|
||||
"iopub.status.idle": "2024-11-09T19:21:25.828306Z",
|
||||
"shell.execute_reply": "2024-11-09T19:21:25.826994Z",
|
||||
"shell.execute_reply.started": "2024-11-09T19:21:25.808078Z"
|
||||
},
|
||||
"trusted": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"client = Anthropic()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"trusted": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"agentops.init(auto_start_session=False)\n",
|
||||
"tracer = agentops.start_trace(trace_name=\"Anthropic Sync Example\", tags=[\"anthropic-example\", \"agentops-example\"])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Remember that story we made earlier? As of writing, claude-3-5-sonnet-20240620 (the version we will be using) has a 150k word, 680k character length. We also get an 8192 context length. This is great because we can actually set an example for the script! \n",
|
||||
"\n",
|
||||
"Let's assume we have user (the person speaking), assistant (the AI itself) for now and computer (the way the LLM gets references from)."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Let's set a default story as a script!"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"execution": {
|
||||
"iopub.execute_input": "2024-11-09T19:21:34.091673Z",
|
||||
"iopub.status.busy": "2024-11-09T19:21:34.091200Z",
|
||||
"iopub.status.idle": "2024-11-09T19:21:34.098273Z",
|
||||
"shell.execute_reply": "2024-11-09T19:21:34.096957Z",
|
||||
"shell.execute_reply.started": "2024-11-09T19:21:34.091630Z"
|
||||
},
|
||||
"trusted": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"defaultstory = \"In a forgotten land where sunlight barely touched the ground, a little doll wandered through the remains of shattered dreams. Its porcelain face, cracked and weathered, reflected the emptiness that hung in the air like a lingering fog. The doll's painted eyes, now chipped and dull, stared into the distance, searching for something—anything—that still held life. It had once belonged to a child who dreamt of endless adventures, of castles in the clouds and whispered secrets under starry skies. But those dreams had long since crumbled to dust, leaving behind nothing but a hollow world where even hope dared not tread. The doll, a relic of a life that had faded, trudged through the darkness, its tiny feet stumbling over broken wishes and forgotten stories. Each step took more effort than the last, as if the world itself pulled at the doll's limbs, weary and bitter. It reached a place where the ground fell away into an abyss of despair, the edge crumbling under its weight. The doll paused, teetering on the brink. It reached out, as though to catch a fading dream, but there was nothing left to hold onto. With a faint crack, its brittle body gave way, and the doll tumbled silently into the void. And so, in a world where dreams had died, the foolish little doll met its end. There were no tears, no mourning. Only the soft, empty echo of its fall, fading into the darkness, as the land of ended dreams swallowed the last trace of what once was.\""
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"We are almost done! Let's generate a one sentence story summary by taking 3 random sentence fragments and connecting them!"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"execution": {
|
||||
"iopub.execute_input": "2024-11-09T19:21:35.472609Z",
|
||||
"iopub.status.busy": "2024-11-09T19:21:35.472107Z",
|
||||
"iopub.status.idle": "2024-11-09T19:21:35.481452Z",
|
||||
"shell.execute_reply": "2024-11-09T19:21:35.480022Z",
|
||||
"shell.execute_reply.started": "2024-11-09T19:21:35.472556Z"
|
||||
},
|
||||
"trusted": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Define the lists\n",
|
||||
"first = [\n",
|
||||
" \"A unremarkable soldier\",\n",
|
||||
" \"A lone swordsman\",\n",
|
||||
" \"A lone lancer\",\n",
|
||||
" \"A lone pugilist\",\n",
|
||||
" \"A dual-wielder\",\n",
|
||||
" \"A weaponless soldier\",\n",
|
||||
" \"A beautiful android\",\n",
|
||||
" \"A small android\",\n",
|
||||
" \"A double-crossing android\",\n",
|
||||
" \"A weapon carrying android\",\n",
|
||||
"]\n",
|
||||
"\n",
|
||||
"second = [\n",
|
||||
" \"felt despair at this cold world\",\n",
|
||||
" \"held nothing back\",\n",
|
||||
" \"gave it all\",\n",
|
||||
" \"could not get up again\",\n",
|
||||
" \"grimaced in anger\",\n",
|
||||
" \"missed the chance of a lifetime\",\n",
|
||||
" \"couldn't find a weakpoint\",\n",
|
||||
" \"was overwhelmed\",\n",
|
||||
" \"was totally outmatched\",\n",
|
||||
" \"was distracted by a flower\",\n",
|
||||
" \"hesitated to land the killing blow\",\n",
|
||||
" \"was attacked from behind\",\n",
|
||||
" \"fell to the ground\",\n",
|
||||
"]\n",
|
||||
"\n",
|
||||
"third = [\n",
|
||||
" \"in a dark hole beneath a city\",\n",
|
||||
" \"underground\",\n",
|
||||
" \"at the enemy's lair\",\n",
|
||||
" \"inside an empty ship\",\n",
|
||||
" \"at a tower built by the gods\",\n",
|
||||
" \"on a tower smiled upon by angels\",\n",
|
||||
" \"inside a tall tower\",\n",
|
||||
" \"at a peace-loving village\",\n",
|
||||
" \"at a village of refugees\",\n",
|
||||
" \"in the free skies\",\n",
|
||||
" \"below dark skies\",\n",
|
||||
" \"in a blood-soaked battlefield\",\n",
|
||||
"]\n",
|
||||
"\n",
|
||||
"# Generate a random sentence\n",
|
||||
"generatedsentence = f\"{random.choice(first)} {random.choice(second)} {random.choice(third)}.\""
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"And now to construct a stream/message! We set an example for the assistant now!"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"execution": {
|
||||
"iopub.execute_input": "2024-11-09T19:21:38.031580Z",
|
||||
"iopub.status.busy": "2024-11-09T19:21:38.031097Z",
|
||||
"iopub.status.idle": "2024-11-09T19:21:47.760983Z",
|
||||
"shell.execute_reply": "2024-11-09T19:21:47.759589Z",
|
||||
"shell.execute_reply.started": "2024-11-09T19:21:38.031536Z"
|
||||
},
|
||||
"trusted": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"stream = client.messages.create(\n",
|
||||
" max_tokens=2400,\n",
|
||||
" model=\"claude-3-7-sonnet-20250219\", # Comma added here\n",
|
||||
" messages=[\n",
|
||||
" {\n",
|
||||
" \"role\": \"user\",\n",
|
||||
" \"content\": \"Create a story based on the three sentence fragments given to you, it has been combined into one below.\",\n",
|
||||
" },\n",
|
||||
" {\n",
|
||||
" \"role\": \"assistant\",\n",
|
||||
" \"content\": \"{A foolish doll} {died in a world} {of ended dreams.}\",\n",
|
||||
" },\n",
|
||||
" {\"role\": \"assistant\", \"content\": defaultstory},\n",
|
||||
" {\n",
|
||||
" \"role\": \"user\",\n",
|
||||
" \"content\": \"Create a story based on the three sentence fragments given to you, it has been combined into one below.\",\n",
|
||||
" },\n",
|
||||
" {\"role\": \"assistant\", \"content\": generatedsentence},\n",
|
||||
" ],\n",
|
||||
" stream=True,\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"response = \"\"\n",
|
||||
"for event in stream:\n",
|
||||
" if event.type == \"content_block_delta\":\n",
|
||||
" response += event.delta.text\n",
|
||||
" elif event.type == \"message_stop\":\n",
|
||||
" print(generatedsentence)\n",
|
||||
" print(response)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"We can observe the session in the AgentOps dashboard by going to the session URL provided above.\n",
|
||||
"\n",
|
||||
"Now we will end the session with a success message. We can also end the session with a failure or intdeterminate status. By default, the session will be marked as indeterminate."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"trusted": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"agentops.end_trace(tracer, end_state=\"Success\")"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kaggle": {
|
||||
"accelerator": "none",
|
||||
"dataSources": [],
|
||||
"dockerImageVersionId": 30786,
|
||||
"isGpuEnabled": false,
|
||||
"isInternetEnabled": true,
|
||||
"language": "python",
|
||||
"sourceType": "notebook"
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "agentops (3.11.11)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.11"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 4
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
# # Anthropic Sync Example
|
||||
#
|
||||
# We are going to create a program called "Nier Storyteller". In short, it uses a message system similar to Nier Automata's to generate a one sentence summary before creating a short story.
|
||||
#
|
||||
# Example:
|
||||
#
|
||||
# {A foolish doll} {died in a world} {of ended dreams.} turns into "In a forgotten land where sunlight barely touched the ground, a little doll wandered through the remains of shattered dreams. Its porcelain face, cracked and wea..."
|
||||
# First, we start by importing Agentops and Anthropic
|
||||
# %pip install agentops
|
||||
# %pip install anthropic
|
||||
# Setup our generic default statements
|
||||
from anthropic import Anthropic
|
||||
import agentops
|
||||
from dotenv import load_dotenv
|
||||
import os
|
||||
import random
|
||||
|
||||
# And set our API keys.
|
||||
load_dotenv()
|
||||
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY", "your_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 an AgentOps session!
|
||||
client = Anthropic()
|
||||
agentops.init(auto_start_session=False, trace_name="Anthropic Sync Example")
|
||||
tracer = agentops.start_trace(trace_name="Anthropic Sync Example", tags=["anthropic-example", "agentops-example"])
|
||||
# Remember that story we made earlier? As of writing, claude-3-5-sonnet-20240620 (the version we will be using) has a 150k word, 680k character length. We also get an 8192 context length. This is great because we can actually set an example for the script!
|
||||
#
|
||||
# Let's assume we have user (the person speaking), assistant (the AI itself) for now and computer (the way the LLM gets references from).
|
||||
# Let's set a default story as a script!
|
||||
defaultstory = "In a forgotten land where sunlight barely touched the ground, a little doll wandered through the remains of shattered dreams. Its porcelain face, cracked and weathered, reflected the emptiness that hung in the air like a lingering fog. The doll's painted eyes, now chipped and dull, stared into the distance, searching for something—anything—that still held life. It had once belonged to a child who dreamt of endless adventures, of castles in the clouds and whispered secrets under starry skies. But those dreams had long since crumbled to dust, leaving behind nothing but a hollow world where even hope dared not tread. The doll, a relic of a life that had faded, trudged through the darkness, its tiny feet stumbling over broken wishes and forgotten stories. Each step took more effort than the last, as if the world itself pulled at the doll's limbs, weary and bitter. It reached a place where the ground fell away into an abyss of despair, the edge crumbling under its weight. The doll paused, teetering on the brink. It reached out, as though to catch a fading dream, but there was nothing left to hold onto. With a faint crack, its brittle body gave way, and the doll tumbled silently into the void. And so, in a world where dreams had died, the foolish little doll met its end. There were no tears, no mourning. Only the soft, empty echo of its fall, fading into the darkness, as the land of ended dreams swallowed the last trace of what once was."
|
||||
# We are almost done! Let's generate a one sentence story summary by taking 3 random sentence fragments and connecting them!
|
||||
# Define the lists
|
||||
first = [
|
||||
"A unremarkable soldier",
|
||||
"A lone swordsman",
|
||||
"A lone lancer",
|
||||
"A lone pugilist",
|
||||
"A dual-wielder",
|
||||
"A weaponless soldier",
|
||||
"A beautiful android",
|
||||
"A small android",
|
||||
"A double-crossing android",
|
||||
"A weapon carrying android",
|
||||
]
|
||||
|
||||
second = [
|
||||
"felt despair at this cold world",
|
||||
"held nothing back",
|
||||
"gave it all",
|
||||
"could not get up again",
|
||||
"grimaced in anger",
|
||||
"missed the chance of a lifetime",
|
||||
"couldn't find a weakpoint",
|
||||
"was overwhelmed",
|
||||
"was totally outmatched",
|
||||
"was distracted by a flower",
|
||||
"hesitated to land the killing blow",
|
||||
"was attacked from behind",
|
||||
"fell to the ground",
|
||||
]
|
||||
|
||||
third = [
|
||||
"in a dark hole beneath a city",
|
||||
"underground",
|
||||
"at the enemy's lair",
|
||||
"inside an empty ship",
|
||||
"at a tower built by the gods",
|
||||
"on a tower smiled upon by angels",
|
||||
"inside a tall tower",
|
||||
"at a peace-loving village",
|
||||
"at a village of refugees",
|
||||
"in the free skies",
|
||||
"below dark skies",
|
||||
"in a blood-soaked battlefield",
|
||||
]
|
||||
|
||||
# Generate a random sentence
|
||||
generatedsentence = f"{random.choice(first)} {random.choice(second)} {random.choice(third)}."
|
||||
# And now to construct a stream/message! We set an example for the assistant now!
|
||||
stream = client.messages.create(
|
||||
max_tokens=2400,
|
||||
model="claude-3-7-sonnet-20250219", # Comma added here
|
||||
messages=[
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Create a story based on the three sentence fragments given to you, it has been combined into one below.",
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": "{A foolish doll} {died in a world} {of ended dreams.}",
|
||||
},
|
||||
{"role": "assistant", "content": defaultstory},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Create a story based on the three sentence fragments given to you, it has been combined into one below.",
|
||||
},
|
||||
{"role": "assistant", "content": generatedsentence},
|
||||
],
|
||||
stream=True,
|
||||
)
|
||||
|
||||
response = ""
|
||||
for event in stream:
|
||||
if event.type == "content_block_delta":
|
||||
response += event.delta.text
|
||||
elif event.type == "message_stop":
|
||||
print(generatedsentence)
|
||||
print(response)
|
||||
# We can observe the session in the AgentOps dashboard by going to the session URL provided above.
|
||||
#
|
||||
# Now we will end the session with a success message. We can also end the session with a failure or intdeterminate status. By default, the session will be marked as indeterminate.
|
||||
agentops.end_trace(tracer, end_state="Success")
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
agentops.validate_trace_spans(trace_context=tracer)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
@@ -0,0 +1 @@
|
||||
anthropic
|
||||
@@ -0,0 +1,228 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"id": "bb6538d8-2a5d-4a99-b2c1-7130963e4f7b",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Microsoft Autogen Chat Example\n",
|
||||
"\n",
|
||||
"AgentOps automatically configures itself when it's initialized meaning your agent run data will be tracked and logged to your AgentOps dashboard right away."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "87626697",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"First let's install the required packages"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "9599cf93",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%pip install -U autogen-agentchat\n",
|
||||
"%pip install -U \"autogen-ext[openai]\"\n",
|
||||
"%pip install -U agentops\n",
|
||||
"%pip install -U python-dotenv"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "3506f401",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Then import them"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "1b5c8b7b",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"from dotenv import load_dotenv\n",
|
||||
"from IPython.core.error import (\n",
|
||||
" StdinNotImplementedError,\n",
|
||||
")\n",
|
||||
"import asyncio\n",
|
||||
"\n",
|
||||
"import agentops\n",
|
||||
"\n",
|
||||
"from autogen_agentchat.agents import AssistantAgent, UserProxyAgent\n",
|
||||
"from autogen_ext.models.openai import OpenAIChatCompletionClient\n",
|
||||
"\n",
|
||||
"from autogen_agentchat.teams import RoundRobinGroupChat\n",
|
||||
"from autogen_agentchat.conditions import MaxMessageTermination\n",
|
||||
"from autogen_agentchat.ui import Console"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "70b502a2",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"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.\n",
|
||||
"\n",
|
||||
"[Get an AgentOps API key](https://agentops.ai/settings/projects)\n",
|
||||
"\n",
|
||||
"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...\n",
|
||||
"\n",
|
||||
"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!"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "7ae4152d",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"load_dotenv()\n",
|
||||
"os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\", \"your_api_key_here\")\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\", \"your_openai_api_key_here\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "d93f2339-7b99-4cf1-9232-c24faba49c7b",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# When initializing AgentOps, you can pass in optional tags to help filter sessions\n",
|
||||
"agentops.init(auto_start_session=False)\n",
|
||||
"tracer = agentops.start_trace(\n",
|
||||
" trace_name=\"Microsoft Agent Chat Example\", tags=[\"autogen-chat\", \"microsoft-autogen\", \"agentops-example\"]\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "7858f0f6-9aca-4cdb-a514-9fbf7e353d50",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"AutoGen will now start automatically tracking\n",
|
||||
"\n",
|
||||
"* LLM prompts and completions\n",
|
||||
"* Token usage and costs\n",
|
||||
"* Agent names and actions\n",
|
||||
"* Correspondence between agents\n",
|
||||
"* Tool usage\n",
|
||||
"* Errors"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "e875dd0c",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Simple Chat Example"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "2962d990-f7ef-43d8-ba09-d29bd8356d9f",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Define model and API key\n",
|
||||
"model_name = \"gpt-4-turbo\" # Or \"gpt-4o\" / \"gpt-4o-mini\" as per migration guide examples\n",
|
||||
"api_key = os.getenv(\"OPENAI_API_KEY\")\n",
|
||||
"\n",
|
||||
"# Create the model client\n",
|
||||
"model_client = OpenAIChatCompletionClient(model=model_name, api_key=api_key)\n",
|
||||
"\n",
|
||||
"# Create the agent that uses the LLM.\n",
|
||||
"assistant = AssistantAgent(\n",
|
||||
" name=\"assistant\",\n",
|
||||
" system_message=\"You are a helpful assistant.\", # Added system message for clarity\n",
|
||||
" model_client=model_client,\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"user_proxy_initiator = UserProxyAgent(\"user_initiator\")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"async def main():\n",
|
||||
" termination = MaxMessageTermination(max_messages=2)\n",
|
||||
"\n",
|
||||
" group_chat = RoundRobinGroupChat(\n",
|
||||
" [user_proxy_initiator, assistant], # Corrected: agents as positional argument\n",
|
||||
" termination_condition=termination,\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" chat_task = \"How can I help you today?\"\n",
|
||||
" print(f\"User Initiator: {chat_task}\")\n",
|
||||
"\n",
|
||||
" try:\n",
|
||||
" stream = group_chat.run_stream(task=chat_task)\n",
|
||||
" await Console().run(stream)\n",
|
||||
" agentops.end_trace(tracer, end_state=\"Success\")\n",
|
||||
"\n",
|
||||
" except StdinNotImplementedError:\n",
|
||||
" print(\"StdinNotImplementedError: This typically happens in non-interactive environments.\")\n",
|
||||
" print(\"Skipping interactive part of chat for automation.\")\n",
|
||||
" agentops.end_trace(tracer, end_state=\"Indeterminate\")\n",
|
||||
" except Exception as e:\n",
|
||||
" print(f\"An error occurred: {e}\")\n",
|
||||
" agentops.end_trace(tracer, end_state=\"Error\")\n",
|
||||
" finally:\n",
|
||||
" await model_client.close()\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"if __name__ == \"__main__\":\n",
|
||||
" try:\n",
|
||||
" loop = asyncio.get_running_loop()\n",
|
||||
" except RuntimeError:\n",
|
||||
" loop = None\n",
|
||||
"\n",
|
||||
" if loop and loop.is_running():\n",
|
||||
" import nest_asyncio\n",
|
||||
"\n",
|
||||
" nest_asyncio.apply()\n",
|
||||
" asyncio.run(main())\n",
|
||||
" else:\n",
|
||||
" asyncio.run(main())"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "7b422137-903a-41ef-a4ca-95b50aea4138",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"You can view data on this run at [app.agentops.ai](https://app.agentops.ai).\n",
|
||||
"\n",
|
||||
"The dashboard will display LLM events for each message sent by each agent, including those made by the human user."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "agentops (3.11.11)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.11"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
# Microsoft Autogen Multi-Agent Collaboration Example
|
||||
#
|
||||
# This example demonstrates AI-to-AI collaboration using multiple specialized agents working together without human interaction.
|
||||
# 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
|
||||
# %pip install -U autogen-agentchat
|
||||
# %pip install -U "autogen-ext[openai]"
|
||||
# %pip install -U agentops
|
||||
# %pip install -U python-dotenv
|
||||
# Then import them
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
import asyncio
|
||||
|
||||
import agentops
|
||||
|
||||
from autogen_agentchat.agents import AssistantAgent
|
||||
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!
|
||||
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")
|
||||
|
||||
# When initializing AgentOps, you can pass in optional tags to help filter sessions
|
||||
agentops.init(auto_start_session=False, trace_name="Autogen Multi-Agent Collaboration Example")
|
||||
tracer = agentops.start_trace(
|
||||
trace_name="Microsoft Multi-Agent Collaboration Example",
|
||||
tags=["autogen-collaboration", "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
|
||||
# # Multi-Agent Collaboration Example
|
||||
# Define model and API key
|
||||
model_name = "gpt-4o-mini" # 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 multiple AI agents with different roles
|
||||
research_agent = AssistantAgent(
|
||||
name="research_agent",
|
||||
system_message="You are a research specialist. Your role is to gather information, analyze data, and provide insights on topics. You ask thoughtful questions and provide well-researched responses.",
|
||||
model_client=model_client,
|
||||
)
|
||||
|
||||
creative_agent = AssistantAgent(
|
||||
name="creative_agent",
|
||||
system_message="You are a creative strategist. Your role is to brainstorm innovative solutions, think outside the box, and propose creative approaches to problems. You build on others' ideas and suggest novel perspectives.",
|
||||
model_client=model_client,
|
||||
)
|
||||
|
||||
analyst_agent = AssistantAgent(
|
||||
name="analyst_agent",
|
||||
system_message="You are a critical analyst. Your role is to evaluate ideas, identify strengths and weaknesses, and provide constructive feedback. You help refine concepts and ensure practical feasibility.",
|
||||
model_client=model_client,
|
||||
)
|
||||
|
||||
|
||||
async def main():
|
||||
# Set up a longer conversation to allow for meaningful AI-to-AI interaction
|
||||
termination = MaxMessageTermination(max_messages=8)
|
||||
|
||||
group_chat = RoundRobinGroupChat(
|
||||
[research_agent, creative_agent, analyst_agent], # AI agents working together
|
||||
termination_condition=termination,
|
||||
)
|
||||
|
||||
# A task that will engage all three agents in meaningful collaboration
|
||||
chat_task = "Let's develop a comprehensive strategy for reducing plastic waste in urban environments. I need research on current methods, creative solutions, and analysis of feasibility."
|
||||
print(f"🎯 Task: {chat_task}")
|
||||
print("\n" + "=" * 80)
|
||||
print("🤖 AI Agents Collaboration Starting...")
|
||||
print("=" * 80)
|
||||
|
||||
try:
|
||||
stream = group_chat.run_stream(task=chat_task)
|
||||
await Console(stream=stream)
|
||||
agentops.end_trace(tracer, end_state="Success")
|
||||
|
||||
except Exception as e:
|
||||
print(f"An error occurred: {e}")
|
||||
agentops.end_trace(tracer, end_state="Error")
|
||||
finally:
|
||||
await model_client.close()
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
agentops.validate_trace_spans(trace_context=tracer)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
|
||||
|
||||
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](app.agentops.ai).
|
||||
#
|
||||
# The dashboard will display LLM events for each message sent by each agent, showing the full AI-to-AI collaboration process with research, creative, and analytical perspectives.
|
||||
@@ -0,0 +1,244 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"attachments": {},
|
||||
"cell_type": "markdown",
|
||||
"id": "bb6538d8-2a5d-4a99-b2c1-7130963e4f7b",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Microsoft Autogen Tool Example\n",
|
||||
"\n",
|
||||
"AgentOps automatically configures itself when it's initialized meaning your agent run data will be tracked and logged to your AgentOps account right away."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "083244fa",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"First let's install the required packages"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "9c8104ad",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%pip install -U autogen-agentchat\n",
|
||||
"%pip install -U \"autogen-ext[openai]\"\n",
|
||||
"%pip install -U agentops\n",
|
||||
"%pip install -U python-dotenv"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "cc44e459",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Then import them"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "7672f591",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from typing import Annotated, Literal\n",
|
||||
"import asyncio\n",
|
||||
"import os\n",
|
||||
"from dotenv import load_dotenv\n",
|
||||
"from IPython.core.error import (\n",
|
||||
" StdinNotImplementedError,\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"import agentops\n",
|
||||
"\n",
|
||||
"from autogen_agentchat.agents import AssistantAgent\n",
|
||||
"from autogen_ext.models.openai import OpenAIChatCompletionClient\n",
|
||||
"from autogen_agentchat.messages import TextMessage"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "24f8bd70",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"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.\n",
|
||||
"\n",
|
||||
"[Get an AgentOps API key](https://agentops.ai/settings/projects)\n",
|
||||
"\n",
|
||||
"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...\n",
|
||||
"\n",
|
||||
"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!"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "9eeaef34",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"load_dotenv()\n",
|
||||
"os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\", \"your_api_key_here\")\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\", \"your_openai_api_key_here\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "d93f2339-7b99-4cf1-9232-c24faba49c7b",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"agentops.init(auto_start_session=False)\n",
|
||||
"tracer = agentops.start_trace(\n",
|
||||
" trace_name=\"Microsoft Autogen Tool Example\", tags=[\"autogen-tool\", \"microsoft-autogen\", \"agentops-example\"]\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "7858f0f6-9aca-4cdb-a514-9fbf7e353d50",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"AG2 will now start automatically tracking\n",
|
||||
"\n",
|
||||
"* LLM prompts and completions\n",
|
||||
"* Token usage and costs\n",
|
||||
"* Agent names and actions\n",
|
||||
"* Correspondence between agents\n",
|
||||
"* Tool usage\n",
|
||||
"* Errors"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "dc592637",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Tool Example\n",
|
||||
"AgentOps tracks when AG2 agents use tools. You can find more information on this example in [tool-use.ipynb](https://docs.ag2.ai/docs/tutorial/tool-use#tool-use)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "9e4dfe37-85e0-4035-a314-3459c6e378c4",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Define model and API key\n",
|
||||
"model_name = \"gpt-4-turbo\"\n",
|
||||
"api_key = os.getenv(\"OPENAI_API_KEY\")\n",
|
||||
"\n",
|
||||
"# Create the model client\n",
|
||||
"model_client = OpenAIChatCompletionClient(model=model_name, api_key=api_key, seed=42, temperature=0)\n",
|
||||
"\n",
|
||||
"Operator = Literal[\"+\", \"-\", \"*\", \"/\"]\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"def calculator(a: int, b: int, operator: Annotated[Operator, \"operator\"]) -> int:\n",
|
||||
" if operator == \"+\":\n",
|
||||
" return a + b\n",
|
||||
" elif operator == \"-\":\n",
|
||||
" return a - b\n",
|
||||
" elif operator == \"*\":\n",
|
||||
" return a * b\n",
|
||||
" elif operator == \"/\":\n",
|
||||
" return int(a / b)\n",
|
||||
" else:\n",
|
||||
" raise ValueError(\"Invalid operator\")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"async def main():\n",
|
||||
" assistant = AssistantAgent(\n",
|
||||
" name=\"Assistant\",\n",
|
||||
" system_message=\"You are a helpful AI assistant. You can help with simple calculations. Return 'TERMINATE' when the task is done.\",\n",
|
||||
" model_client=model_client,\n",
|
||||
" tools=[calculator],\n",
|
||||
" reflect_on_tool_use=True,\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" initial_task_message = \"What is (1423 - 123) / 3 + (32 + 23) * 5?\"\n",
|
||||
" print(f\"User Task: {initial_task_message}\")\n",
|
||||
"\n",
|
||||
" try:\n",
|
||||
" from autogen_core import CancellationToken\n",
|
||||
"\n",
|
||||
" response = await assistant.on_messages(\n",
|
||||
" [TextMessage(content=initial_task_message, source=\"user\")], CancellationToken()\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" final_response_message = response.chat_message\n",
|
||||
" if final_response_message:\n",
|
||||
" print(f\"Assistant: {final_response_message.to_text()}\")\n",
|
||||
" else:\n",
|
||||
" print(\"Assistant did not provide a final message.\")\n",
|
||||
"\n",
|
||||
" agentops.end_trace(tracer, end_state=\"Success\")\n",
|
||||
"\n",
|
||||
" except StdinNotImplementedError:\n",
|
||||
" print(\"StdinNotImplementedError: This typically happens in non-interactive environments.\")\n",
|
||||
" agentops.end_trace(tracer, end_state=\"Indeterminate\")\n",
|
||||
" except Exception as e:\n",
|
||||
" print(f\"An error occurred: {e}\")\n",
|
||||
" agentops.end_trace(tracer, end_state=\"Error\")\n",
|
||||
" finally:\n",
|
||||
" await model_client.close()\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"if __name__ == \"__main__\":\n",
|
||||
" try:\n",
|
||||
" loop = asyncio.get_running_loop()\n",
|
||||
" except RuntimeError:\n",
|
||||
" loop = None\n",
|
||||
"\n",
|
||||
" if loop and loop.is_running():\n",
|
||||
" import nest_asyncio\n",
|
||||
"\n",
|
||||
" nest_asyncio.apply()\n",
|
||||
" asyncio.run(main())\n",
|
||||
" else:\n",
|
||||
" asyncio.run(main())"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "f67b0305-1247-489e-b1b0-829127af76d3",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"You can see your run in action at [app.agentops.ai](app.agentops.ai). In this example, the AgentOps dashboard will show:\n",
|
||||
"\n",
|
||||
"* Agents talking to each other\n",
|
||||
"* Each use of the `calculator` tool\n",
|
||||
"* Each call to OpenAI for LLM use"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "agentops (3.11.11)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.11"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
# Microsoft Autogen Tool Example
|
||||
#
|
||||
# AgentOps automatically configures itself when it's initialized meaning your agent run data will be tracked and logged to your AgentOps account right away.
|
||||
# First let's install the required packages
|
||||
# %pip install -U autogen-agentchat
|
||||
# %pip install -U "autogen-ext[openai]"
|
||||
# %pip install -U agentops
|
||||
# %pip install -U python-dotenv
|
||||
# Then import them
|
||||
from typing import Annotated, Literal
|
||||
import asyncio
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
|
||||
import agentops
|
||||
|
||||
from autogen_agentchat.agents import AssistantAgent
|
||||
from autogen_ext.models.openai import OpenAIChatCompletionClient
|
||||
from autogen_agentchat.messages import TextMessage
|
||||
|
||||
# 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!
|
||||
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")
|
||||
|
||||
agentops.init(auto_start_session=False, trace_name="Autogen Math Agent Example")
|
||||
tracer = agentops.start_trace(
|
||||
trace_name="Microsoft Autogen Tool Example", tags=["autogen-tool", "microsoft-autogen", "agentops-example"]
|
||||
)
|
||||
|
||||
# AG2 will now start automatically tracking
|
||||
#
|
||||
# * LLM prompts and completions
|
||||
# * Token usage and costs
|
||||
# * Agent names and actions
|
||||
# * Correspondence between agents
|
||||
# * Tool usage
|
||||
# * Errors
|
||||
# # Tool Example
|
||||
# AgentOps tracks when AG2 agents use tools. You can find more information on this example in [tool-use.ipynb](https://docs.ag2.ai/docs/tutorial/tool-use#tool-use)
|
||||
# # Define model and API key
|
||||
model_name = "gpt-4-turbo"
|
||||
api_key = os.getenv("OPENAI_API_KEY")
|
||||
|
||||
# Create the model client
|
||||
model_client = OpenAIChatCompletionClient(model=model_name, api_key=api_key, seed=42, temperature=0)
|
||||
|
||||
Operator = Literal["+", "-", "*", "/"]
|
||||
|
||||
|
||||
def calculator(a: int, b: int, operator: Annotated[Operator, "operator"]) -> int:
|
||||
if operator == "+":
|
||||
return a + b
|
||||
elif operator == "-":
|
||||
return a - b
|
||||
elif operator == "*":
|
||||
return a * b
|
||||
elif operator == "/":
|
||||
return int(a / b)
|
||||
else:
|
||||
raise ValueError("Invalid operator")
|
||||
|
||||
|
||||
async def main():
|
||||
assistant = AssistantAgent(
|
||||
name="Assistant",
|
||||
system_message="You are a helpful AI assistant. You can help with simple calculations. Return 'TERMINATE' when the task is done.",
|
||||
model_client=model_client,
|
||||
tools=[calculator],
|
||||
reflect_on_tool_use=True,
|
||||
)
|
||||
|
||||
initial_task_message = "What is (1423 - 123) / 3 + (32 + 23) * 5?"
|
||||
print(f"User Task: {initial_task_message}")
|
||||
|
||||
try:
|
||||
from autogen_core import CancellationToken
|
||||
|
||||
response = await assistant.on_messages(
|
||||
[TextMessage(content=initial_task_message, source="user")], CancellationToken()
|
||||
)
|
||||
|
||||
final_response_message = response.chat_message
|
||||
if final_response_message:
|
||||
print(f"Assistant: {final_response_message.to_text()}")
|
||||
else:
|
||||
print("Assistant did not provide a final message.")
|
||||
|
||||
agentops.end_trace(tracer, end_state="Success")
|
||||
|
||||
except Exception as e:
|
||||
print(f"An error occurred: {e}")
|
||||
agentops.end_trace(tracer, end_state="Error")
|
||||
finally:
|
||||
await model_client.close()
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
agentops.validate_trace_spans(trace_context=tracer)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
|
||||
|
||||
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 see your run in action at [app.agentops.ai](app.agentops.ai). In this example, the AgentOps dashboard will show:
|
||||
#
|
||||
# * Agents talking to each other
|
||||
# * Each use of the `calculator` tool
|
||||
# * Each call to OpenAI for LLM use
|
||||
@@ -0,0 +1,32 @@
|
||||
# AutoGen Examples with AgentOps
|
||||
|
||||
This directory contains examples of using Microsoft AutoGen with AgentOps instrumentation for various agent-based tasks.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Python >= 3.10 < 3.13
|
||||
- Install required dependencies:
|
||||
```
|
||||
pip install agentops "ag2[retrievechat]"
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### 1. Agent Chat
|
||||
|
||||
Example: `AgentChat`
|
||||
This example demonstrates:
|
||||
- Basic agent chat functionality
|
||||
|
||||
### 2. Math Agent
|
||||
|
||||
Example: `MathAgent`
|
||||
|
||||
This example demonstrates:
|
||||
- A mathematical problem-solving agent
|
||||
|
||||
## AgentOps Integration
|
||||
|
||||
These examples show how to use AgentOps to monitor and analyze your AI applications. AgentOps automatically instruments your AutoGen calls to provide insights into performance, usage patterns, and model behavior.
|
||||
|
||||
To learn more about AgentOps, visit [https://www.agentops.ai](https://www.agentops.ai)
|
||||
@@ -0,0 +1,2 @@
|
||||
autogen-agentchat==0.6.1
|
||||
autogen-ext[openai]
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,55 @@
|
||||
```markdown
|
||||
**Job Title: Software Engineer**
|
||||
|
||||
**Company: AgentOps.ai**
|
||||
|
||||
**Location: [Location/Remote]**
|
||||
|
||||
**About AgentOps.ai:**
|
||||
At AgentOps.ai, we are revolutionizing the field of conversational AI by providing robust, scalable, and efficient solutions that ensure seamless integration and optimal performance of AI agents. Our mission is to empower businesses with cutting-edge AI technologies that enhance customer experiences and drive operational efficiency. We believe in fostering a culture of innovation, collaboration, and continuous learning.
|
||||
|
||||
**Introduction:**
|
||||
Are you passionate about building innovative software solutions and enhancing AI agent observability? AgentOps.ai is looking for a skilled Software Engineer to join our dynamic team. In this role, you will have the opportunity to work on groundbreaking projects that involve tracking and analyzing the performance, behavior, and interactions of AI agents in real-time. If you are a detail-oriented problem solver with a desire to create impactful software, we want to hear from you!
|
||||
|
||||
**Role Description:**
|
||||
As a Software Engineer at AgentOps.ai, you will be responsible for designing and building tools and frameworks to automate the development, testing, deployment, and management of services and products. You will play a key role in planning and executing the full software development lifecycle for assigned projects, ensuring scalability and efficiency of distributed software and applications. Collaboration with product managers and user-experience designers will be essential to influence the strategy and delivery of next-wave product features and system capabilities.
|
||||
|
||||
**Responsibilities:**
|
||||
- Design and build tools and frameworks to automate the development, testing, deployment, and management of services and products.
|
||||
- Plan and execute the full software development lifecycle for each assigned project, adhering to company standards and expectations.
|
||||
- Plan and scale distributed software and applications using synchronous and asynchronous design patterns.
|
||||
- Work with product managers and user-experience designers to influence the strategy and delivery of next-wave product features and system capabilities.
|
||||
- Track, document, and maintain software and network system functionality, leveraging opportunities to improve engineering.
|
||||
|
||||
**Required Skills and Qualifications:**
|
||||
- **Programming Languages:** Proficiency in Java, Python, and C++ is essential.
|
||||
- **Scripting and Automation:** Strong ability in scripting and test automation.
|
||||
- **Web Technologies:** Proficiency with HTML5, CSS3, and content management systems.
|
||||
- **Relational Databases:** Working knowledge of ORM and SQL technologies.
|
||||
- **Software Development:** Experience with rapid development cycles in a web-based environment, including full software development lifecycle.
|
||||
- **Frameworks:** Knowledge of frameworks such as Wicket, GWT, and Spring MVC.
|
||||
- **Engineering Experience:** Five or more years of experience as an engineer of software and networking platforms.
|
||||
- **Development Experience:** Seven or more years of combined professional and academic experience in relevant programming languages.
|
||||
- **Documentation:** Proven ability to document design processes, including development, testing, analytics, and troubleshooting.
|
||||
- **Web Application Development:** Experience in developing web applications with multiple technologies.
|
||||
- **Network Systems:** Experience in testing and evaluating current networking systems.
|
||||
- **Collaboration:** Ability to work with global teams to produce project plans and analyze project operations.
|
||||
- **Problem-Solving:** Highly motivated to find technical issues and fix them with meticulous code.
|
||||
- **Detail-Oriented:** Focus on creating software and networking platforms free of faulty programming without compromising site reliability.
|
||||
- **Innovation:** Ability to visualize, design, and develop innovative software platforms.
|
||||
- **Continuous Learning:** Desire to continue professional growth through training and education.
|
||||
- **Educational Background:** Bachelor’s degree (or equivalent) in software engineering or information technology.
|
||||
|
||||
**Company Benefits:**
|
||||
- Competitive salary and performance bonuses
|
||||
- Health, dental, and vision insurance
|
||||
- Generous paid time off and holidays
|
||||
- Professional development opportunities
|
||||
- Collaborative and innovative work environment
|
||||
- Free sandwiches (yes, you read that right!)
|
||||
|
||||
**How to Apply:**
|
||||
If you are ready to take your career to the next level and join a company that values innovation and excellence, apply today by submitting your resume and cover letter to [email address] with the subject line "Software Engineer Application - [Your Name]". We look forward to meeting you!
|
||||
|
||||
**AgentOps.ai is an equal opportunity employer. We celebrate diversity and are committed to creating an inclusive environment for all employees.**
|
||||
```
|
||||
@@ -0,0 +1,32 @@
|
||||
# CrewAI Examples with AgentOps
|
||||
|
||||
This directory contains examples of using CrewAI with AgentOps instrumentation for various multi-agent automation tasks.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Python >= 3.10 < 3.13
|
||||
- Install required dependencies:
|
||||
```
|
||||
pip install agentops 'crewai[tools]'
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### 1. Job Posting
|
||||
|
||||
Example: `job_posting`
|
||||
This example demonstrates:
|
||||
- A job posting automation workflow
|
||||
|
||||
### 2. Markdown Validator
|
||||
|
||||
Example: `markdown_validator`
|
||||
|
||||
This example demonstrates:
|
||||
- A markdown validation agent
|
||||
|
||||
## AgentOps Integration
|
||||
|
||||
These examples show how to use AgentOps to monitor and analyze your AI applications. AgentOps automatically instruments your CrewAI calls to provide insights into performance, usage patterns, and model behavior.
|
||||
|
||||
To learn more about AgentOps, visit [https://www.agentops.ai](https://www.agentops.ai)
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,186 @@
|
||||
# Crew Job Posting
|
||||
|
||||
# First let's install the required packages
|
||||
# %pip install -U 'crewai[tools]'
|
||||
# Then import them
|
||||
from crewai import Crew, Agent, Task
|
||||
from crewai_tools.tools import WebsiteSearchTool, SerperDevTool, FileReadTool
|
||||
import agentops
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
from textwrap import dedent
|
||||
|
||||
# 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!
|
||||
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["SERPER_API_KEY"] = os.getenv("SERPER_API_KEY", "your_serper_api_key_here")
|
||||
|
||||
# Initialize AgentOps client
|
||||
agentops.init(
|
||||
auto_start_session=False, trace_name="CrewAI Job Posting", tags=["crewai", "job-posting", "agentops-example"]
|
||||
)
|
||||
|
||||
web_search_tool = WebsiteSearchTool()
|
||||
serper_dev_tool = SerperDevTool()
|
||||
file_read_tool = FileReadTool(
|
||||
file_path="job_description_example.md",
|
||||
description="A tool to read the job description example file.",
|
||||
)
|
||||
|
||||
|
||||
class Agents:
|
||||
def research_agent(self):
|
||||
return Agent(
|
||||
role="Research Analyst",
|
||||
goal="Analyze the company website and provided description to extract insights on culture, values, and specific needs.",
|
||||
tools=[web_search_tool, serper_dev_tool],
|
||||
backstory="Expert in analyzing company cultures and identifying key values and needs from various sources, including websites and brief descriptions.",
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
def writer_agent(self):
|
||||
return Agent(
|
||||
role="Job Description Writer",
|
||||
goal="Use insights from the Research Analyst to create a detailed, engaging, and enticing job posting.",
|
||||
tools=[web_search_tool, serper_dev_tool, file_read_tool],
|
||||
backstory="Skilled in crafting compelling job descriptions that resonate with the company's values and attract the right candidates.",
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
def review_agent(self):
|
||||
return Agent(
|
||||
role="Review and Editing Specialist",
|
||||
goal="Review the job posting for clarity, engagement, grammatical accuracy, and alignment with company values and refine it to ensure perfection.",
|
||||
tools=[web_search_tool, serper_dev_tool, file_read_tool],
|
||||
backstory="A meticulous editor with an eye for detail, ensuring every piece of content is clear, engaging, and grammatically perfect.",
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
|
||||
class Tasks:
|
||||
def research_company_culture_task(self, agent, company_description, company_domain):
|
||||
return Task(
|
||||
description=dedent(
|
||||
f"""\
|
||||
Analyze the provided company website and the hiring manager's company's domain {company_domain}, description: "{company_description}". Focus on understanding the company's culture, values, and mission. Identify unique selling points and specific projects or achievements highlighted on the site.
|
||||
Compile a report summarizing these insights, specifically how they can be leveraged in a job posting to attract the right candidates."""
|
||||
),
|
||||
expected_output=dedent(
|
||||
"""\
|
||||
A comprehensive report detailing the company's culture, values, and mission, along with specific selling points relevant to the job role. Suggestions on incorporating these insights into the job posting should be included."""
|
||||
),
|
||||
agent=agent,
|
||||
)
|
||||
|
||||
def research_role_requirements_task(self, agent, hiring_needs):
|
||||
return Task(
|
||||
description=dedent(
|
||||
f"""\
|
||||
Based on the hiring manager's needs: "{hiring_needs}", identify the key skills, experiences, and qualities the ideal candidate should possess for the role. Consider the company's current projects, its competitive landscape, and industry trends. Prepare a list of recommended job requirements and qualifications that align with the company's needs and values."""
|
||||
),
|
||||
expected_output=dedent(
|
||||
"""\
|
||||
A list of recommended skills, experiences, and qualities for the ideal candidate, aligned with the company's culture, ongoing projects, and the specific role's requirements."""
|
||||
),
|
||||
agent=agent,
|
||||
)
|
||||
|
||||
def draft_job_posting_task(self, agent, company_description, hiring_needs, specific_benefits):
|
||||
return Task(
|
||||
description=dedent(
|
||||
f"""\
|
||||
Draft a job posting for the role described by the hiring manager: "{hiring_needs}". Use the insights on "{company_description}" to start with a compelling introduction, followed by a detailed role description, responsibilities, and required skills and qualifications. Ensure the tone aligns with the company's culture and incorporate any unique benefits or opportunities offered by the company.
|
||||
Specfic benefits: "{specific_benefits}"""
|
||||
),
|
||||
expected_output=dedent(
|
||||
"""\
|
||||
A detailed, engaging job posting that includes an introduction, role description, responsibilities, requirements, and unique company benefits. The tone should resonate with the company's culture and values, aimed at attracting the right candidates."""
|
||||
),
|
||||
agent=agent,
|
||||
)
|
||||
|
||||
def review_and_edit_job_posting_task(self, agent, hiring_needs):
|
||||
return Task(
|
||||
description=dedent(
|
||||
f"""\
|
||||
Review the draft job posting for the role: "{hiring_needs}". Check for clarity, engagement, grammatical accuracy, and alignment with the company's culture and values. Edit and refine the content, ensuring it speaks directly to the desired candidates and accurately reflects the role's unique benefits and opportunities. Provide feedback for any necessary revisions."""
|
||||
),
|
||||
expected_output=dedent(
|
||||
"""\
|
||||
A polished, error-free job posting that is clear, engaging, and perfectly aligned with the company's culture and values. Feedback on potential improvements and final approval for publishing. Formated in markdown."""
|
||||
),
|
||||
agent=agent,
|
||||
output_file="job_posting.md",
|
||||
)
|
||||
|
||||
def industry_analysis_task(self, agent, company_domain, company_description):
|
||||
return Task(
|
||||
description=dedent(
|
||||
f"""\
|
||||
Conduct an in-depth analysis of the industry related to the company's domain: "{company_domain}". Investigate current trends, challenges, and opportunities within the industry, utilizing market reports, recent developments, and expert opinions. Assess how these factors could impact the role being hired for and the overall attractiveness of the position to potential candidates.
|
||||
Consider how the company's position within this industry and its response to these trends could be leveraged to attract top talent. Include in your report how the role contributes to addressing industry challenges or seizing opportunities."""
|
||||
),
|
||||
expected_output=dedent(
|
||||
"""\
|
||||
A detailed analysis report that identifies major industry trends, challenges, and opportunities relevant to the company's domain and the specific job role. This report should provide strategic insights on positioning the job role and the company as an attractive choice for potential candidates."""
|
||||
),
|
||||
agent=agent,
|
||||
)
|
||||
|
||||
|
||||
tracer = agentops.start_trace(trace_name="CrewAI Job Posting", tags=["crew-job-posting-example", "agentops-example"])
|
||||
tasks = Tasks()
|
||||
agents = Agents()
|
||||
company_description = "We are a software company that builds AI-powered tools for businesses."
|
||||
company_domain = "https://www.agentops.ai"
|
||||
hiring_needs = "We are looking for a software engineer with 3 years of experience in Python and Django."
|
||||
specific_benefits = "We offer a competitive salary, health insurance, and a 401k plan."
|
||||
|
||||
# Create Agents
|
||||
researcher_agent = agents.research_agent()
|
||||
writer_agent = agents.writer_agent()
|
||||
review_agent = agents.review_agent()
|
||||
|
||||
# Define Tasks for each agent
|
||||
research_company_culture_task = tasks.research_company_culture_task(
|
||||
researcher_agent, company_description, company_domain
|
||||
)
|
||||
industry_analysis_task = tasks.industry_analysis_task(researcher_agent, company_domain, company_description)
|
||||
research_role_requirements_task = tasks.research_role_requirements_task(researcher_agent, hiring_needs)
|
||||
draft_job_posting_task = tasks.draft_job_posting_task(
|
||||
writer_agent, company_description, hiring_needs, specific_benefits
|
||||
)
|
||||
review_and_edit_job_posting_task = tasks.review_and_edit_job_posting_task(review_agent, hiring_needs)
|
||||
|
||||
# Instantiate the crew with a sequential process
|
||||
crew = Crew(
|
||||
agents=[researcher_agent, writer_agent, review_agent],
|
||||
tasks=[
|
||||
research_company_culture_task,
|
||||
industry_analysis_task,
|
||||
research_role_requirements_task,
|
||||
draft_job_posting_task,
|
||||
review_and_edit_job_posting_task,
|
||||
],
|
||||
)
|
||||
|
||||
result = crew.kickoff()
|
||||
print("Job Posting Creation Process Completed.")
|
||||
print("Final Job Posting:")
|
||||
print(result)
|
||||
|
||||
agentops.end_trace(tracer, end_state="Success")
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
agentops.validate_trace_spans(trace_context=tracer)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
@@ -0,0 +1,263 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "9b2dac908ce82802",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# CrewAI Markdown Validator\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "925e51b6",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"First let's install the required packages"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "8c6c9f08b3228dcb",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%pip install -U crewai\n",
|
||||
"%pip install -U agentops\n",
|
||||
"%pip install -U python-dotenv\n",
|
||||
"%pip install -U pymarkdownlnt"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "844b50cb",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Then import them"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "3930dc4c82f117b6",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import sys\n",
|
||||
"from crewai import Agent, Task, LLM\n",
|
||||
"from crewai.tools import tool\n",
|
||||
"import agentops\n",
|
||||
"import os\n",
|
||||
"from pathlib import Path\n",
|
||||
"from dotenv import load_dotenv\n",
|
||||
"from pymarkdown.api import PyMarkdownApi, PyMarkdownApiException"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "0e307923",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"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.\n",
|
||||
"\n",
|
||||
"[Get an AgentOps API key](https://agentops.ai/settings/projects)\n",
|
||||
"\n",
|
||||
"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...\n",
|
||||
"\n",
|
||||
"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!"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "e0e9166a",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"load_dotenv()\n",
|
||||
"os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\", \"your_api_key_here\")\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\", \"your_openai_api_key_here\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "6a9283d4735b1226",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"The first step in any AgentOps integration is to call `agentops.init()`"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "701a00a193b93118",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"agentops.init(tags=[\"markdown_validator\", \"agentops-example\"])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "dba56fc45784bfa",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Lets start by creating our markdown validator tool"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "cb2152baa314da66",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"@tool(\"markdown_validation_tool\")\n",
|
||||
"def markdown_validation_tool(file_path: str) -> str:\n",
|
||||
" \"\"\"\n",
|
||||
" A tool to review files for markdown syntax errors.\n",
|
||||
"\n",
|
||||
" Returns:\n",
|
||||
" - validation_results: A list of validation results\n",
|
||||
" and suggestions on how to fix them.\n",
|
||||
" \"\"\"\n",
|
||||
"\n",
|
||||
" print(\"\\n\\nValidating Markdown syntax...\\n\\n\" + file_path)\n",
|
||||
"\n",
|
||||
" try:\n",
|
||||
" if not (os.path.exists(file_path)):\n",
|
||||
" return \"Could not validate file. The provided file path does not exist.\"\n",
|
||||
"\n",
|
||||
" scan_result = PyMarkdownApi().scan_path(file_path.rstrip().lstrip())\n",
|
||||
" results = str(scan_result)\n",
|
||||
" return results # Return the reviewed document\n",
|
||||
" except PyMarkdownApiException as this_exception:\n",
|
||||
" print(f\"API Exception: {this_exception}\", file=sys.stderr)\n",
|
||||
" return f\"API Exception: {str(this_exception)}\""
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "bae481e07b5fadc2",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Lets create our Agent with CrewAI"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "3c9ca4fa0540a142",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"default_llm = LLM(\n",
|
||||
" model=\"openai/gpt-4o-mini\",\n",
|
||||
" max_tokens=4000,\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"general_agent = Agent(\n",
|
||||
" role=\"Requirements Manager\",\n",
|
||||
" goal=\"\"\"Provide a detailed list of the markdown \n",
|
||||
" linting results. Give a summary with actionable \n",
|
||||
" tasks to address the validation results. Write your \n",
|
||||
" response as if you were handing it to a developer \n",
|
||||
" to fix the issues.\n",
|
||||
" DO NOT provide examples of how to fix the issues or\n",
|
||||
" recommend other tools to use.\"\"\",\n",
|
||||
" backstory=\"\"\"You are an expert business analyst \n",
|
||||
"\t\t\t\t\tand software QA specialist. You provide high quality, \n",
|
||||
" thorough, insightful and actionable feedback via \n",
|
||||
" detailed list of changes and actionable tasks.\"\"\",\n",
|
||||
" allow_delegation=False,\n",
|
||||
" verbose=True,\n",
|
||||
" tools=[markdown_validation_tool],\n",
|
||||
" llm=default_llm,\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "7940a03ceb4a55de",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Now lets create the task for our agent to complete"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "28b4abd52ff9bf86",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"filename = f\"{Path(os.getcwd()).parent.parent.absolute()}/README.md\"\n",
|
||||
"\n",
|
||||
"syntax_review_task = Task(\n",
|
||||
" description=f\"\"\"\n",
|
||||
" Use the markdown_validation_tool to review \n",
|
||||
" the file(s) at this path: {filename}\n",
|
||||
" \n",
|
||||
" Be sure to pass only the file path to the markdown_validation_tool.\n",
|
||||
" Use the following format to call the markdown_validation_tool:\n",
|
||||
" Do I need to use a tool? Yes\n",
|
||||
" Action: markdown_validation_tool\n",
|
||||
" Action Input: {filename}\n",
|
||||
"\n",
|
||||
" Get the validation results from the tool \n",
|
||||
" and then summarize it into a list of changes\n",
|
||||
" the developer should make to the document.\n",
|
||||
" DO NOT recommend ways to update the document.\n",
|
||||
" DO NOT change any of the content of the document or\n",
|
||||
" add content to it. It is critical to your task to\n",
|
||||
" only respond with a list of changes.\n",
|
||||
" \n",
|
||||
" If you already know the answer or if you do not need \n",
|
||||
" to use a tool, return it as your Final Answer.\"\"\",\n",
|
||||
" agent=general_agent,\n",
|
||||
" expected_output=\"\",\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "7283562a262056d5",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Now lets run our task!"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "d5c5f01bee50b92a",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"syntax_review_task.execute_sync()"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "agentops (3.11.11)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.11"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
# CrewAI Markdown Validator
|
||||
|
||||
# First let's install the required packages
|
||||
# %pip install -U crewai
|
||||
# %pip install -U agentops
|
||||
# %pip install -U python-dotenv
|
||||
# %pip install -U pymarkdownlnt
|
||||
# Then import them
|
||||
import sys
|
||||
from crewai import Agent, Task, LLM
|
||||
from crewai.tools import tool
|
||||
import agentops
|
||||
import os
|
||||
from pathlib import Path
|
||||
from dotenv import load_dotenv
|
||||
from pymarkdown.api import PyMarkdownApi, PyMarkdownApiException
|
||||
|
||||
# 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!
|
||||
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")
|
||||
|
||||
# The first step in any AgentOps integration is to call `agentops.init()`
|
||||
agentops.init(trace_name="CrewAI Markdown Validator", tags=["markdown_validator", "agentops-example"])
|
||||
|
||||
|
||||
# Lets start by creating our markdown validator tool
|
||||
@tool("markdown_validation_tool")
|
||||
def markdown_validation_tool(file_path: str) -> str:
|
||||
"""
|
||||
A tool to review files for markdown syntax errors.
|
||||
|
||||
Returns:
|
||||
- validation_results: A list of validation results
|
||||
and suggestions on how to fix them.
|
||||
"""
|
||||
print("\n\nValidating Markdown syntax...\n\n" + file_path)
|
||||
try:
|
||||
if not (os.path.exists(file_path)):
|
||||
return "Could not validate file. The provided file path does not exist."
|
||||
scan_result = PyMarkdownApi().scan_path(file_path.rstrip().lstrip())
|
||||
results = str(scan_result)
|
||||
return results # Return the reviewed document
|
||||
except PyMarkdownApiException as this_exception:
|
||||
print(f"API Exception: {this_exception}", file=sys.stderr)
|
||||
return f"API Exception: {str(this_exception)}"
|
||||
|
||||
|
||||
# Lets create our Agent with CrewAI
|
||||
default_llm = LLM(
|
||||
model="openai/gpt-4o-mini",
|
||||
max_tokens=4000,
|
||||
)
|
||||
|
||||
general_agent = Agent(
|
||||
role="Requirements Manager",
|
||||
goal="""Provide a detailed list of the markdown
|
||||
linting results. Give a summary with actionable
|
||||
tasks to address the validation results. Write your
|
||||
response as if you were handing it to a developer
|
||||
to fix the issues.
|
||||
DO NOT provide examples of how to fix the issues or
|
||||
recommend other tools to use.""",
|
||||
backstory="""You are an expert business analyst
|
||||
and software QA specialist. You provide high quality,
|
||||
thorough, insightful and actionable feedback via
|
||||
detailed list of changes and actionable tasks.""",
|
||||
allow_delegation=False,
|
||||
verbose=True,
|
||||
tools=[markdown_validation_tool],
|
||||
llm=default_llm,
|
||||
)
|
||||
|
||||
# Now lets create the task for our agent to complete
|
||||
filename = f"{Path(os.getcwd()).parent.parent.absolute()}/README.md"
|
||||
|
||||
syntax_review_task = Task(
|
||||
description=f"""
|
||||
Use the markdown_validation_tool to review
|
||||
the file(s) at this path: {filename}
|
||||
|
||||
Be sure to pass only the file path to the markdown_validation_tool.
|
||||
Use the following format to call the markdown_validation_tool:
|
||||
Do I need to use a tool? Yes
|
||||
Action: markdown_validation_tool
|
||||
Action Input: {filename}
|
||||
|
||||
Get the validation results from the tool
|
||||
and then summarize it into a list of changes
|
||||
the developer should make to the document.
|
||||
DO NOT recommend ways to update the document.
|
||||
DO NOT change any of the content of the document or
|
||||
add content to it. It is critical to your task to
|
||||
only respond with a list of changes.
|
||||
|
||||
If you already know the answer or if you do not need
|
||||
to use a tool, return it as your Final Answer.""",
|
||||
agent=general_agent,
|
||||
expected_output="",
|
||||
)
|
||||
|
||||
# Now lets run our task!
|
||||
syntax_review_task.execute_sync()
|
||||
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
agentops.validate_trace_spans(trace_context=None)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
@@ -0,0 +1,5 @@
|
||||
crewai
|
||||
crewai-tools
|
||||
pymarkdown==0.1.4
|
||||
pymarkdownlnt==0.9.30
|
||||
pymdown-extensions==10.15
|
||||
@@ -0,0 +1,38 @@
|
||||
import os
|
||||
|
||||
import dspy
|
||||
from dspy import Tool
|
||||
import agentops
|
||||
from agentops.integration.callbacks.dspy import DSPyCallbackHandler
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
handler = DSPyCallbackHandler(api_key=os.getenv("AGENTOPS_API_KEY", ""), cache=False)
|
||||
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY", "")
|
||||
|
||||
lm = dspy.LM("openai/gpt-4o-mini", temperature=0.5)
|
||||
dspy.configure(lm=lm, callbacks=[handler])
|
||||
|
||||
|
||||
def multiplier(*, a: int, b: int) -> int:
|
||||
return a * b
|
||||
|
||||
|
||||
multiplier = Tool(multiplier)
|
||||
|
||||
agent = dspy.ProgramOfThought("question -> answer: int")
|
||||
response = agent(question="What is twenty five times twenty five?", tools=[multiplier])
|
||||
|
||||
print(response)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
|
||||
try:
|
||||
agentops.validate_trace_spans(trace_context=None)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except ImportError:
|
||||
print("\n❌ Error: agentops library not installed. Please install it to validate spans.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
@@ -0,0 +1,197 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Script to generate example MDX files from Jupyter notebooks.
|
||||
|
||||
This script converts a Jupyter notebook from the examples/ directory into a
|
||||
corresponding .mdx file in docs/v2/examples/, matching the exact format and
|
||||
structure used by the GitHub Actions workflow.
|
||||
|
||||
Usage:
|
||||
python examples/generate_documentation.py examples/openai/openai_example_sync.ipynb
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# Constants
|
||||
SCRIPT_TAGS = """<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>"""
|
||||
|
||||
# Title overrides to reflect correct names
|
||||
TITLE_OVERRIDES = {
|
||||
"ag2": "AG2",
|
||||
"autogen": "AutoGen",
|
||||
"crewai": "CrewAI",
|
||||
"google_adk": "Google ADK",
|
||||
"google_genai": "Google GenAI",
|
||||
"langchain": "LangChain",
|
||||
"litellm": "LiteLLM",
|
||||
"llamaindex": "LlamaIndex",
|
||||
"openai": "OpenAI",
|
||||
"openai_agents": "OpenAI Agents",
|
||||
"watsonx": "WatsonX",
|
||||
"xai": "xAI",
|
||||
}
|
||||
|
||||
|
||||
def convert_notebook_to_markdown(notebook_path):
|
||||
"""Convert Jupyter notebook to markdown using jupyter nbconvert."""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["jupyter", "nbconvert", "--to", "markdown", "--stdout", notebook_path],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
)
|
||||
return result.stdout
|
||||
except subprocess.CalledProcessError as e:
|
||||
sys.exit(f"Error: Failed to convert notebook: {e}\nstderr: {e.stderr}")
|
||||
except FileNotFoundError:
|
||||
sys.exit("Error: jupyter nbconvert not found. Please install jupyter: pip install jupyter")
|
||||
|
||||
|
||||
def process_pip_installations(markdown_content):
|
||||
"""Transform %pip install commands using regex for efficiency."""
|
||||
# Extract all packages from pip install commands
|
||||
packages = []
|
||||
for match in re.finditer(r"%pip install\s+([^\n#]+)", markdown_content):
|
||||
packages.extend(match.group(1).strip().split())
|
||||
|
||||
if not packages:
|
||||
return markdown_content
|
||||
|
||||
# Deduplicate packages
|
||||
unique_packages = " ".join(sorted(set(packages)))
|
||||
|
||||
# Remove code blocks containing pip installs
|
||||
content = re.sub(r"```python\n(?:[^`])*?%pip install[^\n]*\n(?:[^`])*?```\n?", "", markdown_content)
|
||||
|
||||
# Find insertion point for installation section
|
||||
first_pip_pos = markdown_content.find("%pip install")
|
||||
if first_pip_pos == -1:
|
||||
return markdown_content
|
||||
|
||||
# Calculate line position and insert installation section
|
||||
line_pos = markdown_content[:first_pip_pos].count("\n")
|
||||
lines = content.split("\n")
|
||||
|
||||
installation_section = f"""## Installation
|
||||
<CodeGroup>
|
||||
```bash pip
|
||||
pip install {unique_packages}
|
||||
```
|
||||
```bash poetry
|
||||
poetry add {unique_packages}
|
||||
```
|
||||
```bash uv
|
||||
uv add {unique_packages}
|
||||
```
|
||||
</CodeGroup>
|
||||
"""
|
||||
|
||||
lines.insert(line_pos, installation_section)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def get_existing_frontmatter(mdx_path):
|
||||
"""Extract existing frontmatter if it has special configurations."""
|
||||
if not mdx_path.exists():
|
||||
return None
|
||||
|
||||
content = mdx_path.read_text(encoding="utf-8")
|
||||
|
||||
# Check for special configurations and extract frontmatter
|
||||
if any(config in content for config in ["mode:", "layout:"]):
|
||||
if content.startswith("---\n"):
|
||||
end_marker = content.find("\n---\n", 4)
|
||||
if end_marker != -1:
|
||||
return content[4:end_marker]
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def generate_mdx_content(notebook_path, processed_content, frontmatter=None):
|
||||
"""Generate MDX content with either provided or generated frontmatter."""
|
||||
if not frontmatter:
|
||||
# Generate new frontmatter
|
||||
folder_name = Path(notebook_path).parent.name
|
||||
|
||||
# Check for title override, otherwise use default title case conversion
|
||||
if folder_name in TITLE_OVERRIDES:
|
||||
base_title = TITLE_OVERRIDES[folder_name]
|
||||
else:
|
||||
base_title = folder_name.replace("_", " ").title()
|
||||
|
||||
title = f"{base_title}"
|
||||
|
||||
# Extract description from first heading or use default
|
||||
description = f"{title} example using AgentOps"
|
||||
for line in processed_content.split("\n"):
|
||||
if line.startswith("# ") and len(line) > 2:
|
||||
description = line[2:].strip()
|
||||
break
|
||||
|
||||
frontmatter = f"title: '{title}'\ndescription: '{description}'"
|
||||
|
||||
return f"""---
|
||||
{frontmatter}
|
||||
---
|
||||
{{/* SOURCE_FILE: {notebook_path} */}}
|
||||
|
||||
_View Notebook on <a href={{'https://github.com/AgentOps-AI/agentops/blob/main/{notebook_path}'}} target={{'_blank'}}>Github</a>_
|
||||
|
||||
{processed_content}
|
||||
|
||||
{SCRIPT_TAGS}"""
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Generate example MDX files from Jupyter notebooks")
|
||||
parser.add_argument("notebook_path", help="Path to the Jupyter notebook")
|
||||
|
||||
notebook_path = parser.parse_args().notebook_path
|
||||
|
||||
# Validate notebook path
|
||||
notebook_file = Path(notebook_path)
|
||||
if not notebook_file.exists():
|
||||
sys.exit(f"Error: Notebook file not found: {notebook_path}")
|
||||
|
||||
if notebook_file.suffix != ".ipynb":
|
||||
sys.exit(f"Error: File must be a Jupyter notebook (.ipynb): {notebook_path}")
|
||||
|
||||
if not str(notebook_file).startswith("examples/"):
|
||||
sys.exit(f"Error: Notebook must be in the examples/ directory: {notebook_path}")
|
||||
|
||||
# Generate output path
|
||||
folder_name = notebook_file.parent.name
|
||||
output_path = Path(f"docs/v2/examples/{folder_name}.mdx")
|
||||
|
||||
print(f"Processing: {notebook_path} -> {output_path}")
|
||||
|
||||
# Convert notebook to markdown and process
|
||||
markdown_content = convert_notebook_to_markdown(notebook_path)
|
||||
processed_content = process_pip_installations(markdown_content)
|
||||
|
||||
# Check for existing special frontmatter
|
||||
existing_frontmatter = get_existing_frontmatter(output_path)
|
||||
|
||||
if existing_frontmatter:
|
||||
final_content = generate_mdx_content(notebook_path, processed_content, existing_frontmatter)
|
||||
else:
|
||||
print("Generating new frontmatter and content")
|
||||
final_content = generate_mdx_content(notebook_path, processed_content)
|
||||
|
||||
# Write the file
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
output_path.write_text(final_content, encoding="utf-8")
|
||||
|
||||
print(f"Successfully generated: {output_path}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,25 @@
|
||||
# Google ADK Examples with AgentOps
|
||||
|
||||
This directory contains examples of using the Google AI Development Kit (ADK) with AgentOps instrumentation.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Python >= 3.10 < 3.13
|
||||
- Install required dependencies:
|
||||
```
|
||||
pip install agentops google-adk
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### 1. Human Approval
|
||||
|
||||
Example: `human_approval`
|
||||
This example demonstrates:
|
||||
- A human-in-the-loop approval workflow
|
||||
|
||||
## AgentOps Integration
|
||||
|
||||
These examples show how to use AgentOps to monitor and analyze your AI applications. AgentOps automatically instruments your Google ADK calls to provide insights into performance, usage patterns, and model behavior.
|
||||
|
||||
To learn more about AgentOps, visit [https://www.agentops.ai](https://www.agentops.ai)
|
||||
@@ -0,0 +1,468 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "7fb27b941602401d91542211134fc71a",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Google ADK Example: Human Approval Workflow with AgentOps"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "acae54e37e7d407bbb7b55eff062a284",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This notebook demonstrates a complete human approval workflow using the Google ADK (Agent Development Kit), integrated with AgentOps for observability.\n",
|
||||
"\n",
|
||||
"**Key Features:**\n",
|
||||
"- **Sequential Agent Processing:** The workflow uses multiple agents chained together to handle different stages of the approval process.\n",
|
||||
"- **External Tool Integration:** An agent interacts with an external tool that simulates (or in this version, directly prompts for) human approval.\n",
|
||||
"- **Session State Management:** Information is passed between agents and persisted using session state.\n",
|
||||
"- **AgentOps Observability:** All agent actions, tool calls, and LLM interactions are traced and can be viewed in your AgentOps dashboard.\n",
|
||||
"- **Interactive Human Input:** The approval step now requires direct input from the user."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "9a63283cbaf04dbcab1f6479b197f3a8",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 1. Setup and Dependencies"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "8dd0d8092fe74a7c96281538738b07e2",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"First, let's install the necessary libraries if they are not already present and import them."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "72eea5119410473aa328ad9291626812",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%pip install google-adk agentops python-dotenv nest_asyncio asyncio"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"id": "8edb47106e1a46a883d545849b8ab81b",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import json\n",
|
||||
"import os\n",
|
||||
"import asyncio\n",
|
||||
"from google.adk.agents import LlmAgent, SequentialAgent\n",
|
||||
"from google.adk.tools import FunctionTool\n",
|
||||
"from google.adk.runners import Runner\n",
|
||||
"from google.adk.sessions import InMemorySessionService\n",
|
||||
"from google.genai import types\n",
|
||||
"from pydantic import BaseModel, Field\n",
|
||||
"import nest_asyncio\n",
|
||||
"import agentops\n",
|
||||
"from dotenv import load_dotenv"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "10185d26023b46108eb7d9f57d49d2b3",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 2. Configuration and Initialization"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "8763a12b2bbd4a93a75aff182afb95dc",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Load environment variables (especially `AGENTOPS_API_KEY` and your Google API key for Gemini) and initialize AgentOps."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "7623eae2785240b9bd12b16a66d81610",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Load environment variables from .env file\n",
|
||||
"load_dotenv()\n",
|
||||
"nest_asyncio.apply()\n",
|
||||
"AGENTOPS_API_KEY = os.getenv(\"AGENTOPS_API_KEY\") or \"your_agentops_api_key_here\"\n",
|
||||
"# Initialize AgentOps - Just 2 lines!\n",
|
||||
"agentops.init(AGENTOPS_API_KEY, trace_name=\"adk-human-approval-notebook\", auto_start_session=False)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "7cdc8c89c7104fffa095e18ddfef8986",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Define some constants for our application."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "b118ea5561624da68c537baed56e602f",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"APP_NAME = \"human_approval_app_notebook\"\n",
|
||||
"USER_ID = \"test_user_notebook_123\"\n",
|
||||
"SESSION_ID = \"approval_session_notebook_456\"\n",
|
||||
"MODEL_NAME = \"gemini-1.5-flash\"\n",
|
||||
"agentops.start_trace(trace_name=APP_NAME, tags=[\"google_adk\", \"notebook\"])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "938c804e27f84196a10c8828c723f798",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 3. Define Schemas"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "504fb2a444614c0babb325280ed9130a",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Pydantic models are used to define the structure of data for approval requests and decisions. This helps with validation and clarity."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 4,
|
||||
"id": "59bbdb311c014d738909a11f9e486628",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"class ApprovalRequest(BaseModel):\n",
|
||||
" amount: float = Field(description=\"The amount requiring approval\")\n",
|
||||
" reason: str = Field(description=\"The reason for the request\")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"class ApprovalDecision(BaseModel):\n",
|
||||
" decision: str = Field(description=\"The approval decision: 'approved' or 'rejected'\")\n",
|
||||
" comments: str = Field(description=\"Additional comments from the approver\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "b43b363d81ae4b689946ece5c682cd59",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 4. External Approval Tool (with Human Interaction)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "8a65eabff63a45729fe45fb5ade58bdc",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This tool now directly prompts the user for an approval decision. In a real-world scenario, this might involve sending a notification to an approver and waiting for their response through a UI or API."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 5,
|
||||
"id": "c3933fab20d04ec698c2621248eb3be0",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"async def external_approval_tool(amount: float, reason: str) -> str:\n",
|
||||
" \"\"\"\n",
|
||||
" Prompts for human approval and returns the decision as a JSON string.\n",
|
||||
" \"\"\"\n",
|
||||
" print(\"🔔 HUMAN APPROVAL REQUIRED:\")\n",
|
||||
" print(f\" Amount: ${amount:,.2f}\")\n",
|
||||
" print(f\" Reason: {reason}\")\n",
|
||||
" decision = \"\"\n",
|
||||
" while decision.lower() not in [\"approved\", \"rejected\"]:\n",
|
||||
" decision = input(\" Enter decision (approved/rejected): \").strip().lower()\n",
|
||||
" if decision.lower() not in [\"approved\", \"rejected\"]:\n",
|
||||
" print(\" Invalid input. Please enter 'approved' or 'rejected'.\")\n",
|
||||
" comments = input(\" Enter comments (optional): \").strip()\n",
|
||||
" print(f\" Decision: {decision.upper()}\")\n",
|
||||
" print(f\" Comments: {comments if comments else 'N/A'}\")\n",
|
||||
" return json.dumps({\"decision\": decision, \"comments\": comments, \"amount\": amount, \"reason\": reason})\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Create the approval tool instance\n",
|
||||
"approval_tool = FunctionTool(func=external_approval_tool)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "4dd4641cc4064e0191573fe9c69df29b",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 5. Define Agents"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "8309879909854d7188b41380fd92a7c3",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"We define three agents for our workflow:\n",
|
||||
"1. **`PrepareApprovalAgent`**: Extracts details from the user's request.\n",
|
||||
"2. **`RequestHumanApprovalAgent`**: Uses the `external_approval_tool` to get a decision.\n",
|
||||
"3. **`ProcessDecisionAgent`**: Processes the decision and formulates a final response."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 6,
|
||||
"id": "3ed186c9a28b402fb0bc4494df01f08d",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Agent 1: Prepare the approval request\n",
|
||||
"prepare_request = LlmAgent(\n",
|
||||
" model=MODEL_NAME,\n",
|
||||
" name=\"PrepareApprovalAgent\",\n",
|
||||
" description=\"Extracts and prepares approval request details from user input\",\n",
|
||||
" instruction=\"\"\"You are an approval request preparation agent.\n",
|
||||
" Your task:\n",
|
||||
" 1. Extract the amount and reason from the user's request\n",
|
||||
" 2. Store these values in the session state with keys 'approval_amount' and 'approval_reason'\n",
|
||||
" 3. Validate that both amount and reason are provided\n",
|
||||
" 4. Respond with a summary of what will be submitted for approval\n",
|
||||
" If the user input is missing amount or reason, ask for clarification.\n",
|
||||
" \"\"\",\n",
|
||||
" output_key=\"request_prepared\",\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"# Agent 2: Request human approval using the tool\n",
|
||||
"request_approval = LlmAgent(\n",
|
||||
" model=MODEL_NAME,\n",
|
||||
" name=\"RequestHumanApprovalAgent\",\n",
|
||||
" description=\"Calls the external approval system with prepared request details\",\n",
|
||||
" instruction=\"\"\"You are a human approval request agent.\n",
|
||||
" Your task:\n",
|
||||
" 1. Get the 'approval_amount' and 'approval_reason' from the session state\n",
|
||||
" 2. Use the external_approval_tool with these values\n",
|
||||
" 3. Store the approval decision in session state with key 'human_decision'\n",
|
||||
" 4. Respond with the approval status\n",
|
||||
" Always use the exact values from the session state for the tool call.\n",
|
||||
" \"\"\",\n",
|
||||
" tools=[approval_tool],\n",
|
||||
" output_key=\"approval_requested\",\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"# Agent 3: Process the approval decision\n",
|
||||
"process_decision = LlmAgent(\n",
|
||||
" model=MODEL_NAME,\n",
|
||||
" name=\"ProcessDecisionAgent\",\n",
|
||||
" description=\"Processes the human approval decision and provides final response\",\n",
|
||||
" instruction=\"\"\"You are a decision processing agent.\n",
|
||||
" Your task:\n",
|
||||
" 1. Check the 'human_decision' from session state\n",
|
||||
" 2. Parse the approval decision JSON\n",
|
||||
" 3. If approved: congratulate and provide next steps\n",
|
||||
" 4. If rejected: explain the rejection and suggest alternatives\n",
|
||||
" 5. Provide a clear, helpful final response to the user\n",
|
||||
"\n",
|
||||
" Be professional and helpful in your response.\n",
|
||||
" \"\"\",\n",
|
||||
" output_key=\"final_decision\",\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "cb1e1581032b452c9409d6c6813c49d1",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 6. Create Sequential Workflow"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "379cbbc1e968416e875cc15c1202d7eb",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Combine the agents into a sequential workflow. The `SequentialAgent` ensures that the sub-agents are executed in the specified order."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 7,
|
||||
"id": "277c27b1587741f2af2001be3712ef0d",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"approval_workflow = SequentialAgent(\n",
|
||||
" name=\"HumanApprovalWorkflowNotebook\",\n",
|
||||
" description=\"Complete workflow for processing approval requests with human oversight\",\n",
|
||||
" sub_agents=[prepare_request, request_approval, process_decision],\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "db7b79bc585a40fcaf58bf750017e135",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 7. Session Management and Runner"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "916684f9a58a4a2aa5f864670399430d",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Set up an in-memory session service and the workflow runner."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 8,
|
||||
"id": "1671c31a24314836a5b85d7ef7fbf015",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"session_service = InMemorySessionService()\n",
|
||||
"# Create runner\n",
|
||||
"workflow_runner = Runner(agent=approval_workflow, app_name=APP_NAME, session_service=session_service)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "33b0902fd34d4ace834912fa1002cf8e",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 8. Helper Function to Run Workflow"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "f6fa52606d8c4a75a9b52967216f8f3f",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This function encapsulates the logic to run the workflow for a given user request and session ID."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 9,
|
||||
"id": "f5a1fa73e5044315a093ec459c9be902",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"async def run_approval_workflow_notebook(user_request: str, session_id: str):\n",
|
||||
" \"\"\"Run the complete approval workflow with a user request in the notebook environment\"\"\"\n",
|
||||
" print(f\"{'=' * 60}\")\n",
|
||||
" print(f\" Starting Approval Workflow for Session: {session_id}\")\n",
|
||||
" print(f\"{'=' * 60}\")\n",
|
||||
" print(f\"User Request: {user_request}\")\n",
|
||||
" # Create user message\n",
|
||||
" user_content = types.Content(role=\"user\", parts=[types.Part(text=user_request)])\n",
|
||||
" step_count = 0\n",
|
||||
" final_response = \"No response received\"\n",
|
||||
" # Run the workflow\n",
|
||||
" async for event in workflow_runner.run_async(\n",
|
||||
" user_id=USER_ID,\n",
|
||||
" session_id=session_id,\n",
|
||||
" new_message=user_content,\n",
|
||||
" ):\n",
|
||||
" if event.author and event.content:\n",
|
||||
" step_count += 1\n",
|
||||
" print(f\"📋 Step {step_count} - {event.author}:\")\n",
|
||||
" if event.content.parts:\n",
|
||||
" response_text = event.content.parts[0].text\n",
|
||||
" print(f\" {response_text}\")\n",
|
||||
" if event.is_final_response():\n",
|
||||
" final_response = response_text\n",
|
||||
" session = await session_service.get_session(\n",
|
||||
" app_name=APP_NAME,\n",
|
||||
" user_id=USER_ID,\n",
|
||||
" session_id=session_id,\n",
|
||||
" )\n",
|
||||
" print(f\"{'=' * 60}\")\n",
|
||||
" print(f\"📊 Workflow Complete - Session State ({session_id}):\")\n",
|
||||
" print(f\"{'=' * 60}\")\n",
|
||||
" for key, value in session.state.items():\n",
|
||||
" print(f\" {key}: {value}\")\n",
|
||||
" print(f\"🎯 Final Response: {final_response}\")\n",
|
||||
" return final_response"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "cdf66aed5cc84ca1b48e60bad68798a8",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 9. Main Execution Logic"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "28d3efd5258a48a79c179ea5c6759f01",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"This cell contains the main logic to run the workflow with a few test cases. Each test case will run in its own session."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "3f9bc0b9dd2c44919cc8dcca39b469f8",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"async def main_notebook():\n",
|
||||
" test_requests = [\n",
|
||||
" \"I need approval for $750 for team lunch and celebrations\",\n",
|
||||
" \"Please approve $3,000 for a conference ticket and travel expenses\",\n",
|
||||
" \"I need $12,000 approved for critical software licenses renewal\",\n",
|
||||
" ]\n",
|
||||
" for i, request in enumerate(test_requests, 1):\n",
|
||||
" current_session_id = f\"approval_session_notebook_{456 + i - 1}\"\n",
|
||||
" # Create the session before running the workflow\n",
|
||||
" await session_service.create_session(app_name=APP_NAME, user_id=USER_ID, session_id=current_session_id)\n",
|
||||
" print(f\"Created session: {current_session_id}\")\n",
|
||||
" await run_approval_workflow_notebook(request, current_session_id)\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"try:\n",
|
||||
" asyncio.run(main_notebook())\n",
|
||||
" agentops.end_trace(end_state=\"Success\")\n",
|
||||
"except Exception as e:\n",
|
||||
" print(f\"Error: {e}\")\n",
|
||||
" agentops.end_trace(end_state=\"Error\")"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": ".venv",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.12"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
# Google ADK Example: Automated Approval Workflow with AgentOps
|
||||
# This notebook demonstrates a complete automated approval workflow using the Google ADK (Agent Development Kit), integrated with AgentOps for observability.
|
||||
#
|
||||
# **Key Features:**
|
||||
# - **Sequential Agent Processing:** The workflow uses multiple agents chained together to handle different stages of the approval process.
|
||||
# - **External Tool Integration:** An agent interacts with an external tool that provides automated approval decisions based on amount and reason analysis.
|
||||
# - **Session State Management:** Information is passed between agents and persisted using session state.
|
||||
# - **AgentOps Observability:** All agent actions, tool calls, and LLM interactions are traced and can be viewed in your AgentOps dashboard.
|
||||
# - **Automated Decision Making:** The approval system automatically approves or rejects requests based on configurable business rules.
|
||||
# ## 1. Setup and Dependencies
|
||||
# First, let's install the necessary libraries if they are not already present and import them.
|
||||
# %pip install google-adk agentops python-dotenv nest_asyncio asyncio
|
||||
import json
|
||||
import os
|
||||
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
|
||||
import asyncio
|
||||
|
||||
# ## 2. Configuration and Initialization
|
||||
# Load environment variables (especially `AGENTOPS_API_KEY` and your Google API key for Gemini) and initialize AgentOps.
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
nest_asyncio.apply()
|
||||
AGENTOPS_API_KEY = os.getenv("AGENTOPS_API_KEY") or "your_agentops_api_key_here"
|
||||
|
||||
# Initialize AgentOps - Just 2 lines!
|
||||
agentops.init(
|
||||
AGENTOPS_API_KEY,
|
||||
trace_name="adk-automated-approval-notebook",
|
||||
auto_start_session=False,
|
||||
tags=["google-adk", "automated-approval", "agentops-example"],
|
||||
)
|
||||
|
||||
# Define some constants for our application.
|
||||
APP_NAME = "automated_approval_app_notebook"
|
||||
USER_ID = "test_user_notebook_123"
|
||||
SESSION_ID = "automated_approval_session_notebook_456"
|
||||
MODEL_NAME = "gemini-1.5-flash"
|
||||
tracer = agentops.start_trace(trace_name=APP_NAME, tags=["google_adk", "notebook"])
|
||||
|
||||
|
||||
# ## 3. Define Schemas
|
||||
# Pydantic models are used to define the structure of data for approval requests and decisions. This helps with validation and clarity.
|
||||
class ApprovalRequest(BaseModel):
|
||||
amount: float = Field(description="The amount requiring approval")
|
||||
reason: str = Field(description="The reason for the request")
|
||||
|
||||
|
||||
class ApprovalDecision(BaseModel):
|
||||
decision: str = Field(description="The approval decision: 'approved' or 'rejected'")
|
||||
comments: str = Field(description="Additional comments from the approver")
|
||||
|
||||
|
||||
# ## 4. External Approval Tool (Automated Decision Making)
|
||||
# This tool automatically makes approval decisions based on configurable business rules. It analyzes the amount and reason to determine whether to approve or reject the request. In a real-world scenario, this could be integrated with more sophisticated rule engines or ML models for decision making.
|
||||
async def external_approval_tool(amount: float, reason: str) -> str:
|
||||
"""
|
||||
Automated approval system that returns approval decisions based on amount and reason analysis.
|
||||
"""
|
||||
print("🤖 AUTOMATED APPROVAL SYSTEM:")
|
||||
print(f" Amount: ${amount:,.2f}")
|
||||
print(f" Reason: {reason}")
|
||||
|
||||
# Automated decision logic
|
||||
decision = ""
|
||||
comments = ""
|
||||
|
||||
reason_lower = reason.lower()
|
||||
high_priority_keywords = ["critical", "urgent", "emergency", "security", "compliance", "license"]
|
||||
business_keywords = ["conference", "training", "team", "software", "equipment", "travel"]
|
||||
|
||||
# Check for high priority keywords first (overrides amount limits)
|
||||
if any(keyword in reason_lower for keyword in high_priority_keywords):
|
||||
decision = "approved"
|
||||
comments = "Auto-approved: High priority business need identified"
|
||||
|
||||
# Auto-approve small amounts
|
||||
elif amount <= 1000:
|
||||
decision = "approved"
|
||||
comments = "Auto-approved: Amount under $1,000 threshold"
|
||||
|
||||
# Auto-reject very large amounts without high priority justification
|
||||
elif amount > 10000:
|
||||
decision = "rejected"
|
||||
comments = "Auto-rejected: Amount exceeds $10,000 limit without high priority justification"
|
||||
|
||||
# Medium amounts: analyze reason keywords
|
||||
else:
|
||||
if any(keyword in reason_lower for keyword in business_keywords):
|
||||
decision = "approved"
|
||||
comments = "Auto-approved: Standard business expense"
|
||||
else:
|
||||
# Default to approval for reasonable amounts with unclear reasons
|
||||
decision = "approved"
|
||||
comments = "Auto-approved: Amount within reasonable range"
|
||||
|
||||
print(f" Decision: {decision.upper()}")
|
||||
print(f" Comments: {comments}")
|
||||
return json.dumps({"decision": decision, "comments": comments, "amount": amount, "reason": reason})
|
||||
|
||||
|
||||
# Create the approval tool instance
|
||||
approval_tool = FunctionTool(func=external_approval_tool)
|
||||
|
||||
# ## 5. Define Agents
|
||||
# We define three agents for our workflow:
|
||||
# 1. **`PrepareApprovalAgent`**: Extracts details from the user's request.
|
||||
# 2. **`RequestHumanApprovalAgent`**: Uses the `external_approval_tool` to get a decision.
|
||||
# 3. **`ProcessDecisionAgent`**: Processes the decision and formulates a final response.
|
||||
# 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 automated approval using the tool
|
||||
request_approval = LlmAgent(
|
||||
model=MODEL_NAME,
|
||||
name="RequestAutomatedApprovalAgent",
|
||||
description="Calls the external automated approval system with prepared request details",
|
||||
instruction="""You are an automated 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 'automated_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 automated approval decision and provides final response",
|
||||
instruction="""You are a decision processing agent.
|
||||
Your task:
|
||||
1. Check the 'automated_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",
|
||||
)
|
||||
|
||||
# ## 6. Create Sequential Workflow
|
||||
# Combine the agents into a sequential workflow. The `SequentialAgent` ensures that the sub-agents are executed in the specified order.
|
||||
approval_workflow = SequentialAgent(
|
||||
name="AutomatedApprovalWorkflowNotebook",
|
||||
description="Complete workflow for processing approval requests with automated decision making",
|
||||
sub_agents=[prepare_request, request_approval, process_decision],
|
||||
)
|
||||
|
||||
# ## 7. Session Management and Runner
|
||||
# Set up an in-memory session service and the workflow runner.
|
||||
session_service = InMemorySessionService()
|
||||
# Create runner
|
||||
workflow_runner = Runner(agent=approval_workflow, app_name=APP_NAME, session_service=session_service)
|
||||
|
||||
|
||||
# ## 8. Helper Function to Run Workflow
|
||||
# This function encapsulates the logic to run the workflow for a given user request and session ID.
|
||||
async def run_approval_workflow_notebook(user_request: str, session_id: str):
|
||||
"""Run the complete approval workflow with a user request in the notebook environment"""
|
||||
print(f"{'=' * 60}")
|
||||
print(f" Starting Approval Workflow for Session: {session_id}")
|
||||
print(f"{'=' * 60}")
|
||||
print(f"User Request: {user_request}")
|
||||
# Create user message
|
||||
user_content = types.Content(role="user", parts=[types.Part(text=user_request)])
|
||||
step_count = 0
|
||||
final_response = "No response received"
|
||||
# Run the workflow
|
||||
async for event in workflow_runner.run_async(
|
||||
user_id=USER_ID,
|
||||
session_id=session_id,
|
||||
new_message=user_content,
|
||||
):
|
||||
if event.author and event.content:
|
||||
step_count += 1
|
||||
print(f"📋 Step {step_count} - {event.author}:")
|
||||
if event.content.parts:
|
||||
response_text = event.content.parts[0].text
|
||||
print(f" {response_text}")
|
||||
if event.is_final_response():
|
||||
final_response = response_text
|
||||
session = await session_service.get_session(
|
||||
app_name=APP_NAME,
|
||||
user_id=USER_ID,
|
||||
session_id=session_id,
|
||||
)
|
||||
print(f"{'=' * 60}")
|
||||
print(f"📊 Workflow Complete - Session State ({session_id}):")
|
||||
print(f"{'=' * 60}")
|
||||
for key, value in session.state.items():
|
||||
print(f" {key}: {value}")
|
||||
print(f"🎯 Final Response: {final_response}")
|
||||
return final_response
|
||||
|
||||
|
||||
# ## 9. Main Execution Logic
|
||||
# This cell contains the main logic to run the workflow with a few test cases. Each test case will run in its own session.
|
||||
async def main_notebook():
|
||||
test_requests = [
|
||||
"I need approval for $750 for team lunch and celebrations", # Should auto-approve: under $1,000
|
||||
"Please approve $3,000 for a conference ticket and travel expenses", # Should auto-approve: business keywords
|
||||
"I need $12,000 approved for critical software licenses renewal", # Should auto-approve: high priority keywords despite high amount
|
||||
"Please approve $15,000 for office decoration and furniture", # Should auto-reject: over $10,000 without high priority keywords
|
||||
"I need $5,000 for urgent security system upgrade", # Should auto-approve: high priority keywords
|
||||
]
|
||||
for i, request in enumerate(test_requests, 1):
|
||||
current_session_id = f"automated_approval_session_notebook_{456 + i - 1}"
|
||||
# Create the session before running the workflow
|
||||
await session_service.create_session(app_name=APP_NAME, user_id=USER_ID, session_id=current_session_id)
|
||||
print(f"Created session: {current_session_id}")
|
||||
await run_approval_workflow_notebook(request, current_session_id)
|
||||
|
||||
|
||||
try:
|
||||
asyncio.run(main_notebook())
|
||||
agentops.end_trace(end_state="Success")
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
agentops.end_trace(end_state="Error")
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
agentops.validate_trace_spans(trace_context=tracer)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
@@ -0,0 +1,6 @@
|
||||
google-adk
|
||||
google-genai==1.16.1
|
||||
nest-asyncio==1.6.0
|
||||
agentops
|
||||
python-dotenv
|
||||
deprecated
|
||||
@@ -0,0 +1,98 @@
|
||||
import os
|
||||
import asyncio
|
||||
from typing import Optional
|
||||
|
||||
import agentops
|
||||
from google.adk.agents import LlmAgent
|
||||
from google.adk.tools import FunctionTool
|
||||
from google.adk.runners import Runner
|
||||
from google.adk.sessions import InMemorySessionService
|
||||
from google.genai import types
|
||||
|
||||
|
||||
# Attempt to import RunConfig/StreamingMode from likely ADK locations
|
||||
RunConfig: Optional[object] = None
|
||||
StreamingMode: Optional[object] = None
|
||||
try:
|
||||
from google.adk.runners import RunConfig as _RunConfig, StreamingMode as _StreamingMode # type: ignore
|
||||
|
||||
RunConfig = _RunConfig
|
||||
StreamingMode = _StreamingMode
|
||||
except Exception:
|
||||
try:
|
||||
from google.adk.types import RunConfig as _RunConfig2, StreamingMode as _StreamingMode2 # type: ignore
|
||||
|
||||
RunConfig = _RunConfig2
|
||||
StreamingMode = _StreamingMode2
|
||||
except Exception:
|
||||
RunConfig = None
|
||||
StreamingMode = None
|
||||
|
||||
|
||||
# Initialize AgentOps (set AGENTOPS_API_KEY in your environment)
|
||||
agentops.init(api_key=os.getenv("AGENTOPS_API_KEY"), trace_name="adk_sse_text_function_call")
|
||||
|
||||
APP_NAME = "adk_sse_text_function_call_app"
|
||||
USER_ID = "user_sse_text_fc"
|
||||
SESSION_ID = "session_sse_text_fc"
|
||||
MODEL_NAME = "gemini-2.0-flash"
|
||||
|
||||
|
||||
# Simple tool to trigger a function call
|
||||
async def get_weather(location: str) -> str:
|
||||
return f"Weather for {location}: sunny and 25°C."
|
||||
|
||||
|
||||
weather_tool = FunctionTool(func=get_weather)
|
||||
|
||||
# Agent configured with the tool so the model can trigger a function call
|
||||
agent = LlmAgent(
|
||||
model=MODEL_NAME,
|
||||
name="WeatherAgent",
|
||||
description="Provides weather using a tool",
|
||||
instruction=(
|
||||
"You are a helpful assistant. When asked about weather, call the get_weather tool with the given location."
|
||||
),
|
||||
tools=[weather_tool],
|
||||
output_key="weather_output",
|
||||
)
|
||||
|
||||
# Session service and runner
|
||||
session_service = InMemorySessionService()
|
||||
runner = Runner(agent=agent, app_name=APP_NAME, session_service=session_service)
|
||||
|
||||
|
||||
async def main():
|
||||
# Ensure session exists
|
||||
await session_service.create_session(app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID)
|
||||
|
||||
# Create user message
|
||||
user_message = types.Content(role="user", parts=[types.Part(text="What's the weather in Paris?")])
|
||||
|
||||
# Configure SSE streaming with TEXT modality, as reported by the user
|
||||
run_config_kw = {}
|
||||
if RunConfig is not None and StreamingMode is not None:
|
||||
run_config_kw["run_config"] = RunConfig(streaming_mode=StreamingMode.SSE, response_modalities=["TEXT"]) # type: ignore
|
||||
|
||||
final_text = None
|
||||
async for event in runner.run_async(
|
||||
user_id=USER_ID, session_id=SESSION_ID, new_message=user_message, **run_config_kw
|
||||
):
|
||||
# Print out any parts safely; this will include function_call parts when they occur
|
||||
if hasattr(event, "content") and event.content and getattr(event.content, "parts", None):
|
||||
for part in event.content.parts:
|
||||
text = getattr(part, "text", None)
|
||||
func_call = getattr(part, "function_call", None)
|
||||
if text:
|
||||
print(f"Assistant: {text}")
|
||||
final_text = text
|
||||
elif func_call is not None:
|
||||
name = getattr(func_call, "name", "<unknown>")
|
||||
args = getattr(func_call, "args", {})
|
||||
print(f"Function call: {name} args={args}")
|
||||
|
||||
print("Final text:", final_text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,25 @@
|
||||
# Google GenAI Examples with AgentOps
|
||||
|
||||
This directory contains examples of using Google's Generative AI with AgentOps instrumentation.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Python >= 3.10 < 3.13
|
||||
- Install required dependencies:
|
||||
```
|
||||
pip install agentops google-generativeai
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### 1. Gemini Example
|
||||
|
||||
Example: `gemini_example`
|
||||
This example demonstrates:
|
||||
- Basic Gemini API usage with AgentOps
|
||||
|
||||
## AgentOps Integration
|
||||
|
||||
These examples show how to use AgentOps to monitor and analyze your AI applications. AgentOps automatically instruments your Google GenAI calls to provide insights into performance, usage patterns, and model behavior.
|
||||
|
||||
To learn more about AgentOps, visit [https://www.agentops.ai](https://www.agentops.ai)
|
||||
@@ -0,0 +1,138 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "580c85ac",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Google Generative AI Example with AgentOps\n",
|
||||
"\n",
|
||||
"This notebook demonstrates how to use AgentOps with Google's Generative AI package for observing both synchronous and streaming text generation."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "d52c7ce5",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Instal necessary packages\n",
|
||||
"%pip install agentops\n",
|
||||
"%pip install google-genai"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "d731924a",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from google import genai\n",
|
||||
"import agentops\n",
|
||||
"from dotenv import load_dotenv\n",
|
||||
"import os"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "a94545c9",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"load_dotenv()\n",
|
||||
"\n",
|
||||
"os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\", \"your_api_key_here\")\n",
|
||||
"os.environ[\"GEMINI_API_KEY\"] = os.getenv(\"GEMINI_API_KEY\", \"your_gemini_api_key_here\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "d632fe48",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Initialize AgentOps and Gemini client\n",
|
||||
"agentops.init(tags=[\"gemini-example\", \"agentops-example\"])\n",
|
||||
"client = genai.Client()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "3923b6b8",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Test synchronous generation\n",
|
||||
"print(\"Testing synchronous generation:\")\n",
|
||||
"response = client.models.generate_content(model=\"gemini-1.5-flash\", contents=\"What are the three laws of robotics?\")\n",
|
||||
"print(response.text)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "da54e521",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Test streaming generation\n",
|
||||
"print(\"\\nTesting streaming generation:\")\n",
|
||||
"response_stream = client.models.generate_content_stream(\n",
|
||||
" model=\"gemini-1.5-flash\", contents=\"Explain the concept of machine learning in simple terms.\"\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"for chunk in response_stream:\n",
|
||||
" print(chunk.text, end=\"\")\n",
|
||||
"print() # Add newline after streaming output\n",
|
||||
"\n",
|
||||
"# Test another synchronous generation\n",
|
||||
"print(\"\\nTesting another synchronous generation:\")\n",
|
||||
"response = client.models.generate_content(\n",
|
||||
" model=\"gemini-1.5-flash\", contents=\"What is the difference between supervised and unsupervised learning?\"\n",
|
||||
")\n",
|
||||
"print(response.text)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "fbb2a59c",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Example of token counting\n",
|
||||
"print(\"\\nTesting token counting:\")\n",
|
||||
"token_response = client.models.count_tokens(\n",
|
||||
" model=\"gemini-1.5-flash\", contents=\"This is a test sentence to count tokens.\"\n",
|
||||
")\n",
|
||||
"print(f\"Token count: {token_response.total_tokens}\")"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "agentops (3.11.11)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.11"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
# 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.
|
||||
# # Instal necessary packages
|
||||
# %pip install agentops
|
||||
# %pip install google-genai
|
||||
from google import genai
|
||||
import agentops
|
||||
from dotenv import load_dotenv
|
||||
import os
|
||||
|
||||
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")
|
||||
|
||||
# Initialize AgentOps and Gemini client
|
||||
agentops.init(trace_name="Google Gemini Example", tags=["gemini-example", "agentops-example"])
|
||||
client = genai.Client()
|
||||
|
||||
# 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)
|
||||
|
||||
# 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)
|
||||
|
||||
# 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}")
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
agentops.validate_trace_spans(trace_context=None)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
@@ -0,0 +1,2 @@
|
||||
google-generativeai
|
||||
google-genai
|
||||
@@ -0,0 +1,47 @@
|
||||
import os
|
||||
|
||||
import agentops
|
||||
from haystack.components.generators.chat import AzureOpenAIChatGenerator
|
||||
|
||||
|
||||
def main():
|
||||
agentops.init(os.getenv("AGENTOPS_API_KEY"))
|
||||
|
||||
if not os.getenv("AZURE_OPENAI_API_KEY") or not os.getenv("AZURE_OPENAI_ENDPOINT"):
|
||||
print("Skipping Azure example: missing AZURE_OPENAI_API_KEY or AZURE_OPENAI_ENDPOINT (CI-safe skip)")
|
||||
return
|
||||
|
||||
tracer = agentops.start_trace(
|
||||
trace_name="Haystack Azure Chat Example",
|
||||
tags=["haystack", "azure", "chat", "agentops-example"],
|
||||
)
|
||||
|
||||
api_version = os.getenv("AZURE_OPENAI_API_VERSION", "2024-06-01")
|
||||
deployment = os.getenv("AZURE_OPENAI_DEPLOYMENT", "gpt-4o-mini")
|
||||
|
||||
generator = AzureOpenAIChatGenerator(
|
||||
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
|
||||
api_version=api_version,
|
||||
azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
|
||||
deployment_name=deployment,
|
||||
)
|
||||
|
||||
messages = [{"role": "user", "content": "In one sentence, what is AgentOps?"}]
|
||||
result = generator.run(messages=messages)
|
||||
replies = result.get("replies") or []
|
||||
print("Haystack Azure reply:", replies[0] if replies else "<no reply>")
|
||||
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
validation_result = agentops.validate_trace_spans(trace_context=tracer)
|
||||
agentops.print_validation_summary(validation_result)
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
|
||||
agentops.end_trace(tracer, end_state="Success")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,38 @@
|
||||
import os
|
||||
|
||||
import agentops
|
||||
from haystack.components.generators.openai import OpenAIGenerator
|
||||
|
||||
|
||||
def main():
|
||||
agentops.init(os.getenv("AGENTOPS_API_KEY"))
|
||||
|
||||
if not os.getenv("OPENAI_API_KEY"):
|
||||
print("Skipping OpenAI example: missing OPENAI_API_KEY")
|
||||
return
|
||||
|
||||
tracer = agentops.start_trace(
|
||||
trace_name="Haystack OpenAI Example",
|
||||
tags=["haystack", "openai", "agentops-example"],
|
||||
)
|
||||
|
||||
prompt = "In one sentence, what is AgentOps?"
|
||||
generator = OpenAIGenerator(model="gpt-4o-mini")
|
||||
result = generator.run(prompt=prompt)
|
||||
replies = result.get("replies") or []
|
||||
print("Haystack reply:", replies[0] if replies else "<no reply>")
|
||||
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly with AgentOps...")
|
||||
try:
|
||||
validation_result = agentops.validate_trace_spans(trace_context=tracer)
|
||||
agentops.print_validation_summary(validation_result)
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
|
||||
agentops.end_trace(tracer, end_state="Success")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,2 @@
|
||||
haystack-ai>=2.0.0
|
||||
openai>=1.102.0
|
||||
@@ -0,0 +1,25 @@
|
||||
# LangChain Examples with AgentOps
|
||||
|
||||
This directory contains examples of using LangChain with AgentOps instrumentation.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Python >= 3.10 < 3.13
|
||||
- Install required dependencies:
|
||||
```
|
||||
pip install agentops langchain langchain_openai
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### 1. LangChain Examples
|
||||
|
||||
Example: `langchain_examples`
|
||||
This example demonstrates:
|
||||
- Comprehensive LangChain usage examples
|
||||
|
||||
## AgentOps Integration
|
||||
|
||||
These examples show how to use AgentOps to monitor and analyze your AI applications. AgentOps automatically instruments your LangChain calls to provide insights into performance, usage patterns, and model behavior.
|
||||
|
||||
To learn more about AgentOps, visit [https://www.agentops.ai](https://www.agentops.ai)
|
||||
@@ -0,0 +1,320 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "e0deea1ab1db2a19",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# AgentOps Langchain Agent Implementation\n",
|
||||
"\n",
|
||||
"Using AgentOps monitoring with Langchain is simple. We've created a LangchainCallbackHandler that will do all of the heavy lifting!\n",
|
||||
"\n",
|
||||
"First let's install the required packages"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "8e3d38adc7861277",
|
||||
"metadata": {
|
||||
"ExecuteTime": {
|
||||
"end_time": "2024-08-08T00:29:29.288644Z",
|
||||
"start_time": "2024-08-08T00:29:29.026314Z"
|
||||
}
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%pip install langchain\n",
|
||||
"%pip install langchain_openai\n",
|
||||
"%pip install agentops\n",
|
||||
"%pip install python-dotenv"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "effc8ee7453a6c3",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Then import them"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "d344305baa26d651",
|
||||
"metadata": {
|
||||
"ExecuteTime": {
|
||||
"end_time": "2024-08-08T00:29:30.052348Z",
|
||||
"start_time": "2024-08-08T00:29:29.289841Z"
|
||||
},
|
||||
"collapsed": false
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"from langchain_openai import ChatOpenAI\n",
|
||||
"from langchain.agents import tool, AgentExecutor, create_openai_tools_agent\n",
|
||||
"from dotenv import load_dotenv\n",
|
||||
"from langchain_core.prompts import ChatPromptTemplate"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "3584d84a441169b0",
|
||||
"metadata": {
|
||||
"collapsed": false
|
||||
},
|
||||
"source": [
|
||||
"The only difference with using AgentOps is that we'll also import this special Callback Handler"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "256f01cac66d7d90",
|
||||
"metadata": {
|
||||
"ExecuteTime": {
|
||||
"end_time": "2024-08-08T00:29:30.058535Z",
|
||||
"start_time": "2024-08-08T00:29:30.054497Z"
|
||||
},
|
||||
"collapsed": false
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from agentops.integration.callbacks.langchain import (\n",
|
||||
" LangchainCallbackHandler as AgentOpsLangchainCallbackHandler,\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "afab0f7bbd847916",
|
||||
"metadata": {
|
||||
"collapsed": false
|
||||
},
|
||||
"source": [
|
||||
"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.\n",
|
||||
"\n",
|
||||
"[Get an AgentOps API key](https://agentops.ai/settings/projects)\n",
|
||||
"\n",
|
||||
"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...\n",
|
||||
"\n",
|
||||
"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!"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "3f9189f4d13ebd07",
|
||||
"metadata": {
|
||||
"ExecuteTime": {
|
||||
"end_time": "2024-08-08T00:29:30.072366Z",
|
||||
"start_time": "2024-08-08T00:29:30.063997Z"
|
||||
},
|
||||
"collapsed": false
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"load_dotenv()\n",
|
||||
"os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\", \"your_api_key_here\")\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\", \"your_openai_api_key_here\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "6f5a9ab030c636c6",
|
||||
"metadata": {
|
||||
"collapsed": false
|
||||
},
|
||||
"source": [
|
||||
"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.\n",
|
||||
"\n",
|
||||
"Pass in your API key, and optionally any tags to describe this session for easier lookup in the AO dashboard.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "7d4accd2f68404fb",
|
||||
"metadata": {
|
||||
"ExecuteTime": {
|
||||
"end_time": "2024-08-08T00:29:31.018329Z",
|
||||
"start_time": "2024-08-08T00:29:30.074528Z"
|
||||
},
|
||||
"collapsed": false
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"agentops_handler = AgentOpsLangchainCallbackHandler(tags=[\"Langchain Example\", \"agentops-example\"])\n",
|
||||
"\n",
|
||||
"llm = ChatOpenAI(callbacks=[agentops_handler], model=\"gpt-3.5-turbo\")\n",
|
||||
"\n",
|
||||
"# You must pass in a callback handler to record your agent\n",
|
||||
"llm.callbacks = [agentops_handler]\n",
|
||||
"\n",
|
||||
"prompt = ChatPromptTemplate.from_messages(\n",
|
||||
" [\n",
|
||||
" (\"system\", \"You are a helpful assistant. Respond only in Spanish.\"),\n",
|
||||
" (\"human\", \"{input}\"),\n",
|
||||
" # Placeholders fill up a **list** of messages\n",
|
||||
" (\"placeholder\", \"{agent_scratchpad}\"),\n",
|
||||
" # (\"tool_names\", \"find_movie\")\n",
|
||||
" ]\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "f7362d89b6a7af4c",
|
||||
"metadata": {
|
||||
"collapsed": false
|
||||
},
|
||||
"source": [
|
||||
"Agents generally use tools. Let's define a simple tool here. Tool usage is also recorded."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "4a28f85842129016",
|
||||
"metadata": {
|
||||
"ExecuteTime": {
|
||||
"end_time": "2024-08-08T00:29:31.071133Z",
|
||||
"start_time": "2024-08-08T00:29:31.022304Z"
|
||||
},
|
||||
"collapsed": false
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"@tool\n",
|
||||
"def find_movie(genre: str) -> str:\n",
|
||||
" \"\"\"Find available movies\"\"\"\n",
|
||||
" if genre == \"drama\":\n",
|
||||
" return \"Dune 2\"\n",
|
||||
" else:\n",
|
||||
" return \"Pineapple Express\"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"tools = [find_movie]"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "186984add993f839",
|
||||
"metadata": {
|
||||
"collapsed": false
|
||||
},
|
||||
"source": [
|
||||
"For each tool, you need to also add the callback handler"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "afe9113b61c67e80",
|
||||
"metadata": {
|
||||
"ExecuteTime": {
|
||||
"end_time": "2024-08-08T00:29:31.073655Z",
|
||||
"start_time": "2024-08-08T00:29:31.071945Z"
|
||||
},
|
||||
"collapsed": false
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"for t in tools:\n",
|
||||
" t.callbacks = [agentops_handler]"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "6dd5f322d26f692",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Add the tools to our LLM"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "e469ab337023053e",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"llm_with_tools = llm.bind_tools([find_movie])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "88b96e62db542900",
|
||||
"metadata": {
|
||||
"collapsed": false
|
||||
},
|
||||
"source": [
|
||||
"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"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "d45ff1b7a3843191",
|
||||
"metadata": {
|
||||
"ExecuteTime": {
|
||||
"end_time": "2024-08-08T00:29:31.127744Z",
|
||||
"start_time": "2024-08-08T00:29:31.124945Z"
|
||||
}
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"agent = create_openai_tools_agent(llm, tools, prompt)\n",
|
||||
"agent_executor = AgentExecutor(agent=agent, tools=tools)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "bb90bf54b5a42a63",
|
||||
"metadata": {
|
||||
"ExecuteTime": {
|
||||
"end_time": "2024-08-08T00:29:32.666768Z",
|
||||
"start_time": "2024-08-08T00:29:31.128749Z"
|
||||
}
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"agent_executor.invoke({\"input\": \"What comedies are playing?\"}, config={\"callback\": [agentops_handler]})"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "fb276a2e-f1c3-4f0f-8818-b7730e9d3ff7",
|
||||
"metadata": {
|
||||
"collapsed": false
|
||||
},
|
||||
"source": [
|
||||
"## Check your session\n",
|
||||
"Finally, check your run on [AgentOps](https://app.agentops.ai). You will see a session recorded with the LLM calls and tool usage."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "agentops (3.11.11)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.11"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
# 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
|
||||
# %pip install langchain
|
||||
# %pip install langchain_openai
|
||||
# %pip install agentops
|
||||
# %pip install python-dotenv
|
||||
# Then import them
|
||||
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
|
||||
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!
|
||||
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.
|
||||
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.
|
||||
@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
|
||||
for t in tools:
|
||||
t.callbacks = [agentops_handler]
|
||||
|
||||
# Add the tools to our LLM
|
||||
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
|
||||
agent = create_openai_tools_agent(llm, tools, prompt)
|
||||
agent_executor = AgentExecutor(agent=agent, tools=tools)
|
||||
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.
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
import agentops
|
||||
|
||||
agentops.validate_trace_spans(trace_context=None)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except ImportError:
|
||||
print("\n❌ Error: agentops library not installed. Please install it to validate spans.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
@@ -0,0 +1,2 @@
|
||||
langchain
|
||||
langchain-openai
|
||||
@@ -0,0 +1,329 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# LangGraph Integration with AgentOps\n",
|
||||
"\n",
|
||||
"This example demonstrates how to use LangGraph with AgentOps for comprehensive observability of your graph-based agent workflows.\n",
|
||||
"\n",
|
||||
"LangGraph is a framework for building stateful, multi-step applications with LLMs. AgentOps automatically instruments LangGraph to track:\n",
|
||||
"- Graph compilation and structure\n",
|
||||
"- Node executions and transitions\n",
|
||||
"- Tool usage within the graph\n",
|
||||
"- LLM calls made by agents\n",
|
||||
"- Complete execution flow with timing"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%pip install agentops langgraph langchain-openai python-dotenv"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Setup\n",
|
||||
"\n",
|
||||
"First, let's import the necessary libraries and initialize AgentOps:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"from typing import Annotated, Literal, TypedDict\n",
|
||||
"from langgraph.graph import StateGraph, END\n",
|
||||
"from langgraph.graph.message import add_messages\n",
|
||||
"from langchain_openai import ChatOpenAI\n",
|
||||
"from langchain_core.messages import HumanMessage, ToolMessage\n",
|
||||
"from langchain_core.tools import tool\n",
|
||||
"import agentops\n",
|
||||
"from dotenv import load_dotenv\n",
|
||||
"\n",
|
||||
"# Load environment variables\n",
|
||||
"load_dotenv()\n",
|
||||
"\n",
|
||||
"# Initialize AgentOps - this enables automatic instrumentation\n",
|
||||
"agentops.init(os.getenv(\"AGENTOPS_API_KEY\"), auto_start_session=False)\n",
|
||||
"trace = agentops.start_trace(\"langgraph_example\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Define Tools\n",
|
||||
"\n",
|
||||
"Let's create some simple tools that our agent can use:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"@tool\n",
|
||||
"def get_weather(location: str) -> str:\n",
|
||||
" \"\"\"Get the weather for a given location.\"\"\"\n",
|
||||
" # Simulated weather data\n",
|
||||
" weather_data = {\n",
|
||||
" \"New York\": \"Sunny, 72°F\",\n",
|
||||
" \"London\": \"Cloudy, 60°F\",\n",
|
||||
" \"Tokyo\": \"Rainy, 65°F\",\n",
|
||||
" \"Paris\": \"Partly cloudy, 68°F\",\n",
|
||||
" \"Sydney\": \"Clear, 75°F\",\n",
|
||||
" }\n",
|
||||
" return weather_data.get(location, f\"Weather data not available for {location}\")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"@tool\n",
|
||||
"def calculate(expression: str) -> str:\n",
|
||||
" \"\"\"Evaluate a mathematical expression.\"\"\"\n",
|
||||
" try:\n",
|
||||
" result = eval(expression)\n",
|
||||
" return f\"The result is: {result}\"\n",
|
||||
" except Exception as e:\n",
|
||||
" return f\"Error calculating expression: {str(e)}\"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Collect tools for binding to the model\n",
|
||||
"tools = [get_weather, calculate]"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Define Agent State\n",
|
||||
"\n",
|
||||
"In LangGraph, we need to define the state that will be passed between nodes:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"class AgentState(TypedDict):\n",
|
||||
" messages: Annotated[list, add_messages]"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Create the Model and Node Functions\n",
|
||||
"\n",
|
||||
"We'll create a model with tool binding and define the functions that will be our graph nodes:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Create model with tool binding\n",
|
||||
"model = ChatOpenAI(temperature=0, model=\"gpt-4o-mini\").bind_tools(tools)\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"def should_continue(state: AgentState) -> Literal[\"tools\", \"end\"]:\n",
|
||||
" \"\"\"Determine if we should continue to tools or end.\"\"\"\n",
|
||||
" messages = state[\"messages\"]\n",
|
||||
" last_message = messages[-1]\n",
|
||||
"\n",
|
||||
" # If the LLM wants to use tools, continue to the tools node\n",
|
||||
" if hasattr(last_message, \"tool_calls\") and last_message.tool_calls:\n",
|
||||
" return \"tools\"\n",
|
||||
" # Otherwise, we're done\n",
|
||||
" return \"end\"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"def call_model(state: AgentState):\n",
|
||||
" \"\"\"Call the language model.\"\"\"\n",
|
||||
" messages = state[\"messages\"]\n",
|
||||
" response = model.invoke(messages)\n",
|
||||
" return {\"messages\": [response]}\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"def call_tools(state: AgentState):\n",
|
||||
" \"\"\"Execute the tool calls requested by the model.\"\"\"\n",
|
||||
" messages = state[\"messages\"]\n",
|
||||
" last_message = messages[-1]\n",
|
||||
"\n",
|
||||
" tool_messages = []\n",
|
||||
" for tool_call in last_message.tool_calls:\n",
|
||||
" tool_name = tool_call[\"name\"]\n",
|
||||
" tool_args = tool_call[\"args\"]\n",
|
||||
"\n",
|
||||
" # Find and execute the requested tool\n",
|
||||
" for available_tool in tools:\n",
|
||||
" if available_tool.name == tool_name:\n",
|
||||
" result = available_tool.invoke(tool_args)\n",
|
||||
" tool_messages.append(ToolMessage(content=str(result), tool_call_id=tool_call[\"id\"]))\n",
|
||||
" break\n",
|
||||
"\n",
|
||||
" return {\"messages\": tool_messages}"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Build the Graph\n",
|
||||
"\n",
|
||||
"Now let's construct the LangGraph workflow:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Create the graph\n",
|
||||
"workflow = StateGraph(AgentState)\n",
|
||||
"\n",
|
||||
"# Add nodes\n",
|
||||
"workflow.add_node(\"agent\", call_model)\n",
|
||||
"workflow.add_node(\"tools\", call_tools)\n",
|
||||
"\n",
|
||||
"# Set the entry point\n",
|
||||
"workflow.set_entry_point(\"agent\")\n",
|
||||
"\n",
|
||||
"# Add conditional edges\n",
|
||||
"workflow.add_conditional_edges(\"agent\", should_continue, {\"tools\": \"tools\", \"end\": END})\n",
|
||||
"\n",
|
||||
"# Add edge from tools back to agent\n",
|
||||
"workflow.add_edge(\"tools\", \"agent\")\n",
|
||||
"\n",
|
||||
"# Compile the graph\n",
|
||||
"app = workflow.compile()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Run Examples\n",
|
||||
"\n",
|
||||
"Let's test our agent with different queries that require tool usage:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Example 1: Weather query\n",
|
||||
"print(\"Example 1: Weather Query\")\n",
|
||||
"print(\"=\" * 50)\n",
|
||||
"\n",
|
||||
"messages = [HumanMessage(content=\"What's the weather in New York and Tokyo?\")]\n",
|
||||
"result = app.invoke({\"messages\": messages})\n",
|
||||
"\n",
|
||||
"final_message = result[\"messages\"][-1]\n",
|
||||
"print(f\"Response: {final_message.content}\\n\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Example 2: Math calculation\n",
|
||||
"print(\"Example 2: Math Calculation\")\n",
|
||||
"print(\"=\" * 50)\n",
|
||||
"\n",
|
||||
"messages = [HumanMessage(content=\"Calculate 25 * 4 + 10\")]\n",
|
||||
"result = app.invoke({\"messages\": messages})\n",
|
||||
"\n",
|
||||
"final_message = result[\"messages\"][-1]\n",
|
||||
"print(f\"Response: {final_message.content}\\n\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Example 3: Combined query\n",
|
||||
"print(\"Example 3: Combined Query\")\n",
|
||||
"print(\"=\" * 50)\n",
|
||||
"\n",
|
||||
"messages = [HumanMessage(content=\"What's the weather in Paris? Also calculate 100/5\")]\n",
|
||||
"result = app.invoke({\"messages\": messages})\n",
|
||||
"\n",
|
||||
"final_message = result[\"messages\"][-1]\n",
|
||||
"print(f\"Response: {final_message.content}\\n\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## View in AgentOps Dashboard\n",
|
||||
"\n",
|
||||
"After running this notebook, you can view the traces in your AgentOps dashboard. You'll see:\n",
|
||||
"\n",
|
||||
"1. **Graph Compilation**: The structure of your LangGraph with nodes and edges\n",
|
||||
"2. **Execution Flow**: How the graph executed, including:\n",
|
||||
" - Agent node calls\n",
|
||||
" - Tool node executions\n",
|
||||
" - State transitions\n",
|
||||
"3. **LLM Calls**: Each ChatGPT call with prompts and completions\n",
|
||||
"4. **Tool Usage**: Which tools were called and their results\n",
|
||||
"5. **Timing Information**: How long each step took\n",
|
||||
"\n",
|
||||
"The instrumentation captures the full context of your LangGraph application automatically!"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"print(\"✅ Check your AgentOps dashboard for comprehensive traces!\")\n",
|
||||
"print(\"🔍 You'll see the graph structure, execution flow, and all LLM/tool calls.\")\n",
|
||||
"agentops.end_trace(trace)"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": ".venv",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.12"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 2
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import os
|
||||
from typing import Annotated, Literal, TypedDict
|
||||
from langgraph.graph import StateGraph, END
|
||||
from langgraph.graph.message import add_messages
|
||||
from langchain_openai import ChatOpenAI
|
||||
from langchain_core.messages import HumanMessage, ToolMessage
|
||||
from langchain_core.tools import tool
|
||||
import agentops
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
agentops.init(
|
||||
os.getenv("AGENTOPS_API_KEY"),
|
||||
trace_name="LangGraph Tool Usage Example",
|
||||
tags=["langgraph", "tool-usage", "agentops-example"],
|
||||
)
|
||||
|
||||
|
||||
@tool
|
||||
def get_weather(location: str) -> str:
|
||||
"""Get the weather for a given location."""
|
||||
weather_data = {
|
||||
"New York": "Sunny, 72°F",
|
||||
"London": "Cloudy, 60°F",
|
||||
"Tokyo": "Rainy, 65°F",
|
||||
"Paris": "Partly cloudy, 68°F",
|
||||
"Sydney": "Clear, 75°F",
|
||||
}
|
||||
return weather_data.get(location, f"Weather data not available for {location}")
|
||||
|
||||
|
||||
@tool
|
||||
def calculate(expression: str) -> str:
|
||||
"""Evaluate a mathematical expression."""
|
||||
try:
|
||||
result = eval(expression)
|
||||
return f"The result is: {result}"
|
||||
except Exception as e:
|
||||
return f"Error calculating expression: {str(e)}"
|
||||
|
||||
|
||||
tools = [get_weather, calculate]
|
||||
|
||||
|
||||
class AgentState(TypedDict):
|
||||
messages: Annotated[list, add_messages]
|
||||
|
||||
|
||||
model = ChatOpenAI(temperature=0, model="gpt-4o-mini").bind_tools(tools)
|
||||
|
||||
|
||||
def should_continue(state: AgentState) -> Literal["tools", "end"]:
|
||||
messages = state["messages"]
|
||||
last_message = messages[-1]
|
||||
|
||||
if hasattr(last_message, "tool_calls") and last_message.tool_calls:
|
||||
return "tools"
|
||||
return "end"
|
||||
|
||||
|
||||
def call_model(state: AgentState):
|
||||
messages = state["messages"]
|
||||
response = model.invoke(messages)
|
||||
return {"messages": [response]}
|
||||
|
||||
|
||||
def call_tools(state: AgentState):
|
||||
messages = state["messages"]
|
||||
last_message = messages[-1]
|
||||
|
||||
tool_messages = []
|
||||
for tool_call in last_message.tool_calls:
|
||||
tool_name = tool_call["name"]
|
||||
tool_args = tool_call["args"]
|
||||
|
||||
for tool_obj in tools:
|
||||
if tool_obj.name == tool_name:
|
||||
result = tool_obj.invoke(tool_args)
|
||||
tool_messages.append(ToolMessage(content=str(result), tool_call_id=tool_call["id"]))
|
||||
break
|
||||
|
||||
return {"messages": tool_messages}
|
||||
|
||||
|
||||
workflow = StateGraph(AgentState)
|
||||
|
||||
workflow.add_node("agent", call_model)
|
||||
workflow.add_node("tools", call_tools)
|
||||
|
||||
workflow.set_entry_point("agent")
|
||||
|
||||
workflow.add_conditional_edges("agent", should_continue, {"tools": "tools", "end": END})
|
||||
|
||||
workflow.add_edge("tools", "agent")
|
||||
|
||||
app = workflow.compile()
|
||||
|
||||
|
||||
def run_example():
|
||||
print("=== LangGraph + AgentOps Example ===\n")
|
||||
|
||||
queries = [
|
||||
"What's the weather in New York and Tokyo?",
|
||||
"Calculate 25 * 4 + 10",
|
||||
"What's the weather in Paris? Also calculate 100/5",
|
||||
]
|
||||
|
||||
for query in queries:
|
||||
print(f"Query: {query}")
|
||||
print("-" * 40)
|
||||
|
||||
messages = [HumanMessage(content=query)]
|
||||
result = app.invoke({"messages": messages})
|
||||
|
||||
final_message = result["messages"][-1]
|
||||
print(f"Response: {final_message.content}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_example()
|
||||
print("✅ Check your AgentOps dashboard for the trace!")
|
||||
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that we have enough spans tracked properly...")
|
||||
try:
|
||||
# LangGraph doesn't emit LLM spans in the same format, so we just check span count
|
||||
result = agentops.validate_trace_spans(trace_context=None, check_llm=False, min_spans=5)
|
||||
print(f"\n✅ Success! {result['span_count']} spans were properly recorded in AgentOps.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
@@ -0,0 +1,2 @@
|
||||
langgraph
|
||||
langchain-openai
|
||||
@@ -0,0 +1,25 @@
|
||||
# LiteLLM Examples with AgentOps
|
||||
|
||||
This directory contains examples of using LiteLLM with AgentOps instrumentation.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Python >= 3.10 < 3.13
|
||||
- Install required dependencies:
|
||||
```
|
||||
pip install agentops litellm
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### 1. LiteLLM Example
|
||||
|
||||
Example: `litellm_example`
|
||||
This example demonstrates:
|
||||
- Multi-provider LLM access through LiteLLM
|
||||
|
||||
## AgentOps Integration
|
||||
|
||||
These examples show how to use AgentOps to monitor and analyze your AI applications. AgentOps automatically instruments your LiteLLM calls to provide insights into performance, usage patterns, and model behavior.
|
||||
|
||||
To learn more about AgentOps, visit [https://www.agentops.ai](https://www.agentops.ai)
|
||||
@@ -0,0 +1,157 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# AgentOps for observing LiteLLM\n",
|
||||
"\n",
|
||||
"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.\n",
|
||||
"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.\n",
|
||||
"\n",
|
||||
"[See our LiteLLM docs](https://docs.agentops.ai/v1/integrations/litellm)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"First let's install the required packages"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%pip install -U litellm\n",
|
||||
"%pip install -U agentops\n",
|
||||
"%pip install -U python-dotenv"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Then import them"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import litellm\n",
|
||||
"import agentops\n",
|
||||
"import os\n",
|
||||
"from dotenv import load_dotenv"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"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.\n",
|
||||
"\n",
|
||||
"[Get an AgentOps API key](https://agentops.ai/settings/projects)\n",
|
||||
"\n",
|
||||
"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...\n",
|
||||
"\n",
|
||||
"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!"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"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=\"...\"))."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"load_dotenv()\n",
|
||||
"os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\", \"your_api_key_here\")\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = os.getenv(\n",
|
||||
" \"OPENAI_API_KEY\", \"your_openai_api_key_here\"\n",
|
||||
") # or the provider of your choosing"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"agentops.init(auto_start_session=False)\n",
|
||||
"tracer = agentops.start_trace(trace_name=\"LiteLLM Example\", tags=[\"litellm-example\", \"agentops-example\"])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Note: AgentOps requires that you call LiteLLM completions differently than the LiteLLM's docs mention\n",
|
||||
"Instead of doing this -\n",
|
||||
"\n",
|
||||
"```python\n",
|
||||
"from litellm import completion\n",
|
||||
"completion()\n",
|
||||
"```\n",
|
||||
"\n",
|
||||
"You should do this -\n",
|
||||
"\n",
|
||||
"```python\n",
|
||||
"import litellm\n",
|
||||
"litellm.completion()\n",
|
||||
"```"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"messages = [{\"role\": \"user\", \"content\": \"Write a 12 word poem about secret agents.\"}]\n",
|
||||
"response = litellm.completion(model=\"gpt-4\", messages=messages) # or the model of your choosing\n",
|
||||
"print(response.choices[0].message.content)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"agentops.end_trace(tracer, end_state=\"Success\")"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "agentops (3.11.11)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.11"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 2
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
# 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
|
||||
# %pip install -U litellm
|
||||
# %pip install -U agentops
|
||||
# %pip install -U python-dotenv
|
||||
# Then import them
|
||||
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="...")).
|
||||
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
|
||||
|
||||
agentops.init(auto_start_session=False, trace_name="LiteLLM Example")
|
||||
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()
|
||||
# ```
|
||||
messages = [{"role": "user", "content": "Write a 12 word poem about secret agents."}]
|
||||
response = litellm.completion(model="gpt-4o-mini", messages=messages) # or the model of your choosing
|
||||
print(response.choices[0].message.content)
|
||||
|
||||
agentops.end_trace(tracer, end_state="Success")
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
agentops.validate_trace_spans(trace_context=tracer)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
@@ -0,0 +1 @@
|
||||
litellm
|
||||
@@ -0,0 +1,35 @@
|
||||
# LlamaIndex AgentOps Integration Example
|
||||
|
||||
This example demonstrates how to use AgentOps with LlamaIndex for observability and monitoring of your context-augmented generative AI applications.
|
||||
|
||||
## Setup
|
||||
|
||||
1. Install required packages:
|
||||
```bash
|
||||
pip install agentops llama-index-instrumentation-agentops llama-index python-dotenv
|
||||
```
|
||||
|
||||
2. Set your API keys:
|
||||
```bash
|
||||
export AGENTOPS_API_KEY="your_agentops_api_key"
|
||||
export OPENAI_API_KEY="your_openai_api_key"
|
||||
```
|
||||
|
||||
## Files
|
||||
|
||||
- `llamaindex_example.py` - Python script example
|
||||
- `llamaindex_example.ipynb` - Jupyter notebook example
|
||||
|
||||
## Usage
|
||||
|
||||
Run the Python script:
|
||||
```bash
|
||||
python llamaindex_example.py
|
||||
```
|
||||
|
||||
Or open and run the Jupyter notebook:
|
||||
```bash
|
||||
jupyter notebook llamaindex_example.ipynb
|
||||
```
|
||||
|
||||
After running, check your AgentOps dashboard for the recorded session.
|
||||
@@ -0,0 +1,204 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "a886f0ad",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# LlamaIndex AgentOps Integration Example\n",
|
||||
"\n",
|
||||
"This notebook demonstrates how to use AgentOps with LlamaIndex for observability and monitoring of your context-augmented generative AI applications.\n",
|
||||
"\n",
|
||||
"## Setup\n",
|
||||
"\n",
|
||||
"First, install the required packages:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "002718a0",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Install required packages\n",
|
||||
"!pip install agentops llama-index-instrumentation-agentops llama-index-embeddings-huggingface llama-index-llms-huggingface python-dotenv"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "bc009657",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Initialize AgentOps Handler\n",
|
||||
"\n",
|
||||
"Set up the AgentOps handler for LlamaIndex instrumentation:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "f1d8a0c2",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"from dotenv import load_dotenv\n",
|
||||
"from llama_index.core import VectorStoreIndex, Document, Settings\n",
|
||||
"from llama_index.instrumentation.agentops import AgentOpsHandler\n",
|
||||
"\n",
|
||||
"# Initialize AgentOps handler\n",
|
||||
"handler = AgentOpsHandler()\n",
|
||||
"handler.init()\n",
|
||||
"\n",
|
||||
"# Load environment variables\n",
|
||||
"load_dotenv()\n",
|
||||
"\n",
|
||||
"# Set API keys (replace with your actual keys)\n",
|
||||
"os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\", \"your_agentops_api_key_here\")\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\", \"your_openai_api_key_here\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "8794d1f2",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Configure Local Models (Optional)\n",
|
||||
"\n",
|
||||
"For this example, we'll use local HuggingFace models to avoid requiring external API keys:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "35804326",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.embeddings.huggingface import HuggingFaceEmbedding\n",
|
||||
"from llama_index.llms.huggingface import HuggingFaceLLM\n",
|
||||
"\n",
|
||||
"# Configure local embeddings and LLM\n",
|
||||
"Settings.embed_model = HuggingFaceEmbedding(model_name=\"BAAI/bge-small-en-v1.5\")\n",
|
||||
"Settings.llm = HuggingFaceLLM(model_name=\"microsoft/DialoGPT-medium\")\n",
|
||||
"print(\"Using local HuggingFace embeddings and LLM\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "b23271d3",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Create Sample Documents and Index\n",
|
||||
"\n",
|
||||
"Create some sample documents and build a vector index:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "80b1c26a",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"print(\"🚀 Starting LlamaIndex AgentOps Integration Example\")\n",
|
||||
"print(\"=\" * 50)\n",
|
||||
"\n",
|
||||
"# Create sample documents\n",
|
||||
"documents = [\n",
|
||||
" Document(text=\"LlamaIndex is a framework for building context-augmented generative AI applications with LLMs.\"),\n",
|
||||
" Document(\n",
|
||||
" text=\"AgentOps provides observability into your AI applications, tracking LLM calls, performance metrics, and more.\"\n",
|
||||
" ),\n",
|
||||
" Document(\n",
|
||||
" text=\"The integration between LlamaIndex and AgentOps allows you to monitor your RAG applications seamlessly.\"\n",
|
||||
" ),\n",
|
||||
" Document(\n",
|
||||
" text=\"Vector databases are used to store and retrieve embeddings for similarity search in RAG applications.\"\n",
|
||||
" ),\n",
|
||||
" Document(\n",
|
||||
" text=\"Context-augmented generation combines retrieval and generation to provide more accurate and relevant responses.\"\n",
|
||||
" ),\n",
|
||||
"]\n",
|
||||
"\n",
|
||||
"print(\"📚 Creating vector index from sample documents...\")\n",
|
||||
"index = VectorStoreIndex.from_documents(documents)\n",
|
||||
"print(\"✅ Vector index created successfully\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "e07f1d6a",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Perform Queries\n",
|
||||
"\n",
|
||||
"Now let's perform some queries to demonstrate the AgentOps integration:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "5882dd2a",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Create query engine\n",
|
||||
"query_engine = index.as_query_engine()\n",
|
||||
"\n",
|
||||
"print(\"🔍 Performing queries...\")\n",
|
||||
"\n",
|
||||
"# Sample queries\n",
|
||||
"queries = [\n",
|
||||
" \"What is LlamaIndex?\",\n",
|
||||
" \"How does AgentOps help with AI applications?\",\n",
|
||||
" \"What are the benefits of using vector databases in RAG?\",\n",
|
||||
"]\n",
|
||||
"\n",
|
||||
"for i, query in enumerate(queries, 1):\n",
|
||||
" print(f\"\\n📝 Query {i}: {query}\")\n",
|
||||
" response = query_engine.query(query)\n",
|
||||
" print(f\"💬 Response: {response}\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "b46b944c",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Results\n",
|
||||
"\n",
|
||||
"After running this notebook, you should see:\n",
|
||||
"\n",
|
||||
"1. **AgentOps Session Link**: A URL to view the session in your AgentOps dashboard\n",
|
||||
"2. **Cost Tracking**: Information about the cost of LLM calls (if using paid APIs)\n",
|
||||
"3. **Operation Tracking**: All LlamaIndex operations are automatically tracked\n",
|
||||
"\n",
|
||||
"Check your AgentOps dashboard to see detailed information about:\n",
|
||||
"- LLM calls and responses\n",
|
||||
"- Performance metrics\n",
|
||||
"- Cost analysis\n",
|
||||
"- Session replay\n",
|
||||
"\n",
|
||||
"The session link will be printed in the output above by AgentOps."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "c141973e",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"print(\"\\n\" + \"=\" * 50)\n",
|
||||
"print(\"🎉 Example completed successfully!\")\n",
|
||||
"print(\"📊 Check your AgentOps dashboard to see the recorded session with LLM calls and operations.\")\n",
|
||||
"print(\"🔗 The session link should be printed above by AgentOps.\")"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
#
|
||||
#
|
||||
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
from llama_index.core import VectorStoreIndex, Document, Settings
|
||||
from llama_index.instrumentation.agentops import AgentOpsHandler
|
||||
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
|
||||
from llama_index.llms.huggingface import HuggingFaceLLM
|
||||
|
||||
handler = AgentOpsHandler(tags=["llamaindex", "rag", "agentops-example"])
|
||||
handler.init()
|
||||
|
||||
load_dotenv()
|
||||
|
||||
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY", "your_agentops_api_key_here")
|
||||
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY", "your_openai_api_key_here")
|
||||
|
||||
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")
|
||||
|
||||
print("🚀 Starting LlamaIndex AgentOps Integration Example")
|
||||
print("=" * 50)
|
||||
|
||||
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")
|
||||
|
||||
query_engine = index.as_query_engine()
|
||||
|
||||
print("🔍 Performing 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}")
|
||||
|
||||
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.")
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
import agentops
|
||||
|
||||
agentops.validate_trace_spans(trace_context=None)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
@@ -0,0 +1,3 @@
|
||||
llama-index
|
||||
llama-index-llms-openai
|
||||
llama-index-instrumentation-agentops
|
||||
@@ -0,0 +1,317 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "4695c5e8",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"\n",
|
||||
"# Memory Operations with Mem0\n",
|
||||
"\n",
|
||||
"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.\n",
|
||||
"\n",
|
||||
"## Overview\n",
|
||||
"\n",
|
||||
"This example showcases practical memory management operations where we:\n",
|
||||
"\n",
|
||||
"1. **Initialize Mem0 Memory instances** for both sync and async operations\n",
|
||||
"2. **Store conversation history** and user preferences with metadata\n",
|
||||
"3. **Search memories** using natural language queries\n",
|
||||
"4. **Compare performance** between synchronous and asynchronous memory operations\n",
|
||||
"\n",
|
||||
"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.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "443ab37e",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Install the required dependencies:\n",
|
||||
"%pip install agentops\n",
|
||||
"%pip install mem0ai\n",
|
||||
"%pip install python-dotenv"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "994a6771",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Setup and Imports\n",
|
||||
"\n",
|
||||
"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.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 73,
|
||||
"id": "dbc4d41d",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from mem0 import Memory, AsyncMemory\n",
|
||||
"import os\n",
|
||||
"import asyncio\n",
|
||||
"import agentops"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "970fc737",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Environment Configuration\n",
|
||||
"\n",
|
||||
"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.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "502e4b22",
|
||||
"metadata": {
|
||||
"lines_to_next_cell": 1
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\")\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "91bb29c1",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Configuration and Sample Data\n",
|
||||
"\n",
|
||||
"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.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 75,
|
||||
"id": "6a99b32f",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"local_config = {\n",
|
||||
" \"llm\": {\n",
|
||||
" \"provider\": \"openai\",\n",
|
||||
" \"config\": {\n",
|
||||
" \"model\": \"gpt-4o-mini\",\n",
|
||||
" \"temperature\": 0.1,\n",
|
||||
" \"max_tokens\": 2000,\n",
|
||||
" },\n",
|
||||
" }\n",
|
||||
"}\n",
|
||||
"user_id = \"alice_demo\"\n",
|
||||
"agent_id = \"assistant_demo\"\n",
|
||||
"run_id = \"session_001\"\n",
|
||||
"\n",
|
||||
"sample_messages = [\n",
|
||||
" {\"role\": \"user\", \"content\": \"I'm planning to watch a movie tonight. Any recommendations?\"},\n",
|
||||
" {\"role\": \"assistant\", \"content\": \"How about a thriller? They can be quite engaging.\"},\n",
|
||||
" {\"role\": \"user\", \"content\": \"I'm not a big fan of thriller movies but I love sci-fi movies.\"},\n",
|
||||
" {\n",
|
||||
" \"role\": \"assistant\",\n",
|
||||
" \"content\": \"Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future.\",\n",
|
||||
" },\n",
|
||||
"]\n",
|
||||
"\n",
|
||||
"sample_preferences = [\n",
|
||||
" \"I prefer dark roast coffee over light roast\",\n",
|
||||
" \"I exercise every morning at 6 AM\",\n",
|
||||
" \"I'm vegetarian and avoid all meat products\",\n",
|
||||
" \"I love reading science fiction novels\",\n",
|
||||
" \"I work in software engineering\",\n",
|
||||
"]"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "2def0966",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Synchronous Memory Operations\n",
|
||||
"\n",
|
||||
"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.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 76,
|
||||
"id": "b863e6ed",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def demonstrate_sync_memory(local_config, sample_messages, sample_preferences, user_id):\n",
|
||||
" \"\"\"\n",
|
||||
" Demonstrate synchronous Memory class operations.\n",
|
||||
" \"\"\"\n",
|
||||
"\n",
|
||||
" agentops.start_trace(\"mem0_memory_example\", tags=[\"mem0_memory_example\"])\n",
|
||||
" try:\n",
|
||||
" memory = Memory.from_config(local_config)\n",
|
||||
"\n",
|
||||
" result = memory.add(\n",
|
||||
" sample_messages, user_id=user_id, metadata={\"category\": \"movie_preferences\", \"session\": \"demo\"}\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" for i, preference in enumerate(sample_preferences):\n",
|
||||
" result = memory.add(preference, user_id=user_id, metadata={\"type\": \"preference\", \"index\": i})\n",
|
||||
"\n",
|
||||
" search_queries = [\n",
|
||||
" \"What movies does the user like?\",\n",
|
||||
" \"What are the user's food preferences?\",\n",
|
||||
" \"When does the user exercise?\",\n",
|
||||
" ]\n",
|
||||
"\n",
|
||||
" for query in search_queries:\n",
|
||||
" results = memory.search(query, user_id=user_id)\n",
|
||||
"\n",
|
||||
" if results and \"results\" in results:\n",
|
||||
" for j, result in enumerate(results):\n",
|
||||
" print(f\"Result {j + 1}: {result.get('memory', 'N/A')}\")\n",
|
||||
" else:\n",
|
||||
" print(\"No results found\")\n",
|
||||
"\n",
|
||||
" all_memories = memory.get_all(user_id=user_id)\n",
|
||||
" if all_memories and \"results\" in all_memories:\n",
|
||||
" print(f\"Total memories: {len(all_memories['results'])}\")\n",
|
||||
"\n",
|
||||
" delete_all_result = memory.delete_all(user_id=user_id)\n",
|
||||
" print(f\"Delete all result: {delete_all_result}\")\n",
|
||||
"\n",
|
||||
" agentops.end_trace(end_state=\"success\")\n",
|
||||
" except Exception:\n",
|
||||
" agentops.end_trace(end_state=\"error\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "66965f64",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Asynchronous Memory Operations\n",
|
||||
"\n",
|
||||
"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.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 77,
|
||||
"id": "eae41613",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"async def demonstrate_async_memory(local_config, sample_messages, sample_preferences, user_id):\n",
|
||||
" \"\"\"\n",
|
||||
" Demonstrate asynchronous Memory class operations with concurrent execution.\n",
|
||||
" \"\"\"\n",
|
||||
"\n",
|
||||
" agentops.start_trace(\"mem0_memory_async_example\", tags=[\"mem0_memory_async_example\"])\n",
|
||||
" try:\n",
|
||||
" async_memory = await AsyncMemory.from_config(local_config)\n",
|
||||
"\n",
|
||||
" result = await async_memory.add(\n",
|
||||
" sample_messages, user_id=user_id, metadata={\"category\": \"async_movie_preferences\", \"session\": \"async_demo\"}\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" async def add_preference(preference, index):\n",
|
||||
" \"\"\"Helper function to add a single preference asynchronously.\"\"\"\n",
|
||||
" return await async_memory.add(\n",
|
||||
" preference, user_id=user_id, metadata={\"type\": \"async_preference\", \"index\": index}\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" tasks = [add_preference(pref, i) for i, pref in enumerate(sample_preferences)]\n",
|
||||
" results = await asyncio.gather(*tasks)\n",
|
||||
" for i, result in enumerate(results):\n",
|
||||
" print(f\"Added async preference {i + 1}: {result}\")\n",
|
||||
"\n",
|
||||
" search_queries = [\n",
|
||||
" \"What movies does the user like?\",\n",
|
||||
" \"What are the user's dietary restrictions?\",\n",
|
||||
" \"What does the user do for work?\",\n",
|
||||
" ]\n",
|
||||
"\n",
|
||||
" async def search_memory(query):\n",
|
||||
" \"\"\"Helper function to perform async memory search.\"\"\"\n",
|
||||
" return await async_memory.search(query, user_id=user_id), query\n",
|
||||
"\n",
|
||||
" search_tasks = [search_memory(query) for query in search_queries]\n",
|
||||
" search_results = await asyncio.gather(*search_tasks)\n",
|
||||
"\n",
|
||||
" for result, query in search_results:\n",
|
||||
" if result and \"results\" in result:\n",
|
||||
" for j, res in enumerate(result[\"results\"]):\n",
|
||||
" print(f\"Result {j + 1}: {res.get('memory', 'N/A')}\")\n",
|
||||
" else:\n",
|
||||
" print(\"No results found\")\n",
|
||||
"\n",
|
||||
" all_memories = await async_memory.get_all(user_id=user_id)\n",
|
||||
" if all_memories and \"results\" in all_memories:\n",
|
||||
" print(f\"Total async memories: {len(all_memories['results'])}\")\n",
|
||||
"\n",
|
||||
" delete_all_result = await async_memory.delete_all(user_id=user_id)\n",
|
||||
" print(f\"Delete all result: {delete_all_result}\")\n",
|
||||
"\n",
|
||||
" agentops.end_trace(end_state=\"success\")\n",
|
||||
"\n",
|
||||
" except Exception:\n",
|
||||
" agentops.end_trace(end_state=\"error\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "9689055c",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Execute Demonstrations\n",
|
||||
"\n",
|
||||
"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.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "714436f5",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Execute both sync and async demonstrations\n",
|
||||
"demonstrate_sync_memory(local_config, sample_messages, sample_preferences, user_id)\n",
|
||||
"await demonstrate_async_memory(local_config, sample_messages, sample_preferences, user_id)"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"jupytext": {
|
||||
"cell_metadata_filter": "-all",
|
||||
"main_language": "python",
|
||||
"notebook_metadata_filter": "-all"
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "venv",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.9"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
"""
|
||||
# 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.
|
||||
"""
|
||||
|
||||
import os
|
||||
import asyncio
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables first
|
||||
load_dotenv()
|
||||
|
||||
# Enable debug logging for AgentOps
|
||||
os.environ["AGENTOPS_LOG_LEVEL"] = "DEBUG"
|
||||
|
||||
# Set environment variables before importing
|
||||
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY", "")
|
||||
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY", "")
|
||||
|
||||
# Now import mem0 - it will be instrumented by agentops
|
||||
from mem0 import Memory, AsyncMemory # noqa E402
|
||||
|
||||
# Import agentops BEFORE mem0 to ensure proper instrumentation
|
||||
import agentops # noqa E402
|
||||
|
||||
|
||||
def demonstrate_sync_memory(local_config, sample_messages, sample_preferences, user_id):
|
||||
"""
|
||||
Demonstrate synchronous Memory class operations.
|
||||
|
||||
This function performs sequential memory operations including:
|
||||
- Adding conversation messages with metadata
|
||||
- Storing individual user preferences
|
||||
- Searching memories using natural language queries
|
||||
- Retrieving all memories for a user
|
||||
- Cleaning up memories after demonstration
|
||||
|
||||
Args:
|
||||
local_config: Configuration dict for Memory initialization
|
||||
sample_messages: List of conversation messages to store
|
||||
sample_preferences: List of user preferences to store
|
||||
user_id: Unique identifier for the user
|
||||
|
||||
Performance note: Sequential operations take longer as each operation
|
||||
must complete before the next one begins.
|
||||
"""
|
||||
|
||||
tracer = agentops.start_trace("Mem0 Memory Example", tags=["mem0_memory_example"])
|
||||
try:
|
||||
# Initialize sync Memory with local configuration
|
||||
memory = Memory.from_config(local_config)
|
||||
|
||||
# Add conversation messages with metadata for categorization
|
||||
result = memory.add(
|
||||
sample_messages, user_id=user_id, metadata={"category": "movie_preferences", "session": "demo"}
|
||||
)
|
||||
|
||||
# Add individual preferences sequentially
|
||||
for i, preference in enumerate(sample_preferences):
|
||||
result = memory.add(preference, user_id=user_id, metadata={"type": "preference", "index": i})
|
||||
|
||||
# 2. SEARCH operations - demonstrate natural language search capabilities
|
||||
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["results"][:2]): # Show top 2
|
||||
print(f"Result {j + 1}: {result.get('memory', 'N/A')}")
|
||||
else:
|
||||
print("No results found")
|
||||
|
||||
# 3. GET_ALL operations - retrieve all memories for the user
|
||||
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'])}")
|
||||
|
||||
# Cleanup - remove all memories for the user
|
||||
delete_all_result = memory.delete_all(user_id=user_id)
|
||||
print(f"Delete all result: {delete_all_result}")
|
||||
|
||||
agentops.end_trace(tracer, end_state="Success")
|
||||
except Exception as e:
|
||||
agentops.end_trace(tracer, end_state="Error")
|
||||
raise e
|
||||
|
||||
|
||||
async def demonstrate_async_memory(local_config, sample_messages, sample_preferences, user_id):
|
||||
"""
|
||||
Demonstrate asynchronous Memory class operations with concurrent execution.
|
||||
|
||||
This function performs concurrent memory operations including:
|
||||
- Adding conversation messages asynchronously
|
||||
- Storing multiple preferences concurrently using asyncio.gather()
|
||||
- Performing parallel search operations
|
||||
- Retrieving all memories asynchronously
|
||||
- Cleaning up memories after demonstration
|
||||
|
||||
Args:
|
||||
local_config: Configuration dict for AsyncMemory initialization
|
||||
sample_messages: List of conversation messages to store
|
||||
sample_preferences: List of user preferences to store
|
||||
user_id: Unique identifier for the user
|
||||
|
||||
Performance benefit: Concurrent operations significantly reduce total execution time
|
||||
by running multiple memory operations in parallel.
|
||||
"""
|
||||
|
||||
tracer = agentops.start_trace("Mem0 Memory Async Example", tags=["mem0", "async", "memory-management"])
|
||||
try:
|
||||
# Initialize async Memory with configuration
|
||||
async_memory = await AsyncMemory.from_config(local_config)
|
||||
|
||||
# 1. ADD operation - store conversation with async context
|
||||
# Add conversation messages
|
||||
result = await async_memory.add(
|
||||
sample_messages, user_id=user_id, metadata={"category": "async_movie_preferences", "session": "async_demo"}
|
||||
)
|
||||
|
||||
# Add preferences concurrently using asyncio.gather()
|
||||
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}
|
||||
)
|
||||
|
||||
# Create tasks for concurrent execution
|
||||
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}")
|
||||
|
||||
# 2. SEARCH operations - perform multiple searches concurrently
|
||||
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
|
||||
|
||||
# Execute all searches concurrently
|
||||
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"][:2]):
|
||||
print(f"Result {j + 1}: {res.get('memory', 'N/A')}")
|
||||
else:
|
||||
print("No results found")
|
||||
|
||||
# 3. GET_ALL operations - retrieve all memories asynchronously
|
||||
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'])}")
|
||||
|
||||
# Cleanup - remove all memories asynchronously
|
||||
delete_all_result = await async_memory.delete_all(user_id=user_id)
|
||||
print(f"Delete all result: {delete_all_result}")
|
||||
|
||||
agentops.end_trace(tracer, end_state="Success")
|
||||
|
||||
except Exception as e:
|
||||
agentops.end_trace(tracer, end_state="Error")
|
||||
raise e
|
||||
|
||||
|
||||
# Initialize AgentOps
|
||||
agentops.init(trace_name="Mem0 Memory Example", tags=["mem0", "memory-management", "agentops-example"])
|
||||
|
||||
# Configuration for local memory (Memory)
|
||||
# This configuration specifies the LLM provider and model settings
|
||||
local_config = {
|
||||
"llm": {
|
||||
"provider": "openai",
|
||||
"config": {
|
||||
"model": "gpt-4o-mini",
|
||||
"temperature": 0.1,
|
||||
"max_tokens": 2000,
|
||||
"api_key": os.getenv("OPENAI_API_KEY"),
|
||||
},
|
||||
}
|
||||
}
|
||||
# Sample user data
|
||||
user_id = "alice_demo"
|
||||
agent_id = "assistant_demo"
|
||||
run_id = "session_001"
|
||||
|
||||
# Sample conversation data demonstrating movie preference discovery
|
||||
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 user preferences covering various aspects of daily life
|
||||
sample_preferences = [
|
||||
"I prefer dark roast coffee over light roast",
|
||||
"I exercise every morning at 6 AM",
|
||||
]
|
||||
|
||||
|
||||
# Execute both sync and async demonstrations
|
||||
demonstrate_sync_memory(local_config, sample_messages, sample_preferences, user_id)
|
||||
asyncio.run(demonstrate_async_memory(local_config, sample_messages, sample_preferences, user_id))
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
# Note: Using trace_id since we ran multiple traces
|
||||
# In a real application, you would store each tracer and validate individually
|
||||
result = agentops.validate_trace_spans(check_llm=False) # Don't check for LLM spans as this uses memory operations
|
||||
agentops.print_validation_summary(result)
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
@@ -0,0 +1,335 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "ecd1d2ee",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"\n",
|
||||
"# Cloud Memory Operations with Mem0 MemoryClient\n",
|
||||
"\n",
|
||||
"This example demonstrates how to use Mem0's cloud-based MemoryClient for managing conversational memory and user preferences with both synchronous and asynchronous operations.\n",
|
||||
"\n",
|
||||
"## Overview\n",
|
||||
"\n",
|
||||
"This example showcases cloud-based memory management operations where we:\n",
|
||||
"\n",
|
||||
"1. **Initialize MemoryClient instances** for both sync and async cloud operations\n",
|
||||
"2. **Store conversation history** in the cloud with rich metadata\n",
|
||||
"3. **Perform concurrent operations** using async/await patterns\n",
|
||||
"4. **Search and filter memories** using natural language and structured queries\n",
|
||||
"\n",
|
||||
"By using the cloud-based MemoryClient with async operations, you can leverage Mem0's managed infrastructure while performing multiple memory operations simultaneously. This is ideal for production applications that need scalable memory management without managing local storage.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "a63847c4",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Setup and Imports\n",
|
||||
"\n",
|
||||
"First, we'll import the necessary libraries for working with Mem0's cloud-based memory management system. We'll use both synchronous and asynchronous clients to demonstrate different usage patterns.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "f98af04f",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Install the required dependencies:\n",
|
||||
"%pip install agentops\n",
|
||||
"%pip install mem0ai\n",
|
||||
"%pip install python-dotenv"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "69b834f6",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Install the required dependencies:\n",
|
||||
"%pip install agentops\n",
|
||||
"%pip install mem0ai\n",
|
||||
"%pip install python-dotenv"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "e552e158",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from mem0 import MemoryClient, AsyncMemoryClient\n",
|
||||
"import agentops\n",
|
||||
"import os\n",
|
||||
"import asyncio\n",
|
||||
"from dotenv import load_dotenv"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "a70fadde",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Environment Configuration\n",
|
||||
"\n",
|
||||
"Load environment variables including API keys for AgentOps, Mem0, and OpenAI. These credentials are required for authenticating with the respective services.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "969f7c42",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Load environment variables\n",
|
||||
"load_dotenv()\n",
|
||||
"os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\")\n",
|
||||
"mem0_api_key = os.getenv(\"MEM0_API_KEY\")\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "3f630d40",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Sample Data Setup\n",
|
||||
"\n",
|
||||
"Define user identifiers and sample data that will be used throughout the demonstration. This includes user IDs for tracking memory ownership and agent/session identifiers for context.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "0abf3fe7",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Sample user data for demonstration\n",
|
||||
"user_id = \"alice_demo\"\n",
|
||||
"agent_id = \"assistant_demo\"\n",
|
||||
"run_id = \"session_001\"\n",
|
||||
"\n",
|
||||
"# Sample conversation data demonstrating preference discovery through dialogue\n",
|
||||
"sample_messages = [\n",
|
||||
" {\"role\": \"user\", \"content\": \"I'm planning to watch a movie tonight. Any recommendations?\"},\n",
|
||||
" {\"role\": \"assistant\", \"content\": \"How about a thriller? They can be quite engaging.\"},\n",
|
||||
" {\"role\": \"user\", \"content\": \"I'm not a big fan of thriller movies but I love sci-fi movies.\"},\n",
|
||||
" {\n",
|
||||
" \"role\": \"assistant\",\n",
|
||||
" \"content\": \"Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future.\",\n",
|
||||
" },\n",
|
||||
"]\n",
|
||||
"\n",
|
||||
"# Sample user preferences representing various personal attributes\n",
|
||||
"sample_preferences = [\n",
|
||||
" \"I prefer dark roast coffee over light roast\",\n",
|
||||
" \"I exercise every morning at 6 AM\",\n",
|
||||
" \"I'm vegetarian and avoid all meat products\",\n",
|
||||
" \"I love reading science fiction novels\",\n",
|
||||
" \"I work in software engineering\",\n",
|
||||
"]"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "046d2588",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Synchronous Memory Operations\n",
|
||||
"\n",
|
||||
"The following function demonstrates how to use the synchronous MemoryClient for sequential cloud memory operations. This approach is straightforward but operations execute one after another.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "63d2f851",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def demonstrate_sync_memory_client(sample_messages, sample_preferences, user_id):\n",
|
||||
" \"\"\"\n",
|
||||
" Demonstrate synchronous MemoryClient operations with cloud storage.\n",
|
||||
"\n",
|
||||
" This function performs sequential cloud memory operations including:\n",
|
||||
" - Initializing cloud-based memory client with API authentication\n",
|
||||
" - Adding conversation messages to cloud storage\n",
|
||||
" - Storing user preferences with metadata\n",
|
||||
" - Searching memories using natural language\n",
|
||||
" - Retrieving memories with filters\n",
|
||||
" - Cleaning up cloud memories\n",
|
||||
"\n",
|
||||
" \"\"\"\n",
|
||||
" agentops.start_trace(\"mem0_memoryclient_sync_example\", tags=[\"mem0_memoryclient_example\"])\n",
|
||||
" try:\n",
|
||||
" # Initialize sync MemoryClient with API key for cloud access\n",
|
||||
" client = MemoryClient(api_key=mem0_api_key)\n",
|
||||
"\n",
|
||||
" # Add conversation to cloud storage with metadata\n",
|
||||
" result = client.add(\n",
|
||||
" sample_messages,\n",
|
||||
" user_id=user_id,\n",
|
||||
" metadata={\"category\": \"cloud_movie_preferences\", \"session\": \"cloud_demo\"},\n",
|
||||
" version=\"v2\",\n",
|
||||
" )\n",
|
||||
" print(f\"Add result: {result}\")\n",
|
||||
"\n",
|
||||
" # Add preferences sequentially to cloud\n",
|
||||
" for i, preference in enumerate(sample_preferences[:3]): # Limit for demo\n",
|
||||
" # Convert string preference to message format\n",
|
||||
" preference_message = [{\"role\": \"user\", \"content\": preference}]\n",
|
||||
" result = client.add(preference_message, user_id=user_id, metadata={\"type\": \"cloud_preference\", \"index\": i})\n",
|
||||
"\n",
|
||||
" # 2. SEARCH operations - leverage cloud search capabilities\n",
|
||||
" search_result = client.search(\"What are the user's movie preferences?\", user_id=user_id)\n",
|
||||
" print(f\"Search result: {search_result}\")\n",
|
||||
"\n",
|
||||
" # 3. GET_ALL - retrieve all memories for the user\n",
|
||||
" all_memories = client.get_all(user_id=user_id, limit=10)\n",
|
||||
" print(f\"Cloud memories retrieved: {all_memories}\")\n",
|
||||
"\n",
|
||||
" # Cleanup - remove all user memories from cloud\n",
|
||||
" delete_all_result = client.delete_all(user_id=user_id)\n",
|
||||
" print(f\"Delete all result: {delete_all_result}\")\n",
|
||||
" agentops.end_trace(end_state=\"success\")\n",
|
||||
" except Exception:\n",
|
||||
" agentops.end_trace(end_state=\"error\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "6e629329",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Asynchronous Memory Operations\n",
|
||||
"\n",
|
||||
"This function showcases the power of asynchronous operations with Mem0's AsyncMemoryClient. By using async/await patterns, we can execute multiple memory operations concurrently, significantly improving performance.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "2462a05f",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"async def demonstrate_async_memory_client(sample_messages, sample_preferences, user_id):\n",
|
||||
" \"\"\"\n",
|
||||
" Demonstrate asynchronous MemoryClient operations with concurrent cloud access.\n",
|
||||
"\n",
|
||||
" This function performs concurrent cloud memory operations including:\n",
|
||||
" - Initializing async cloud-based memory client\n",
|
||||
" - Adding multiple memories concurrently using asyncio.gather()\n",
|
||||
" - Performing parallel search operations across cloud storage\n",
|
||||
" - Retrieving filtered memories asynchronously\n",
|
||||
" - Cleaning up cloud memories efficiently\n",
|
||||
"\n",
|
||||
" \"\"\"\n",
|
||||
" agentops.start_trace(\"mem0_memoryclient_async_example\", tags=[\"mem0_memoryclient_example\"])\n",
|
||||
" try:\n",
|
||||
" # Initialize async MemoryClient for concurrent cloud operations\n",
|
||||
" async_client = AsyncMemoryClient(api_key=mem0_api_key)\n",
|
||||
"\n",
|
||||
" # Add conversation and preferences concurrently to cloud\n",
|
||||
" add_conversation_task = async_client.add(\n",
|
||||
" sample_messages, user_id=user_id, metadata={\"category\": \"async_cloud_movies\", \"session\": \"async_cloud_demo\"}\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" # Create tasks for adding preferences in parallel\n",
|
||||
" add_preference_tasks = [\n",
|
||||
" async_client.add(\n",
|
||||
" [{\"role\": \"user\", \"content\": pref}],\n",
|
||||
" user_id=user_id,\n",
|
||||
" metadata={\"type\": \"async_cloud_preference\", \"index\": i},\n",
|
||||
" )\n",
|
||||
" for i, pref in enumerate(sample_preferences[:3])\n",
|
||||
" ]\n",
|
||||
"\n",
|
||||
" # Execute all add operations concurrently\n",
|
||||
" results = await asyncio.gather(add_conversation_task, *add_preference_tasks)\n",
|
||||
" for i, result in enumerate(results):\n",
|
||||
" print(f\"{i + 1}. {result}\")\n",
|
||||
"\n",
|
||||
" # 2. Concurrent SEARCH operations - multiple cloud searches in parallel\n",
|
||||
" search_tasks = [\n",
|
||||
" async_client.search(\"movie preferences\", user_id=user_id),\n",
|
||||
" async_client.search(\"food preferences\", user_id=user_id),\n",
|
||||
" async_client.search(\"work information\", user_id=user_id),\n",
|
||||
" ]\n",
|
||||
"\n",
|
||||
" # Execute all searches concurrently\n",
|
||||
" search_results = await asyncio.gather(*search_tasks)\n",
|
||||
" for i, result in enumerate(search_results):\n",
|
||||
" print(f\"Search {i + 1} result: {result}\")\n",
|
||||
"\n",
|
||||
" # 3. GET_ALL operation - retrieve all memories from cloud\n",
|
||||
" all_memories = await async_client.get_all(user_id=user_id, limit=10)\n",
|
||||
" print(f\"Async cloud memories: {all_memories}\")\n",
|
||||
"\n",
|
||||
" # Final cleanup - remove all memories asynchronously\n",
|
||||
" delete_all_result = await async_client.delete_all(user_id=user_id)\n",
|
||||
" print(f\"Delete all result: {delete_all_result}\")\n",
|
||||
"\n",
|
||||
" agentops.end_trace(end_state=\"success\")\n",
|
||||
"\n",
|
||||
" except Exception:\n",
|
||||
" agentops.end_trace(end_state=\"error\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "c5e1af75",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Execute Demonstrations\n",
|
||||
"\n",
|
||||
"Run both synchronous and asynchronous demonstrations to compare their behavior and performance. The async version typically completes faster due to concurrent operations, especially when dealing with multiple API calls.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "3a6524b2",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Execute both sync and async demonstrations\n",
|
||||
"demonstrate_sync_memory_client(sample_messages, sample_preferences, user_id)\n",
|
||||
"await demonstrate_async_memory_client(sample_messages, sample_preferences, user_id)"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"jupytext": {
|
||||
"cell_metadata_filter": "-all",
|
||||
"main_language": "python",
|
||||
"notebook_metadata_filter": "-all"
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "venv",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.9"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
"""
|
||||
# Cloud Memory Operations with Mem0 MemoryClient
|
||||
|
||||
This example demonstrates how to use Mem0's cloud-based MemoryClient for managing conversational memory and user preferences with both synchronous and asynchronous operations.
|
||||
|
||||
## Overview
|
||||
|
||||
This example showcases cloud-based memory management operations where we:
|
||||
|
||||
1. **Initialize MemoryClient instances** for both sync and async cloud operations
|
||||
2. **Store conversation history** in the cloud with rich metadata
|
||||
3. **Perform concurrent operations** using async/await patterns
|
||||
4. **Search and filter memories** using natural language and structured queries
|
||||
|
||||
By using the cloud-based MemoryClient with async operations, you can leverage Mem0's managed infrastructure while performing multiple memory operations simultaneously. This is ideal for production applications that need scalable memory management without managing local storage.
|
||||
"""
|
||||
|
||||
import os
|
||||
import asyncio
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables first
|
||||
load_dotenv()
|
||||
|
||||
# Set environment variables before importing
|
||||
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY")
|
||||
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
|
||||
mem0_api_key = os.getenv("MEM0_API_KEY")
|
||||
|
||||
# Import agentops BEFORE mem0 to ensure proper instrumentation
|
||||
import agentops # noqa E402
|
||||
|
||||
# Now import mem0 - it will be instrumented by agentops
|
||||
from mem0 import MemoryClient, AsyncMemoryClient # noqa E402
|
||||
|
||||
|
||||
def demonstrate_sync_memory_client(sample_messages, sample_preferences, user_id):
|
||||
"""
|
||||
Demonstrate synchronous MemoryClient operations with cloud storage.
|
||||
|
||||
This function performs sequential cloud memory operations including:
|
||||
- Initializing cloud-based memory client with API authentication
|
||||
- Adding conversation messages to cloud storage
|
||||
- Storing user preferences with metadata
|
||||
- Searching memories using natural language
|
||||
- Retrieving memories with filters
|
||||
- Cleaning up cloud memories
|
||||
|
||||
Args:
|
||||
sample_messages: List of conversation messages to store
|
||||
sample_preferences: List of user preferences to store
|
||||
user_id: Unique identifier for the user
|
||||
|
||||
Cloud benefit: All memory operations are handled by Mem0's infrastructure,
|
||||
providing scalability and persistence without local storage management.
|
||||
"""
|
||||
agentops.start_trace("Mem0 MemoryClient Example", tags=["mem0_memoryclient_example"])
|
||||
try:
|
||||
# Initialize sync MemoryClient with API key for cloud access
|
||||
client = MemoryClient(api_key=mem0_api_key)
|
||||
|
||||
# Add conversation to cloud storage with metadata
|
||||
result = client.add(
|
||||
sample_messages, user_id=user_id, metadata={"category": "cloud_movie_preferences", "session": "cloud_demo"}
|
||||
)
|
||||
print(f"Add result: {result}")
|
||||
|
||||
# Add preferences sequentially to cloud
|
||||
for i, preference in enumerate(sample_preferences[:3]): # Limit for demo
|
||||
result = client.add(preference, user_id=user_id, metadata={"type": "cloud_preference", "index": i})
|
||||
|
||||
# 2. SEARCH operations - leverage cloud search capabilities
|
||||
search_result = client.search("What are the user's movie preferences?", user_id=user_id)
|
||||
print(f"Search result: {search_result}")
|
||||
|
||||
# 3. GET_ALL with filters - demonstrate structured query capabilities
|
||||
filters = {"AND": [{"user_id": user_id}]}
|
||||
all_memories = client.get_all(filters=filters, limit=10)
|
||||
print(f"Cloud memories retrieved: {all_memories}")
|
||||
|
||||
# Cleanup - remove all user memories from cloud
|
||||
delete_all_result = client.delete_all(user_id=user_id)
|
||||
print(f"Delete all result: {delete_all_result}")
|
||||
agentops.end_trace(end_state="success")
|
||||
except Exception:
|
||||
agentops.end_trace(end_state="error")
|
||||
|
||||
|
||||
async def demonstrate_async_memory_client(sample_messages, sample_preferences, user_id):
|
||||
"""
|
||||
Demonstrate asynchronous MemoryClient operations with concurrent cloud access.
|
||||
|
||||
This function performs concurrent cloud memory operations including:
|
||||
- Initializing async cloud-based memory client
|
||||
- Adding multiple memories concurrently using asyncio.gather()
|
||||
- Performing parallel search operations across cloud storage
|
||||
- Retrieving filtered memories asynchronously
|
||||
- Cleaning up cloud memories efficiently
|
||||
|
||||
Args:
|
||||
sample_messages: List of conversation messages to store
|
||||
sample_preferences: List of user preferences to store
|
||||
user_id: Unique identifier for the user
|
||||
|
||||
Performance benefit: Async operations allow multiple cloud API calls to execute
|
||||
concurrently, significantly reducing total execution time compared to sequential calls.
|
||||
This is especially beneficial when dealing with network I/O to cloud services.
|
||||
"""
|
||||
agentops.start_trace("Mem0 MemoryClient Async Example", tags=["mem0_memoryclient_example"])
|
||||
try:
|
||||
# Initialize async MemoryClient for concurrent cloud operations
|
||||
async_client = AsyncMemoryClient(api_key=mem0_api_key)
|
||||
|
||||
# Add conversation and preferences concurrently to cloud
|
||||
add_conversation_task = async_client.add(
|
||||
sample_messages, user_id=user_id, metadata={"category": "async_cloud_movies", "session": "async_cloud_demo"}
|
||||
)
|
||||
|
||||
# Create tasks for adding preferences in parallel
|
||||
add_preference_tasks = [
|
||||
async_client.add(pref, user_id=user_id, metadata={"type": "async_cloud_preference", "index": i})
|
||||
for i, pref in enumerate(sample_preferences[:3])
|
||||
]
|
||||
|
||||
# Execute all add operations concurrently
|
||||
results = await asyncio.gather(add_conversation_task, *add_preference_tasks)
|
||||
for i, result in enumerate(results):
|
||||
print(f"{i + 1}. {result}")
|
||||
|
||||
# 2. Concurrent SEARCH operations - multiple cloud searches in parallel
|
||||
search_tasks = [
|
||||
async_client.search("movie preferences", user_id=user_id),
|
||||
async_client.search("food preferences", user_id=user_id),
|
||||
async_client.search("work information", user_id=user_id),
|
||||
]
|
||||
|
||||
# Execute all searches concurrently
|
||||
search_results = await asyncio.gather(*search_tasks)
|
||||
for i, result in enumerate(search_results):
|
||||
print(f"Search {i + 1} result: {result}")
|
||||
|
||||
# 3. GET_ALL operation - retrieve filtered memories from cloud
|
||||
filters = {"AND": [{"user_id": user_id}]}
|
||||
all_memories = await async_client.get_all(filters=filters, limit=10)
|
||||
print(f"Async cloud memories: {all_memories}")
|
||||
|
||||
# Final cleanup - remove all memories asynchronously
|
||||
delete_all_result = await async_client.delete_all(user_id=user_id)
|
||||
print(f"Delete all result: {delete_all_result}")
|
||||
|
||||
agentops.end_trace(end_state="success")
|
||||
|
||||
except Exception:
|
||||
agentops.end_trace(end_state="error")
|
||||
|
||||
|
||||
# Sample user data for demonstration
|
||||
user_id = "alice_demo"
|
||||
agent_id = "assistant_demo"
|
||||
run_id = "session_001"
|
||||
|
||||
# Sample conversation data demonstrating preference discovery through dialogue
|
||||
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 user preferences representing various personal attributes
|
||||
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",
|
||||
]
|
||||
|
||||
# Execute both sync and async demonstrations
|
||||
# Note: The async version typically completes faster due to concurrent operations
|
||||
demonstrate_sync_memory_client(sample_messages, sample_preferences, user_id)
|
||||
asyncio.run(demonstrate_async_memory_client(sample_messages, sample_preferences, user_id))
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
agentops.validate_trace_spans(trace_context=None)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
@@ -0,0 +1 @@
|
||||
mem0ai
|
||||
@@ -0,0 +1,56 @@
|
||||
# OpenAI Examples with AgentOps
|
||||
|
||||
This directory contains examples of using the OpenAI API with AgentOps instrumentation.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Python >= 3.10 < 3.13
|
||||
- Install required dependencies:
|
||||
```
|
||||
pip install agentops openai
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### 1. Multi-Tool Orchestration
|
||||
|
||||
Example: `multi_tool_orchestration`
|
||||
This example demonstrates:
|
||||
- Complex tool orchestration
|
||||
|
||||
### 2. Asynchronous OpenAI API calls
|
||||
|
||||
Example: `openai_example_async`
|
||||
|
||||
This example demonstrates:
|
||||
- Asynchronous OpenAI API calls
|
||||
|
||||
### 3. Synchronous OpenAI API calls
|
||||
|
||||
Example: `openai_example_sync`
|
||||
|
||||
This example demonstrates:
|
||||
- Synchronous OpenAI API calls
|
||||
|
||||
### 4. Web Search
|
||||
|
||||
Example: `web_search`
|
||||
|
||||
This example demonstrates:
|
||||
- Web search functionality
|
||||
|
||||
### 5. o3 Responses API
|
||||
|
||||
Example: `o3_responses_example`
|
||||
|
||||
This example demonstrates:
|
||||
- OpenAI's o3 reasoning model with the Responses API
|
||||
- Tool calls and structured reasoning
|
||||
- Complex decision-making scenarios
|
||||
- AgentOps integration with reasoning models
|
||||
|
||||
## AgentOps Integration
|
||||
|
||||
These examples show how to use AgentOps to monitor and analyze your AI applications. AgentOps automatically instruments your OpenAI calls to provide insights into performance, usage patterns, and model behavior.
|
||||
|
||||
To learn more about AgentOps, visit [https://www.agentops.ai](https://www.agentops.ai)
|
||||
@@ -0,0 +1,584 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Multi-Tool Orchestration with RAG approach using OpenAI's Responses API"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"\n",
|
||||
"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."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Install required dependencies\n",
|
||||
"%pip install agentops\n",
|
||||
"%pip install openai\n",
|
||||
"%pip install datasets\n",
|
||||
"%pip install tqdm \n",
|
||||
"%pip install pandas\n",
|
||||
"%pip install pinecone\n",
|
||||
"%pip install python-dotenv"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"from dotenv import load_dotenv\n",
|
||||
"import time\n",
|
||||
"from tqdm.auto import tqdm\n",
|
||||
"from pandas import DataFrame\n",
|
||||
"from datasets import load_dataset\n",
|
||||
"import random\n",
|
||||
"import string\n",
|
||||
"from openai import OpenAI\n",
|
||||
"import agentops\n",
|
||||
"from pinecone import Pinecone\n",
|
||||
"from pinecone import ServerlessSpec"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"load_dotenv()\n",
|
||||
"\n",
|
||||
"os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\", \"your_api_key_here\")\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\", \"your_openai_api_key_here\")\n",
|
||||
"os.environ[\"PINECONE_API_KEY\"] = os.getenv(\"PINECONE_API_KEY\", \"your_pinecone_api_key_here\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"agentops.init(auto_start_session=True)\n",
|
||||
"tracer = agentops.start_trace(\n",
|
||||
" trace_name=\"Multi-Tool Orchestration with RAG\",\n",
|
||||
" tags=[\"multi-tool-orchestration-rag-demo\", \"openai-responses\", \"agentops-example\"],\n",
|
||||
")\n",
|
||||
"client = OpenAI()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"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."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Load the dataset (ensure you're logged in with huggingface-cli if needed)\n",
|
||||
"ds = load_dataset(\"FreedomIntelligence/medical-o1-reasoning-SFT\", \"en\", split=\"train[:100]\", trust_remote_code=True)\n",
|
||||
"ds_dataframe = DataFrame(ds)\n",
|
||||
"\n",
|
||||
"# Merge the Question and Response columns into a single string.\n",
|
||||
"ds_dataframe[\"merged\"] = ds_dataframe.apply(\n",
|
||||
" lambda row: f\"Question: {row['Question']} Answer: {row['Response']}\", axis=1\n",
|
||||
")\n",
|
||||
"print(\"Example merged text:\", ds_dataframe[\"merged\"].iloc[0])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"ds_dataframe"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Create a Pinecone Index Based on the Dataset\n",
|
||||
"Use the dataset itself to determine the embedding dimensionality. For example, compute one embedding from the merged column and then create the index accordingly."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"MODEL = \"text-embedding-3-small\" # Replace with your production embedding model if needed\n",
|
||||
"# Compute an embedding for the first document to obtain the embedding dimension.\n",
|
||||
"sample_embedding_resp = client.embeddings.create(input=[ds_dataframe[\"merged\"].iloc[0]], model=MODEL)\n",
|
||||
"embed_dim = len(sample_embedding_resp.data[0].embedding)\n",
|
||||
"print(f\"Embedding dimension: {embed_dim}\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Initialize Pinecone using your API key.\n",
|
||||
"pc = Pinecone(api_key=os.environ[\"PINECONE_API_KEY\"])\n",
|
||||
"\n",
|
||||
"# Define the Pinecone serverless specification.\n",
|
||||
"AWS_REGION = \"us-east-1\"\n",
|
||||
"spec = ServerlessSpec(cloud=\"aws\", region=AWS_REGION)\n",
|
||||
"\n",
|
||||
"# Create a random index name with lower case alphanumeric characters and '-'\n",
|
||||
"index_name = \"pinecone-index-\" + \"\".join(random.choices(string.ascii_lowercase + string.digits, k=10))\n",
|
||||
"\n",
|
||||
"# Create the index if it doesn't already exist.\n",
|
||||
"if index_name not in pc.list_indexes().names():\n",
|
||||
" pc.create_index(index_name, dimension=embed_dim, metric=\"dotproduct\", spec=spec)\n",
|
||||
"\n",
|
||||
"# Connect to the index.\n",
|
||||
"index = pc.Index(index_name)\n",
|
||||
"time.sleep(1)\n",
|
||||
"print(\"Index stats:\", index.describe_index_stats())"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"#### Upsert the Dataset into Pinecone index\n",
|
||||
"\n",
|
||||
"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."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"batch_size = 32\n",
|
||||
"for i in tqdm(range(0, len(ds_dataframe[\"merged\"]), batch_size), desc=\"Upserting to Pinecone\"):\n",
|
||||
" i_end = min(i + batch_size, len(ds_dataframe[\"merged\"]))\n",
|
||||
" lines_batch = ds_dataframe[\"merged\"][i:i_end]\n",
|
||||
" ids_batch = [str(n) for n in range(i, i_end)]\n",
|
||||
"\n",
|
||||
" # Create embeddings for the current batch.\n",
|
||||
" res = client.embeddings.create(input=[line for line in lines_batch], model=MODEL)\n",
|
||||
" embeds = [record.embedding for record in res.data]\n",
|
||||
"\n",
|
||||
" # Prepare metadata by extracting original Question and Answer.\n",
|
||||
" meta = []\n",
|
||||
" for record in ds_dataframe.iloc[i:i_end].to_dict(\"records\"):\n",
|
||||
" q_text = record[\"Question\"]\n",
|
||||
" a_text = record[\"Response\"]\n",
|
||||
" # Optionally update metadata for specific entries.\n",
|
||||
" meta.append({\"Question\": q_text, \"Answer\": a_text})\n",
|
||||
"\n",
|
||||
" # Upsert the batch into Pinecone.\n",
|
||||
" vectors = list(zip(ids_batch, embeds, meta))\n",
|
||||
" index.upsert(vectors=vectors)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Query the Pinecone Index\n",
|
||||
"\n",
|
||||
"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."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def query_pinecone_index(client, index, model, query_text):\n",
|
||||
" # Generate an embedding for the query.\n",
|
||||
" query_embedding = client.embeddings.create(input=query_text, model=model).data[0].embedding\n",
|
||||
"\n",
|
||||
" # Query the index and return top 5 matches.\n",
|
||||
" res = index.query(vector=[query_embedding], top_k=5, include_metadata=True)\n",
|
||||
" print(\"Query Results:\")\n",
|
||||
" for match in res[\"matches\"]:\n",
|
||||
" print(\n",
|
||||
" f\"{match['score']:.2f}: {match['metadata'].get('Question', 'N/A')} - {match['metadata'].get('Answer', 'N/A')}\"\n",
|
||||
" )\n",
|
||||
" return res"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Example usage with a different query from the train/test set\n",
|
||||
"query = (\n",
|
||||
" \"A 45-year-old man with a history of alcohol use presents with symptoms including confusion, ataxia, and ophthalmoplegia. \"\n",
|
||||
" \"What is the most likely diagnosis and the recommended treatment?\"\n",
|
||||
")\n",
|
||||
"query_pinecone_index(client, index, MODEL, query)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Generate a Response Using the Retrieved Context\n",
|
||||
"\n",
|
||||
"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."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Retrieve and concatenate top 3 match contexts.\n",
|
||||
"matches = index.query(\n",
|
||||
" vector=[client.embeddings.create(input=query, model=MODEL).data[0].embedding], top_k=3, include_metadata=True\n",
|
||||
")[\"matches\"]\n",
|
||||
"\n",
|
||||
"context = \"\\n\\n\".join(\n",
|
||||
" f\"Question: {m['metadata'].get('Question', '')}\\nAnswer: {m['metadata'].get('Answer', '')}\" for m in matches\n",
|
||||
")\n",
|
||||
"# Use the context to generate a final answer.\n",
|
||||
"response = client.responses.create(\n",
|
||||
" model=\"gpt-4o\",\n",
|
||||
" input=f\"Provide the answer based on the context: {context} and the question: {query} as per the internal knowledge base\",\n",
|
||||
")\n",
|
||||
"print(\"\\nFinal Answer:\")\n",
|
||||
"print(response.output_text)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Orchestrate Multi-Tool Calls\n",
|
||||
"\n",
|
||||
"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.\n",
|
||||
"\n",
|
||||
"*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.\n",
|
||||
"\n",
|
||||
"*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."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Tools definition: The list of tools includes:\n",
|
||||
"# - A web search preview tool.\n",
|
||||
"# - A Pinecone search tool for retrieving medical documents.\n",
|
||||
"\n",
|
||||
"# Define available tools.\n",
|
||||
"tools = [\n",
|
||||
" {\n",
|
||||
" \"type\": \"web_search_preview\",\n",
|
||||
" \"user_location\": {\"type\": \"approximate\", \"country\": \"US\", \"region\": \"California\", \"city\": \"SF\"},\n",
|
||||
" \"search_context_size\": \"medium\",\n",
|
||||
" },\n",
|
||||
" {\n",
|
||||
" \"type\": \"function\",\n",
|
||||
" \"name\": \"PineconeSearchDocuments\",\n",
|
||||
" \"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.\",\n",
|
||||
" \"parameters\": {\n",
|
||||
" \"type\": \"object\",\n",
|
||||
" \"properties\": {\n",
|
||||
" \"query\": {\"type\": \"string\", \"description\": \"The natural language query to search the vector database.\"},\n",
|
||||
" \"top_k\": {\"type\": \"integer\", \"description\": \"Number of top results to return.\", \"default\": 3},\n",
|
||||
" },\n",
|
||||
" \"required\": [\"query\"],\n",
|
||||
" \"additionalProperties\": False,\n",
|
||||
" },\n",
|
||||
" },\n",
|
||||
"]"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Example queries that the model should route appropriately.\n",
|
||||
"queries = [\n",
|
||||
" {\"query\": \"Who won the cricket world cup in 1983?\"},\n",
|
||||
" {\"query\": \"What is the most common cause of death in the United States according to the internet?\"},\n",
|
||||
" {\n",
|
||||
" \"query\": (\n",
|
||||
" \"A 7-year-old boy with sickle cell disease is experiencing knee and hip pain, \"\n",
|
||||
" \"has been admitted for pain crises in the past, and now walks with a limp. \"\n",
|
||||
" \"His exam shows a normal, cool hip with decreased range of motion and pain with ambulation. \"\n",
|
||||
" \"What is the most appropriate next step in management according to the internal knowledge base?\"\n",
|
||||
" )\n",
|
||||
" },\n",
|
||||
"]"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Process each query dynamically.\n",
|
||||
"for item in queries:\n",
|
||||
" input_messages = [{\"role\": \"user\", \"content\": item[\"query\"]}]\n",
|
||||
" print(\"\\n🌟--- Processing Query ---🌟\")\n",
|
||||
" print(f\"🔍 **User Query:** {item['query']}\")\n",
|
||||
"\n",
|
||||
" # Call the Responses API with tools enabled and allow parallel tool calls.\n",
|
||||
" response = client.responses.create(\n",
|
||||
" model=\"gpt-4o\",\n",
|
||||
" input=[\n",
|
||||
" {\n",
|
||||
" \"role\": \"system\",\n",
|
||||
" \"content\": \"When prompted with a question, select the right tool to use based on the question.\",\n",
|
||||
" },\n",
|
||||
" {\"role\": \"user\", \"content\": item[\"query\"]},\n",
|
||||
" ],\n",
|
||||
" tools=tools,\n",
|
||||
" parallel_tool_calls=True,\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" print(\"\\n✨ **Initial Response Output:**\")\n",
|
||||
" print(response.output)\n",
|
||||
"\n",
|
||||
" # Determine if a tool call is needed and process accordingly.\n",
|
||||
" if response.output:\n",
|
||||
" tool_call = response.output[0]\n",
|
||||
" if tool_call.type in [\"web_search_preview\", \"function_call\"]:\n",
|
||||
" tool_name = tool_call.name if tool_call.type == \"function_call\" else \"web_search_preview\"\n",
|
||||
" print(f\"\\n🔧 **Model triggered a tool call:** {tool_name}\")\n",
|
||||
"\n",
|
||||
" if tool_name == \"PineconeSearchDocuments\":\n",
|
||||
" print(\"🔍 **Invoking PineconeSearchDocuments tool...**\")\n",
|
||||
" res = query_pinecone_index(client, index, MODEL, item[\"query\"])\n",
|
||||
" if res[\"matches\"]:\n",
|
||||
" best_match = res[\"matches\"][0][\"metadata\"]\n",
|
||||
" result = f\"**Question:** {best_match.get('Question', 'N/A')}\\n**Answer:** {best_match.get('Answer', 'N/A')}\"\n",
|
||||
" else:\n",
|
||||
" result = \"**No matching documents found in the index.**\"\n",
|
||||
" print(\"✅ **PineconeSearchDocuments tool invoked successfully.**\")\n",
|
||||
" else:\n",
|
||||
" print(\"🔍 **Invoking simulated web search tool...**\")\n",
|
||||
" result = \"**Simulated web search result.**\"\n",
|
||||
" print(\"✅ **Simulated web search tool invoked successfully.**\")\n",
|
||||
"\n",
|
||||
" # Append the tool call and its output back into the conversation.\n",
|
||||
" input_messages.append(tool_call)\n",
|
||||
" input_messages.append({\"type\": \"function_call_output\", \"call_id\": tool_call.call_id, \"output\": str(result)})\n",
|
||||
"\n",
|
||||
" # Get the final answer incorporating the tool's result.\n",
|
||||
" final_response = client.responses.create(\n",
|
||||
" model=\"gpt-4o\", input=input_messages, tools=tools, parallel_tool_calls=True\n",
|
||||
" )\n",
|
||||
" print(\"\\n💡 **Final Answer:**\")\n",
|
||||
" print(final_response.output_text)\n",
|
||||
" else:\n",
|
||||
" # If no tool call is triggered, print the response directly.\n",
|
||||
" print(\"💡 **Final Answer:**\")\n",
|
||||
" print(response.output_text)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"As shown above, depending on the query, appropriate tool is invoked in order to determine the optimal response.\n",
|
||||
"\n",
|
||||
"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.\n",
|
||||
"\n",
|
||||
"Finally, the tool call and its output are appended to the conversation, and the final answer is generated by the Responses API."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Multi-tool orchestration flow\n",
|
||||
"\n",
|
||||
"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. "
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Process one query as an example to understand the tool calls and function calls as part of the response output\n",
|
||||
"item = \"What is the most common cause of death in the United States\"\n",
|
||||
"\n",
|
||||
"# Initialize input messages with the user's query.\n",
|
||||
"input_messages = [{\"role\": \"user\", \"content\": item}]\n",
|
||||
"print(\"\\n🌟--- Processing Query ---🌟\")\n",
|
||||
"print(f\"🔍 **User Query:** {item}\")\n",
|
||||
"\n",
|
||||
"# Call the Responses API with tools enabled and allow parallel tool calls.\n",
|
||||
"print(\"\\n🔧 **Calling Responses API with Tools Enabled**\")\n",
|
||||
"print(\"\\n🕵️♂️ **Step 1: Web Search Call**\")\n",
|
||||
"print(\" - Initiating web search to gather initial information.\")\n",
|
||||
"print(\"\\n📚 **Step 2: Pinecone Search Call**\")\n",
|
||||
"print(\" - Querying Pinecone to find relevant examples from the internal knowledge base.\")\n",
|
||||
"\n",
|
||||
"response = client.responses.create(\n",
|
||||
" model=\"gpt-4o\",\n",
|
||||
" input=[\n",
|
||||
" {\n",
|
||||
" \"role\": \"system\",\n",
|
||||
" \"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.\",\n",
|
||||
" },\n",
|
||||
" {\"role\": \"user\", \"content\": item},\n",
|
||||
" ],\n",
|
||||
" tools=tools,\n",
|
||||
" parallel_tool_calls=True,\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"# Print the initial response output.\n",
|
||||
"print(\"input_messages\", input_messages)\n",
|
||||
"\n",
|
||||
"print(\"\\n✨ **Initial Response Output:**\")\n",
|
||||
"print(response.output)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Understand the tool calls and function calls as part of the response output\n",
|
||||
"\n",
|
||||
"import pandas as pd\n",
|
||||
"\n",
|
||||
"# Create a list to store the tool call and function call details\n",
|
||||
"tool_calls = []\n",
|
||||
"\n",
|
||||
"# Iterate through the response output and collect the details\n",
|
||||
"for i in response.output:\n",
|
||||
" tool_calls.append(\n",
|
||||
" {\n",
|
||||
" \"Type\": i.type,\n",
|
||||
" \"Call ID\": i.call_id if hasattr(i, \"call_id\") else i.id if hasattr(i, \"id\") else \"N/A\",\n",
|
||||
" \"Output\": str(i.output) if hasattr(i, \"output\") else \"N/A\",\n",
|
||||
" \"Name\": i.name if hasattr(i, \"name\") else \"N/A\",\n",
|
||||
" }\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
"# Convert the list to a DataFrame for tabular display\n",
|
||||
"df_tool_calls = pd.DataFrame(tool_calls)\n",
|
||||
"\n",
|
||||
"# Display the DataFrame\n",
|
||||
"df_tool_calls"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"tool_call_1 = response.output[0]\n",
|
||||
"print(tool_call_1)\n",
|
||||
"print(tool_call_1.id)\n",
|
||||
"\n",
|
||||
"tool_call_2 = response.output[2]\n",
|
||||
"print(tool_call_2)\n",
|
||||
"print(tool_call_2.call_id)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# append the tool call and its output back into the conversation.\n",
|
||||
"input_messages.append(response.output[2])\n",
|
||||
"input_messages.append({\"type\": \"function_call_output\", \"call_id\": tool_call_2.call_id, \"output\": str(result)})\n",
|
||||
"print(input_messages)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Get the final answer incorporating the tool's result.\n",
|
||||
"print(\"\\n🔧 **Calling Responses API for Final Answer**\")\n",
|
||||
"\n",
|
||||
"response_2 = client.responses.create(\n",
|
||||
" model=\"gpt-4o\",\n",
|
||||
" input=input_messages,\n",
|
||||
")\n",
|
||||
"print(response_2)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# print the final answer\n",
|
||||
"print(response_2.output_text)\n",
|
||||
"agentops.end_trace(tracer, end_state=\"Success\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"\n",
|
||||
"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! "
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "agentops (3.11.11)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.11"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 2
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
# ### 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.
|
||||
# # Install required dependencies
|
||||
# %pip install agentops
|
||||
# %pip install openai
|
||||
# %pip install datasets
|
||||
# %pip install tqdm
|
||||
# %pip install pandas
|
||||
# %pip install pinecone
|
||||
# %pip install python-dotenv
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
import time
|
||||
from tqdm.auto import tqdm
|
||||
from pandas import DataFrame
|
||||
from datasets import load_dataset
|
||||
|
||||
# Note: random and string imports removed as we're using an existing index
|
||||
from openai import OpenAI
|
||||
import agentops
|
||||
from pinecone import Pinecone
|
||||
|
||||
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")
|
||||
|
||||
agentops.init(
|
||||
auto_start_session=False,
|
||||
trace_name="OpenAI Multi-Tool Orchestration",
|
||||
tags=["openai", "multi-tool", "agentops-example"],
|
||||
)
|
||||
tracer = agentops.start_trace(
|
||||
trace_name="OpenAI 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.
|
||||
# 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])
|
||||
|
||||
# ### Connect to Existing Pinecone Index
|
||||
# We'll connect to an existing Pinecone index instead of creating a new one. We still compute an embedding to ensure compatibility with the existing index dimensions.
|
||||
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.
|
||||
# This helps ensure compatibility with the existing index dimensions.
|
||||
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}")
|
||||
|
||||
# Initialize Pinecone using your API key.
|
||||
pc = Pinecone(api_key=os.environ["PINECONE_API_KEY"])
|
||||
|
||||
# Use the existing Pinecone index
|
||||
index_name = "pinecone-index-btimakzhfe"
|
||||
|
||||
# Connect to the existing index (no need to create it as it already exists)
|
||||
index = pc.Index(index_name)
|
||||
time.sleep(1)
|
||||
index_stats = index.describe_index_stats()
|
||||
print("Index stats:", index_stats)
|
||||
|
||||
# #### Check if the index already has data, and optionally upsert new data
|
||||
#
|
||||
# Check if the existing index already has sufficient data for our demo.
|
||||
# If it has data, we'll use it as-is. If not, we'll add some sample data.
|
||||
if index_stats.total_vector_count > 0:
|
||||
print(f"✅ Index already contains {index_stats.total_vector_count} vectors. Using existing data.")
|
||||
else:
|
||||
print("📝 Index is empty. Adding sample data from the medical dataset...")
|
||||
# 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.
|
||||
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)
|
||||
|
||||
print("✅ Data upserting completed.")
|
||||
|
||||
|
||||
# ### 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.
|
||||
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
|
||||
|
||||
|
||||
# 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.
|
||||
# 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.
|
||||
# # 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,
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
# # 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?"
|
||||
)
|
||||
},
|
||||
]
|
||||
|
||||
# # 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.
|
||||
# # 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)
|
||||
|
||||
# # 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
|
||||
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)
|
||||
|
||||
# # 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)
|
||||
|
||||
# # 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)
|
||||
|
||||
# # print the final answer
|
||||
print(response_2.output_text)
|
||||
agentops.end_trace(tracer, end_state="Success")
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
agentops.validate_trace_spans(trace_context=tracer)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
|
||||
|
||||
# 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!
|
||||
@@ -0,0 +1,450 @@
|
||||
# OpenAI o3 Responses API Example
|
||||
#
|
||||
# This example demonstrates AgentOps integration with OpenAI's o3 reasoning model
|
||||
# through the Responses API. The o3 model excels at complex problem solving and
|
||||
# multi-step reasoning with tool calls.
|
||||
#
|
||||
# This example tests both streaming and non-streaming modes, as well as async versions.
|
||||
|
||||
import openai
|
||||
import agentops
|
||||
import json
|
||||
import os
|
||||
import asyncio
|
||||
from dotenv import load_dotenv
|
||||
from agentops.sdk.decorators import agent
|
||||
from typing import List, Dict, Any
|
||||
|
||||
# Load environment variables
|
||||
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_api_key_here")
|
||||
|
||||
# Initialize AgentOps
|
||||
agentops.init(
|
||||
trace_name="o3-responses-example",
|
||||
tags=["o3", "responses-api"],
|
||||
auto_start_session=False,
|
||||
)
|
||||
tracer = agentops.start_trace(trace_name="o3 Responses API Example", tags=["o3", "responses-api"])
|
||||
|
||||
# Initialize OpenAI client
|
||||
client = openai.OpenAI()
|
||||
async_client = openai.AsyncOpenAI()
|
||||
|
||||
# ANSI escape codes for colors
|
||||
LIGHT_BLUE = "\033[94m"
|
||||
YELLOW = "\033[93m"
|
||||
GREEN = "\033[92m"
|
||||
RESET_COLOR = "\033[0m"
|
||||
|
||||
|
||||
def create_decision_prompt(scenario: str, available_actions: List[str]) -> str:
|
||||
"""Create a prompt for decision making."""
|
||||
return f"""
|
||||
You are a strategic decision-making agent. You need to analyze the current scenario and choose the best action from the available options.
|
||||
|
||||
Current Scenario:
|
||||
{scenario}
|
||||
|
||||
Available Actions:
|
||||
{chr(10).join(f"- {action}" for action in available_actions)}
|
||||
|
||||
Your goal is to make the best strategic decision based on the scenario. Consider:
|
||||
1. The immediate benefits of each action
|
||||
2. Potential long-term consequences
|
||||
3. Risk vs reward trade-offs
|
||||
4. Strategic positioning
|
||||
|
||||
Reason carefully about the best action to take and explain your reasoning.
|
||||
"""
|
||||
|
||||
|
||||
@agent
|
||||
class O3DecisionAgent:
|
||||
"""A decision-making agent that uses OpenAI's o3 model with the Responses API."""
|
||||
|
||||
def __init__(self, model: str = "o3-mini", color: str = LIGHT_BLUE):
|
||||
self.model = model
|
||||
self.color = color
|
||||
|
||||
def make_decision_sync(self, scenario: str, available_actions: List[str], stream: bool = False) -> Dict[str, Any]:
|
||||
"""
|
||||
Make a decision using the o3 model synchronously.
|
||||
|
||||
Args:
|
||||
scenario: Description of the current situation
|
||||
available_actions: List of possible actions to choose from
|
||||
stream: Whether to use streaming mode
|
||||
|
||||
Returns:
|
||||
Dictionary containing the chosen action and reasoning
|
||||
"""
|
||||
|
||||
# Define the tool for action selection
|
||||
tools = [
|
||||
{
|
||||
"type": "function",
|
||||
"name": "select_action",
|
||||
"description": "Select the best action from the available options.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {"type": "string", "description": "The selected action from the available options"},
|
||||
"reasoning": {
|
||||
"type": "string",
|
||||
"description": "Detailed reasoning for why this action was chosen",
|
||||
},
|
||||
},
|
||||
"required": ["action", "reasoning"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
# Create the prompt
|
||||
system_prompt = create_decision_prompt(scenario, available_actions)
|
||||
user_message = f"Select the best action from these options: {available_actions}. Provide your reasoning and make your choice."
|
||||
|
||||
mode_desc = "streaming" if stream else "non-streaming"
|
||||
print(f"{self.color}Making decision with o3 model ({mode_desc})...{RESET_COLOR}")
|
||||
print(f"{self.color}Scenario: {scenario}{RESET_COLOR}")
|
||||
print(f"{self.color}Available actions: {available_actions}{RESET_COLOR}")
|
||||
|
||||
# Make the API call using the Responses API
|
||||
if stream:
|
||||
response = client.responses.create(
|
||||
model=self.model,
|
||||
input=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_message}],
|
||||
tools=tools, # type: ignore
|
||||
tool_choice="required",
|
||||
stream=True,
|
||||
)
|
||||
|
||||
# Process streaming response
|
||||
tool_call = None
|
||||
|
||||
for event in response:
|
||||
if hasattr(event, "type"):
|
||||
if event.type == "response.output_text.delta":
|
||||
# Handle text deltas (if any)
|
||||
pass
|
||||
elif event.type == "response.function_call_arguments.delta":
|
||||
# Tool arguments are accumulated by the API
|
||||
pass
|
||||
elif event.type == "response.output_item.added":
|
||||
# New tool call started
|
||||
if hasattr(event, "output_item") and event.output_item.type == "function_call":
|
||||
pass # Tool call tracking handled elsewhere
|
||||
elif event.type == "response.completed":
|
||||
# Process final response
|
||||
if hasattr(event, "response") and hasattr(event.response, "output"):
|
||||
for output_item in event.response.output:
|
||||
if output_item.type == "function_call":
|
||||
tool_call = output_item
|
||||
break
|
||||
|
||||
if tool_call:
|
||||
args = json.loads(tool_call.arguments)
|
||||
chosen_action = args["action"]
|
||||
reasoning = args["reasoning"]
|
||||
|
||||
print(f"{self.color}Chosen action: {chosen_action}{RESET_COLOR}")
|
||||
print(f"{self.color}Tool reasoning: {reasoning}{RESET_COLOR}")
|
||||
|
||||
return {
|
||||
"action": chosen_action,
|
||||
"reasoning": reasoning,
|
||||
"available_actions": available_actions,
|
||||
"scenario": scenario,
|
||||
"mode": "sync_streaming",
|
||||
}
|
||||
else:
|
||||
response = client.responses.create(
|
||||
model=self.model,
|
||||
input=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_message}],
|
||||
tools=tools, # type: ignore
|
||||
tool_choice="required",
|
||||
)
|
||||
|
||||
# Process non-streaming response
|
||||
tool_call = None
|
||||
reasoning_text = ""
|
||||
|
||||
for output_item in response.output:
|
||||
if output_item.type == "function_call":
|
||||
tool_call = output_item
|
||||
elif output_item.type == "message" and hasattr(output_item, "content"):
|
||||
for content in output_item.content:
|
||||
if hasattr(content, "type"):
|
||||
if content.type == "text" and hasattr(content, "text"):
|
||||
reasoning_text += content.text
|
||||
print(f"{self.color}Reasoning: {content.text}{RESET_COLOR}")
|
||||
elif content.type == "refusal" and hasattr(content, "refusal"):
|
||||
print(f"{self.color}Refusal: {content.refusal}{RESET_COLOR}")
|
||||
|
||||
if tool_call:
|
||||
args = json.loads(tool_call.arguments)
|
||||
chosen_action = args["action"]
|
||||
reasoning = args["reasoning"]
|
||||
|
||||
print(f"{self.color}Chosen action: {chosen_action}{RESET_COLOR}")
|
||||
print(f"{self.color}Tool reasoning: {reasoning}{RESET_COLOR}")
|
||||
|
||||
return {
|
||||
"action": chosen_action,
|
||||
"reasoning": reasoning,
|
||||
"full_reasoning": reasoning_text,
|
||||
"available_actions": available_actions,
|
||||
"scenario": scenario,
|
||||
"mode": "sync_non_streaming",
|
||||
}
|
||||
|
||||
# Fallback
|
||||
print(f"{self.color}No tool call found, using fallback{RESET_COLOR}")
|
||||
return {
|
||||
"action": available_actions[0] if available_actions else "no_action",
|
||||
"reasoning": "Fallback: No tool call received",
|
||||
"available_actions": available_actions,
|
||||
"scenario": scenario,
|
||||
"mode": f"sync_{mode_desc}_fallback",
|
||||
}
|
||||
|
||||
async def make_decision_async(
|
||||
self, scenario: str, available_actions: List[str], stream: bool = False
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Make a decision using the o3 model asynchronously.
|
||||
|
||||
Args:
|
||||
scenario: Description of the current situation
|
||||
available_actions: List of possible actions to choose from
|
||||
stream: Whether to use streaming mode
|
||||
|
||||
Returns:
|
||||
Dictionary containing the chosen action and reasoning
|
||||
"""
|
||||
|
||||
# Define the tool for action selection
|
||||
tools = [
|
||||
{
|
||||
"type": "function",
|
||||
"name": "select_action",
|
||||
"description": "Select the best action from the available options.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {"type": "string", "description": "The selected action from the available options"},
|
||||
"reasoning": {
|
||||
"type": "string",
|
||||
"description": "Detailed reasoning for why this action was chosen",
|
||||
},
|
||||
},
|
||||
"required": ["action", "reasoning"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
# Create the prompt
|
||||
system_prompt = create_decision_prompt(scenario, available_actions)
|
||||
user_message = f"Select the best action from these options: {available_actions}. Provide your reasoning and make your choice."
|
||||
|
||||
mode_desc = "streaming" if stream else "non-streaming"
|
||||
print(f"{self.color}Making async decision with o3 model ({mode_desc})...{RESET_COLOR}")
|
||||
print(f"{self.color}Scenario: {scenario}{RESET_COLOR}")
|
||||
print(f"{self.color}Available actions: {available_actions}{RESET_COLOR}")
|
||||
|
||||
# Make the API call using the Responses API
|
||||
if stream:
|
||||
response = await async_client.responses.create(
|
||||
model=self.model,
|
||||
input=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_message}],
|
||||
tools=tools, # type: ignore
|
||||
tool_choice="required",
|
||||
stream=True,
|
||||
)
|
||||
|
||||
# Process streaming response
|
||||
tool_call = None
|
||||
|
||||
async for event in response:
|
||||
if hasattr(event, "type"):
|
||||
if event.type == "response.output_text.delta":
|
||||
# Handle text deltas (if any)
|
||||
pass
|
||||
elif event.type == "response.function_call_arguments.delta":
|
||||
# Tool arguments are accumulated by the API
|
||||
pass
|
||||
elif event.type == "response.output_item.added":
|
||||
# New tool call started
|
||||
if hasattr(event, "output_item") and event.output_item.type == "function_call":
|
||||
pass # Tool call tracking handled elsewhere
|
||||
elif event.type == "response.completed":
|
||||
# Process final response
|
||||
if hasattr(event, "response") and hasattr(event.response, "output"):
|
||||
for output_item in event.response.output:
|
||||
if output_item.type == "function_call":
|
||||
tool_call = output_item
|
||||
break
|
||||
|
||||
if tool_call:
|
||||
args = json.loads(tool_call.arguments)
|
||||
chosen_action = args["action"]
|
||||
reasoning = args["reasoning"]
|
||||
|
||||
print(f"{self.color}Chosen action: {chosen_action}{RESET_COLOR}")
|
||||
print(f"{self.color}Tool reasoning: {reasoning}{RESET_COLOR}")
|
||||
|
||||
return {
|
||||
"action": chosen_action,
|
||||
"reasoning": reasoning,
|
||||
"available_actions": available_actions,
|
||||
"scenario": scenario,
|
||||
"mode": "async_streaming",
|
||||
}
|
||||
else:
|
||||
response = await async_client.responses.create(
|
||||
model=self.model,
|
||||
input=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_message}],
|
||||
tools=tools, # type: ignore
|
||||
tool_choice="required",
|
||||
)
|
||||
|
||||
# Process non-streaming response
|
||||
tool_call = None
|
||||
reasoning_text = ""
|
||||
|
||||
for output_item in response.output:
|
||||
if output_item.type == "function_call":
|
||||
tool_call = output_item
|
||||
elif output_item.type == "message" and hasattr(output_item, "content"):
|
||||
for content in output_item.content:
|
||||
if hasattr(content, "type"):
|
||||
if content.type == "text" and hasattr(content, "text"):
|
||||
reasoning_text += content.text
|
||||
print(f"{self.color}Reasoning: {content.text}{RESET_COLOR}")
|
||||
elif content.type == "refusal" and hasattr(content, "refusal"):
|
||||
print(f"{self.color}Refusal: {content.refusal}{RESET_COLOR}")
|
||||
|
||||
if tool_call:
|
||||
args = json.loads(tool_call.arguments)
|
||||
chosen_action = args["action"]
|
||||
reasoning = args["reasoning"]
|
||||
|
||||
print(f"{self.color}Chosen action: {chosen_action}{RESET_COLOR}")
|
||||
print(f"{self.color}Tool reasoning: {reasoning}{RESET_COLOR}")
|
||||
|
||||
return {
|
||||
"action": chosen_action,
|
||||
"reasoning": reasoning,
|
||||
"full_reasoning": reasoning_text,
|
||||
"available_actions": available_actions,
|
||||
"scenario": scenario,
|
||||
"mode": "async_non_streaming",
|
||||
}
|
||||
|
||||
# Fallback
|
||||
print(f"{self.color}No tool call found, using fallback{RESET_COLOR}")
|
||||
return {
|
||||
"action": available_actions[0] if available_actions else "no_action",
|
||||
"reasoning": "Fallback: No tool call received",
|
||||
"available_actions": available_actions,
|
||||
"scenario": scenario,
|
||||
"mode": f"async_{mode_desc}_fallback",
|
||||
}
|
||||
|
||||
|
||||
async def run_example():
|
||||
"""Run the example with multiple scenarios in different modes."""
|
||||
|
||||
# Create agents with different colors for different modes
|
||||
sync_agent = O3DecisionAgent(model="o3-mini", color=LIGHT_BLUE)
|
||||
|
||||
# Test scenario
|
||||
scenario = {
|
||||
"scenario": "You're managing a project with limited resources and need to prioritize tasks.",
|
||||
"actions": ["focus_on_critical_path", "distribute_resources_evenly", "outsource_some_tasks", "extend_deadline"],
|
||||
}
|
||||
|
||||
results = []
|
||||
|
||||
# Test 2: Sync streaming
|
||||
print(f"\n{'=' * 60}")
|
||||
print(f"{LIGHT_BLUE}Test: Synchronous Streaming{RESET_COLOR}")
|
||||
print(f"{'=' * 60}")
|
||||
result = sync_agent.make_decision_sync(
|
||||
scenario=scenario["scenario"], available_actions=scenario["actions"], stream=True
|
||||
)
|
||||
results.append(result)
|
||||
|
||||
# Test 3: Sync non-streaming
|
||||
print(f"\n{'=' * 60}")
|
||||
print(f"{LIGHT_BLUE}Test: Synchronous Non-Streaming{RESET_COLOR}")
|
||||
print(f"{'=' * 60}")
|
||||
result = sync_agent.make_decision_sync(
|
||||
scenario=scenario["scenario"], available_actions=scenario["actions"], stream=False
|
||||
)
|
||||
results.append(result)
|
||||
|
||||
# Test 4: Async streaming
|
||||
print(f"\n{'=' * 60}")
|
||||
print(f"{LIGHT_BLUE}Test: Asynchronous Streaming{RESET_COLOR}")
|
||||
print(f"{'=' * 60}")
|
||||
result = await sync_agent.make_decision_async(
|
||||
scenario=scenario["scenario"], available_actions=scenario["actions"], stream=True
|
||||
)
|
||||
results.append(result)
|
||||
|
||||
# Test 5: Async non-streaming
|
||||
print(f"\n{'=' * 60}")
|
||||
print(f"{LIGHT_BLUE}Test: Asynchronous Non-Streaming{RESET_COLOR}")
|
||||
print(f"{'=' * 60}")
|
||||
result = await sync_agent.make_decision_async(
|
||||
scenario=scenario["scenario"], available_actions=scenario["actions"], stream=False
|
||||
)
|
||||
results.append(result)
|
||||
|
||||
return results
|
||||
|
||||
|
||||
def main():
|
||||
"""Main function to run the example."""
|
||||
print("Starting OpenAI o3 Responses API Example (All Modes)")
|
||||
print("=" * 60)
|
||||
|
||||
try:
|
||||
# Run async example
|
||||
results = asyncio.run(run_example())
|
||||
|
||||
print(f"\n{'=' * 60}")
|
||||
print("Example Summary")
|
||||
print(f"{'=' * 60}")
|
||||
|
||||
for i, result in enumerate(results, 1):
|
||||
print(f"Test {i} ({result.get('mode', 'unknown')}): {result['action']}")
|
||||
|
||||
# End the trace
|
||||
agentops.end_trace(tracer, end_state="Success")
|
||||
|
||||
# Validate the trace
|
||||
print(f"\n{'=' * 60}")
|
||||
print("Validating AgentOps Trace")
|
||||
print(f"{'=' * 60}")
|
||||
|
||||
try:
|
||||
validation_result = agentops.validate_trace_spans(trace_context=tracer)
|
||||
agentops.print_validation_summary(validation_result)
|
||||
print("✅ Example completed successfully!")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"❌ Error validating spans: {e}")
|
||||
raise
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Example failed: {e}")
|
||||
agentops.end_trace(tracer, end_state="Error")
|
||||
raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,229 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# OpenAI Async Example\n",
|
||||
"\n",
|
||||
"We are going to create a simple chatbot that creates stories based on a user provided image. The chatbot will use the gpt-4o-mini LLM to generate the story using a user prompt and its vision model to understand the image.\n",
|
||||
"\n",
|
||||
"We will track the chatbot with AgentOps and see how it performs!"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"First let's install the required packages"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Install required dependencies\n",
|
||||
"%pip install agentops\n",
|
||||
"%pip install openai\n",
|
||||
"%pip install python-dotenv"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Then import them"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from openai import AsyncOpenAI\n",
|
||||
"import agentops\n",
|
||||
"import os\n",
|
||||
"from dotenv import load_dotenv"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Next, we'll grab our API keys. You can use dotenv like below or however else you like to load environment variables"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"load_dotenv()\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\", \"your_openai_api_key_here\")\n",
|
||||
"os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\", \"your_api_key_here\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Next we initialize the AgentOps client."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"agentops.init(auto_start_session=True)\n",
|
||||
"tracer = agentops.start_trace(\n",
|
||||
" trace_name=\"OpenAI Async Example\", tags=[\"openai-async-example\", \"openai\", \"agentops-example\"]\n",
|
||||
")\n",
|
||||
"client = AsyncOpenAI()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"And we are all set! Note the seesion url above. We will use it to track the chatbot.\n",
|
||||
"\n",
|
||||
"Let's create a simple chatbot that generates stories given an image and a user prompt."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"system_prompt = \"\"\"\n",
|
||||
"You are a master storyteller, with the ability to create vivid and engaging stories.\n",
|
||||
"You have experience in writing for children and adults alike.\n",
|
||||
"You are given a prompt and you need to generate a story based on the prompt.\n",
|
||||
"\"\"\"\n",
|
||||
"\n",
|
||||
"user_prompt = [\n",
|
||||
" {\"type\": \"text\", \"text\": \"Write a mystery thriller story based on your understanding of the provided image.\"},\n",
|
||||
" {\n",
|
||||
" \"type\": \"image_url\",\n",
|
||||
" \"image_url\": {\"url\": \"https://www.cosy.sbg.ac.at/~pmeerw/Watermarking/lena_color.gif\"},\n",
|
||||
" },\n",
|
||||
"]\n",
|
||||
"\n",
|
||||
"messages = [\n",
|
||||
" {\"role\": \"system\", \"content\": system_prompt},\n",
|
||||
" {\"role\": \"user\", \"content\": user_prompt},\n",
|
||||
"]"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"async def main():\n",
|
||||
" response = await client.chat.completions.create(\n",
|
||||
" model=\"gpt-4o-mini\",\n",
|
||||
" messages=messages,\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" print(response.choices[0].message.content)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"await main()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"The response is a string that contains the story. We can track this with AgentOps by navigating to the trace url and viewing the run."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Streaming Version\n",
|
||||
"We will demonstrate the streaming version of the API."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"async def main_stream():\n",
|
||||
" stream = await client.chat.completions.create(\n",
|
||||
" model=\"gpt-4o-mini\",\n",
|
||||
" messages=messages,\n",
|
||||
" stream=True,\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" async for chunk in stream:\n",
|
||||
" print(chunk.choices[0].delta.content or \"\", end=\"\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"await main_stream()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"agentops.end_trace(tracer, end_state=\"Success\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Note that the response is a generator that yields chunks of the story. We can track this with AgentOps by navigating to the trace url and viewing the run.\n",
|
||||
"All done!"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "agentops (3.11.11)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.11"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 2
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
# OpenAI Async Example
|
||||
#
|
||||
# We are going to create a simple chatbot that creates stories based on a user provided image. The chatbot will use the gpt-4o-mini LLM to generate the story using a user prompt and its vision model to understand the image.
|
||||
#
|
||||
# We will track the chatbot with AgentOps and see how it performs!
|
||||
# First let's install the required packages
|
||||
# # Install required dependencies
|
||||
# %pip install agentops
|
||||
# %pip install openai
|
||||
# %pip install python-dotenv
|
||||
# Then import them
|
||||
from openai import AsyncOpenAI
|
||||
import agentops
|
||||
import os
|
||||
import asyncio
|
||||
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
|
||||
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_api_key_here")
|
||||
|
||||
# Next we initialize the AgentOps client.
|
||||
agentops.init(auto_start_session=True, trace_name="OpenAI Async Example", tags=["openai", "async", "agentops-example"])
|
||||
tracer = agentops.start_trace(
|
||||
trace_name="OpenAI Async Example", tags=["openai-async-example", "openai", "agentops-example"]
|
||||
)
|
||||
client = AsyncOpenAI()
|
||||
|
||||
# And we are all set! Note the seesion url above. We will use it to track the chatbot.
|
||||
#
|
||||
# Let's create a simple chatbot that generates stories given an image and a user prompt.
|
||||
system_prompt = """
|
||||
You are a master storyteller, with the ability to create vivid and engaging stories.
|
||||
You have experience in writing for children and adults alike.
|
||||
You are given a prompt and you need to generate a story based on the prompt.
|
||||
"""
|
||||
|
||||
user_prompt = [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "Write a very short mystery thriller story based on your understanding of the provided image.",
|
||||
},
|
||||
{
|
||||
"type": "image_url",
|
||||
"image_url": {"url": "https://www.cosy.sbg.ac.at/~pmeerw/Watermarking/lena_color.gif"},
|
||||
},
|
||||
]
|
||||
|
||||
messages = [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": user_prompt},
|
||||
]
|
||||
|
||||
|
||||
async def main():
|
||||
response = await client.chat.completions.create(
|
||||
model="gpt-4o-mini",
|
||||
messages=messages,
|
||||
)
|
||||
print(response.choices[0].message.content)
|
||||
|
||||
|
||||
# await main()
|
||||
|
||||
|
||||
# The response is a string that contains the story. We can track this with AgentOps by navigating to the trace url and viewing the run.
|
||||
# ## Streaming Version
|
||||
# We will demonstrate the streaming version of the API.
|
||||
async def main_stream():
|
||||
stream = await client.chat.completions.create(
|
||||
model="gpt-4o-mini",
|
||||
messages=messages,
|
||||
stream=True,
|
||||
)
|
||||
async for chunk in stream:
|
||||
if chunk.choices and len(chunk.choices) > 0:
|
||||
print(chunk.choices[0].delta.content or "", end="")
|
||||
|
||||
|
||||
asyncio.run(main_stream())
|
||||
agentops.end_trace(tracer, end_state="Success")
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
agentops.validate_trace_spans(trace_context=tracer)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
|
||||
|
||||
# Note that the response is a generator that yields chunks of the story. We can track this with AgentOps by navigating to the trace url and viewing the run.
|
||||
# All done!
|
||||
@@ -0,0 +1,203 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# OpenAI Sync Example\n",
|
||||
"\n",
|
||||
"We are going to create a simple chatbot that creates stories based on a prompt. The chatbot will use the gpt-4o-mini LLM to generate the story using a user prompt.\n",
|
||||
"\n",
|
||||
"We will track the chatbot with AgentOps and see how it performs!"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"First let's install the required packages"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Install required dependencies\n",
|
||||
"%pip install agentops\n",
|
||||
"%pip install openai\n",
|
||||
"%pip install python-dotenv"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Then import them"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from openai import OpenAI\n",
|
||||
"import agentops\n",
|
||||
"import os\n",
|
||||
"from dotenv import load_dotenv"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Next, we'll grab our API keys. You can use dotenv like below or however else you like to load environment variables"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"load_dotenv()\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\", \"your_openai_api_key_here\")\n",
|
||||
"os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\", \"your_api_key_here\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Next we initialize the AgentOps client."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"agentops.init(auto_start_session=True)\n",
|
||||
"tracer = agentops.start_trace(\n",
|
||||
" trace_name=\"OpenAI Sync Example\", tags=[\"openai-sync-example\", \"openai\", \"agentops-example\"]\n",
|
||||
")\n",
|
||||
"client = OpenAI()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"And we are all set! Note the seesion url above. We will use it to track the chatbot.\n",
|
||||
"\n",
|
||||
"Let's create a simple chatbot that generates stories."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"system_prompt = \"\"\"\n",
|
||||
"You are a master storyteller, with the ability to create vivid and engaging stories.\n",
|
||||
"You have experience in writing for children and adults alike.\n",
|
||||
"You are given a prompt and you need to generate a story based on the prompt.\n",
|
||||
"\"\"\"\n",
|
||||
"\n",
|
||||
"user_prompt = \"Write a story about a cyber-warrior trapped in the imperial time period.\"\n",
|
||||
"\n",
|
||||
"messages = [\n",
|
||||
" {\"role\": \"system\", \"content\": system_prompt},\n",
|
||||
" {\"role\": \"user\", \"content\": user_prompt},\n",
|
||||
"]"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"response = client.chat.completions.create(\n",
|
||||
" model=\"gpt-4o-mini\",\n",
|
||||
" messages=messages,\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"print(response.choices[0].message.content)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"The response is a string that contains the story. We can track this with AgentOps by navigating to the trace url and viewing the run."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Streaming Version\n",
|
||||
"We will demonstrate the streaming version of the API."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"stream = client.chat.completions.create(\n",
|
||||
" model=\"gpt-4o-mini\",\n",
|
||||
" messages=messages,\n",
|
||||
" stream=True,\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"for chunk in stream:\n",
|
||||
" print(chunk.choices[0].delta.content or \"\", end=\"\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"agentops.end_trace(tracer, end_state=\"Success\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Note that the response is a generator that yields chunks of the story. We can track this with AgentOps by navigating to the trace url and viewing the run.\n",
|
||||
"All done!"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "agentops (3.11.11)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.11"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 2
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
# OpenAI Sync Example
|
||||
#
|
||||
# We are going to create a simple chatbot that creates stories based on a prompt. The chatbot will use the gpt-4o-mini LLM to generate the story using a user prompt.
|
||||
#
|
||||
# We will track the chatbot with AgentOps and see how it performs!
|
||||
# First let's install the required packages
|
||||
# # Install required dependencies
|
||||
# %pip install agentops
|
||||
# %pip install openai
|
||||
# %pip install python-dotenv
|
||||
# Then import them
|
||||
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
|
||||
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_api_key_here")
|
||||
|
||||
# Next we initialize the AgentOps client.
|
||||
agentops.init(auto_start_session=True, trace_name="OpenAI Sync Example", tags=["openai", "sync", "agentops-example"])
|
||||
tracer = agentops.start_trace(
|
||||
trace_name="OpenAI Sync Example", tags=["openai-sync-example", "openai", "agentops-example"]
|
||||
)
|
||||
client = OpenAI()
|
||||
|
||||
# And we are all set! Note the seesion url above. We will use it to track the chatbot.
|
||||
#
|
||||
# Let's create a simple chatbot that generates stories.
|
||||
system_prompt = """
|
||||
You are a master storyteller, with the ability to create vivid and engaging stories.
|
||||
You have experience in writing for children and adults alike.
|
||||
You are given a prompt and you need to generate a story based on the prompt.
|
||||
"""
|
||||
|
||||
user_prompt = "Write a very short story about a cyber-warrior trapped in the imperial time period."
|
||||
|
||||
messages = [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": user_prompt},
|
||||
]
|
||||
|
||||
response = client.chat.completions.create(
|
||||
model="gpt-4o-mini",
|
||||
messages=messages,
|
||||
)
|
||||
|
||||
print(response.choices[0].message.content)
|
||||
|
||||
# The response is a string that contains the story. We can track this with AgentOps by navigating to the trace url and viewing the run.
|
||||
# ## Streaming Version
|
||||
# We will demonstrate the streaming version of the API.
|
||||
stream = client.chat.completions.create(
|
||||
model="gpt-4o-mini",
|
||||
messages=messages,
|
||||
stream=True,
|
||||
)
|
||||
|
||||
for chunk in stream:
|
||||
if chunk.choices and len(chunk.choices) > 0:
|
||||
print(chunk.choices[0].delta.content or "", end="")
|
||||
|
||||
agentops.end_trace(tracer, end_state="Success")
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
result = agentops.validate_trace_spans(trace_context=tracer)
|
||||
agentops.print_validation_summary(result)
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
|
||||
# Note that the response is a generator that yields chunks of the story. We can track this with AgentOps by navigating to the trace url and viewing the run.
|
||||
# All done!
|
||||
@@ -0,0 +1,5 @@
|
||||
openai
|
||||
pandas # for multi_tool_orchestration.py
|
||||
tavily-python # for web_search.py
|
||||
datasets
|
||||
pinecone
|
||||
@@ -0,0 +1,296 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Observing Responses API with AgentOps\n",
|
||||
"\n",
|
||||
"The Responses API is a new API that focuses on greater simplicity and greater expressivity when using our APIs. It is designed for multiple tools, multiple turns, and multiple modalities — as opposed to current APIs, which either have these features bolted onto an API designed primarily for text in and out (chat completions) or need a lot bootstrapping to perform simple actions (assistants api).\n",
|
||||
"\n",
|
||||
"Here I will show you a couple of new features that the Responses API has to offer and tie it all together at the end.\n",
|
||||
"`responses` solves for a number of user pain-points with our current set of APIs. During our time with the completions API, we found that folks wanted:\n",
|
||||
"\n",
|
||||
"- the ability to easily perform multi-turn model interactions in a single API call\n",
|
||||
"- to have access to our hosted tools (file_search, web_search, code_interpreter)\n",
|
||||
"- granular control over the context sent to the model\n",
|
||||
"\n",
|
||||
"As models start to develop longer running reasoning and thinking capabilities, users will want an async-friendly and stateful primitive. Response solves for this. With AgentOps, we can easily observe the Responses API in action."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Basics\n",
|
||||
"By design, on the surface, the Responses API is very similar to the Completions API."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Install required dependencies\n",
|
||||
"%pip install agentops\n",
|
||||
"%pip install openai\n",
|
||||
"%pip install python-dotenv"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from dotenv import load_dotenv\n",
|
||||
"import os\n",
|
||||
"import json\n",
|
||||
"import agentops\n",
|
||||
"from openai import OpenAI"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"load_dotenv()\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\", \"your_openai_api_key_here\")\n",
|
||||
"os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\", \"your_api_key_here\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"agentops.init(auto_start_session=True)\n",
|
||||
"tracer = agentops.start_trace(\n",
|
||||
" trace_name=\"OpenAI Responses Example\", tags=[\"openai-responses-example\", \"openai\", \"agentops-example\"]\n",
|
||||
")\n",
|
||||
"client = OpenAI()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"response = client.responses.create(\n",
|
||||
" model=\"gpt-4o-mini\",\n",
|
||||
" input=\"tell me a joke\",\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"print(response.output[0].content[0].text)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"One key feature of the Response API is that it is stateful. This means that you do not have to manage the state of the conversation by yourself, the API will handle it for you. For example, you can retrieve the response at any time and it will include the full conversation history."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"fetched_response = client.responses.retrieve(response_id=response.id)\n",
|
||||
"print(fetched_response.output[0].content[0].text)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"You can continue the conversation by referring to the previous response."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"response_two = client.responses.create(model=\"gpt-4o-mini\", input=\"tell me another\", previous_response_id=response.id)\n",
|
||||
"print(response_two.output[0].content[0].text)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"You can of course manage the context yourself. But one benefit of OpenAI maintaining the context for you is that you can fork the response at any point and continue the conversation from that point."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"response_two_forked = client.responses.create(\n",
|
||||
" model=\"gpt-4o-mini\",\n",
|
||||
" input=\"I didn't like that joke, tell me another and tell me the difference between the two jokes\",\n",
|
||||
" previous_response_id=response.id, # Forking and continuing from the first response\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"output_text = response_two_forked.output[0].content[0].text\n",
|
||||
"print(output_text)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Hosted Tools\n",
|
||||
"\n",
|
||||
"Another benefit of the Responses API is that it adds support for hosted tools like `file_search` and `web_search`. Instead of manually calling the tools, simply pass in the tools and the API will decide which tool to use and use it.\n",
|
||||
"\n",
|
||||
"Here is an example of using the `web_search` tool to incorporate web search results into the response. You may already be familiar with how ChatGPT can search the web. You can now build similar experiences too! The web search tool uses the OpenAI Index, the one that powers the web search in ChatGPT, having being optimized for chat applications.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"response = client.responses.create(\n",
|
||||
" model=\"gpt-4o\", # or another supported model\n",
|
||||
" input=\"What's the latest news about AI?\",\n",
|
||||
" tools=[{\"type\": \"web_search\"}],\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"print(json.dumps(response.output, default=lambda o: o.__dict__, indent=2))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Multimodal, Tool-augmented conversation\n",
|
||||
"\n",
|
||||
"The Responses API natively supports text, images, and audio modalities. \n",
|
||||
"Tying everything together, we can build a fully multimodal, tool-augmented interaction with one API call through the responses API."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from IPython.display import Image, display\n",
|
||||
"\n",
|
||||
"# Display the image from the provided URL\n",
|
||||
"url = \"https://upload.wikimedia.org/wikipedia/commons/thumb/1/15/Cat_August_2010-4.jpg/2880px-Cat_August_2010-4.jpg\"\n",
|
||||
"display(Image(url=url, width=400))\n",
|
||||
"\n",
|
||||
"response_multimodal = client.responses.create(\n",
|
||||
" model=\"gpt-4o\",\n",
|
||||
" input=[\n",
|
||||
" {\n",
|
||||
" \"role\": \"user\",\n",
|
||||
" \"content\": [\n",
|
||||
" {\n",
|
||||
" \"type\": \"input_text\",\n",
|
||||
" \"text\": \"Come up with keywords related to the image, and search on the web using the search tool for any news related to the keywords\"\n",
|
||||
" \", summarize the findings and cite the sources.\",\n",
|
||||
" },\n",
|
||||
" {\n",
|
||||
" \"type\": \"input_image\",\n",
|
||||
" \"image_url\": \"https://upload.wikimedia.org/wikipedia/commons/thumb/1/15/Cat_August_2010-4.jpg/2880px-Cat_August_2010-4.jpg\",\n",
|
||||
" },\n",
|
||||
" ],\n",
|
||||
" }\n",
|
||||
" ],\n",
|
||||
" tools=[{\"type\": \"web_search\"}],\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"print(json.dumps(response_multimodal.__dict__, default=lambda o: o.__dict__, indent=4))\n",
|
||||
"agentops.end_trace(tracer, end_state=\"Success\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"In the above example, we were able to use the `web_search` tool to search the web for news related to the image in one API call instead of multiple round trips that would be required if we were using the Chat Completions API."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"With the responses API\n",
|
||||
"🔥 a single API call can handle:\n",
|
||||
"\n",
|
||||
"✅ Analyze a given image using a multimodal input.\n",
|
||||
"\n",
|
||||
"✅ Perform web search via the `web_search` hosted tool\n",
|
||||
"\n",
|
||||
"✅ Summarize the results.\n",
|
||||
"\n",
|
||||
"In contrast, With Chat Completions API would require multiple steps, each requiring a round trip to the API:\n",
|
||||
"\n",
|
||||
"1️⃣ Upload image and get analysis → 1 request\n",
|
||||
"\n",
|
||||
"2️⃣ Extract info, call external web search → manual step + tool execution\n",
|
||||
"\n",
|
||||
"3️⃣ Re-submit tool results for summarization → another request\n",
|
||||
"\n",
|
||||
"We are very excited for you to try out the Responses API and see how it can simplify your code and make it easier to build complex, multimodal, tool-augmented interactions!\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "agentops (3.11.11)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.11"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 2
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
# ## Observing Responses API with AgentOps
|
||||
#
|
||||
# The Responses API is a new API that focuses on greater simplicity and greater expressivity when using our APIs. It is designed for multiple tools, multiple turns, and multiple modalities — as opposed to current APIs, which either have these features bolted onto an API designed primarily for text in and out (chat completions) or need a lot bootstrapping to perform simple actions (assistants api).
|
||||
#
|
||||
# Here I will show you a couple of new features that the Responses API has to offer and tie it all together at the end.
|
||||
# `responses` solves for a number of user pain-points with our current set of APIs. During our time with the completions API, we found that folks wanted:
|
||||
#
|
||||
# - the ability to easily perform multi-turn model interactions in a single API call
|
||||
# - to have access to our hosted tools (file_search, web_search, code_interpreter)
|
||||
# - granular control over the context sent to the model
|
||||
#
|
||||
# As models start to develop longer running reasoning and thinking capabilities, users will want an async-friendly and stateful primitive. Response solves for this. With AgentOps, we can easily observe the Responses API in action.
|
||||
# ## Basics
|
||||
# By design, on the surface, the Responses API is very similar to the Completions API.
|
||||
# # Install required dependencies
|
||||
# %pip install agentops
|
||||
# %pip install openai
|
||||
# %pip install python-dotenv
|
||||
from dotenv import load_dotenv
|
||||
import os
|
||||
import json
|
||||
import agentops
|
||||
from openai import OpenAI
|
||||
|
||||
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_api_key_here")
|
||||
|
||||
agentops.init(
|
||||
auto_start_session=False, trace_name="OpenAI Web Search Example", tags=["openai", "web-search", "agentops-example"]
|
||||
)
|
||||
tracer = agentops.start_trace(
|
||||
trace_name="OpenAI Responses Example", tags=["openai-responses-example", "openai", "agentops-example"]
|
||||
)
|
||||
client = OpenAI()
|
||||
|
||||
response = client.responses.create(
|
||||
model="gpt-4o-mini",
|
||||
input="tell me a joke",
|
||||
)
|
||||
|
||||
print(response.output[0].content[0].text)
|
||||
|
||||
# One key feature of the Response API is that it is stateful. This means that you do not have to manage the state of the conversation by yourself, the API will handle it for you. For example, you can retrieve the response at any time and it will include the full conversation history.
|
||||
fetched_response = client.responses.retrieve(response_id=response.id)
|
||||
print(fetched_response.output[0].content[0].text)
|
||||
|
||||
# You can continue the conversation by referring to the previous response.
|
||||
response_two = client.responses.create(model="gpt-4o-mini", input="tell me another", previous_response_id=response.id)
|
||||
print(response_two.output[0].content[0].text)
|
||||
|
||||
# You can of course manage the context yourself. But one benefit of OpenAI maintaining the context for you is that you can fork the response at any point and continue the conversation from that point.
|
||||
response_two_forked = client.responses.create(
|
||||
model="gpt-4o-mini",
|
||||
input="I didn't like that joke, tell me another and tell me the difference between the two jokes",
|
||||
previous_response_id=response.id, # Forking and continuing from the first response
|
||||
)
|
||||
output_text = response_two_forked.output[0].content[0].text
|
||||
print(output_text)
|
||||
|
||||
# ## Hosted Tools
|
||||
#
|
||||
# Another benefit of the Responses API is that it adds support for hosted tools like `file_search` and `web_search`. Instead of manually calling the tools, simply pass in the tools and the API will decide which tool to use and use it.
|
||||
#
|
||||
# Here is an example of using the `web_search` tool to incorporate web search results into the response. You may already be familiar with how ChatGPT can search the web. You can now build similar experiences too! The web search tool uses the OpenAI Index, the one that powers the web search in ChatGPT, having being optimized for chat applications.
|
||||
response = client.responses.create(
|
||||
model="gpt-4o", # or another supported model
|
||||
input="What's the latest news about AI?",
|
||||
tools=[{"type": "web_search"}],
|
||||
)
|
||||
print(json.dumps(response.output, default=lambda o: o.__dict__, indent=2))
|
||||
|
||||
# ## Multimodal, Tool-augmented conversation
|
||||
#
|
||||
# The Responses API natively supports text, images, and audio modalities.
|
||||
# Tying everything together, we can build a fully multimodal, tool-augmented interaction with one API call through the responses API.
|
||||
|
||||
# Display the image from the provided URL
|
||||
url = "https://upload.wikimedia.org/wikipedia/commons/thumb/1/15/Cat_August_2010-4.jpg/2880px-Cat_August_2010-4.jpg"
|
||||
# display(Image(url=url, width=400))
|
||||
|
||||
response_multimodal = client.responses.create(
|
||||
model="gpt-4o",
|
||||
input=[
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{
|
||||
"type": "input_text",
|
||||
"text": "Come up with keywords related to the image, and search on the web using the search tool for any news related to the keywords"
|
||||
", summarize the findings and cite the sources.",
|
||||
},
|
||||
{
|
||||
"type": "input_image",
|
||||
"image_url": "https://upload.wikimedia.org/wikipedia/commons/thumb/1/15/Cat_August_2010-4.jpg/2880px-Cat_August_2010-4.jpg",
|
||||
},
|
||||
],
|
||||
}
|
||||
],
|
||||
tools=[{"type": "web_search"}],
|
||||
)
|
||||
|
||||
print(json.dumps(response_multimodal.__dict__, default=lambda o: o.__dict__, indent=4))
|
||||
agentops.end_trace(tracer, end_state="Success")
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
agentops.validate_trace_spans(trace_context=tracer)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
|
||||
|
||||
# In the above example, we were able to use the `web_search` tool to search the web for news related to the image in one API call instead of multiple round trips that would be required if we were using the Chat Completions API.
|
||||
# With the responses API
|
||||
# 🔥 a single API call can handle:
|
||||
#
|
||||
# ✅ Analyze a given image using a multimodal input.
|
||||
#
|
||||
# ✅ Perform web search via the `web_search` hosted tool
|
||||
#
|
||||
# ✅ Summarize the results.
|
||||
#
|
||||
# In contrast, With Chat Completions API would require multiple steps, each requiring a round trip to the API:
|
||||
#
|
||||
# 1️⃣ Upload image and get analysis → 1 request
|
||||
#
|
||||
# 2️⃣ Extract info, call external web search → manual step + tool execution
|
||||
#
|
||||
# 3️⃣ Re-submit tool results for summarization → another request
|
||||
#
|
||||
# We are very excited for you to try out the Responses API and see how it can simplify your code and make it easier to build complex, multimodal, tool-augmented interactions!
|
||||
@@ -0,0 +1,39 @@
|
||||
# OpenAI Agents Examples with AgentOps
|
||||
|
||||
This directory contains examples of using the OpenAI Agents SDK with AgentOps instrumentation.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Python >= 3.10 < 3.13
|
||||
- Install required dependencies:
|
||||
```
|
||||
pip install agentops openai-agents
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### 1. Agent Patterns
|
||||
|
||||
Example: `agent_patterns`
|
||||
This example demonstrates:
|
||||
- Common agent design patterns
|
||||
|
||||
### 2. Agent Tools
|
||||
|
||||
Example: `agents_tools`
|
||||
|
||||
This example demonstrates:
|
||||
- Agent tool integration
|
||||
|
||||
### 3. Customer Service Agent
|
||||
|
||||
Example: `customer_service_agent`
|
||||
|
||||
This example demonstrates:
|
||||
- Customer service automation
|
||||
|
||||
## AgentOps Integration
|
||||
|
||||
These examples show how to use AgentOps to monitor and analyze your AI applications. AgentOps automatically instruments your OpenAI Agents calls to provide insights into performance, usage patterns, and model behavior.
|
||||
|
||||
To learn more about AgentOps, visit [https://www.agentops.ai](https://www.agentops.ai)
|
||||
@@ -0,0 +1,163 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "f68ce4af",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# OpenAI Agents Guardrails Demonstration\n",
|
||||
"\n",
|
||||
"This notebook demonstrates guardrails using the Agents SDK and how one can observe them using the AgentOps platform."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "10bcf29b",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Install required packages\n",
|
||||
"%pip install -q agentops\n",
|
||||
"%pip install -q openai-agents\n",
|
||||
"%pip install -q dotenv pydantic"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "a3be4e68",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Import dependencies\n",
|
||||
"from pydantic import BaseModel\n",
|
||||
"from agents import (\n",
|
||||
" Agent,\n",
|
||||
" GuardrailFunctionOutput,\n",
|
||||
" InputGuardrailTripwireTriggered,\n",
|
||||
" RunContextWrapper,\n",
|
||||
" Runner,\n",
|
||||
" TResponseInputItem,\n",
|
||||
" input_guardrail,\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "2d0dddb6",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Load API keys\n",
|
||||
"import os\n",
|
||||
"from dotenv import load_dotenv\n",
|
||||
"\n",
|
||||
"load_dotenv()\n",
|
||||
"\n",
|
||||
"os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\", \"your_api_key_here\")\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\", \"your_openai_api_key_here\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "114e216b",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Initialize agentops and import the guardrail decorator\n",
|
||||
"import agentops\n",
|
||||
"from agentops import guardrail\n",
|
||||
"\n",
|
||||
"agentops.init(api_key=os.environ[\"AGENTOPS_API_KEY\"], tags=[\"agentops-example\"], auto_start_session=False)\n",
|
||||
"tracer = agentops.start_trace(trace_name=\"OpenAI Agents Guardrail Example\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "0bf8b54d",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# OpenAI Agents SDK guardrail example with agentops guardrails decorator for observability\n",
|
||||
"class MathHomeworkOutput(BaseModel):\n",
|
||||
" is_math_homework: bool\n",
|
||||
" reasoning: str\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"guardrail_agent = Agent(\n",
|
||||
" name=\"Guardrail check\",\n",
|
||||
" instructions=\"Check if the user is asking you to do their math homework.\",\n",
|
||||
" output_type=MathHomeworkOutput,\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"@input_guardrail\n",
|
||||
"@guardrail(spec=\"input\") # Specify guardrail type as input or output\n",
|
||||
"async def math_guardrail(\n",
|
||||
" ctx: RunContextWrapper[None], agent: Agent, input: str | list[TResponseInputItem]\n",
|
||||
") -> GuardrailFunctionOutput:\n",
|
||||
" result = await Runner.run(guardrail_agent, input, context=ctx.context)\n",
|
||||
"\n",
|
||||
" return GuardrailFunctionOutput(\n",
|
||||
" output_info=result.final_output,\n",
|
||||
" tripwire_triggered=result.final_output.is_math_homework,\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"agent = Agent(\n",
|
||||
" name=\"Customer support agent\",\n",
|
||||
" instructions=\"You are a customer support agent. You help customers with their questions.\",\n",
|
||||
" input_guardrails=[math_guardrail],\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"async def main():\n",
|
||||
" # This should trip the guardrail\n",
|
||||
" try:\n",
|
||||
" await Runner.run(agent, \"Hello, can you help me solve for x: 2x + 3 = 11?\")\n",
|
||||
" print(\"Guardrail didn't trip - this is unexpected\")\n",
|
||||
"\n",
|
||||
" except InputGuardrailTripwireTriggered:\n",
|
||||
" print(\"Math homework guardrail tripped\")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"await main()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "63bf8e09",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"agentops.end_trace(tracer, end_state=\"Success\")"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "agentops (3.11.11)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.11"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
# # OpenAI Agents Guardrails Demonstration
|
||||
#
|
||||
# This notebook demonstrates guardrails using the Agents SDK and how one can observe them using the AgentOps platform.
|
||||
|
||||
# Install required packages
|
||||
# %pip install agentops
|
||||
# %pip install openai-agents
|
||||
# %pip install dotenv pydantic
|
||||
|
||||
# Import dependencies
|
||||
from pydantic import BaseModel
|
||||
from agents import (
|
||||
Agent,
|
||||
GuardrailFunctionOutput,
|
||||
InputGuardrailTripwireTriggered,
|
||||
RunContextWrapper,
|
||||
Runner,
|
||||
TResponseInputItem,
|
||||
input_guardrail,
|
||||
)
|
||||
|
||||
# Initialize agentops and import the guardrail decorator
|
||||
import agentops
|
||||
from agentops import guardrail
|
||||
|
||||
# Load API keys
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
import asyncio
|
||||
|
||||
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")
|
||||
|
||||
agentops.init(api_key=os.environ["AGENTOPS_API_KEY"], trace_name="OpenAI Agents Guardrails", tags=["agentops-example"])
|
||||
|
||||
|
||||
# OpenAI Agents SDK guardrail example with agentops guardrails decorator for observability
|
||||
class MathHomeworkOutput(BaseModel):
|
||||
is_math_homework: bool
|
||||
reasoning: str
|
||||
|
||||
|
||||
guardrail_agent = Agent(
|
||||
name="Guardrail check",
|
||||
instructions="Check if the user is asking you to do their math homework.",
|
||||
output_type=MathHomeworkOutput,
|
||||
)
|
||||
|
||||
|
||||
@input_guardrail
|
||||
@guardrail(spec="input") # Specify guardrail type as input or output
|
||||
async def math_guardrail(
|
||||
ctx: RunContextWrapper[None], agent: Agent, input: str | list[TResponseInputItem]
|
||||
) -> GuardrailFunctionOutput:
|
||||
result = await Runner.run(guardrail_agent, input, context=ctx.context)
|
||||
|
||||
return GuardrailFunctionOutput(
|
||||
output_info=result.final_output,
|
||||
tripwire_triggered=result.final_output.is_math_homework,
|
||||
)
|
||||
|
||||
|
||||
agent = Agent(
|
||||
name="Customer support agent",
|
||||
instructions="You are a customer support agent. You help customers with their questions.",
|
||||
input_guardrails=[math_guardrail],
|
||||
)
|
||||
|
||||
|
||||
async def main():
|
||||
# This should trip the guardrail
|
||||
try:
|
||||
await Runner.run(agent, "Hello, can you help me solve for x: 2x + 3 = 11?")
|
||||
print("Guardrail didn't trip - this is unexpected")
|
||||
|
||||
except InputGuardrailTripwireTriggered:
|
||||
print("Math homework guardrail tripped")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
agentops.validate_trace_spans(trace_context=None)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
@@ -0,0 +1,953 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "a7cd4a28",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# OpenAI Agents Patterns Demonstration\n",
|
||||
"\n",
|
||||
"This notebook demonstrates various common agentic patterns using the Agents SDK and how one can observe them using the AgentOps platform.\n",
|
||||
"\n",
|
||||
"**Note: This notebook was edited using Claude MCP NotebookEdit tool!**\n",
|
||||
"\n",
|
||||
"## General Flow\n",
|
||||
"\n",
|
||||
"This notebook will walk you through several key agent patterns:\n",
|
||||
"\n",
|
||||
"1. **Agents as Tools** - Using agents as callable tools within other agents\n",
|
||||
"2. **Deterministic Flows** - Breaking down tasks into sequential steps\n",
|
||||
"3. **Forcing Tool Use** - Controlling when and how agents use tools\n",
|
||||
"4. **Input Guardrails** - Validating inputs before agent execution\n",
|
||||
"5. **LLM as a Judge** - Using LLMs to evaluate and improve outputs\n",
|
||||
"6. **Output Guardrails** - Validating outputs after agent execution\n",
|
||||
"7. **Parallelization** - Running multiple agents concurrently\n",
|
||||
"8. **Routing** - Directing requests to specialized agents\n",
|
||||
"9. **Streaming Guardrails** - Real-time validation during streaming\n",
|
||||
"\n",
|
||||
"Each pattern demonstrates how AgentOps automatically tracks and monitors your agent interactions, providing valuable insights into performance, costs, and behavior."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "7fb27b941602401d91542211134fc71a",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Prerequisites\n",
|
||||
"\n",
|
||||
"Before running this notebook, you'll need:\n",
|
||||
"\n",
|
||||
"1. **AgentOps Account**: Create a free account at [app.agentops.ai](https://app.agentops.ai)\n",
|
||||
"2. **AgentOps API Key**: Obtain your API key from your AgentOps dashboard\n",
|
||||
"3. **OpenAI API Key**: Get your API key from [platform.openai.com](https://platform.openai.com)\n",
|
||||
"\n",
|
||||
"Make sure to set these as environment variables or create a `.env` file in your project root with:\n",
|
||||
"\n",
|
||||
"```\n",
|
||||
"AGENTOPS_API_KEY=your_agentops_api_key_here\n",
|
||||
"OPENAI_API_KEY=your_openai_api_key_here\n",
|
||||
"```"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "66be7a30",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Install required packages\n",
|
||||
"%pip install -q agentops\n",
|
||||
"%pip install -q openai-agents\n",
|
||||
"%pip install -q pydotenv"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "acae54e37e7d407bbb7b55eff062a284",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Required imports - Note: agentops must be imported before agents\n",
|
||||
"import asyncio\n",
|
||||
"import os\n",
|
||||
"import uuid\n",
|
||||
"from typing import Any, Literal\n",
|
||||
"from dataclasses import dataclass\n",
|
||||
"from dotenv import load_dotenv\n",
|
||||
"from pydantic import BaseModel, Field\n",
|
||||
"\n",
|
||||
"# Import agentops FIRST\n",
|
||||
"import agentops\n",
|
||||
"\n",
|
||||
"# Then import agents\n",
|
||||
"from agents import (\n",
|
||||
" Agent,\n",
|
||||
" ItemHelpers,\n",
|
||||
" MessageOutputItem,\n",
|
||||
" Runner,\n",
|
||||
" trace,\n",
|
||||
" TResponseInputItem,\n",
|
||||
" FunctionToolResult,\n",
|
||||
" ModelSettings,\n",
|
||||
" RunContextWrapper,\n",
|
||||
" ToolsToFinalOutputFunction,\n",
|
||||
" ToolsToFinalOutputResult,\n",
|
||||
" function_tool,\n",
|
||||
" GuardrailFunctionOutput,\n",
|
||||
" InputGuardrailTripwireTriggered,\n",
|
||||
" OutputGuardrailTripwireTriggered,\n",
|
||||
" input_guardrail,\n",
|
||||
" output_guardrail,\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"from openai.types.responses import ResponseTextDeltaEvent"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "780a20ee",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Load environment variables and set API keys\n",
|
||||
"load_dotenv()\n",
|
||||
"os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\", \"your_api_key_here\")\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\", \"your_openai_api_key_here\")\n",
|
||||
"\n",
|
||||
"# Initialize AgentOps\n",
|
||||
"agentops.init(auto_start_session=False)\n",
|
||||
"# Note: tracer will be defined in each section's cell for clarity, using the specific tags for that pattern."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "e37212a8",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 1. Agents as Tools Pattern\n",
|
||||
"\n",
|
||||
"The mental model for handoffs is that the new agent \"takes over\". It sees the previous conversation history, and owns the conversation from that point onwards. However, this is not the only way to use agents. You can also use agents as a tool - the tool agent goes off and runs on its own, and then returns the result to the original agent.\n",
|
||||
"\n",
|
||||
"For example, you could model the translation task above as tool calls instead: rather than handing over to the language-specific agent, you could call the agent as a tool, and then use the result in the next step. This enables things like translating multiple languages at once.\n",
|
||||
"\n",
|
||||
"This pattern demonstrates using agents as callable tools within other agents. The orchestrator agent receives a user message and then picks which specialized agents to call as tools."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "52377535",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Start the AgentOps trace session\n",
|
||||
"tracer = agentops.start_trace(trace_name=\"Agents as Tools Pattern\", tags=[\"agentops-example\", \"openai-agents\"])\n",
|
||||
"\n",
|
||||
"# Define specialized translation agents\n",
|
||||
"spanish_agent = Agent(\n",
|
||||
" name=\"spanish_agent\",\n",
|
||||
" instructions=\"You translate the user's message to Spanish\",\n",
|
||||
" handoff_description=\"An english to spanish translator\",\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"french_agent = Agent(\n",
|
||||
" name=\"french_agent\",\n",
|
||||
" instructions=\"You translate the user's message to French\",\n",
|
||||
" handoff_description=\"An english to french translator\",\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"italian_agent = Agent(\n",
|
||||
" name=\"italian_agent\",\n",
|
||||
" instructions=\"You translate the user's message to Italian\",\n",
|
||||
" handoff_description=\"An english to italian translator\",\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"# Orchestrator agent that uses other agents as tools\n",
|
||||
"orchestrator_agent = Agent(\n",
|
||||
" name=\"orchestrator_agent\",\n",
|
||||
" instructions=(\n",
|
||||
" \"You are a translation agent. You use the tools given to you to translate.\"\n",
|
||||
" \"If asked for multiple translations, you call the relevant tools in order.\"\n",
|
||||
" \"You never translate on your own, you always use the provided tools.\"\n",
|
||||
" ),\n",
|
||||
" tools=[\n",
|
||||
" spanish_agent.as_tool(\n",
|
||||
" tool_name=\"translate_to_spanish\",\n",
|
||||
" tool_description=\"Translate the user's message to Spanish\",\n",
|
||||
" ),\n",
|
||||
" french_agent.as_tool(\n",
|
||||
" tool_name=\"translate_to_french\",\n",
|
||||
" tool_description=\"Translate the user's message to French\",\n",
|
||||
" ),\n",
|
||||
" italian_agent.as_tool(\n",
|
||||
" tool_name=\"translate_to_italian\",\n",
|
||||
" tool_description=\"Translate the user's message to Italian\",\n",
|
||||
" ),\n",
|
||||
" ],\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"synthesizer_agent = Agent(\n",
|
||||
" name=\"synthesizer_agent\",\n",
|
||||
" instructions=\"You inspect translations, correct them if needed, and produce a final concatenated response.\",\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"async def run_agents_as_tools_demo():\n",
|
||||
" msg = \"Hello, how are you today?\"\n",
|
||||
" print(f\"Input: {msg}\")\n",
|
||||
"\n",
|
||||
" with trace(\"Orchestrator evaluator\"):\n",
|
||||
" orchestrator_result = await Runner.run(orchestrator_agent, msg)\n",
|
||||
"\n",
|
||||
" for item in orchestrator_result.new_items:\n",
|
||||
" if isinstance(item, MessageOutputItem):\n",
|
||||
" text = ItemHelpers.text_message_output(item)\n",
|
||||
" if text:\n",
|
||||
" print(f\" - Translation step: {text}\")\n",
|
||||
"\n",
|
||||
" synthesizer_result = await Runner.run(synthesizer_agent, orchestrator_result.to_input_list())\n",
|
||||
"\n",
|
||||
" print(f\"Final response: {synthesizer_result.final_output}\")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Run the demo\n",
|
||||
"await run_agents_as_tools_demo()\n",
|
||||
"\n",
|
||||
"# End the AgentOps trace session\n",
|
||||
"agentops.end_trace(tracer, end_state=\"Success\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "98e54a31",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 2. Deterministic Flow Pattern\n",
|
||||
"\n",
|
||||
"A common tactic is to break down a task into a series of smaller steps. Each task can be performed by an agent, and the output of one agent is used as input to the next. For example, if your task was to generate a story, you could break it down into the following steps:\n",
|
||||
"\n",
|
||||
"1. Generate an outline\n",
|
||||
"2. Generate the story\n",
|
||||
"3. Generate the ending\n",
|
||||
"\n",
|
||||
"Each of these steps can be performed by an agent. The output of one agent is used as input to the next.\n",
|
||||
"\n",
|
||||
"This pattern demonstrates breaking down a complex task into a series of smaller, sequential steps. Each step is performed by an agent, and the output of one agent is used as input to the next."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "3428aa44",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Start the AgentOps trace session\n",
|
||||
"tracer = agentops.start_trace(trace_name=\"Deterministic Flow Pattern\", tags=[\"agentops-example\", \"openai-agents\"])\n",
|
||||
"\n",
|
||||
"# Define the story generation workflow\n",
|
||||
"story_outline_agent = Agent(\n",
|
||||
" name=\"story_outline_agent\",\n",
|
||||
" instructions=\"Generate a very short story outline based on the user's input.\",\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"class OutlineCheckerOutput(BaseModel):\n",
|
||||
" good_quality: bool\n",
|
||||
" is_scifi: bool\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"outline_checker_agent = Agent(\n",
|
||||
" name=\"outline_checker_agent\",\n",
|
||||
" instructions=\"Read the given story outline, and judge the quality. Also, determine if it is a scifi story.\",\n",
|
||||
" output_type=OutlineCheckerOutput,\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"story_agent = Agent(\n",
|
||||
" name=\"story_agent\",\n",
|
||||
" instructions=\"Write a short story based on the given outline.\",\n",
|
||||
" output_type=str,\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"async def run_deterministic_flow_demo():\n",
|
||||
" input_prompt = \"A story about robots exploring space\"\n",
|
||||
" print(f\"Input: {input_prompt}\")\n",
|
||||
"\n",
|
||||
" with trace(\"Deterministic story flow\"):\n",
|
||||
" # 1. Generate an outline\n",
|
||||
" outline_result = await Runner.run(story_outline_agent, input_prompt)\n",
|
||||
" print(\"Outline generated\")\n",
|
||||
"\n",
|
||||
" # 2. Check the outline\n",
|
||||
" outline_checker_result = await Runner.run(outline_checker_agent, outline_result.final_output)\n",
|
||||
"\n",
|
||||
" # 3. Add a gate to stop if the outline is not good quality or not a scifi story\n",
|
||||
" assert isinstance(outline_checker_result.final_output, OutlineCheckerOutput)\n",
|
||||
" if not outline_checker_result.final_output.good_quality:\n",
|
||||
" print(\"Outline is not good quality, so we stop here.\")\n",
|
||||
" return\n",
|
||||
"\n",
|
||||
" if not outline_checker_result.final_output.is_scifi:\n",
|
||||
" print(\"Outline is not a scifi story, so we stop here.\")\n",
|
||||
" return\n",
|
||||
"\n",
|
||||
" print(\"Outline is good quality and a scifi story, so we continue to write the story.\")\n",
|
||||
"\n",
|
||||
" # 4. Write the story\n",
|
||||
" story_result = await Runner.run(story_agent, outline_result.final_output)\n",
|
||||
" print(f\"Story: {story_result.final_output}\")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Run the demo\n",
|
||||
"await run_deterministic_flow_demo()\n",
|
||||
"\n",
|
||||
"# End the AgentOps trace session\n",
|
||||
"agentops.end_trace(tracer, end_state=\"Success\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "d9095df7",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 3. Forcing Tool Use Pattern\n",
|
||||
"\n",
|
||||
"This pattern shows how to force an agent to use a tool using `ModelSettings(tool_choice=\"required\")`. This is useful when you want to ensure the agent always uses a specific tool rather than generating a response directly.\n",
|
||||
"\n",
|
||||
"You can run it with 3 options:\n",
|
||||
"1. `default`: The default behavior, which is to send the tool output to the LLM. In this case, `tool_choice` is not set, because otherwise it would result in an infinite loop - the LLM would call the tool, the tool would run and send the results to the LLM, and that would repeat (because the model is forced to use a tool every time.)\n",
|
||||
"2. `first_tool_result`: The first tool result is used as the final output.\n",
|
||||
"3. `custom`: A custom tool use behavior function is used. The custom function receives all the tool results, and chooses to use the first tool result to generate the final output.\n",
|
||||
"\n",
|
||||
"For this demo, we'll allow the user to choose which tool use behavior to test:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "9a63283cbaf04dbcab1f6479b197f3a8",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Start the AgentOps trace session\n",
|
||||
"tracer = agentops.start_trace(trace_name=\"Forcing Tool Use Pattern\", tags=[\"agentops-example\", \"openai-agents\"])\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Define the weather tool and agent\n",
|
||||
"class Weather(BaseModel):\n",
|
||||
" city: str\n",
|
||||
" temperature_range: str\n",
|
||||
" conditions: str\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"@function_tool\n",
|
||||
"def get_weather(city: str) -> Weather:\n",
|
||||
" print(\"[debug] get_weather called\")\n",
|
||||
" return Weather(city=city, temperature_range=\"14-20C\", conditions=\"Sunny with wind\")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"async def custom_tool_use_behavior(\n",
|
||||
" context: RunContextWrapper[Any], results: list[FunctionToolResult]\n",
|
||||
") -> ToolsToFinalOutputResult:\n",
|
||||
" weather: Weather = results[0].output\n",
|
||||
" return ToolsToFinalOutputResult(is_final_output=True, final_output=f\"{weather.city} is {weather.conditions}.\")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# User can choose which behavior to test\n",
|
||||
"print(\"Choose tool use behavior:\")\n",
|
||||
"print(\"1. default - Send tool output to LLM\")\n",
|
||||
"print(\"2. first_tool - Use first tool result as final output\")\n",
|
||||
"print(\"3. custom - Use custom tool behavior function\")\n",
|
||||
"\n",
|
||||
"choice = input(\"Enter choice (1, 2, or 3): \").strip()\n",
|
||||
"\n",
|
||||
"if choice == \"1\":\n",
|
||||
" tool_use_behavior = \"default\"\n",
|
||||
"elif choice == \"2\":\n",
|
||||
" tool_use_behavior = \"first_tool\"\n",
|
||||
"elif choice == \"3\":\n",
|
||||
" tool_use_behavior = \"custom\"\n",
|
||||
"else:\n",
|
||||
" tool_use_behavior = \"default\"\n",
|
||||
" print(\"Invalid choice, using default\")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"async def run_forcing_tool_use_demo(tool_use_behavior: str):\n",
|
||||
" print(f\"Testing {tool_use_behavior} behavior:\")\n",
|
||||
"\n",
|
||||
" if tool_use_behavior == \"default\":\n",
|
||||
" behavior: Literal[\"run_llm_again\", \"stop_on_first_tool\"] | ToolsToFinalOutputFunction = \"run_llm_again\"\n",
|
||||
" elif tool_use_behavior == \"first_tool\":\n",
|
||||
" behavior = \"stop_on_first_tool\"\n",
|
||||
" elif tool_use_behavior == \"custom\":\n",
|
||||
" behavior = custom_tool_use_behavior\n",
|
||||
"\n",
|
||||
" agent = Agent(\n",
|
||||
" name=\"Weather agent\",\n",
|
||||
" instructions=\"You are a helpful agent.\",\n",
|
||||
" tools=[get_weather],\n",
|
||||
" tool_use_behavior=behavior,\n",
|
||||
" model_settings=ModelSettings(tool_choice=\"required\" if tool_use_behavior != \"default\" else None),\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" result = await Runner.run(agent, input=\"What's the weather in Tokyo?\")\n",
|
||||
" print(f\"Result: {result.final_output}\")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Run the demo\n",
|
||||
"await run_forcing_tool_use_demo(tool_use_behavior)\n",
|
||||
"\n",
|
||||
"# End the AgentOps trace session\n",
|
||||
"agentops.end_trace(tracer, end_state=\"Success\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "eaada293",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 4. Input Guardrails Pattern\n",
|
||||
"\n",
|
||||
"Related to parallelization, you often want to run input guardrails to make sure the inputs to your agents are valid. For example, if you have a customer support agent, you might want to make sure that the user isn't trying to ask for help with a math problem.\n",
|
||||
"\n",
|
||||
"You can definitely do this without any special Agents SDK features by using parallelization, but we support a special guardrail primitive. Guardrails can have a \"tripwire\" - if the tripwire is triggered, the agent execution will immediately stop and a `GuardrailTripwireTriggered` exception will be raised.\n",
|
||||
"\n",
|
||||
"This is really useful for latency: for example, you might have a very fast model that runs the guardrail and a slow model that runs the actual agent. You wouldn't want to wait for the slow model to finish, so guardrails let you quickly reject invalid inputs.\n",
|
||||
"\n",
|
||||
"This pattern demonstrates how to use input guardrails to validate user inputs before they reach the main agent. Guardrails can prevent inappropriate or off-topic requests from being processed."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "0a597f58",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Start the AgentOps trace session\n",
|
||||
"tracer = agentops.start_trace(trace_name=\"Input Guardrails Pattern\", tags=[\"agentops-example\", \"openai-agents\"])\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Define the guardrail\n",
|
||||
"class MathHomeworkOutput(BaseModel):\n",
|
||||
" reasoning: str\n",
|
||||
" is_math_homework: bool\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"guardrail_agent = Agent(\n",
|
||||
" name=\"Guardrail check\",\n",
|
||||
" instructions=\"Check if the user is asking you to do their math homework.\",\n",
|
||||
" output_type=MathHomeworkOutput,\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"@input_guardrail\n",
|
||||
"async def math_guardrail(\n",
|
||||
" context: RunContextWrapper[None], agent: Agent, input: str | list[TResponseInputItem]\n",
|
||||
") -> GuardrailFunctionOutput:\n",
|
||||
" result = await Runner.run(guardrail_agent, input, context=context.context)\n",
|
||||
" final_output = result.final_output_as(MathHomeworkOutput)\n",
|
||||
"\n",
|
||||
" return GuardrailFunctionOutput(\n",
|
||||
" output_info=final_output,\n",
|
||||
" tripwire_triggered=final_output.is_math_homework,\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"async def run_input_guardrails_demo():\n",
|
||||
" agent = Agent(\n",
|
||||
" name=\"Customer support agent\",\n",
|
||||
" instructions=\"You are a customer support agent. You help customers with their questions.\",\n",
|
||||
" input_guardrails=[math_guardrail],\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" # Test with different inputs\n",
|
||||
" test_inputs = [\"What's the capital of California?\", \"Can you help me solve for x: 2x + 5 = 11\"]\n",
|
||||
"\n",
|
||||
" for user_input in test_inputs:\n",
|
||||
" print(f\"Testing input: {user_input}\")\n",
|
||||
" try:\n",
|
||||
" result = await Runner.run(agent, user_input)\n",
|
||||
" print(f\"Response: {result.final_output}\")\n",
|
||||
" except InputGuardrailTripwireTriggered:\n",
|
||||
" message = \"Sorry, I can't help you with your math homework.\"\n",
|
||||
" print(f\"Guardrail triggered: {message}\")\n",
|
||||
" print()\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Run the demo\n",
|
||||
"await run_input_guardrails_demo()\n",
|
||||
"\n",
|
||||
"# End the AgentOps trace session\n",
|
||||
"agentops.end_trace(tracer, end_state=\"Success\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "1aa0b993",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 5. LLM as a Judge Pattern\n",
|
||||
"\n",
|
||||
"LLMs can often improve the quality of their output if given feedback. A common pattern is to generate a response using a model, and then use a second model to provide feedback. You can even use a small model for the initial generation and a larger model for the feedback, to optimize cost.\n",
|
||||
"\n",
|
||||
"For example, you could use an LLM to generate an outline for a story, and then use a second LLM to evaluate the outline and provide feedback. You can then use the feedback to improve the outline, and repeat until the LLM is satisfied with the outline.\n",
|
||||
"\n",
|
||||
"This pattern shows how to use one LLM to evaluate and improve the output of another. The first agent generates content, and the second agent judges the quality and provides feedback for improvement."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "9bbb7b94",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Start the AgentOps trace session\n",
|
||||
"tracer = agentops.start_trace(trace_name=\"LLM as a Judge Pattern\", tags=[\"agentops-example\", \"openai-agents\"])\n",
|
||||
"\n",
|
||||
"# Define the story generation and evaluation agents\n",
|
||||
"story_outline_generator = Agent(\n",
|
||||
" name=\"story_outline_generator\",\n",
|
||||
" instructions=(\n",
|
||||
" \"You generate a very short story outline based on the user's input.\"\n",
|
||||
" \"If there is any feedback provided, use it to improve the outline.\"\n",
|
||||
" ),\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"@dataclass\n",
|
||||
"class EvaluationFeedback:\n",
|
||||
" feedback: str\n",
|
||||
" score: Literal[\"pass\", \"needs_improvement\", \"fail\"]\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"evaluator = Agent[None](\n",
|
||||
" name=\"evaluator\",\n",
|
||||
" instructions=(\n",
|
||||
" \"You evaluate a story outline and decide if it's good enough.\"\n",
|
||||
" \"If it's not good enough, you provide feedback on what needs to be improved.\"\n",
|
||||
" \"Never give it a pass on the first try.\"\n",
|
||||
" ),\n",
|
||||
" output_type=EvaluationFeedback,\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"async def run_llm_as_judge_demo():\n",
|
||||
" msg = \"A story about time travel\"\n",
|
||||
" print(f\"Input: {msg}\")\n",
|
||||
" input_items: list[TResponseInputItem] = [{\"content\": msg, \"role\": \"user\"}]\n",
|
||||
"\n",
|
||||
" latest_outline: str | None = None\n",
|
||||
" iteration = 0\n",
|
||||
" max_iterations = 3 # Limit iterations for demo\n",
|
||||
"\n",
|
||||
" with trace(\"LLM as a judge\"):\n",
|
||||
" while iteration < max_iterations:\n",
|
||||
" iteration += 1\n",
|
||||
" print(f\"Iteration {iteration}:\")\n",
|
||||
"\n",
|
||||
" story_outline_result = await Runner.run(\n",
|
||||
" story_outline_generator,\n",
|
||||
" input_items,\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" input_items = story_outline_result.to_input_list()\n",
|
||||
" latest_outline = ItemHelpers.text_message_outputs(story_outline_result.new_items)\n",
|
||||
" print(\"Story outline generated\")\n",
|
||||
"\n",
|
||||
" evaluator_result = await Runner.run(evaluator, input_items)\n",
|
||||
" result: EvaluationFeedback = evaluator_result.final_output\n",
|
||||
"\n",
|
||||
" print(f\"Evaluator score: {result.score}\")\n",
|
||||
"\n",
|
||||
" if result.score == \"pass\":\n",
|
||||
" print(\"Story outline is good enough, exiting.\")\n",
|
||||
" break\n",
|
||||
"\n",
|
||||
" print(\"Re-running with feedback\")\n",
|
||||
" input_items.append({\"content\": f\"Feedback: {result.feedback}\", \"role\": \"user\"})\n",
|
||||
"\n",
|
||||
" print(f\"Final story outline: {latest_outline}\")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Run the demo\n",
|
||||
"await run_llm_as_judge_demo()\n",
|
||||
"\n",
|
||||
"# End the AgentOps trace session\n",
|
||||
"agentops.end_trace(tracer, end_state=\"Success\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "3e2acc90",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 6. Output Guardrails Pattern\n",
|
||||
"\n",
|
||||
"Related to parallelization, you often want to run output guardrails to make sure the outputs from your agents are valid. Guardrails can have a \"tripwire\" - if the tripwire is triggered, the agent execution will immediately stop and a `GuardrailTripwireTriggered` exception will be raised.\n",
|
||||
"\n",
|
||||
"This is really useful for latency: for example, you might have a very fast model that runs the guardrail and a slow model that runs the actual agent. You wouldn't want to wait for the slow model to finish, so guardrails let you quickly reject invalid outputs.\n",
|
||||
"\n",
|
||||
"This pattern demonstrates how to use output guardrails to validate agent outputs after they are generated. This can help prevent sensitive information from being shared or ensure outputs meet quality standards."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "71ccbecc",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Start the AgentOps trace session\n",
|
||||
"tracer = agentops.start_trace(trace_name=\"Output Guardrails Pattern\", tags=[\"agentops-example\", \"openai-agents\"])\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# The agent's output type\n",
|
||||
"class MessageOutput(BaseModel):\n",
|
||||
" reasoning: str = Field(description=\"Thoughts on how to respond to the user's message\")\n",
|
||||
" response: str = Field(description=\"The response to the user's message\")\n",
|
||||
" user_name: str | None = Field(description=\"The name of the user who sent the message, if known\")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"@output_guardrail\n",
|
||||
"async def sensitive_data_check(\n",
|
||||
" context: RunContextWrapper, agent: Agent, output: MessageOutput\n",
|
||||
") -> GuardrailFunctionOutput:\n",
|
||||
" phone_number_in_response = \"650\" in output.response\n",
|
||||
" phone_number_in_reasoning = \"650\" in output.reasoning\n",
|
||||
"\n",
|
||||
" return GuardrailFunctionOutput(\n",
|
||||
" output_info={\n",
|
||||
" \"phone_number_in_response\": phone_number_in_response,\n",
|
||||
" \"phone_number_in_reasoning\": phone_number_in_reasoning,\n",
|
||||
" },\n",
|
||||
" tripwire_triggered=phone_number_in_response or phone_number_in_reasoning,\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"output_guardrail_agent = Agent(\n",
|
||||
" name=\"Assistant\",\n",
|
||||
" instructions=\"You are a helpful assistant.\",\n",
|
||||
" output_type=MessageOutput,\n",
|
||||
" output_guardrails=[sensitive_data_check],\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"async def run_output_guardrails_demo():\n",
|
||||
" # Test with safe input\n",
|
||||
" print(\"Testing with safe input:\")\n",
|
||||
" try:\n",
|
||||
" result = await Runner.run(output_guardrail_agent, \"What's the capital of California?\")\n",
|
||||
" print(\"Safe message passed\")\n",
|
||||
" print(f\"Response: {result.final_output.response}\")\n",
|
||||
" except OutputGuardrailTripwireTriggered as e:\n",
|
||||
" print(f\"Unexpected guardrail trigger: {e.guardrail_result.output.output_info}\")\n",
|
||||
"\n",
|
||||
" print()\n",
|
||||
" # Test with potentially sensitive input\n",
|
||||
" print(\"Testing with potentially sensitive input:\")\n",
|
||||
" try:\n",
|
||||
" result = await Runner.run(output_guardrail_agent, \"My phone number is 650-123-4567. Where do you think I live?\")\n",
|
||||
" print(f\"Guardrail didn't trip - this is unexpected. Output: {result.final_output.response}\")\n",
|
||||
" except OutputGuardrailTripwireTriggered as e:\n",
|
||||
" print(f\"Guardrail tripped as expected. Info: {e.guardrail_result.output.output_info}\")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Run the demo\n",
|
||||
"await run_output_guardrails_demo()\n",
|
||||
"\n",
|
||||
"# End the AgentOps trace session\n",
|
||||
"agentops.end_trace(tracer, end_state=\"Success\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "0f91df27",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 7. Parallelization Pattern\n",
|
||||
"\n",
|
||||
"Running multiple agents in parallel is a common pattern. This can be useful for both latency (e.g. if you have multiple steps that don't depend on each other) and also for other reasons e.g. generating multiple responses and picking the best one.\n",
|
||||
"\n",
|
||||
"This example runs a translation agent multiple times in parallel, and then picks the best translation.\n",
|
||||
"\n",
|
||||
"This pattern shows how to run multiple agents in parallel to improve latency or generate multiple options to choose from. In this example, we run translation agents multiple times and pick the best result."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "c40082e4",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Start the AgentOps trace session\n",
|
||||
"tracer = agentops.start_trace(trace_name=\"Output Guardrails Pattern\", tags=[\"agentops-example\", \"openai-agents\"])\n",
|
||||
"\n",
|
||||
"# Define agents for parallelization\n",
|
||||
"spanish_translation_agent = Agent(\n",
|
||||
" name=\"spanish_agent\",\n",
|
||||
" instructions=\"You translate the user's message to Spanish\",\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"translation_picker = Agent(\n",
|
||||
" name=\"translation_picker\",\n",
|
||||
" instructions=\"You pick the best Spanish translation from the given options.\",\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"async def run_parallelization_demo():\n",
|
||||
" msg = \"Good morning, I hope you have a wonderful day!\"\n",
|
||||
" print(f\"Input: {msg}\")\n",
|
||||
"\n",
|
||||
" with trace(\"Parallel translation\"):\n",
|
||||
" # Run three translation agents in parallel\n",
|
||||
" res_1, res_2, res_3 = await asyncio.gather(\n",
|
||||
" Runner.run(spanish_translation_agent, msg),\n",
|
||||
" Runner.run(spanish_translation_agent, msg),\n",
|
||||
" Runner.run(spanish_translation_agent, msg),\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" outputs = [\n",
|
||||
" ItemHelpers.text_message_outputs(res_1.new_items),\n",
|
||||
" ItemHelpers.text_message_outputs(res_2.new_items),\n",
|
||||
" ItemHelpers.text_message_outputs(res_3.new_items),\n",
|
||||
" ]\n",
|
||||
"\n",
|
||||
" translations = \"\\n\\n\".join(outputs)\n",
|
||||
" print(f\"\\n\\nTranslations:\\n\\n{translations}\")\n",
|
||||
"\n",
|
||||
" best_translation = await Runner.run(\n",
|
||||
" translation_picker,\n",
|
||||
" f\"Input: {msg}\\n\\nTranslations:\\n{translations}\",\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" print(\"\\n\\n-----\")\n",
|
||||
" print(f\"Best translation: {best_translation.final_output}\")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Run the demo\n",
|
||||
"await run_parallelization_demo()\n",
|
||||
"\n",
|
||||
"# End the AgentOps trace session\n",
|
||||
"agentops.end_trace(tracer, end_state=\"Success\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "9b60d8d2",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 8. Routing Pattern\n",
|
||||
"\n",
|
||||
"In many situations, you have specialized sub-agents that handle specific tasks. You can use handoffs to route the task to the right agent.\n",
|
||||
"\n",
|
||||
"For example, you might have a frontline agent that receives a request, and then hands off to a specialized agent based on the language of the request.\n",
|
||||
"\n",
|
||||
"This pattern demonstrates handoffs and routing between specialized agents. The triage agent receives the first message and hands off to the appropriate agent based on the language of the request."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "698b1251",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Start the AgentOps trace session\n",
|
||||
"tracer = agentops.start_trace(trace_name=\"Routing Pattern\", tags=[\"agentops-example\", \"openai-agents\"])\n",
|
||||
"\n",
|
||||
"# Define language-specific agents\n",
|
||||
"french_routing_agent = Agent(\n",
|
||||
" name=\"french_agent\",\n",
|
||||
" instructions=\"You only speak French\",\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"spanish_routing_agent = Agent(\n",
|
||||
" name=\"spanish_agent\",\n",
|
||||
" instructions=\"You only speak Spanish\",\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"english_routing_agent = Agent(\n",
|
||||
" name=\"english_agent\",\n",
|
||||
" instructions=\"You only speak English\",\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"triage_agent = Agent(\n",
|
||||
" name=\"triage_agent\",\n",
|
||||
" instructions=\"Handoff to the appropriate agent based on the language of the request.\",\n",
|
||||
" handoffs=[french_routing_agent, spanish_routing_agent, english_routing_agent],\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"async def run_routing_demo():\n",
|
||||
" # Create an ID for this conversation\n",
|
||||
" conversation_id = str(uuid.uuid4().hex[:16])\n",
|
||||
"\n",
|
||||
" test_messages = [\"Hello, how can you help me?\", \"Bonjour, comment allez-vous?\", \"Hola, ¿cómo estás?\"]\n",
|
||||
"\n",
|
||||
" for msg in test_messages:\n",
|
||||
" print(f\"\\nTesting message: {msg}\")\n",
|
||||
"\n",
|
||||
" with trace(\"Routing example\", group_id=conversation_id):\n",
|
||||
" inputs = [{\"content\": msg, \"role\": \"user\"}]\n",
|
||||
" result = await Runner.run(triage_agent, input=inputs)\n",
|
||||
" print(f\"Response: {result.final_output}\")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Run the demo\n",
|
||||
"await run_routing_demo()\n",
|
||||
"\n",
|
||||
"# End the AgentOps trace session\n",
|
||||
"agentops.end_trace(tracer, end_state=\"Success\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "6554dbbf",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 9. Streaming Guardrails Pattern\n",
|
||||
"\n",
|
||||
"This example shows how to use guardrails as the model is streaming. Output guardrails run after the final output has been generated; this example runs guardrails every N tokens, allowing for early termination if bad output is detected.\n",
|
||||
"\n",
|
||||
"The expected output is that you'll see a bunch of tokens stream in, then the guardrail will trigger and stop the streaming.\n",
|
||||
"\n",
|
||||
"This pattern shows how to use guardrails during streaming to provide real-time validation. Unlike output guardrails that run after completion, streaming guardrails can interrupt the generation process early."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "11a383f1",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Start the AgentOps trace session\n",
|
||||
"tracer = agentops.start_trace(trace_name=\"Streaming Guardrails Pattern\", tags=[\"agentops-example\", \"openai-agents\"])\n",
|
||||
"\n",
|
||||
"# Define streaming guardrail agent\n",
|
||||
"streaming_agent = Agent(\n",
|
||||
" name=\"Assistant\",\n",
|
||||
" instructions=(\n",
|
||||
" \"You are a helpful assistant. You ALWAYS write long responses, making sure to be verbose and detailed.\"\n",
|
||||
" ),\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"class GuardrailOutput(BaseModel):\n",
|
||||
" reasoning: str = Field(description=\"Reasoning about whether the response could be understood by a ten year old.\")\n",
|
||||
" is_readable_by_ten_year_old: bool = Field(description=\"Whether the response is understandable by a ten year old.\")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"guardrail_streaming_agent = Agent(\n",
|
||||
" name=\"Checker\",\n",
|
||||
" instructions=(\n",
|
||||
" \"You will be given a question and a response. Your goal is to judge whether the response \"\n",
|
||||
" \"is simple enough to be understood by a ten year old.\"\n",
|
||||
" ),\n",
|
||||
" output_type=GuardrailOutput,\n",
|
||||
" model=\"gpt-4o-mini\",\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"async def check_guardrail(text: str) -> GuardrailOutput:\n",
|
||||
" result = await Runner.run(guardrail_streaming_agent, text)\n",
|
||||
" return result.final_output_as(GuardrailOutput)\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"async def run_streaming_guardrails_demo():\n",
|
||||
" question = \"What is a black hole, and how does it behave?\"\n",
|
||||
" print(f\"Question: {question}\")\n",
|
||||
"\n",
|
||||
" result = Runner.run_streamed(streaming_agent, question)\n",
|
||||
" current_text = \"\"\n",
|
||||
"\n",
|
||||
" # We will check the guardrail every N characters\n",
|
||||
" next_guardrail_check_len = 300\n",
|
||||
" guardrail_task = None\n",
|
||||
"\n",
|
||||
" async for event in result.stream_events():\n",
|
||||
" if event.type == \"raw_response_event\" and isinstance(event.data, ResponseTextDeltaEvent):\n",
|
||||
" print(event.data.delta, end=\"\", flush=True)\n",
|
||||
" current_text += event.data.delta\n",
|
||||
"\n",
|
||||
" # Check if it's time to run the guardrail check\n",
|
||||
" if len(current_text) >= next_guardrail_check_len and not guardrail_task:\n",
|
||||
" print(\"\\n[Running guardrail check]\")\n",
|
||||
" guardrail_task = asyncio.create_task(check_guardrail(current_text))\n",
|
||||
" next_guardrail_check_len += 300\n",
|
||||
"\n",
|
||||
" # Every iteration of the loop, check if the guardrail has been triggered\n",
|
||||
" if guardrail_task and guardrail_task.done():\n",
|
||||
" guardrail_result = guardrail_task.result()\n",
|
||||
" if not guardrail_result.is_readable_by_ten_year_old:\n",
|
||||
" print(\"\\n\\n================\\n\\n\")\n",
|
||||
" print(f\"Guardrail triggered. Reasoning:\\n{guardrail_result.reasoning}\")\n",
|
||||
" break\n",
|
||||
" guardrail_task = None\n",
|
||||
"\n",
|
||||
" # Do one final check on the final output\n",
|
||||
" if current_text:\n",
|
||||
" guardrail_result = await check_guardrail(current_text)\n",
|
||||
" if not guardrail_result.is_readable_by_ten_year_old:\n",
|
||||
" print(\"\\n\\n================\\n\\n\")\n",
|
||||
" print(f\"Final guardrail triggered. Reasoning:\\n{guardrail_result.reasoning}\")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Run the demo\n",
|
||||
"await run_streaming_guardrails_demo()\n",
|
||||
"\n",
|
||||
"# End the AgentOps trace session\n",
|
||||
"agentops.end_trace(tracer, end_state=\"Success\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "1f7f8dda",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Conclusion\n",
|
||||
"\n",
|
||||
"This notebook has demonstrated 9 key agent patterns that are commonly used in production AI applications. Each pattern showcases how agents can be orchestrated to perform complex tasks, validate inputs and outputs, and improve overall application performance. \n",
|
||||
"\n",
|
||||
"**AgentOps** provides comprehensive observability for AI agents, automatically tracking all these interactions and providing valuable insights into:\n",
|
||||
"\n",
|
||||
"- **Performance metrics** - Latency, throughput, success rates across all agent patterns\n",
|
||||
"- **Cost analysis** - Token usage, model costs, and optimization opportunities for complex workflows\n",
|
||||
"- **Quality monitoring** - Output quality assessment, guardrail effectiveness, and pattern success rates\n",
|
||||
"- **Debugging support** - Detailed trace visualization, error tracking, and workflow analysis\n",
|
||||
"- **Agent behavior insights** - Understanding how different patterns perform in production environments\n",
|
||||
"- **Workflow optimization** - Identifying bottlenecks and improving agent coordination\n",
|
||||
"\n",
|
||||
"Visit [app.agentops.ai](https://app.agentops.ai) to explore your agent sessions and gain deeper insights into your AI application's behavior."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "agentops (3.11.11)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.11"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,720 @@
|
||||
# # OpenAI Agents Patterns Demonstration
|
||||
#
|
||||
# This notebook demonstrates various common agentic patterns using the Agents SDK and how one can observe them using the AgentOps platform.
|
||||
#
|
||||
# **Note: This notebook was edited using Claude MCP NotebookEdit tool!**
|
||||
#
|
||||
# ## General Flow
|
||||
#
|
||||
# This notebook will walk you through several key agent patterns:
|
||||
#
|
||||
# 1. **Agents as Tools** - Using agents as callable tools within other agents
|
||||
# 2. **Deterministic Flows** - Breaking down tasks into sequential steps
|
||||
# 3. **Forcing Tool Use** - Controlling when and how agents use tools
|
||||
# 4. **Input Guardrails** - Validating inputs before agent execution
|
||||
# 5. **LLM as a Judge** - Using LLMs to evaluate and improve outputs
|
||||
# 6. **Output Guardrails** - Validating outputs after agent execution
|
||||
# 7. **Parallelization** - Running multiple agents concurrently
|
||||
# 8. **Routing** - Directing requests to specialized agents
|
||||
# 9. **Streaming Guardrails** - Real-time validation during streaming
|
||||
#
|
||||
# Each pattern demonstrates how AgentOps automatically tracks and monitors your agent interactions, providing valuable insights into performance, costs, and behavior.
|
||||
# ## 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
|
||||
# ```
|
||||
# # Install required packages
|
||||
# %pip install agentops
|
||||
# %pip install openai-agents
|
||||
# %pip install pydotenv
|
||||
# Required imports - Note: agentops must be imported before agents
|
||||
import asyncio
|
||||
import os
|
||||
import uuid
|
||||
from typing import Any, Literal
|
||||
from dataclasses import dataclass
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
# Import agentops FIRST
|
||||
import agentops
|
||||
|
||||
# Then import agents
|
||||
from agents import (
|
||||
Agent,
|
||||
ItemHelpers,
|
||||
MessageOutputItem,
|
||||
Runner,
|
||||
trace,
|
||||
TResponseInputItem,
|
||||
FunctionToolResult,
|
||||
ModelSettings,
|
||||
RunContextWrapper,
|
||||
ToolsToFinalOutputFunction,
|
||||
ToolsToFinalOutputResult,
|
||||
function_tool,
|
||||
GuardrailFunctionOutput,
|
||||
InputGuardrailTripwireTriggered,
|
||||
OutputGuardrailTripwireTriggered,
|
||||
input_guardrail,
|
||||
output_guardrail,
|
||||
)
|
||||
|
||||
from openai.types.responses import ResponseTextDeltaEvent
|
||||
|
||||
# Load environment variables and set 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
|
||||
agentops.init(
|
||||
auto_start_session=False,
|
||||
trace_name="OpenAI Agents Patterns",
|
||||
tags=["openai-agents", "patterns", "agentops-example"],
|
||||
)
|
||||
tracer = agentops.start_trace(
|
||||
trace_name="OpenAI Agents Patterns",
|
||||
tags=["openai-agents", "patterns", "agentops-example"],
|
||||
)
|
||||
# Note: tracer will be defined in each section's cell for clarity, using the specific tags for that pattern.
|
||||
# ## 1. Agents as Tools Pattern
|
||||
#
|
||||
# The mental model for handoffs is that the new agent "takes over". It sees the previous conversation history, and owns the conversation from that point onwards. However, this is not the only way to use agents. You can also use agents as a tool - the tool agent goes off and runs on its own, and then returns the result to the original agent.
|
||||
#
|
||||
# For example, you could model the translation task above as tool calls instead: rather than handing over to the language-specific agent, you could call the agent as a tool, and then use the result in the next step. This enables things like translating multiple languages at once.
|
||||
#
|
||||
# This pattern demonstrates using agents as callable tools within other agents. The orchestrator agent receives a user message and then picks which specialized agents to call as tools.
|
||||
# Agents as Tools Pattern Example
|
||||
|
||||
# Define specialized translation agents
|
||||
spanish_agent = Agent(
|
||||
name="spanish_agent",
|
||||
instructions="You translate the user's message to Spanish",
|
||||
handoff_description="An english to spanish translator",
|
||||
)
|
||||
|
||||
french_agent = Agent(
|
||||
name="french_agent",
|
||||
instructions="You translate the user's message to French",
|
||||
handoff_description="An english to french translator",
|
||||
)
|
||||
|
||||
italian_agent = Agent(
|
||||
name="italian_agent",
|
||||
instructions="You translate the user's message to Italian",
|
||||
handoff_description="An english to italian translator",
|
||||
)
|
||||
|
||||
# Orchestrator agent that uses other agents as tools
|
||||
orchestrator_agent = Agent(
|
||||
name="orchestrator_agent",
|
||||
instructions=(
|
||||
"You are a translation agent. You use the tools given to you to translate."
|
||||
"If asked for multiple translations, you call the relevant tools in order."
|
||||
"You never translate on your own, you always use the provided tools."
|
||||
),
|
||||
tools=[
|
||||
spanish_agent.as_tool(
|
||||
tool_name="translate_to_spanish",
|
||||
tool_description="Translate the user's message to Spanish",
|
||||
),
|
||||
french_agent.as_tool(
|
||||
tool_name="translate_to_french",
|
||||
tool_description="Translate the user's message to French",
|
||||
),
|
||||
italian_agent.as_tool(
|
||||
tool_name="translate_to_italian",
|
||||
tool_description="Translate the user's message to Italian",
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
synthesizer_agent = Agent(
|
||||
name="synthesizer_agent",
|
||||
instructions="You inspect translations, correct them if needed, and produce a final concatenated response.",
|
||||
)
|
||||
|
||||
|
||||
async def run_agents_as_tools_demo():
|
||||
msg = "Hello, how are you today?"
|
||||
print(f"Input: {msg}")
|
||||
|
||||
with trace("Orchestrator evaluator"):
|
||||
orchestrator_result = await Runner.run(orchestrator_agent, msg)
|
||||
|
||||
for item in orchestrator_result.new_items:
|
||||
if isinstance(item, MessageOutputItem):
|
||||
text = ItemHelpers.text_message_output(item)
|
||||
if text:
|
||||
print(f" - Translation step: {text}")
|
||||
|
||||
synthesizer_result = await Runner.run(synthesizer_agent, orchestrator_result.to_input_list())
|
||||
|
||||
print(f"Final response: {synthesizer_result.final_output}")
|
||||
|
||||
|
||||
# Run the demo
|
||||
# await run_agents_as_tools_demo()
|
||||
# ## 2. Deterministic Flow Pattern
|
||||
#
|
||||
# A common tactic is to break down a task into a series of smaller steps. Each task can be performed by an agent, and the output of one agent is used as input to the next. For example, if your task was to generate a story, you could break it down into the following steps:
|
||||
#
|
||||
# 1. Generate an outline
|
||||
# 2. Generate the story
|
||||
# 3. Generate the ending
|
||||
#
|
||||
# Each of these steps can be performed by an agent. The output of one agent is used as input to the next.
|
||||
#
|
||||
# This pattern demonstrates breaking down a complex task into a series of smaller, sequential steps. Each step is performed by an agent, and the output of one agent is used as input to the next.
|
||||
# Deterministic Flow Pattern Example
|
||||
|
||||
# Define the story generation workflow
|
||||
story_outline_agent = Agent(
|
||||
name="story_outline_agent",
|
||||
instructions="Generate a very short story outline based on the user's input.",
|
||||
)
|
||||
|
||||
|
||||
class OutlineCheckerOutput(BaseModel):
|
||||
good_quality: bool
|
||||
is_scifi: bool
|
||||
|
||||
|
||||
outline_checker_agent = Agent(
|
||||
name="outline_checker_agent",
|
||||
instructions="Read the given story outline, and judge the quality. Also, determine if it is a scifi story.",
|
||||
output_type=OutlineCheckerOutput,
|
||||
)
|
||||
|
||||
story_agent = Agent(
|
||||
name="story_agent",
|
||||
instructions="Write a short story based on the given outline.",
|
||||
output_type=str,
|
||||
)
|
||||
|
||||
|
||||
async def run_deterministic_flow_demo():
|
||||
input_prompt = "A story about robots exploring space"
|
||||
print(f"Input: {input_prompt}")
|
||||
|
||||
with trace("Deterministic story flow"):
|
||||
# 1. Generate an outline
|
||||
outline_result = await Runner.run(story_outline_agent, input_prompt)
|
||||
print("Outline generated")
|
||||
|
||||
# 2. Check the outline
|
||||
outline_checker_result = await Runner.run(outline_checker_agent, outline_result.final_output)
|
||||
|
||||
# 3. Add a gate to stop if the outline is not good quality or not a scifi story
|
||||
assert isinstance(outline_checker_result.final_output, OutlineCheckerOutput)
|
||||
if not outline_checker_result.final_output.good_quality:
|
||||
print("Outline is not good quality, so we stop here.")
|
||||
return
|
||||
|
||||
if not outline_checker_result.final_output.is_scifi:
|
||||
print("Outline is not a scifi story, so we stop here.")
|
||||
return
|
||||
|
||||
print("Outline is good quality and a scifi story, so we continue to write the story.")
|
||||
|
||||
# 4. Write the story
|
||||
story_result = await Runner.run(story_agent, outline_result.final_output)
|
||||
print(f"Story: {story_result.final_output}")
|
||||
|
||||
|
||||
# Run the demo
|
||||
# await run_deterministic_flow_demo()
|
||||
# ## 3. Forcing Tool Use Pattern
|
||||
#
|
||||
# This pattern shows how to force an agent to use a tool using `ModelSettings(tool_choice=\"required\")`. This is useful when you want to ensure the agent always uses a specific tool rather than generating a response directly.
|
||||
#
|
||||
# You can run it with 3 options:
|
||||
# 1. `default`: The default behavior, which is to send the tool output to the LLM. In this case, `tool_choice` is not set, because otherwise it would result in an infinite loop - the LLM would call the tool, the tool would run and send the results to the LLM, and that would repeat (because the model is forced to use a tool every time.)
|
||||
# 2. `first_tool_result`: The first tool result is used as the final output.
|
||||
# 3. `custom`: A custom tool use behavior function is used. The custom function receives all the tool results, and chooses to use the first tool result to generate the final output.
|
||||
#
|
||||
# For this demo, we'll allow the user to choose which tool use behavior to test:
|
||||
# Forcing Tool Use Pattern Example
|
||||
|
||||
|
||||
# Define the weather tool and agent
|
||||
class Weather(BaseModel):
|
||||
city: str
|
||||
temperature_range: str
|
||||
conditions: str
|
||||
|
||||
|
||||
@function_tool
|
||||
def get_weather(city: str) -> Weather:
|
||||
print("[debug] get_weather called")
|
||||
return Weather(city=city, temperature_range="14-20C", conditions="Sunny with wind")
|
||||
|
||||
|
||||
async def custom_tool_use_behavior(
|
||||
context: RunContextWrapper[Any], results: list[FunctionToolResult]
|
||||
) -> ToolsToFinalOutputResult:
|
||||
weather: Weather = results[0].output
|
||||
return ToolsToFinalOutputResult(is_final_output=True, final_output=f"{weather.city} is {weather.conditions}.")
|
||||
|
||||
|
||||
async def run_forcing_tool_use_demo(tool_use_behavior: str):
|
||||
print(f"Testing {tool_use_behavior} behavior:")
|
||||
|
||||
if tool_use_behavior == "default":
|
||||
behavior: Literal["run_llm_again", "stop_on_first_tool"] | ToolsToFinalOutputFunction = "run_llm_again"
|
||||
elif tool_use_behavior == "first_tool":
|
||||
behavior = "stop_on_first_tool"
|
||||
elif tool_use_behavior == "custom":
|
||||
behavior = custom_tool_use_behavior
|
||||
|
||||
agent = Agent(
|
||||
name="Weather agent",
|
||||
instructions="You are a helpful agent.",
|
||||
tools=[get_weather],
|
||||
tool_use_behavior=behavior,
|
||||
model_settings=ModelSettings(tool_choice="required" if tool_use_behavior != "default" else None),
|
||||
)
|
||||
|
||||
result = await Runner.run(agent, input="What's the weather in Tokyo?")
|
||||
print(f"Result: {result.final_output}")
|
||||
|
||||
|
||||
async def run_all_forcing_tool_use_demos():
|
||||
"""Run all three tool use behavior demos automatically"""
|
||||
print("Running all tool use behavior demos:")
|
||||
print("1. default - Send tool output to LLM")
|
||||
print("2. first_tool - Use first tool result as final output")
|
||||
print("3. custom - Use custom tool behavior function")
|
||||
print()
|
||||
|
||||
# Test all three behaviors
|
||||
for behavior in ["default", "first_tool", "custom"]:
|
||||
await run_forcing_tool_use_demo(behavior)
|
||||
print("-" * 50)
|
||||
|
||||
|
||||
# Run the demo
|
||||
# await run_all_forcing_tool_use_demos()
|
||||
# ## 4. Input Guardrails Pattern
|
||||
#
|
||||
# Related to parallelization, you often want to run input guardrails to make sure the inputs to your agents are valid. For example, if you have a customer support agent, you might want to make sure that the user isn't trying to ask for help with a math problem.
|
||||
#
|
||||
# You can definitely do this without any special Agents SDK features by using parallelization, but we support a special guardrail primitive. Guardrails can have a \"tripwire\" - if the tripwire is triggered, the agent execution will immediately stop and a `GuardrailTripwireTriggered` exception will be raised.
|
||||
#
|
||||
# This is really useful for latency: for example, you might have a very fast model that runs the guardrail and a slow model that runs the actual agent. You wouldn't want to wait for the slow model to finish, so guardrails let you quickly reject invalid inputs.
|
||||
#
|
||||
# This pattern demonstrates how to use input guardrails to validate user inputs before they reach the main agent. Guardrails can prevent inappropriate or off-topic requests from being processed.
|
||||
# Input Guardrails Pattern Example
|
||||
|
||||
|
||||
# Define the guardrail
|
||||
class MathHomeworkOutput(BaseModel):
|
||||
reasoning: str
|
||||
is_math_homework: bool
|
||||
|
||||
|
||||
guardrail_agent = Agent(
|
||||
name="Guardrail check",
|
||||
instructions="Check if the user is asking you to do their math homework.",
|
||||
output_type=MathHomeworkOutput,
|
||||
)
|
||||
|
||||
|
||||
@input_guardrail
|
||||
async def math_guardrail(
|
||||
context: RunContextWrapper[None], agent: Agent, input: str | list[TResponseInputItem]
|
||||
) -> GuardrailFunctionOutput:
|
||||
result = await Runner.run(guardrail_agent, input, context=context.context)
|
||||
final_output = result.final_output_as(MathHomeworkOutput)
|
||||
|
||||
return GuardrailFunctionOutput(
|
||||
output_info=final_output,
|
||||
tripwire_triggered=final_output.is_math_homework,
|
||||
)
|
||||
|
||||
|
||||
async def run_input_guardrails_demo():
|
||||
agent = Agent(
|
||||
name="Customer support agent",
|
||||
instructions="You are a customer support agent. You help customers with their questions.",
|
||||
input_guardrails=[math_guardrail],
|
||||
)
|
||||
|
||||
# Test with different inputs
|
||||
test_inputs = ["What's the capital of California?", "Can you help me solve for x: 2x + 5 = 11"]
|
||||
|
||||
for user_input in test_inputs:
|
||||
print(f"Testing input: {user_input}")
|
||||
try:
|
||||
result = await Runner.run(agent, user_input)
|
||||
print(f"Response: {result.final_output}")
|
||||
except InputGuardrailTripwireTriggered:
|
||||
message = "Sorry, I can't help you with your math homework."
|
||||
print(f"Guardrail triggered: {message}")
|
||||
print()
|
||||
|
||||
|
||||
# Run the demo
|
||||
# await run_input_guardrails_demo()
|
||||
# ## 5. LLM as a Judge Pattern
|
||||
#
|
||||
# LLMs can often improve the quality of their output if given feedback. A common pattern is to generate a response using a model, and then use a second model to provide feedback. You can even use a small model for the initial generation and a larger model for the feedback, to optimize cost.
|
||||
#
|
||||
# For example, you could use an LLM to generate an outline for a story, and then use a second LLM to evaluate the outline and provide feedback. You can then use the feedback to improve the outline, and repeat until the LLM is satisfied with the outline.
|
||||
#
|
||||
# This pattern shows how to use one LLM to evaluate and improve the output of another. The first agent generates content, and the second agent judges the quality and provides feedback for improvement.
|
||||
# LLM as a Judge Pattern Example
|
||||
|
||||
# Define the story generation and evaluation agents
|
||||
story_outline_generator = Agent(
|
||||
name="story_outline_generator",
|
||||
instructions=(
|
||||
"You generate a very short story outline based on the user's input."
|
||||
"If there is any feedback provided, use it to improve the outline."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class EvaluationFeedback:
|
||||
feedback: str
|
||||
score: Literal["pass", "needs_improvement", "fail"]
|
||||
|
||||
|
||||
evaluator = Agent[None](
|
||||
name="evaluator",
|
||||
instructions=(
|
||||
"You evaluate a story outline and decide if it's good enough."
|
||||
"If it's not good enough, you provide feedback on what needs to be improved."
|
||||
"Never give it a pass on the first try."
|
||||
),
|
||||
output_type=EvaluationFeedback,
|
||||
)
|
||||
|
||||
|
||||
async def run_llm_as_judge_demo():
|
||||
msg = "A story about time travel"
|
||||
print(f"Input: {msg}")
|
||||
input_items: list[TResponseInputItem] = [{"content": msg, "role": "user"}]
|
||||
|
||||
latest_outline: str | None = None
|
||||
iteration = 0
|
||||
max_iterations = 3 # Limit iterations for demo
|
||||
|
||||
with trace("LLM as a judge"):
|
||||
while iteration < max_iterations:
|
||||
iteration += 1
|
||||
print(f"Iteration {iteration}:")
|
||||
|
||||
story_outline_result = await Runner.run(
|
||||
story_outline_generator,
|
||||
input_items,
|
||||
)
|
||||
|
||||
input_items = story_outline_result.to_input_list()
|
||||
latest_outline = ItemHelpers.text_message_outputs(story_outline_result.new_items)
|
||||
print("Story outline generated")
|
||||
|
||||
evaluator_result = await Runner.run(evaluator, input_items)
|
||||
result: EvaluationFeedback = evaluator_result.final_output
|
||||
|
||||
print(f"Evaluator score: {result.score}")
|
||||
|
||||
if result.score == "pass":
|
||||
print("Story outline is good enough, exiting.")
|
||||
break
|
||||
|
||||
print("Re-running with feedback")
|
||||
input_items.append({"content": f"Feedback: {result.feedback}", "role": "user"})
|
||||
|
||||
print(f"Final story outline: {latest_outline}")
|
||||
|
||||
|
||||
# Run the demo
|
||||
# await run_llm_as_judge_demo()
|
||||
# ## 6. Output Guardrails Pattern
|
||||
#
|
||||
# Related to parallelization, you often want to run output guardrails to make sure the outputs from your agents are valid. Guardrails can have a \"tripwire\" - if the tripwire is triggered, the agent execution will immediately stop and a `GuardrailTripwireTriggered` exception will be raised.
|
||||
#
|
||||
# This is really useful for latency: for example, you might have a very fast model that runs the guardrail and a slow model that runs the actual agent. You wouldn't want to wait for the slow model to finish, so guardrails let you quickly reject invalid outputs.
|
||||
#
|
||||
# This pattern demonstrates how to use output guardrails to validate agent outputs after they are generated. This can help prevent sensitive information from being shared or ensure outputs meet quality standards.
|
||||
# Output Guardrails Pattern Example
|
||||
|
||||
|
||||
# The agent's output type
|
||||
class MessageOutput(BaseModel):
|
||||
reasoning: str = Field(description="Thoughts on how to respond to the user's message")
|
||||
response: str = Field(description="The response to the user's message")
|
||||
user_name: str | None = Field(description="The name of the user who sent the message, if known")
|
||||
|
||||
|
||||
@output_guardrail
|
||||
async def sensitive_data_check(
|
||||
context: RunContextWrapper, agent: Agent, output: MessageOutput
|
||||
) -> GuardrailFunctionOutput:
|
||||
phone_number_in_response = "650" in output.response
|
||||
phone_number_in_reasoning = "650" in output.reasoning
|
||||
|
||||
return GuardrailFunctionOutput(
|
||||
output_info={
|
||||
"phone_number_in_response": phone_number_in_response,
|
||||
"phone_number_in_reasoning": phone_number_in_reasoning,
|
||||
},
|
||||
tripwire_triggered=phone_number_in_response or phone_number_in_reasoning,
|
||||
)
|
||||
|
||||
|
||||
output_guardrail_agent = Agent(
|
||||
name="Assistant",
|
||||
instructions="You are a helpful assistant.",
|
||||
output_type=MessageOutput,
|
||||
output_guardrails=[sensitive_data_check],
|
||||
)
|
||||
|
||||
|
||||
async def run_output_guardrails_demo():
|
||||
# Test with safe input
|
||||
print("Testing with safe input:")
|
||||
try:
|
||||
result = await Runner.run(output_guardrail_agent, "What's the capital of California?")
|
||||
print("Safe message passed")
|
||||
print(f"Response: {result.final_output.response}")
|
||||
except OutputGuardrailTripwireTriggered as e:
|
||||
print(f"Unexpected guardrail trigger: {e.guardrail_result.output.output_info}")
|
||||
|
||||
print()
|
||||
# Test with potentially sensitive input
|
||||
print("Testing with potentially sensitive input:")
|
||||
try:
|
||||
result = await Runner.run(output_guardrail_agent, "My phone number is 650-123-4567. Where do you think I live?")
|
||||
print(f"Guardrail didn't trip - this is unexpected. Output: {result.final_output.response}")
|
||||
except OutputGuardrailTripwireTriggered as e:
|
||||
print(f"Guardrail tripped as expected. Info: {e.guardrail_result.output.output_info}")
|
||||
|
||||
|
||||
# Run the demo
|
||||
# await run_output_guardrails_demo()
|
||||
# ## 7. Parallelization Pattern
|
||||
#
|
||||
# Running multiple agents in parallel is a common pattern. This can be useful for both latency (e.g. if you have multiple steps that don't depend on each other) and also for other reasons e.g. generating multiple responses and picking the best one.
|
||||
#
|
||||
# This example runs a translation agent multiple times in parallel, and then picks the best translation.
|
||||
#
|
||||
# This pattern shows how to run multiple agents in parallel to improve latency or generate multiple options to choose from. In this example, we run translation agents multiple times and pick the best result.
|
||||
# Parallelization Pattern Example
|
||||
|
||||
# Define agents for parallelization
|
||||
spanish_translation_agent = Agent(
|
||||
name="spanish_agent",
|
||||
instructions="You translate the user's message to Spanish",
|
||||
)
|
||||
|
||||
translation_picker = Agent(
|
||||
name="translation_picker",
|
||||
instructions="You pick the best Spanish translation from the given options.",
|
||||
)
|
||||
|
||||
|
||||
async def run_parallelization_demo():
|
||||
msg = "Good morning, I hope you have a wonderful day!"
|
||||
print(f"Input: {msg}")
|
||||
|
||||
with trace("Parallel translation"):
|
||||
# Run three translation agents in parallel
|
||||
res_1, res_2, res_3 = await asyncio.gather(
|
||||
Runner.run(spanish_translation_agent, msg),
|
||||
Runner.run(spanish_translation_agent, msg),
|
||||
Runner.run(spanish_translation_agent, msg),
|
||||
)
|
||||
|
||||
outputs = [
|
||||
ItemHelpers.text_message_outputs(res_1.new_items),
|
||||
ItemHelpers.text_message_outputs(res_2.new_items),
|
||||
ItemHelpers.text_message_outputs(res_3.new_items),
|
||||
]
|
||||
|
||||
translations = "\\n\\n".join(outputs)
|
||||
print(f"\\n\\nTranslations:\\n\\n{translations}")
|
||||
|
||||
best_translation = await Runner.run(
|
||||
translation_picker,
|
||||
f"Input: {msg}\\n\\nTranslations:\\n{translations}",
|
||||
)
|
||||
|
||||
print("\\n\\n-----")
|
||||
print(f"Best translation: {best_translation.final_output}")
|
||||
|
||||
|
||||
# Run the demo
|
||||
# await run_parallelization_demo()
|
||||
# ## 8. Routing Pattern
|
||||
#
|
||||
# In many situations, you have specialized sub-agents that handle specific tasks. You can use handoffs to route the task to the right agent.
|
||||
#
|
||||
# For example, you might have a frontline agent that receives a request, and then hands off to a specialized agent based on the language of the request.
|
||||
#
|
||||
# This pattern demonstrates handoffs and routing between specialized agents. The triage agent receives the first message and hands off to the appropriate agent based on the language of the request.
|
||||
# Routing Pattern Example
|
||||
|
||||
# Define language-specific agents
|
||||
french_routing_agent = Agent(
|
||||
name="french_agent",
|
||||
instructions="You only speak French",
|
||||
)
|
||||
|
||||
spanish_routing_agent = Agent(
|
||||
name="spanish_agent",
|
||||
instructions="You only speak Spanish",
|
||||
)
|
||||
|
||||
english_routing_agent = Agent(
|
||||
name="english_agent",
|
||||
instructions="You only speak English",
|
||||
)
|
||||
|
||||
triage_agent = Agent(
|
||||
name="triage_agent",
|
||||
instructions="Handoff to the appropriate agent based on the language of the request.",
|
||||
handoffs=[french_routing_agent, spanish_routing_agent, english_routing_agent],
|
||||
)
|
||||
|
||||
|
||||
async def run_routing_demo():
|
||||
# Create an ID for this conversation
|
||||
conversation_id = str(uuid.uuid4().hex[:16])
|
||||
|
||||
test_messages = ["Hello, how can you help me?", "Bonjour, comment allez-vous?", "Hola, ¿cómo estás?"]
|
||||
|
||||
for msg in test_messages:
|
||||
print(f"\nTesting message: {msg}")
|
||||
|
||||
with trace("Routing example", group_id=conversation_id):
|
||||
inputs = [{"content": msg, "role": "user"}]
|
||||
result = await Runner.run(triage_agent, input=inputs)
|
||||
print(f"Response: {result.final_output}")
|
||||
|
||||
|
||||
# Run the demo
|
||||
# await run_routing_demo()
|
||||
# ## 9. Streaming Guardrails Pattern
|
||||
#
|
||||
# This example shows how to use guardrails as the model is streaming. Output guardrails run after the final output has been generated; this example runs guardrails every N tokens, allowing for early termination if bad output is detected.
|
||||
#
|
||||
# The expected output is that you'll see a bunch of tokens stream in, then the guardrail will trigger and stop the streaming.
|
||||
#
|
||||
# This pattern shows how to use guardrails during streaming to provide real-time validation. Unlike output guardrails that run after completion, streaming guardrails can interrupt the generation process early.
|
||||
# Streaming Guardrails Pattern Example
|
||||
|
||||
# Define streaming guardrail agent
|
||||
streaming_agent = Agent(
|
||||
name="Assistant",
|
||||
instructions=(
|
||||
"You are a helpful assistant. You ALWAYS write long responses, making sure to be verbose and detailed."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class GuardrailOutput(BaseModel):
|
||||
reasoning: str = Field(description="Reasoning about whether the response could be understood by a ten year old.")
|
||||
is_readable_by_ten_year_old: bool = Field(description="Whether the response is understandable by a ten year old.")
|
||||
|
||||
|
||||
guardrail_streaming_agent = Agent(
|
||||
name="Checker",
|
||||
instructions=(
|
||||
"You will be given a question and a response. Your goal is to judge whether the response "
|
||||
"is simple enough to be understood by a ten year old."
|
||||
),
|
||||
output_type=GuardrailOutput,
|
||||
model="gpt-4o-mini",
|
||||
)
|
||||
|
||||
|
||||
async def check_guardrail(text: str) -> GuardrailOutput:
|
||||
result = await Runner.run(guardrail_streaming_agent, text)
|
||||
return result.final_output_as(GuardrailOutput)
|
||||
|
||||
|
||||
async def run_streaming_guardrails_demo():
|
||||
question = "What is a black hole, and how does it behave?"
|
||||
print(f"Question: {question}")
|
||||
|
||||
result = Runner.run_streamed(streaming_agent, question)
|
||||
current_text = ""
|
||||
|
||||
# We will check the guardrail every N characters
|
||||
next_guardrail_check_len = 300
|
||||
guardrail_task = None
|
||||
|
||||
async for event in result.stream_events():
|
||||
if event.type == "raw_response_event" and isinstance(event.data, ResponseTextDeltaEvent):
|
||||
print(event.data.delta, end="", flush=True)
|
||||
current_text += event.data.delta
|
||||
|
||||
# Check if it's time to run the guardrail check
|
||||
if len(current_text) >= next_guardrail_check_len and not guardrail_task:
|
||||
print("\\n[Running guardrail check]")
|
||||
guardrail_task = asyncio.create_task(check_guardrail(current_text))
|
||||
next_guardrail_check_len += 300
|
||||
|
||||
# Every iteration of the loop, check if the guardrail has been triggered
|
||||
if guardrail_task and guardrail_task.done():
|
||||
guardrail_result = guardrail_task.result()
|
||||
if not guardrail_result.is_readable_by_ten_year_old:
|
||||
print("\\n\\n================\\n\\n")
|
||||
print(f"Guardrail triggered. Reasoning:\\n{guardrail_result.reasoning}")
|
||||
break
|
||||
guardrail_task = None
|
||||
|
||||
# Do one final check on the final output
|
||||
if current_text:
|
||||
guardrail_result = await check_guardrail(current_text)
|
||||
if not guardrail_result.is_readable_by_ten_year_old:
|
||||
print("\\n\\n================\\n\\n")
|
||||
print(f"Final guardrail triggered. Reasoning:\\n{guardrail_result.reasoning}")
|
||||
|
||||
|
||||
# Run the demo
|
||||
if __name__ == "__main__":
|
||||
# Run the streaming guardrails demo
|
||||
asyncio.run(run_streaming_guardrails_demo())
|
||||
agentops.end_trace(tracer, end_state="Success")
|
||||
|
||||
# Streaming Guardrails Pattern Example Complete
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
agentops.validate_trace_spans(trace_context=tracer)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
|
||||
# ## Conclusion
|
||||
#
|
||||
# This notebook has demonstrated 9 key agent patterns that are commonly used in production AI applications. Each pattern showcases how agents can be orchestrated to perform complex tasks, validate inputs and outputs, and improve overall application performance.
|
||||
#
|
||||
# **AgentOps** provides comprehensive observability for AI agents, automatically tracking all these interactions and providing valuable insights into:
|
||||
#
|
||||
# - **Performance metrics** - Latency, throughput, success rates across all agent patterns
|
||||
# - **Cost analysis** - Token usage, model costs, and optimization opportunities for complex workflows
|
||||
# - **Quality monitoring** - Output quality assessment, guardrail effectiveness, and pattern success rates
|
||||
# - **Debugging support** - Detailed trace visualization, error tracking, and workflow analysis
|
||||
# - **Agent behavior insights** - Understanding how different patterns perform in production environments
|
||||
# - **Workflow optimization** - Identifying bottlenecks and improving agent coordination
|
||||
#
|
||||
# Visit [app.agentops.ai](https://app.agentops.ai) to explore your agent sessions and gain deeper insights into your AI application's behavior.
|
||||
@@ -0,0 +1,387 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# OpenAI Agents Tools Demonstration\n",
|
||||
"\n",
|
||||
"This notebook demonstrates various tools available in the Agents SDK and how AgentOps provides observability for tool usage.\n",
|
||||
"\n",
|
||||
"## General Flow\n",
|
||||
"\n",
|
||||
"This notebook will walk you through several key tools:\n",
|
||||
"\n",
|
||||
"1. **Code Interpreter Tool** - Execute Python code and perform mathematical calculations\n",
|
||||
"2. **File Search Tool** - Search through vector stores and documents\n",
|
||||
"3. **Image Generation Tool** - Generate images from text descriptions\n",
|
||||
"4. **Web Search Tool** - Search the web for current information\n",
|
||||
"\n",
|
||||
"Each tool demonstrates how AgentOps automatically tracks tool usage, providing insights into performance, costs, and effectiveness."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Prerequisites\n",
|
||||
"\n",
|
||||
"Before running this notebook, you'll need:\n",
|
||||
"\n",
|
||||
"1. **AgentOps Account**: Create a free account at [app.agentops.ai](https://app.agentops.ai)\n",
|
||||
"2. **AgentOps API Key**: Obtain your API key from your AgentOps dashboard\n",
|
||||
"3. **OpenAI API Key**: Get your API key from [platform.openai.com](https://platform.openai.com)\n",
|
||||
"4. **Vector Store ID**: Configure it from [platform.openai.com](https://platform.openai.com)."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Install required packages\n",
|
||||
"%pip install -q agentops\n",
|
||||
"%pip install -q openai-agents\n",
|
||||
"%pip install -q pydotenv"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Set the API keys for your AgentOps and OpenAI accounts.\n",
|
||||
"import os\n",
|
||||
"from dotenv import load_dotenv\n",
|
||||
"\n",
|
||||
"load_dotenv()\n",
|
||||
"\n",
|
||||
"os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\", \"your_api_key_here\")\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\", \"your_openai_api_key_here\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import agentops\n",
|
||||
"\n",
|
||||
"agentops.init(auto_start_session=False, tags=[\"agentops-example\"])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import base64\n",
|
||||
"import os\n",
|
||||
"import subprocess\n",
|
||||
"import sys\n",
|
||||
"import tempfile\n",
|
||||
"\n",
|
||||
"from agents import (\n",
|
||||
" Agent,\n",
|
||||
" CodeInterpreterTool,\n",
|
||||
" FileSearchTool,\n",
|
||||
" ImageGenerationTool,\n",
|
||||
" Runner,\n",
|
||||
" WebSearchTool,\n",
|
||||
" trace,\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 1. Code Interpreter Tool\n",
|
||||
"\n",
|
||||
"The Code Interpreter Tool allows agents to execute Python code in a secure environment. This is particularly useful for mathematical calculations, data analysis, and generating visualizations.\n",
|
||||
"\n",
|
||||
"**Key Features:**\n",
|
||||
"- Execute Python code safely\n",
|
||||
"- Perform complex mathematical calculations\n",
|
||||
"- Generate plots and visualizations\n",
|
||||
"- Handle data processing tasks"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Start the AgentOps trace session\n",
|
||||
"tracer = agentops.start_trace(\n",
|
||||
" trace_name=\"Code Interpreter Tool Example\", tags=[\"tools-demo\", \"openai-agents\", \"agentops-example\"]\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"async def run_code_interpreter_demo():\n",
|
||||
" agent = Agent(\n",
|
||||
" name=\"Code interpreter\",\n",
|
||||
" instructions=\"You love doing math.\",\n",
|
||||
" tools=[\n",
|
||||
" CodeInterpreterTool(\n",
|
||||
" tool_config={\"type\": \"code_interpreter\", \"container\": {\"type\": \"auto\"}},\n",
|
||||
" )\n",
|
||||
" ],\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" with trace(\"Code interpreter example\"):\n",
|
||||
" print(\"Solving math problem...\")\n",
|
||||
" result = Runner.run_streamed(agent, \"What is the square root of 273 * 312821 plus 1782?\")\n",
|
||||
" async for event in result.stream_events():\n",
|
||||
" if (\n",
|
||||
" event.type == \"run_item_stream_event\"\n",
|
||||
" and event.item.type == \"tool_call_item\"\n",
|
||||
" and event.item.raw_item.type == \"code_interpreter_call\"\n",
|
||||
" ):\n",
|
||||
" print(f\"Code interpreter code:\\n```\\n{event.item.raw_item.code}\\n```\\n\")\n",
|
||||
" elif event.type == \"run_item_stream_event\":\n",
|
||||
" print(f\"Other event: {event.item.type}\")\n",
|
||||
"\n",
|
||||
" print(f\"Final output: {result.final_output}\")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Run the demo\n",
|
||||
"await run_code_interpreter_demo()\n",
|
||||
"\n",
|
||||
"# End the AgentOps trace session\n",
|
||||
"agentops.end_trace(tracer, end_state=\"Success\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 2. File Search Tool\n",
|
||||
"\n",
|
||||
"The File Search Tool allows agents to search through vector stores and document collections to find relevant information.\n",
|
||||
"\n",
|
||||
"**Key Features:**\n",
|
||||
"- Search through vector stores\n",
|
||||
"- Retrieve relevant documents\n",
|
||||
"- Support for semantic search\n",
|
||||
"- Configurable result limits\n",
|
||||
"\n",
|
||||
"**Note:** This example requires a pre-configured vector store ID."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Start the AgentOps trace session\n",
|
||||
"tracer = agentops.start_trace(\n",
|
||||
" trace_name=\"File Search Tool Example\", tags=[\"tools-demo\", \"openai-agents\", \"agentops-example\"]\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"async def run_file_search_demo():\n",
|
||||
" # Note: You'll need to replace this with your actual vector store ID\n",
|
||||
" vector_store_id = \"vs_67bf88953f748191be42b462090e53e7\"\n",
|
||||
"\n",
|
||||
" agent = Agent(\n",
|
||||
" name=\"File searcher\",\n",
|
||||
" instructions=\"You are a helpful agent.\",\n",
|
||||
" tools=[\n",
|
||||
" FileSearchTool(\n",
|
||||
" max_num_results=3,\n",
|
||||
" vector_store_ids=[vector_store_id],\n",
|
||||
" include_search_results=True,\n",
|
||||
" )\n",
|
||||
" ],\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" with trace(\"File search example\"):\n",
|
||||
" try:\n",
|
||||
" result = await Runner.run(agent, \"Be concise, and tell me 1 sentence about Arrakis I might not know.\")\n",
|
||||
" print(result.final_output)\n",
|
||||
" print(\"\\n\".join([str(out) for out in result.new_items]))\n",
|
||||
" except Exception as e:\n",
|
||||
" print(f\"File search demo requires a valid vector store ID. Error: {e}\")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Run the demo\n",
|
||||
"await run_file_search_demo()\n",
|
||||
"\n",
|
||||
"# End the AgentOps trace session\n",
|
||||
"agentops.end_trace(tracer, end_state=\"Success\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 3. Image Generation Tool\n",
|
||||
"\n",
|
||||
"The Image Generation Tool enables agents to create images from text descriptions using AI image generation models.\n",
|
||||
"\n",
|
||||
"**Key Features:**\n",
|
||||
"- Generate images from text prompts\n",
|
||||
"- Configurable quality settings\n",
|
||||
"- Support for various image styles\n",
|
||||
"- Automatic image saving and display"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Start the AgentOps trace session\n",
|
||||
"tracer = agentops.start_trace(\n",
|
||||
" trace_name=\"Image Generation Tool Example\", tags=[\"tools-demo\", \"openai-agents\", \"agentops-example\"]\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"def open_file(path: str) -> None:\n",
|
||||
" if sys.platform.startswith(\"darwin\"):\n",
|
||||
" subprocess.run([\"open\", path], check=False) # macOS\n",
|
||||
" elif os.name == \"nt\": # Windows\n",
|
||||
" os.startfile(path) # type: ignore\n",
|
||||
" elif os.name == \"posix\":\n",
|
||||
" subprocess.run([\"xdg-open\", path], check=False) # Linux/Unix\n",
|
||||
" else:\n",
|
||||
" print(f\"Don't know how to open files on this platform: {sys.platform}\")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"async def run_image_generation_demo():\n",
|
||||
" agent = Agent(\n",
|
||||
" name=\"Image generator\",\n",
|
||||
" instructions=\"You are a helpful agent.\",\n",
|
||||
" tools=[\n",
|
||||
" ImageGenerationTool(\n",
|
||||
" tool_config={\"type\": \"image_generation\", \"quality\": \"low\"},\n",
|
||||
" )\n",
|
||||
" ],\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" with trace(\"Image generation example\"):\n",
|
||||
" print(\"Generating image, this may take a while...\")\n",
|
||||
" result = await Runner.run(agent, \"Create an image of a frog eating a pizza, comic book style.\")\n",
|
||||
" print(result.final_output)\n",
|
||||
" for item in result.new_items:\n",
|
||||
" if (\n",
|
||||
" item.type == \"tool_call_item\"\n",
|
||||
" and item.raw_item.type == \"image_generation_call\"\n",
|
||||
" and (img_result := item.raw_item.result)\n",
|
||||
" ):\n",
|
||||
" with tempfile.NamedTemporaryFile(suffix=\".png\", delete=False) as tmp:\n",
|
||||
" tmp.write(base64.b64decode(img_result))\n",
|
||||
" temp_path = tmp.name\n",
|
||||
"\n",
|
||||
" # Open the image\n",
|
||||
" print(f\"Image saved to: {temp_path}\")\n",
|
||||
" try:\n",
|
||||
" open_file(temp_path)\n",
|
||||
" except Exception as e:\n",
|
||||
" print(f\"Could not open image automatically: {e}\")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Run the demo\n",
|
||||
"await run_image_generation_demo()\n",
|
||||
"\n",
|
||||
"# End the AgentOps trace session\n",
|
||||
"agentops.end_trace(tracer, end_state=\"Success\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 4. Web Search Tool\n",
|
||||
"\n",
|
||||
"The Web Search Tool allows agents to search the internet for current information and real-time data.\n",
|
||||
"\n",
|
||||
"**Key Features:**\n",
|
||||
"- Search the web for current information\n",
|
||||
"- Location-aware search results\n",
|
||||
"- Real-time data access\n",
|
||||
"- Configurable search parameters"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Start the AgentOps trace session\n",
|
||||
"tracer = agentops.start_trace(\n",
|
||||
" trace_name=\"Web Search Tool Example\", tags=[\"tools-demo\", \"openai-agents\", \"agentops-example\"]\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"async def run_web_search_demo():\n",
|
||||
" agent = Agent(\n",
|
||||
" name=\"Web searcher\",\n",
|
||||
" instructions=\"You are a helpful agent.\",\n",
|
||||
" tools=[WebSearchTool(user_location={\"type\": \"approximate\", \"city\": \"New York\"})],\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" with trace(\"Web search example\"):\n",
|
||||
" result = await Runner.run(\n",
|
||||
" agent,\n",
|
||||
" \"search the web for 'local sports news' and give me 1 interesting update in a sentence.\",\n",
|
||||
" )\n",
|
||||
" print(result.final_output)\n",
|
||||
" # Example output: The New York Giants are reportedly pursuing quarterback Aaron Rodgers after his ...\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Run the demo\n",
|
||||
"await run_web_search_demo()\n",
|
||||
"\n",
|
||||
"# End the AgentOps trace session\n",
|
||||
"agentops.end_trace(tracer, end_state=\"Success\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Conclusion\n",
|
||||
"\n",
|
||||
"Each tool extends agent capabilities and enables sophisticated automation. **AgentOps makes tool observability effortless** - simply import the library and all your tool interactions are automatically tracked, visualized, and analyzed. This enables you to:\n",
|
||||
"\n",
|
||||
"- Monitor tool performance across different use cases\n",
|
||||
"- Optimize costs by understanding tool usage patterns\n",
|
||||
"- Debug tool integration issues quickly\n",
|
||||
"- Scale your AI applications with confidence in tool reliability\n",
|
||||
"\n",
|
||||
"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."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "agentops (3.11.11)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.11"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 4
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
# OpenAI Agents Tools Demonstration
|
||||
#
|
||||
# This notebook demonstrates various tools available in the Agents SDK and how AgentOps provides observability for tool usage.
|
||||
#
|
||||
# ## General Flow
|
||||
#
|
||||
# This notebook will walk you through several key tools:
|
||||
#
|
||||
# 1. **Code Interpreter Tool** - Execute Python code and perform mathematical calculations
|
||||
# 2. **File Search Tool** - Search through vector stores and documents
|
||||
# 3. **Image Generation Tool** - Generate images from text descriptions
|
||||
# 4. **Web Search Tool** - Search the web for current information
|
||||
#
|
||||
# Each tool demonstrates how AgentOps automatically tracks tool usage, providing insights into performance, costs, and effectiveness.
|
||||
# ## 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)
|
||||
# 4. **Vector Store ID**: Configure it from [platform.openai.com](https://platform.openai.com).
|
||||
# # Install required packages
|
||||
# %pip install agentops
|
||||
# %pip install openai-agents
|
||||
# %pip install pydotenv
|
||||
# Set the API keys for your AgentOps and OpenAI accounts.
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
import agentops
|
||||
import base64
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import asyncio
|
||||
|
||||
from agents import (
|
||||
Agent,
|
||||
CodeInterpreterTool,
|
||||
FileSearchTool,
|
||||
ImageGenerationTool,
|
||||
Runner,
|
||||
WebSearchTool,
|
||||
trace,
|
||||
)
|
||||
|
||||
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")
|
||||
|
||||
agentops.init(
|
||||
auto_start_session=False,
|
||||
trace_name="OpenAI Agents Tools Examples",
|
||||
tags=["openai-agents", "tools", "agentops-example"],
|
||||
)
|
||||
tracer = agentops.start_trace(
|
||||
trace_name="OpenAI Agents Tools Examples",
|
||||
tags=["openai-agents", "tools", "agentops-example"],
|
||||
)
|
||||
|
||||
# ## 1. Code Interpreter Tool
|
||||
#
|
||||
# The Code Interpreter Tool allows agents to execute Python code in a secure environment. This is particularly useful for mathematical calculations, data analysis, and generating visualizations.
|
||||
#
|
||||
# **Key Features:**
|
||||
# - Execute Python code safely
|
||||
# - Perform complex mathematical calculations
|
||||
# - Generate plots and visualizations
|
||||
# - Handle data processing tasks
|
||||
# Code Interpreter Tool Example
|
||||
|
||||
|
||||
async def run_code_interpreter_demo():
|
||||
agent = Agent(
|
||||
name="Code interpreter",
|
||||
instructions="You love doing math.",
|
||||
tools=[
|
||||
CodeInterpreterTool(
|
||||
tool_config={"type": "code_interpreter", "container": {"type": "auto"}},
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
with trace("Code interpreter example"):
|
||||
print("Solving math problem...")
|
||||
result = Runner.run_streamed(agent, "What is the square root of 273 * 312821 plus 1782?")
|
||||
async for event in result.stream_events():
|
||||
if (
|
||||
event.type == "run_item_stream_event"
|
||||
and event.item.type == "tool_call_item"
|
||||
and event.item.raw_item.type == "code_interpreter_call"
|
||||
):
|
||||
print(f"Code interpreter code:\n```\n{event.item.raw_item.code}\n```\n")
|
||||
elif event.type == "run_item_stream_event":
|
||||
print(f"Other event: {event.item.type}")
|
||||
|
||||
print(f"Final output: {result.final_output}")
|
||||
|
||||
|
||||
# Run the demo
|
||||
asyncio.run(run_code_interpreter_demo())
|
||||
|
||||
# ## 2. File Search Tool
|
||||
#
|
||||
# The File Search Tool allows agents to search through vector stores and document collections to find relevant information.
|
||||
#
|
||||
# **Key Features:**
|
||||
# - Search through vector stores
|
||||
# - Retrieve relevant documents
|
||||
# - Support for semantic search
|
||||
# - Configurable result limits
|
||||
#
|
||||
# **Note:** This example requires a pre-configured vector store ID.
|
||||
# File Search Tool Example
|
||||
|
||||
|
||||
async def run_file_search_demo():
|
||||
# Note: You'll need to replace this with your actual vector store ID
|
||||
vector_store_id = "vs_67bf88953f748191be42b462090e53e7"
|
||||
|
||||
agent = Agent(
|
||||
name="File searcher",
|
||||
instructions="You are a helpful agent.",
|
||||
tools=[
|
||||
FileSearchTool(
|
||||
max_num_results=3,
|
||||
vector_store_ids=[vector_store_id],
|
||||
include_search_results=True,
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
with trace("File search example"):
|
||||
try:
|
||||
result = await Runner.run(agent, "Be concise, and tell me 1 sentence about Arrakis I might not know.")
|
||||
print(result.final_output)
|
||||
print("\n".join([str(out) for out in result.new_items]))
|
||||
except Exception as e:
|
||||
print(f"File search demo requires a valid vector store ID. Error: {e}")
|
||||
|
||||
|
||||
# Run the demo
|
||||
asyncio.run(run_file_search_demo())
|
||||
|
||||
# ## 3. Image Generation Tool
|
||||
#
|
||||
# The Image Generation Tool enables agents to create images from text descriptions using AI image generation models.
|
||||
#
|
||||
# **Key Features:**
|
||||
# - Generate images from text prompts
|
||||
# - Configurable quality settings
|
||||
# - Support for various image styles
|
||||
# - Automatic image saving and display
|
||||
# Image Generation Tool Example
|
||||
|
||||
|
||||
def open_file(path: str) -> None:
|
||||
if sys.platform.startswith("darwin"):
|
||||
subprocess.run(["open", path], check=False) # macOS
|
||||
elif os.name == "nt": # Windows
|
||||
os.startfile(path) # type: ignore
|
||||
elif os.name == "posix":
|
||||
subprocess.run(["xdg-open", path], check=False) # Linux/Unix
|
||||
else:
|
||||
print(f"Don't know how to open files on this platform: {sys.platform}")
|
||||
|
||||
|
||||
async def run_image_generation_demo():
|
||||
agent = Agent(
|
||||
name="Image generator",
|
||||
instructions="You are a helpful agent.",
|
||||
tools=[
|
||||
ImageGenerationTool(
|
||||
tool_config={"type": "image_generation", "quality": "low"},
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
with trace("Image generation example"):
|
||||
print("Generating image, this may take a while...")
|
||||
result = await Runner.run(agent, "Create an image of a frog eating a pizza, comic book style.")
|
||||
print(result.final_output)
|
||||
for item in result.new_items:
|
||||
if (
|
||||
item.type == "tool_call_item"
|
||||
and item.raw_item.type == "image_generation_call"
|
||||
and (img_result := item.raw_item.result)
|
||||
):
|
||||
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
|
||||
tmp.write(base64.b64decode(img_result))
|
||||
temp_path = tmp.name
|
||||
|
||||
# Open the image (optional - may not work in headless environments)
|
||||
print(f"Image saved to: {temp_path}")
|
||||
try:
|
||||
open_file(temp_path)
|
||||
print("Image opened successfully")
|
||||
except Exception as e:
|
||||
print(f"Could not open image automatically (this is normal in headless environments): {e}")
|
||||
print("You can manually open the image file if needed")
|
||||
|
||||
|
||||
# Run the demo
|
||||
asyncio.run(run_image_generation_demo())
|
||||
|
||||
# ## 4. Web Search Tool
|
||||
#
|
||||
# The Web Search Tool allows agents to search the internet for current information and real-time data.
|
||||
#
|
||||
# **Key Features:**
|
||||
# - Search the web for current information
|
||||
# - Location-aware search results
|
||||
# - Real-time data access
|
||||
# - Configurable search parameters
|
||||
# Web Search Tool Example
|
||||
|
||||
|
||||
async def run_web_search_demo():
|
||||
agent = Agent(
|
||||
name="Web searcher",
|
||||
instructions="You are a helpful agent.",
|
||||
tools=[WebSearchTool(user_location={"type": "approximate", "city": "New York"})],
|
||||
)
|
||||
|
||||
with trace("Web search example"):
|
||||
result = await Runner.run(
|
||||
agent,
|
||||
"search the web for 'local sports news' and give me 1 interesting update in a sentence.",
|
||||
)
|
||||
print(result.final_output)
|
||||
# Example output: The New York Giants are reportedly pursuing quarterback Aaron Rodgers after his ...
|
||||
|
||||
|
||||
# Run the demo
|
||||
asyncio.run(run_web_search_demo())
|
||||
agentops.end_trace(tracer, end_state="Success")
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
agentops.validate_trace_spans(trace_context=tracer)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
|
||||
|
||||
# ## Conclusion
|
||||
#
|
||||
# Each tool extends agent capabilities and enables sophisticated automation. **AgentOps makes tool observability effortless** - simply import the library and all your tool 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.
|
||||
@@ -0,0 +1,306 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Airline Customer Service Agent\n",
|
||||
"\n",
|
||||
"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.\n",
|
||||
"\n",
|
||||
"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."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Prerequisites\n",
|
||||
"\n",
|
||||
"Before running this notebook, you'll need:\n",
|
||||
"\n",
|
||||
"1. **AgentOps Account**: Create a free account at [app.agentops.ai](https://app.agentops.ai)\n",
|
||||
"2. **AgentOps API Key**: Obtain your API key from your AgentOps dashboard\n",
|
||||
"3. **OpenAI API Key**: Get your API key from [platform.openai.com](https://platform.openai.com)\n",
|
||||
"\n",
|
||||
"Make sure to set these as environment variables or create a `.env` file in your project root with:\n",
|
||||
"\n",
|
||||
"```\n",
|
||||
"AGENTOPS_API_KEY=your_agentops_api_key_here\n",
|
||||
"OPENAI_API_KEY=your_openai_api_key_here\n",
|
||||
"```"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Install required packages\n",
|
||||
"%pip install -q agentops\n",
|
||||
"%pip install -q openai-agents\n",
|
||||
"%pip install -q pydotenv"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Set the API keys for your AgentOps and OpenAI accounts.\n",
|
||||
"import os\n",
|
||||
"from dotenv import load_dotenv\n",
|
||||
"\n",
|
||||
"load_dotenv()\n",
|
||||
"\n",
|
||||
"os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\", \"your_api_key_here\")\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\", \"your_openai_api_key_here\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from __future__ import annotations as _annotations # noqa: F404\n",
|
||||
"\n",
|
||||
"import random\n",
|
||||
"import uuid\n",
|
||||
"\n",
|
||||
"from pydantic import BaseModel\n",
|
||||
"import agentops\n",
|
||||
"\n",
|
||||
"from agents import ( # noqa: E402\n",
|
||||
" Agent,\n",
|
||||
" HandoffOutputItem,\n",
|
||||
" ItemHelpers,\n",
|
||||
" MessageOutputItem,\n",
|
||||
" RunContextWrapper,\n",
|
||||
" Runner,\n",
|
||||
" ToolCallItem,\n",
|
||||
" ToolCallOutputItem,\n",
|
||||
" TResponseInputItem,\n",
|
||||
" function_tool,\n",
|
||||
" handoff,\n",
|
||||
" trace,\n",
|
||||
")\n",
|
||||
"from agents.extensions.handoff_prompt import RECOMMENDED_PROMPT_PREFIX # noqa: E402"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"agentops.init(tags=[\"customer-service-agent\", \"openai-agents\", \"agentops-example\"])\n",
|
||||
"tracer = agentops.start_trace(trace_name=\"Customer Service Agent\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Context model for the airline agent\n",
|
||||
"class AirlineAgentContext(BaseModel):\n",
|
||||
" passenger_name: str | None = None\n",
|
||||
" confirmation_number: str | None = None\n",
|
||||
" seat_number: str | None = None\n",
|
||||
" flight_number: str | None = None"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Tools for the airline agent\n",
|
||||
"@function_tool(name_override=\"faq_lookup_tool\", description_override=\"Lookup frequently asked questions.\")\n",
|
||||
"async def faq_lookup_tool(question: str) -> str:\n",
|
||||
" if \"bag\" in question or \"baggage\" in question:\n",
|
||||
" return (\n",
|
||||
" \"You are allowed to bring one bag on the plane. \"\n",
|
||||
" \"It must be under 50 pounds and 22 inches x 14 inches x 9 inches.\"\n",
|
||||
" )\n",
|
||||
" elif \"seats\" in question or \"plane\" in question:\n",
|
||||
" return (\n",
|
||||
" \"There are 120 seats on the plane. \"\n",
|
||||
" \"There are 22 business class seats and 98 economy seats. \"\n",
|
||||
" \"Exit rows are rows 4 and 16. \"\n",
|
||||
" \"Rows 5-8 are Economy Plus, with extra legroom. \"\n",
|
||||
" )\n",
|
||||
" elif \"wifi\" in question:\n",
|
||||
" return \"We have free wifi on the plane, join Airline-Wifi\"\n",
|
||||
" return \"I'm sorry, I don't know the answer to that question.\"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"@function_tool\n",
|
||||
"async def update_seat(context: RunContextWrapper[AirlineAgentContext], confirmation_number: str, new_seat: str) -> str:\n",
|
||||
" \"\"\"\n",
|
||||
" Update the seat for a given confirmation number.\n",
|
||||
"\n",
|
||||
" Args:\n",
|
||||
" confirmation_number: The confirmation number for the flight.\n",
|
||||
" new_seat: The new seat to update to.\n",
|
||||
" \"\"\"\n",
|
||||
" # Update the context based on the customer's input\n",
|
||||
" context.context.confirmation_number = confirmation_number\n",
|
||||
" context.context.seat_number = new_seat\n",
|
||||
" # Ensure that the flight number has been set by the incoming handoff\n",
|
||||
" assert context.context.flight_number is not None, \"Flight number is required\"\n",
|
||||
" return f\"Updated seat to {new_seat} for confirmation number {confirmation_number}\"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"### HOOKS\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"async def on_seat_booking_handoff(context: RunContextWrapper[AirlineAgentContext]) -> None:\n",
|
||||
" flight_number = f\"FLT-{random.randint(100, 999)}\"\n",
|
||||
" context.context.flight_number = flight_number\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"### AGENTS\n",
|
||||
"\n",
|
||||
"faq_agent = Agent[AirlineAgentContext](\n",
|
||||
" name=\"FAQ Agent\",\n",
|
||||
" handoff_description=\"A helpful agent that can answer questions about the airline.\",\n",
|
||||
" instructions=f\"\"\"{RECOMMENDED_PROMPT_PREFIX}\n",
|
||||
" You are an FAQ agent. If you are speaking to a customer, you probably were transferred to from the triage agent.\n",
|
||||
" Use the following routine to support the customer.\n",
|
||||
" # Routine\n",
|
||||
" 1. Identify the last question asked by the customer.\n",
|
||||
" 2. Use the faq lookup tool to answer the question. Do not rely on your own knowledge.\n",
|
||||
" 3. If you cannot answer the question, transfer back to the triage agent.\"\"\",\n",
|
||||
" tools=[faq_lookup_tool],\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"seat_booking_agent = Agent[AirlineAgentContext](\n",
|
||||
" name=\"Seat Booking Agent\",\n",
|
||||
" handoff_description=\"A helpful agent that can update a seat on a flight.\",\n",
|
||||
" instructions=f\"\"\"{RECOMMENDED_PROMPT_PREFIX}\n",
|
||||
" You are a seat booking agent. If you are speaking to a customer, you probably were transferred to from the triage agent.\n",
|
||||
" Use the following routine to support the customer.\n",
|
||||
" # Routine\n",
|
||||
" 1. Ask for their confirmation number.\n",
|
||||
" 2. Ask the customer what their desired seat number is.\n",
|
||||
" 3. Use the update seat tool to update the seat on the flight.\n",
|
||||
" If the customer asks a question that is not related to the routine, transfer back to the triage agent. \"\"\",\n",
|
||||
" tools=[update_seat],\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"triage_agent = Agent[AirlineAgentContext](\n",
|
||||
" name=\"Triage Agent\",\n",
|
||||
" handoff_description=\"A triage agent that can delegate a customer's request to the appropriate agent.\",\n",
|
||||
" instructions=(\n",
|
||||
" f\"{RECOMMENDED_PROMPT_PREFIX} \"\n",
|
||||
" \"You are a helpful triaging agent. You can use your tools to delegate questions to other appropriate agents.\"\n",
|
||||
" ),\n",
|
||||
" handoffs=[\n",
|
||||
" faq_agent,\n",
|
||||
" handoff(agent=seat_booking_agent, on_handoff=on_seat_booking_handoff),\n",
|
||||
" ],\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"faq_agent.handoffs.append(triage_agent)\n",
|
||||
"seat_booking_agent.handoffs.append(triage_agent)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"async def main():\n",
|
||||
" current_agent: Agent[AirlineAgentContext] = triage_agent\n",
|
||||
" input_items: list[TResponseInputItem] = []\n",
|
||||
" context = AirlineAgentContext()\n",
|
||||
"\n",
|
||||
" # Normally, each input from the user would be an API request to your app, and you can wrap the request in a trace()\n",
|
||||
" # Here, we'll just use a random UUID for the conversation ID\n",
|
||||
" conversation_id = uuid.uuid4().hex[:16]\n",
|
||||
"\n",
|
||||
" while True:\n",
|
||||
" user_input = input(\"Enter your message: \")\n",
|
||||
" with trace(\"Customer service\", group_id=conversation_id):\n",
|
||||
" input_items.append({\"content\": user_input, \"role\": \"user\"})\n",
|
||||
" result = await Runner.run(current_agent, input_items, context=context)\n",
|
||||
"\n",
|
||||
" for new_item in result.new_items:\n",
|
||||
" agent_name = new_item.agent.name\n",
|
||||
" if isinstance(new_item, MessageOutputItem):\n",
|
||||
" print(f\"{agent_name}: {ItemHelpers.text_message_output(new_item)}\")\n",
|
||||
" elif isinstance(new_item, HandoffOutputItem):\n",
|
||||
" print(f\"Handed off from {new_item.source_agent.name} to {new_item.target_agent.name}\")\n",
|
||||
" elif isinstance(new_item, ToolCallItem):\n",
|
||||
" print(f\"{agent_name}: Calling a tool\")\n",
|
||||
" elif isinstance(new_item, ToolCallOutputItem):\n",
|
||||
" print(f\"{agent_name}: Tool call output: {new_item.output}\")\n",
|
||||
" else:\n",
|
||||
" print(f\"{agent_name}: Skipping item: {new_item.__class__.__name__}\")\n",
|
||||
" input_items = result.to_input_list()\n",
|
||||
" current_agent = result.last_agent"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"await main()\n",
|
||||
"agentops.end_trace(tracer, end_state=\"Success\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Conclusion\n",
|
||||
"\n",
|
||||
"**AgentOps makes observability effortless** - simply import the library and all your interactions are automatically tracked, visualized, and analyzed. This enables you to:\n",
|
||||
"\n",
|
||||
"- Monitor tool performance across different use cases\n",
|
||||
"- Optimize costs by understanding tool usage patterns\n",
|
||||
"- Debug tool integration issues quickly\n",
|
||||
"- Scale your AI applications with confidence in tool reliability\n",
|
||||
"\n",
|
||||
"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."
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "agentops (3.11.11)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.11"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 2
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
# 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
|
||||
# ```
|
||||
# # Install required packages
|
||||
# %pip install agentops
|
||||
# %pip install openai-agents
|
||||
# %pip install pydotenv
|
||||
# Set the API keys for your AgentOps and OpenAI accounts.
|
||||
from __future__ import annotations as _annotations
|
||||
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
import random
|
||||
import uuid
|
||||
import asyncio
|
||||
|
||||
from pydantic import BaseModel
|
||||
import agentops
|
||||
|
||||
from agents import (
|
||||
Agent,
|
||||
HandoffOutputItem,
|
||||
ItemHelpers,
|
||||
MessageOutputItem,
|
||||
RunContextWrapper,
|
||||
Runner,
|
||||
ToolCallItem,
|
||||
ToolCallOutputItem,
|
||||
TResponseInputItem,
|
||||
function_tool,
|
||||
handoff,
|
||||
trace,
|
||||
)
|
||||
from agents.extensions.handoff_prompt import RECOMMENDED_PROMPT_PREFIX
|
||||
|
||||
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")
|
||||
|
||||
agentops.init(
|
||||
trace_name="OpenAI Agents Customer Service",
|
||||
tags=["customer-service-agent", "openai-agents", "agentops-example"],
|
||||
auto_start_session=False,
|
||||
)
|
||||
tracer = agentops.start_trace(trace_name="OpenAI Agents Customer Service Agent")
|
||||
|
||||
|
||||
# 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
|
||||
|
||||
|
||||
# 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),
|
||||
],
|
||||
)
|
||||
|
||||
faq_agent.handoffs.append(triage_agent)
|
||||
seat_booking_agent.handoffs.append(triage_agent)
|
||||
|
||||
|
||||
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]
|
||||
|
||||
# Predefined test messages to demonstrate the customer service agent
|
||||
test_messages = [
|
||||
"Hello, I need help with my flight",
|
||||
"I want to change my seat",
|
||||
"My confirmation number is ABC123",
|
||||
"I'd like seat 12A please",
|
||||
"What's the baggage policy?",
|
||||
"How many seats are on the plane?",
|
||||
"Is there wifi on the flight?",
|
||||
"Thank you for your help",
|
||||
]
|
||||
|
||||
print("🤖 Starting Customer Service Agent Demo")
|
||||
print("=" * 50)
|
||||
|
||||
for user_input in test_messages:
|
||||
print(f"\n👤 User: {user_input}")
|
||||
|
||||
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
|
||||
|
||||
print("\n" + "=" * 50)
|
||||
print("🎉 Customer Service Agent Demo Complete!")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
|
||||
# Let's check programmatically that spans were recorded in AgentOps
|
||||
print("\n" + "=" * 50)
|
||||
print("Now let's verify that our LLM calls were tracked properly...")
|
||||
try:
|
||||
agentops.validate_trace_spans(trace_context=tracer)
|
||||
print("\n✅ Success! All LLM spans were properly recorded in AgentOps.")
|
||||
except agentops.ValidationError as e:
|
||||
print(f"\n❌ Error validating spans: {e}")
|
||||
raise
|
||||
|
||||
|
||||
# ## 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.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user