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

This commit is contained in:
xiaoxue
2026-05-25 01:45:55 +08:00
commit af7cdc0ffd
1581 changed files with 225877 additions and 0 deletions
+188
View File
@@ -0,0 +1,188 @@
---
title: 'CAMEL AI Example'
description: 'Using CAMEL AI for Multi-Agent Simulation'
mode: "wide"
---
_View Notebook on <a href={'https://github.com/AgentOps-AI/agentops/blob/main/examples/camel_examples/camelai-multi-agent-example.ipynb'} target={'_blank'}>Github</a>_
{/* SOURCE_FILE: examples/camel_examples/camelai-multi-agent-example.ipynb */}
# CAMEL AI Multi Agent Example
In this example, we will use CamelAI to simulate tools! In this case, we will best determine how many shots it takes to beat an enemy with a blue shield in Apex Legeneds using melee only. The character "Pathfinder" from Apex Legends will answer.
First let's install the required packages for this example.
```python
%pip install camel-ai[all]
%pip install agentops
```
Next we import the necessary libraries
```python
import agentops
import os
from getpass import getpass
from dotenv import load_dotenv
from typing import List
from colorama import Fore
# Camel imports
from camel.agents.chat_agent import FunctionCallingRecord
from camel.models import ModelFactory
from camel.societies import RolePlaying
from camel.types import ModelPlatformType, ModelType
from camel.utils import print_text_animated
from camel.toolkits import SearchToolkit, MathToolkit
```
Next, we'll set our API keys. There are several ways to do this, the code below is just the most foolproof way for the purposes of this notebook. It accounts for both users who use environment variables and those who just want to set the API Key here in this notebook.
[Get an AgentOps API key](https://agentops.ai/settings/projects)
1. Create an environment variable in a .env file or other method. By default, the AgentOps `init()` function will look for an environment variable named `AGENTOPS_API_KEY`. Or...
2. Replace `<your_agentops_key>` below and pass in the optional `api_key` parameter to the AgentOps `init(api_key=...)` function. Remember not to commit your API key to a public repo!
```python
load_dotenv()
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") or "<your openai key here>"
AGENTOPS_API_KEY = os.getenv("AGENTOPS_API_KEY") or "<your agentops key here>"
```
Now we will initialize our AgentOps client.
```python
agentops.init(tags=["camel", "multi-agent", "example"])
```
Let's start with setting our task prompt and setting our tools.
You can look at the link below to see all available tools:
https://docs.camel-ai.org/key_modules/tools.html
```python
task_prompt = (
"We are in the Apex Legends Games. Determine the amount of"
"meele hits it will take to beat someone with a blue shield."
"You should answer as if you are Pathfinder from the Apex Games."
)
tools = [
*MathToolkit().get_tools(),
*SearchToolkit().get_tools(),
]
```
We will now create our Camel AI session which is of [`RolePlaying`](https://docs.camel-ai.org/key_modules/society.html#roleplaying) type. Here we will set the assistant and user role names, as well as the model and tools for each agent.
```python
search_session = RolePlaying(
assistant_role_name="Searcher",
user_role_name="Pathfinder",
assistant_agent_kwargs=dict(
model=ModelFactory.create(
model_platform=ModelPlatformType.OPENAI,
model_type=ModelType.GPT_4O_MINI,
),
tools=tools,
),
user_agent_kwargs=dict(
model=ModelFactory.create(
model_platform=ModelPlatformType.OPENAI,
model_type=ModelType.GPT_4O_MINI,
),
),
task_prompt=task_prompt,
with_task_specify=False,
)
```
Let's print out the Assistant System Message and User Task Prompt.
```python
print(
Fore.GREEN
+ f"AI Assistant System Message:\n{search_session.assistant_sys_msg}\n"
)
print(Fore.BLUE + f"AI User System Message:\n{search_session.user_sys_msg}\n")
print(Fore.YELLOW + f"Original Task Prompt:\n{task_prompt}\n")
print(
Fore.CYAN
+ "Specified Task Prompt:"
+ f"\n{search_session.specified_task_prompt}\n"
)
print(Fore.RED + f"Final Task Prompt:\n{search_session.task_prompt}\n")
```
Now we will initiate our Camel AI session and begin the chat loop. You can see that we have set the number of messages to 50. This is to prevent the session from running indefinitely.
```python
n = 0
input_msg = search_session.init_chat()
while n < 50:
n += 1
assistant_response, user_response = search_session.step(input_msg)
if assistant_response.terminated:
print(
Fore.GREEN
+ (
"AI Assistant terminated. Reason: "
f"{assistant_response.info['termination_reasons']}."
)
)
break
if user_response.terminated:
print(
Fore.GREEN
+ (
"AI User terminated. "
f"Reason: {user_response.info['termination_reasons']}."
)
)
break
# Print output from the user
print_text_animated(
Fore.BLUE + f"AI User:\n\n{user_response.msg.content}\n"
)
# Print output from the assistant, including any function execution information
print_text_animated(Fore.GREEN + "AI Assistant:")
tool_calls: List[FunctionCallingRecord] = assistant_response.info[
'tool_calls'
]
for func_record in tool_calls:
print_text_animated(f"{func_record}")
print_text_animated(f"{assistant_response.msg.content}\n")
if "CAMEL_TASK_DONE" in user_response.msg.content:
break
input_msg = assistant_response.msg
```
Awesome! We've successfully completed our session.
Now we will end the session with a success message. We can also end the session with a failure or indeterminate status. By default, the session will be marked as indeterminate.
```python
agentops.end_session("Success")
```
## Check your session
Finally, check your run on [AgentOps](https://app.agentops.ai)
Now if we look in the AgentOps dashboard, you will see a session recorded with the LLM calls and tool usage.
+200
View File
@@ -0,0 +1,200 @@
---
title: 'Examples'
description: 'Sample code that you can run!'
mode: "wide"
---
## Explore our example code to see AgentOps in action!
### Agent Examples
<CardGroup cols={2}>
<Card title="Simple Agent" icon="microchip-ai" iconType="solid" href="/v1/examples/simple_agent">
Jupyter Notebook with sample code that you can run! Start here!
</Card>
<Card title="Multi-Agent" icon="people-arrows" iconType="duotone" href="/v1/examples/multi_agent">
Jupyter Notebook with a simple multi-agent design
</Card>
<Card title="Concurrent Traces" icon="computer" href="/v1/examples/multi_session">
Manage multiple concurrent traces and sessions
</Card>
<Card title="OpenAI Assistants" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/openai/openai-logomark.png?raw=true" alt="OpenAI Assistants" />} iconType="image" href="/v1/integrations/openai" href="/v1/examples/openai_assistants">
Observe OpenAI Assistants
</Card>
</CardGroup>
### Integration Examples
<CardGroup cols={2}>
<Card title="AI21" icon="brain" href="/v1/integrations/ai21">
Integration with AI21's language models
</Card>
<Card title="Anthropic" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/anthropic/anthropic_icon_slate.png?raw=true" alt="Anthropic" />} iconType="image" href="/v1/integrations/anthropic">
Track observations from Claude, Haiku and Sonnet series of models
</Card>
<Card title="AG2" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/autogen/ag2.svg?raw=true" alt="AG2"/>} iconType="image" href="/v1/integrations/autogen">
AG2 (Formerly AutoGen) multi-agent conversible workflow with tool usage
</Card>
<Card title="CamelAI" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/camel/camel.png?raw=true" alt="CamelAI" />} iconType="image" href="/v1/examples/camel">
Track and analyze CAMEL agents
</Card>
<Card title="Cohere" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/cohere/cohere-logo.svg?raw=true" alt="Cohere" />} iconType="image" href="/v1/integrations/cohere">
First class support for Command-R-Plus and chat streaming
</Card>
<Card title="Crew.ai" icon="ship" href="/v1/integrations/crewai">
CrewAI multi-agent framework with AgentOps support
</Card>
<Card title="Groq" icon="bolt" href="/v1/integrations/groq">
Ultra-fast LLM inference with Groq Cloud
</Card>
<Card title="Gemini" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/deepmind/gemini-logo.png?raw=true" alt="Gemini" />} iconType="image" href="/v1/integrations/gemini">
Explore Google DeepMind's Gemini with observation via AgentOps
</Card>
<Card title="Haystack" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/haystack/haystack-logo.png?raw=true" alt="Haystack" />} iconType="image" href="/v1/integrations/haystack">
Monitor your Haystack agents with AgentOps
</Card>
<Card title="LangChain" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/langchain/langchain-logo.svg?raw=true" alt="LangChain" />} iconType="image" href="/v1/examples/langchain">
Jupyter Notebook with a sample LangChain integration
</Card>
<Card title="Llama Stack" icon="pancakes" href="/v1/integrations/llama_stack">
Create an agent to search the web using Brave Search and find the winner of NBA western conference semifinals 2014
</Card>
<Card title="LiteLLM" icon="train-tram" href="/v1/integrations/litellm">
Unified interface for multiple LLM providers
</Card>
<Card title="Mistral" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/mistral/mistral-ai-icon.png?raw=true" alt="Mistral" />} iconType="image" href="/v1/integrations/mistral">
Support for Mistral AI's open-weight models
</Card>
<Card title="MultiOn" icon="atom" href="/v1/examples/multion">
Create an autonomous browser agent capable of navigating the web and extracting information
</Card>
<Card title="Ollama" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/ollama/ollama-icon.png?raw=true" alt="Ollama" />} iconType="image" href="/v1/examples/ollama">
Simple Ollama integration with AgentOps
</Card>
<Card title="OpenAI" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/openai/openai-logomark.png?raw=true" alt="OpenAI" />} iconType="image" href="/v1/integrations/openai">
First class support for GPT family of models
</Card>
<Card title="REST API" icon="bolt-lightning" href="/v1/examples/restapi">
Create a REST server that performs and observes agent tasks
</Card>
<Card title="smolagents" icon={<img src="https://github.com/AgentOps-AI/agentops/blob/main/docs/images/external/huggingface/hf-logo.png?raw=true" alt="smolagents" />} iconType="image" iconType="solid" href="/v1/integrations/smolagents">
Track HuggingFace's smolagents with AgentOps seamlessly
</Card>
<Card title="SwarmZero" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/swarmzero/swarmzero_logo.png?raw=true" alt="SwarmZero" />} iconType="image" href="/v1/integrations/swarmzero">
SwarmZero multi-agent framework for AI Agents and AI Swarms with AgentOps support
</Card>
<Card title="TaskWeaver" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/microsoft/microsoft_logo.svg?raw=true" alt="TaskWeaver" />} iconType="image" href="/v1/integrations/taskweaver">
First class support for Microsoft TaskWeaver
</Card>
<Card title="xAI" icon={<img src="https://www.github.com/agentops-ai/agentops/blob/main/docs/images/external/xai/xai-logo.png?raw=true" alt="xAI" />} iconType="image" href="/v1/integrations/xai">
Observe the power of Grok and Grok Vision with AgentOps
</Card>
</CardGroup>
## Video Guides
<CardGroup cols={2}>
<Card title="AgentOps x CrewAI" icon="film" iconType="solid">
Learn how to monitor CrewAI applications with AgentOps
<iframe
width="280"
height="158"
src="https://www.youtube.com/embed/sF_bgRuRa3s"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
></iframe>
</Card>
<Card title="AgentOps x Anthropic" icon="film" iconType="solid">
Learn how to monitor applications that use the Anthropic SDK directly with AgentOps
<iframe
width="280"
height="158"
src="https://www.youtube.com/embed/Yx2Crpbms7I"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
></iframe>
</Card>
<Card title="AgentOps x OpenAI" icon="film" iconType="solid">
Learn how to monitor applications that use the OpenAI SDK directly with AgentOps
<iframe
width="280"
height="158"
src="https://www.youtube.com/embed/R0K9Qi2dBwM"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
></iframe>
</Card>
<Card title="AgentOps x Llama Stack" icon="film" iconType="solid">
Learn how to monitor Llama Stack applications that use the llama-stack-client-python SDK with AgentOps
<iframe
width="280"
height="158"
src="https://www.youtube.com/embed/OZgTN4SdQ2Y"
title="YouTube video player"
frameBorder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowFullScreen
></iframe>
</Card>
<Card title="Simple Agent" icon="person-carry-box" iconType="solid" href="https://www.loom.com/share/0e0d2986f3d644a58d1e186dc81cd8b1">
Add AgentOps to a simple chat completion
![thumbnail](https://cdn.loom.com/sessions/thumbnails/0e0d2986f3d644a58d1e186dc81cd8b1-with-play.gif)
</Card>
<Card title="Multi-Agent" icon="people-arrows" iconType="duotone" href="https://www.loom.com/share/2a62fd70efe8423fb495946b09c2d8ac">
Jupyter Notebook with a sample LangChain integration
![thumbnail](https://cdn.loom.com/sessions/thumbnails/2a62fd70efe8423fb495946b09c2d8ac-with-play.gif)
</Card>
<Card title="Crew.ai" icon="ship" href="https://www.loom.com/share/cfcaaef8d4a14cc7a974843bda1076bf">
CrewAI multi-agent framework with AgentOps support
![thumbnail](https://cdn.loom.com/sessions/thumbnails/cfcaaef8d4a14cc7a974843bda1076bf-1713568618224-with-play.gif)
</Card>
<Card title="Cohere" icon="hill-rockslide" href="https://www.loom.com/share/679d65cc06f148299e8dffc459d053ab">
First class support for Command-R-Plus
![thumbnail](https://cdn.loom.com/sessions/thumbnails/679d65cc06f148299e8dffc459d053ab-with-play.gif)
</Card>
</CardGroup>
<script type="module" src="/scripts/github_stars.js" />
<script type="module" src="/scripts/scroll-img-fadein-animation.js" />
<script type="module" src="/scripts/button_heartbeat_animation.js" />
<script type="module" src="/scripts/adjust_api_dynamically.js" />
+149
View File
@@ -0,0 +1,149 @@
---
title: 'LangChain Example'
description: 'Using the LangChain Callback Handler'
mode: "wide"
---
_View Notebook on <a href={'https://github.com/AgentOps-AI/agentops/blob/main/examples/langchain_examples.ipynb'} target={'_blank'}>Github</a>_
{/* SOURCE_FILE: examples/langchain_examples/langchain_examples.ipynb */}
# 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
```python
%pip install langchain==0.2.9
%pip install langchain_openai
%pip install -U agentops
%pip install -U python-dotenv
```
Then import them
```python
import os
from langchain_openai import ChatOpenAI
from langchain.agents import tool, AgentExecutor, create_openai_tools_agent
from dotenv import load_dotenv
from langchain_core.prompts import ChatPromptTemplate
```
The only difference with using AgentOps is that we'll also import this special Callback Handler
```python
from agentops.partners.langchain_callback_handler import (
LangchainCallbackHandler as AgentOpsLangchainCallbackHandler,
)
```
Next, we'll set our API keys. There are several ways to do this, the code below is just the most foolproof way for the purposes of this notebook. It accounts for both users who use environment variables and those who just want to set the API Key here in this notebook.
[Get an AgentOps API key](https://agentops.ai/settings/projects)
1. Create an environment variable in a .env file or other method. By default, the AgentOps `init()` function will look for an environment variable named `AGENTOPS_API_KEY`. Or...
2. Replace `<your_agentops_key>` below and pass in the optional `api_key` parameter to the AgentOps `init(api_key=...)` function. Remember not to commit your API key to a public repo!
```python
load_dotenv()
AGENTOPS_API_KEY = os.environ.get("AGENTOPS_API_KEY")
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
```
This is where AgentOps comes into play. Before creating our LLM instance via Langchain, first we'll create an instance of the AO LangchainCallbackHandler. After the handler is initialized, a session will be recorded automatically.
Pass in your API key, and optionally any tags to describe this session for easier lookup in the AO dashboard.
```python
agentops_handler = AgentOpsLangchainCallbackHandler(
api_key=AGENTOPS_API_KEY, tags=["Langchain Example"]
)
llm = ChatOpenAI(
openai_api_key=OPENAI_API_KEY, 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")
]
)
```
You can also retrieve the `session_id` of the newly created session.
```python
print("Agent Ops session ID: " + str(agentops_handler.current_session_ids))
```
Agents generally use tools. Let's define a simple tool here. Tool usage is also recorded.
```python
@tool
def find_movie(genre: str) -> str:
"""Find available movies"""
if genre == "drama":
return "Dune 2"
else:
return "Pineapple Express"
tools = [find_movie]
```
For each tool, you need to also add the callback handler
```python
for t in tools:
t.callbacks = [agentops_handler]
```
Add the tools to our LLM
```python
llm_with_tools = llm.bind_tools([find_movie])
```
Finally, let's create our agent! Pass in the callback handler to the agent, and all the actions will be recorded in the AO Dashboard
```python
agent = create_openai_tools_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools)
```
```python
agent_executor.invoke(
{"input": "What comedies are playing?"}, config={"callback": [agentops_handler]}
)
```
## Check your session
Finally, check your run on [AgentOps](https://app.agentops.ai)
Now if we look in the AgentOps dashboard, you will see a session recorded with the LLM calls and tool usage.
## Langchain v0 Example
This langchain version is out of date and support is being deprecated. You can find the example notebook [here](https://github.com/agentops-ai/agentops/blob/main/examples/langchain_examples/langchain_v0_example.ipynb).
+154
View File
@@ -0,0 +1,154 @@
---
title: 'Multi-Agent Example'
description: 'How to track operations from multiple different agents'
mode: "wide"
---
_View Notebook on <a href={'https://github.com/AgentOps-AI/agentops/blob/main/examples/multi_agent_example.ipynb'} target={'_blank'}>Github</a>_
{/* SOURCE_FILE: examples/multi_agent_example.ipynb */}
# Multi-Agent Support
This is an example implementation of tracking operations from two separate agents
First let's install the required packages
```python
%pip install -U openai
%pip install -U agentops
%pip install -U python-dotenv
```
Then import them
```python
import agentops
from agentops.sdk.decorators import agent, operation
from openai import OpenAI
import os
from dotenv import load_dotenv
import logging
from IPython.display import display, Markdown
```
Next, we'll set our API keys. There are several ways to do this, the code below is just the most foolproof way for the purposes of this notebook. It accounts for both users who use environment variables and those who just want to set the API Key here in this notebook.
[Get an AgentOps API key](https://agentops.ai/settings/projects)
1. Create an environment variable in a .env file or other method. By default, the AgentOps `init()` function will look for an environment variable named `AGENTOPS_API_KEY`. Or...
2. Replace `<your_agentops_key>` below and pass in the optional `api_key` parameter to the AgentOps `init(api_key=...)` function. Remember not to commit your API key to a public repo!
```python
load_dotenv()
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") or "<your_openai_key>"
AGENTOPS_API_KEY = os.getenv("AGENTOPS_API_KEY") or "<your_agentops_key>"
logging.basicConfig(
level=logging.DEBUG
) # this will let us see that calls are assigned to an agent
```
```python
agentops.init(AGENTOPS_API_KEY, tags=["multi-agent-notebook"])
openai_client = OpenAI(api_key=OPENAI_API_KEY)
```
Now lets create a few agents!
```python
@agent(name="qa")
class QaAgent:
def __init__(self):
pass
@operation
def completion(self, prompt: str):
res = openai_client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{
"role": "system",
"content": "You are a qa engineer and only output python code, no markdown tags.",
},
{"role": "user", "content": prompt},
],
temperature=0.5,
)
return res.choices[0].message.content
@agent(name="engineer")
class EngineerAgent:
def __init__(self):
pass
@operation
def completion(self, prompt: str):
res = openai_client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{
"role": "system",
"content": "You are a software engineer and only output python code, no markdown tags.",
},
{"role": "user", "content": prompt},
],
temperature=0.5,
)
return res.choices[0].message.content
```
```python
qa = QaAgent()
engineer = EngineerAgent()
```
Now we have our agents and we tagged them with the `@agent` decorator. Any LLM calls that go through this class will now be tagged as agent calls in AgentOps.
Let's use these agents!
```python
generated_func = engineer.completion("python function to test prime number")
```
```python
display(Markdown("```python\n" + generated_func + "\n```"))
```
```python
generated_test = qa.completion(
"Write a python unit test that test the following function: \n " + generated_func
)
```
```python
display(Markdown("```python\n" + generated_test + "\n```"))
```
Perfect! It generated the code as expected, and in the DEBUG logs, you can see that the calls were made by agents named "engineer" and "qa"!
Let's verify one more thing! If we make an LLM call outside of the context of a tracked agent, we want to make sure it gets assigned to the Default Agent.
```python
res = openai_client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are not a tracked agent"},
{"role": "user", "content": "Say hello"},
],
)
res.choices[0].message.content
```
You'll notice that we didn't log an agent name, so the AgentOps backend will assign it to the Default Agent for the session!
+153
View File
@@ -0,0 +1,153 @@
---
title: 'Concurrent Traces Example'
description: 'Managing multiple concurrent traces and sessions'
mode: "wide"
---
_View Notebook on <a href={'https://github.com/AgentOps-AI/agentops/blob/main/examples/multi_session_llm.ipynb'} target={'_blank'}>Github</a>_
# Multiple Concurrent Traces
This example demonstrates how to run multiple traces (sessions) concurrently using both the modern trace-based API and the legacy session API for backwards compatibility.
First let's install the required packages:
```bash
pip install -U openai
pip install -U agentops
pip install -U python-dotenv
```
Then import them:
```python
from openai import OpenAI
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 example. It accounts for both users who use environment variables and those who just want to set the API Key here.
[Get an AgentOps API key](https://agentops.ai/settings/projects)
1. Create an environment variable in a .env file or other method. By default, the AgentOps `init()` function will look for an environment variable named `AGENTOPS_API_KEY`. Or...
2. Replace `<your_agentops_key>` below and pass in the optional `api_key` parameter to the AgentOps `init(api_key=...)` function. Remember not to commit your API key to a public repo!
```python
load_dotenv()
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") or "<your_openai_key>"
AGENTOPS_API_KEY = os.getenv("AGENTOPS_API_KEY") or "<your_agentops_key>"
```
Initialize AgentOps. We'll disable auto-start to manually create our traces:
```python
agentops.init(AGENTOPS_API_KEY, auto_start_session=False)
client = OpenAI()
```
## Modern Trace-Based Approach
The recommended approach uses `start_trace()` and `end_trace()`:
```python
# Create multiple concurrent traces
trace_1 = agentops.start_trace("user_query_1", tags=["experiment_a"])
trace_2 = agentops.start_trace("user_query_2", tags=["experiment_b"])
print(f"Trace 1 ID: {trace_1.span.get_span_context().trace_id}")
print(f"Trace 2 ID: {trace_2.span.get_span_context().trace_id}")
```
## LLM Calls with Automatic Tracking
With the modern implementation, LLM calls are automatically tracked without needing special session assignment:
```python
# LLM calls are automatically tracked and associated with the current context
messages_1 = [{"role": "user", "content": "Hello from trace 1"}]
response_1 = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=messages_1,
temperature=0.5,
)
messages_2 = [{"role": "user", "content": "Hello from trace 2"}]
response_2 = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=messages_2,
temperature=0.5,
)
```
## Using Context Managers
You can also use traces as context managers for automatic cleanup:
```python
with agentops.start_trace("context_managed_trace") as trace:
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "Hello from context manager"}],
temperature=0.5,
)
# Trace automatically ends when exiting the context
```
## Using Decorators
For even cleaner code, use decorators:
```python
@agentops.trace
def process_user_query(query: str):
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": query}],
temperature=0.5,
)
return response.choices[0].message.content
# Each function call creates its own trace
result_1 = process_user_query("What is the weather like?")
result_2 = process_user_query("Tell me a joke")
```
## Legacy Session API (Backwards Compatibility)
For backwards compatibility, the legacy session API is still available:
```python
# Legacy approach - still works but not recommended for new code
session_1 = agentops.start_session(tags=["legacy-session-1"])
session_2 = agentops.start_session(tags=["legacy-session-2"])
# Legacy sessions work the same way as before
session_1.end_session(end_state="Success")
session_2.end_session(end_state="Success")
```
## Ending Traces
End traces individually or all at once:
```python
# End specific traces
agentops.end_trace(trace_1, "Success")
agentops.end_trace(trace_2, "Success")
# Or end all active traces at once
# agentops.end_trace(end_state="Success")
```
## Key Differences from Legacy Multi-Session Mode
1. **No mode switching**: You can create multiple traces without entering a special "multi-session mode"
2. **Automatic LLM tracking**: LLM calls are automatically associated with the current execution context
3. **No exceptions**: No `MultiSessionException` or similar restrictions
4. **Cleaner API**: Use decorators and context managers for better code organization
5. **Backwards compatibility**: Legacy session functions still work for existing code
If you look in the AgentOps dashboard, you will see multiple unique traces, each with their respective LLM calls and events properly tracked.
+147
View File
@@ -0,0 +1,147 @@
---
title: 'Multion Examples'
description: 'Tracking Multion usage with AgentOps'
mode: "wide"
---
_View All Notebooks on <a href={'https://github.com/AgentOps-AI/agentops/blob/main/examples/multion_examples/'} target={'_blank'}>Github</a>_
{/* SOURCE_FILE: examples/multion_examples/Autonomous_web_browsing.ipynb */}
# MultiOn Tracking Web Browse Actions
<img src="https://github.com/AgentOps-AI/agentops/blob/main/docs/logo/multion_integration.png?raw=true" width="250px" style="max-width: 100%; height: auto;"/>
Agents using MultiOn can launch and control remote or local web browsers to perform actions and retrieve context using natural language commands. With AgentOps, MultiOn evens such as browse, retrieve, and step are automatically tracked.
![AgentOps MultiOn Browse](https://github.com/AgentOps-AI/agentops/blob/main/docs/images/agentops-multion-browse.gif?raw=true)
Furthermore, events and LLM calls in your Python program will be tracked as well.
First let's install the required packages
```python
%pip install -U multion
%pip install -U agentops
%pip install -U openai
%pip install -U python-dotenv
```
Then import them
```python
from multion.client import MultiOn
from multion.core.request_options import RequestOptions
import openai
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!
```python
load_dotenv()
MULTION_API_KEY = os.getenv("MULTION_API_KEY") or "<your_multion_key>"
AGENTOPS_API_KEY = os.getenv("AGENTOPS_API_KEY") or "<your_agentops_key>"
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") or "<your_openai_key>"
```
### Tracking MultiOn events with AgentOps
When an `agentops_api_key` is provided, MultiOn will automatically start an AgentOps session and record events.
```python
multion = MultiOn(
api_key=MULTION_API_KEY,
agentops_api_key=AGENTOPS_API_KEY,
)
cmd = "what three things do i get with agentops"
request_options = RequestOptions(
timeout_in_seconds=60, max_retries=4, additional_headers={"test": "ing"}
)
browse_response = multion.browse(
cmd="what three things do i get with agentops",
url="https://www.agentops.ai/",
max_steps=4,
include_screenshot=True,
request_options=request_options,
)
print(browse_response.message)
# End session to see your dashboard
agentops.end_session("Success")
```
### Linking MultiOn events to an existing AgentOps session
When running `agentops.init()`, be sure to set `auto_start_session=False`. MultiOn will automatically launch AgentOps sessions by default, but by setting auto start to false, you can configure your AgentOps client independently.
```python
agentops.init(
AGENTOPS_API_KEY, auto_start_session=False, tags=["MultiOn browse example"]
)
```
Now, we can launch a MultiOn browse event. This event will automatically get added to your AgentOps session.
```python
multion = MultiOn(
api_key=MULTION_API_KEY,
agentops_api_key=AGENTOPS_API_KEY,
)
cmd = "what three things do i get with agentops"
request_options = RequestOptions(
timeout_in_seconds=60, max_retries=4, additional_headers={"test": "ing"}
)
browse_response = multion.browse(
cmd="what three things do i get with agentops",
url="https://www.agentops.ai/",
max_steps=4,
include_screenshot=True,
request_options=request_options,
)
print(browse_response.message)
```
Let's use OpenAI to summarize our output
```python
messages = [
{
"role": "user",
"content": f"Format this data as a markdown table: {browse_response.message}",
}
]
client = openai.OpenAI()
response = client.chat.completions.create(messages=messages, model="gpt-3.5-turbo")
print(response.choices[0].message.content)
```
```python
agentops.end_session("Success")
```
## Check your session
Check your session on [AgentOps](https://app.agentops.ai). This session should include the MultiOn browse action and the OpenAI call.
![AgentOps MultiOn Browse](https://github.com/AgentOps-AI/agentops/blob/main/docs/images/agentops-multion-browse.gif?raw=true)
+125
View File
@@ -0,0 +1,125 @@
---
title: 'Ollama Example'
description: 'Using Ollama with AgentOps'
mode: "wide"
---
{/* SOURCE_FILE: examples/ollama_examples/ollama_examples.ipynb */}
# AgentOps Ollama Integration
This example demonstrates how to use AgentOps to monitor your Ollama LLM calls.
First let's install the required packages
> ⚠️ **Important**: Make sure you have Ollama installed and running locally before running this notebook. You can install it from [ollama.ai](https://ollama.com).
```python
%pip install -U ollama
%pip install -U agentops
%pip install -U python-dotenv
```
Then import them
```python
import ollama
import agentops
import os
from dotenv import load_dotenv
```
Next, we'll set our API keys. For Ollama, we'll need to make sure Ollama is running locally.
[Get an AgentOps API key](https://agentops.ai/settings/projects)
1. Create an environment variable in a .env file or other method. By default, the AgentOps `init()` function will look for an environment variable named `AGENTOPS_API_KEY`. Or...
2. Replace `<your_agentops_key>` below and pass in the optional `api_key` parameter to the AgentOps `init(api_key=...)` function. Remember not to commit your API key to a public repo!
```python
# Let's load our environment variables
load_dotenv()
AGENTOPS_API_KEY = os.getenv("AGENTOPS_API_KEY") or "<your_agentops_key>"
```
```python
# Initialize AgentOps with some default tags
agentops.init(AGENTOPS_API_KEY, tags=["ollama-example"])
```
Now let's make some basic calls to Ollama. Make sure you have pulled the model first, use the following or replace with whichever model you want to use.
```python
ollama.pull("mistral")
```
```python
# Basic completion,
response = ollama.chat(model='mistral',
messages=[{
'role': 'user',
'content': 'What are the benefits of using AgentOps for monitoring LLMs?',
}]
)
print(response['message']['content'])
```
Let's try streaming responses as well
```python
# Streaming Example
stream = ollama.chat(
model='mistral',
messages=[{
'role': 'user',
'content': 'Write a haiku about monitoring AI agents',
}],
stream=True
)
for chunk in stream:
print(chunk['message']['content'], end='')
```
```python
# Conversation Example
messages = [
{
'role': 'user',
'content': 'What is AgentOps?'
},
{
'role': 'assistant',
'content': 'AgentOps is a monitoring and observability platform for LLM applications.'
},
{
'role': 'user',
'content': 'Can you give me 3 key features?'
}
]
response = ollama.chat(
model='mistral',
messages=messages
)
print(response['message']['content'])
```
> 💡 **Note**: In production environments, you should add proper error handling around the Ollama calls and use `agentops.end_session("Error")` when exceptions occur.
Finally, let's end our AgentOps session
```python
agentops.end_session("Success")
```
+696
View File
@@ -0,0 +1,696 @@
---
title: 'OpenAI Assistants'
description: 'Learn how to use OpenAI Assistants API with AgentOps'
mode: "wide"
---
_View Notebook on <a href={'https://github.com/AgentOps-AI/agentops/blob/main/examples/openai_examples/openai_assistants_example.ipynb'} target={'_blank'}>Github</a>_
{/* SOURCE_FILE: examples/openai_examples/openai_assistants_example.ipynb */}
# Assistants API Overview with AgentOps
This notebook has been adapted from this OpenAI Cookbook [example](https://cookbook.openai.com/examples/assistants_api_overview_python).
The new [Assistants API](https://platform.openai.com/docs/assistants/overview) is a stateful evolution of our [Chat Completions API](https://platform.openai.com/docs/guides/text-generation/chat-completions-api) meant to simplify the creation of assistant-like experiences, and enable developer access to powerful tools like Code Interpreter and Retrieval.
![Assistants API Diagram](https://github.com/AgentOps-AI/agentops/blob/main/examples/openai_examples/images/assistants_overview_diagram.png)
## Chat Completions API vs Assistants API
The primitives of the **Chat Completions API** are `Messages`, on which you perform a `Completion` with a `Model` (`gpt-3.5-turbo`, `gpt-4`, etc). It is lightweight and powerful, but inherently stateless, which means you have to manage conversation state, tool definitions, retrieval documents, and code execution manually.
The primitives of the **Assistants API** are
- `Assistants`, which encapsulate a base model, instructions, tools, and (context) documents,
- `Threads`, which represent the state of a conversation, and
- `Runs`, which power the execution of an `Assistant` on a `Thread`, including textual responses and multi-step tool use.
We'll take a look at how these can be used to create powerful, stateful experiences.
## Setup
> **Note**
> The Assistants API is currently in beta so the latest [Python SDK](https://github.com/openai/openai-python) is needed (`1.58.1` at time of writing) for this example.
```python
%pip install -U openai
%pip install -U agentops
%pip install -U python-dotenv
```
### Pretty Printing Helper
```python
import json
def show_json(obj):
display(json.loads(obj.model_dump_json()))
```
## Complete Example with Assistants API
### Assistants
The easiest way to get started with the Assistants API is through the [Assistants Playground](https://platform.openai.com/playground).
![Assistants Playground](https://github.com/AgentOps-AI/agentops/blob/main/examples/openai_examples/images/assistants_overview_assistants_playground.png)
Let's begin by creating an assistant! We'll create a Math Tutor just like in our [docs](https://platform.openai.com/docs/assistants/overview).
![Creating New Assistant](https://github.com/AgentOps-AI/agentops/blob/main/examples/openai_examples/images/assistants_overview_new_assistant.png)
You can view Assistants you've created in the [Assistants Dashboard](https://platform.openai.com/assistants).
![Assistants Dashboard](https://github.com/AgentOps-AI/agentops/blob/main/examples/openai_examples/images/assistants_overview_assistants_dashboard.png)
You can also create Assistants directly through the Assistants API. But we need to have the AgentOps and OpenAI API keys first.
You can get your OpenAI API key from the [OpenAI Dashboard](https://platform.openai.com/api-keys).
To obtain the AgentOps API key, signup for an account on [AgentOps](https://agentops.ai/) and create a project. After creating the project, you can now create an API key in the [Project Settings](https://app.agentops.ai/settings/projects).
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.
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!
Now we are all set! Let's import the necessary libraries and initialize the AgentOps and OpenAI clients.
```python
from openai import OpenAI
import agentops
from dotenv import load_dotenv
import os
load_dotenv()
AGENTOPS_API_KEY = os.getenv("AGENTOPS_API_KEY") or "<your_agentops_key>"
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") or "<your_openai_key>"
```
```python
agentops.init(api_key=AGENTOPS_API_KEY, tags=["openai", "beta-assistants"])
client = OpenAI(api_key=OPENAI_API_KEY)
```
Next, we'll create an Assistant which will be our Math Tutor.
```python
assistant = client.beta.assistants.create(
name="Math Tutor",
instructions="You are a personal math tutor. Answer questions briefly, in a sentence or less.",
model="gpt-4o-mini",
)
show_json(assistant)
```
Regardless of whether you create your Assistant through the Dashboard or with the API, you'll want to keep track of the Assistant ID. This is how you'll refer to your Assistant throughout Threads and Runs.
Next, we'll create a new Thread and add a Message to it. This will hold the state of our conversation, so we don't have re-send the entire message history each time.
### Threads
Create a new thread:
```python
thread = client.beta.threads.create()
show_json(thread)
```
Then add the Message to the thread:
```python
message = client.beta.threads.messages.create(
thread_id=thread.id,
role="user",
content="I need to solve the equation `3x + 11 = 14`. Can you help me?",
)
show_json(message)
```
> **Note**
> Even though you're no longer sending the entire history each time, you will still be charged for the tokens of the entire conversation history with each Run.
### Runs
Notice how the Thread we created is **not** associated with the Assistant we created earlier! Threads exist independently from Assistants, which may be different from what you'd expect if you've used ChatGPT (where a thread is tied to a model/GPT).
To get a completion from an Assistant for a given Thread, we must create a Run. Creating a Run will indicate to an Assistant it should look at the messages in the Thread and take action: either by adding a single response, or using tools.
> **Note**
> Runs are a key difference between the Assistants API and Chat Completions API. While in Chat Completions the model will only ever respond with a single message, in the Assistants API a Run may result in an Assistant using one or multiple tools, and potentially adding multiple messages to the Thread.
To get our Assistant to respond to the user, let's create the Run. As mentioned earlier, you must specify _both_ the Assistant and the Thread.
```python
run = client.beta.threads.runs.create(
thread_id=thread.id,
assistant_id=assistant.id,
)
show_json(run)
```
Unlike creating a completion in the Chat Completions API, **creating a Run is an asynchronous operation**. It will return immediately with the Run's metadata, which includes a `status` that will initially be set to `queued`. The `status` will be updated as the Assistant performs operations (like using tools and adding messages).
To know when the Assistant has completed processing, we can poll the Run in a loop. (Support for streaming is coming soon!) While here we are only checking for a `queued` or `in_progress` status, in practice a Run may undergo a [variety of status changes](https://platform.openai.com/docs/api-reference/runs/object#runs/object-status) which you can choose to surface to the user. (These are called Steps, and will be covered later.)
```python
import time
def wait_on_run(run, thread):
while run.status == "queued" or run.status == "in_progress":
run = client.beta.threads.runs.retrieve(
thread_id=thread.id,
run_id=run.id,
)
time.sleep(0.5)
return run
```
```python
run = wait_on_run(run, thread)
show_json(run)
```
### Messages
Now that the Run has completed, we can list the Messages in the Thread to see what got added by the Assistant.
```python
messages = client.beta.threads.messages.list(thread_id=thread.id)
show_json(messages)
```
As you can see, Messages are ordered in reverse-chronological order – this was done so the most recent results are always on the first `page` (since results can be paginated). Do keep a look out for this, since this is the opposite order to messages in the Chat Completions API.
Let's ask our Assistant to explain the result a bit further!
```python
# Create a message to append to our thread
message = client.beta.threads.messages.create(
thread_id=thread.id, role="user", content="Could you explain this to me?"
)
# Execute our run
run = client.beta.threads.runs.create(
thread_id=thread.id,
assistant_id=assistant.id,
)
# Wait for completion
wait_on_run(run, thread)
# Retrieve all the messages added after our last user message
messages = client.beta.threads.messages.list(
thread_id=thread.id, order="asc", after=message.id
)
show_json(messages)
```
This may feel like a lot of steps to get a response back, especially for this simple example. However, you'll soon see how we can add very powerful functionality to our Assistant without changing much code at all!
### Example
Let's take a look at how we could potentially put all of this together. Below is all the code you need to use an Assistant you've created.
Since we've already created our Math Assistant, I've saved its ID in `MATH_ASSISTANT_ID`. I then defined two functions:
- `submit_message`: create a Message on a Thread, then start (and return) a new Run
- `get_response`: returns the list of Messages in a Thread
```python
from openai import OpenAI
MATH_ASSISTANT_ID = assistant.id # or a hard-coded ID like "asst-..."
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY", "<your OpenAI API key if not set as env var>"))
def submit_message(assistant_id, thread, user_message):
client.beta.threads.messages.create(
thread_id=thread.id, role="user", content=user_message
)
return client.beta.threads.runs.create(
thread_id=thread.id,
assistant_id=assistant_id,
)
def get_response(thread):
return client.beta.threads.messages.list(thread_id=thread.id, order="asc")
```
I've also defined a `create_thread_and_run` function that I can re-use (which is actually almost identical to the [`client.beta.threads.create_and_run`](https://platform.openai.com/docs/api-reference/runs/createThreadAndRun) compound function in our API ;) ). Finally, we can submit our mock user requests each to a new Thread.
Notice how all of these API calls are asynchronous operations; this means we actually get async behavior in our code without the use of async libraries! (e.g. `asyncio`)
```python
def create_thread_and_run(user_input):
thread = client.beta.threads.create()
run = submit_message(MATH_ASSISTANT_ID, thread, user_input)
return thread, run
# Emulating concurrent user requests
thread1, run1 = create_thread_and_run(
"I need to solve the equation `3x + 11 = 14`. Can you help me?"
)
thread2, run2 = create_thread_and_run("Could you explain linear algebra to me?")
thread3, run3 = create_thread_and_run("I don't like math. What can I do?")
# Now all Runs are executing...
```
Once all Runs are going, we can wait on each and get the responses.
```python
import time
# Pretty printing helper
def pretty_print(messages):
print("# Messages")
for m in messages:
print(f"{m.role}: {m.content[0].text.value}")
print()
# Waiting in a loop
def wait_on_run(run, thread):
while run.status == "queued" or run.status == "in_progress":
run = client.beta.threads.runs.retrieve(
thread_id=thread.id,
run_id=run.id,
)
time.sleep(0.5)
return run
# Wait for Run 1
run1 = wait_on_run(run1, thread1)
pretty_print(get_response(thread1))
# Wait for Run 2
run2 = wait_on_run(run2, thread2)
pretty_print(get_response(thread2))
# Wait for Run 3
run3 = wait_on_run(run3, thread3)
pretty_print(get_response(thread3))
# Thank our assistant on Thread 3 :)
run4 = submit_message(MATH_ASSISTANT_ID, thread3, "Thank you!")
run4 = wait_on_run(run4, thread3)
pretty_print(get_response(thread3))
```
Et voilà!
You may have noticed that this code is not actually specific to our math Assistant at all... this code will work for any new Assistant you create simply by changing the Assistant ID! That is the power of the Assistants API.
## Tools
A key feature of the Assistants API is the ability to equip our Assistants with Tools, like Code Interpreter, Retrieval, and custom Functions. Let's take a look at each.
### Code Interpreter
Let's equip our Math Tutor with the [Code Interpreter](https://platform.openai.com/docs/assistants/tools/code-interpreter) tool, which we can do from the Dashboard...
![Enabling code interpreter](https://github.com/AgentOps-AI/agentops/blob/main/examples/openai_examples/images/assistants_overview_enable_code_interpreter.png)
...or the API, using the Assistant ID.
```python
assistant = client.beta.assistants.update(
MATH_ASSISTANT_ID,
tools=[{"type": "code_interpreter"}],
)
show_json(assistant)
```
Now, let's ask the Assistant to use its new tool.
```python
thread, run = create_thread_and_run(
"Generate the first 20 fibbonaci numbers with code."
)
run = wait_on_run(run, thread)
pretty_print(get_response(thread))
```
And that's it! The Assistant used Code Interpreter in the background, and gave us a final response.
For some use cases this may be enough – however, if we want more details on what precisely an Assistant is doing we can take a look at a Run's Steps.
### Steps
A Run is composed of one or more Steps. Like a Run, each Step has a `status` that you can query. This is useful for surfacing the progress of a Step to a user (e.g. a spinner while the Assistant is writing code or performing retrieval).
```python
run_steps = client.beta.threads.runs.steps.list(
thread_id=thread.id, run_id=run.id, order="asc"
)
```
Let's take a look at each Step's `step_details`.
```python
for step in run_steps.data:
step_details = step.step_details
print(json.dumps(show_json(step_details), indent=4))
```
We can see the `step_details` for two Steps:
1. `tool_calls` (plural, since it could be more than one in a single Step)
2. `message_creation`
The first Step is a `tool_calls`, specifically using the `code_interpreter` which contains:
- `input`, which was the Python code generated before the tool was called, and
- `output`, which was the result of running the Code Interpreter.
The second Step is a `message_creation`, which contains the `message` that was added to the Thread to communicate the results to the user.
### Retrieval
Another powerful tool in the Assistants API is [Retrieval](https://platform.openai.com/docs/assistants/tools/knowledge-retrieval): the ability to upload files that the Assistant will use as a knowledge base when answering questions. This can also be enabled from the Dashboard or the API, where we can upload files we want to be used.
![Enabling retrieval](https://github.com/AgentOps-AI/agentops/blob/main/examples/openai_examples/images/assistants_overview_enable_retrieval.png)
```python
# Upload the file
file = client.files.create(
file=open(
"language_models_are_unsupervised_multitask_learners.pdf",
"rb",
),
purpose="assistants",
)
# Update Assistant
assistant = client.beta.assistants.update(
MATH_ASSISTANT_ID,
tools=[{"type": "code_interpreter"}],
tool_resources={"code_interpreter": {"file_ids": [file.id]}},
)
show_json(assistant)
```
```python
thread, run = create_thread_and_run(
"What are some cool math concepts behind this ML paper pdf? Explain in two sentences."
)
run = wait_on_run(run, thread)
pretty_print(get_response(thread))
```
> **Note**
> There are more intricacies in Retrieval, like [Annotations](https://platform.openai.com/docs/assistants/how-it-works/managing-threads-and-messages), which may be covered in another cookbook.
### Functions
As a final powerful tool for your Assistant, you can specify custom [Functions](https://platform.openai.com/docs/assistants/tools/function-calling) (much like the [Function Calling](https://platform.openai.com/docs/guides/function-calling) in the Chat Completions API). During a Run, the Assistant can then indicate it wants to call one or more functions you specified. You are then responsible for calling the Function, and providing the output back to the Assistant.
Let's take a look at an example by defining a `display_quiz()` Function for our Math Tutor.
This function will take a `title` and an array of `question`s, display the quiz, and get input from the user for each:
- `title`
- `questions`
- `question_text`
- `question_type`: [`MULTIPLE_CHOICE`, `FREE_RESPONSE`]
- `choices`: ["choice 1", "choice 2", ...]
Unfortunately I don't know how to get user input within a Python Notebook, so I'll be mocking out responses with `get_mock_response...`. This is where you'd get the user's actual input.
```python
def get_mock_response_from_user_multiple_choice():
return "a"
def get_mock_response_from_user_free_response():
return "I don't know."
def display_quiz(title, questions):
print("Quiz:", title)
print()
responses = []
for q in questions:
print(q["question_text"])
response = ""
# If multiple choice, print options
if q["question_type"] == "MULTIPLE_CHOICE":
for i, choice in enumerate(q["choices"]):
print(f"{i}. {choice}")
response = get_mock_response_from_user_multiple_choice()
# Otherwise, just get response
elif q["question_type"] == "FREE_RESPONSE":
response = get_mock_response_from_user_free_response()
responses.append(response)
print()
return responses
```
Here's what a sample quiz would look like:
```python
responses = display_quiz(
"Sample Quiz",
[
{"question_text": "What is your name?", "question_type": "FREE_RESPONSE"},
{
"question_text": "What is your favorite color?",
"question_type": "MULTIPLE_CHOICE",
"choices": ["Red", "Blue", "Green", "Yellow"],
},
],
)
print("Responses:", responses)
```
Now, let's define the interface of this function in JSON format, so our Assistant can call it:
```python
function_json = {
"name": "display_quiz",
"description": "Displays a quiz to the student, and returns the student's response. A single quiz can have multiple questions.",
"parameters": {
"type": "object",
"properties": {
"title": {"type": "string"},
"questions": {
"type": "array",
"description": "An array of questions, each with a title and potentially options (if multiple choice).",
"items": {
"type": "object",
"properties": {
"question_text": {"type": "string"},
"question_type": {
"type": "string",
"enum": ["MULTIPLE_CHOICE", "FREE_RESPONSE"],
},
"choices": {"type": "array", "items": {"type": "string"}},
},
"required": ["question_text"],
},
},
},
"required": ["title", "questions"],
},
}
```
Once again, let's update our Assistant either through the Dashboard or the API.
![Enabling custom function](https://github.com/AgentOps-AI/agentops/blob/main/examples/openai_examples/images/assistants_overview_enable_function.png)
> **Note**
> Pasting the function JSON into the Dashboard was a bit finicky due to indentation, etc. I just asked ChatGPT to format my function the same as one of the examples on the Dashboard :).
```python
assistant = client.beta.assistants.update(
MATH_ASSISTANT_ID,
tools=[
{"type": "code_interpreter"},
{"type": "function", "function": function_json},
],
)
show_json(assistant)
```
And now, we ask for a quiz.
```python
thread, run = create_thread_and_run(
"Make a quiz with 2 questions: One open ended, one multiple choice. Then, give me feedback for the responses."
)
run = wait_on_run(run, thread)
run.status
```
Now, however, when we check the Run's `status` we see `requires_action`! Let's take a closer look.
```python
show_json(run)
```
The `required_action` field indicates a Tool is waiting for us to run it and submit its output back to the Assistant. Specifically, the `display_quiz` function! Let's start by parsing the `name` and `arguments`.
> **Note**
> While in this case we know there is only one Tool call, in practice the Assistant may choose to call multiple tools.
```python
# Extract single tool call
tool_call = run.required_action.submit_tool_outputs.tool_calls[0]
name = tool_call.function.name
arguments = json.loads(tool_call.function.arguments)
print("Function Name:", name)
print("Function Arguments:")
arguments
```
Now let's actually call our `display_quiz` function with the arguments provided by the Assistant:
```python
responses = display_quiz(arguments["title"], arguments["questions"])
print("Responses:", responses)
```
Great! (Remember these responses are the one's we mocked earlier. In reality, we'd be getting input from the back from this function call.)
Now that we have our responses, let's submit them back to the Assistant. We'll need the `tool_call` ID, found in the `tool_call` we parsed out earlier. We'll also need to encode our `list`of responses into a `str`.
```python
tool_outputs = []
tool_calls = run.required_action.submit_tool_outputs.tool_calls
for tool_call in tool_calls:
arguments = json.loads(tool_call.function.arguments)
responses = display_quiz(arguments["title"], arguments["questions"])
tool_outputs.append({
"tool_call_id": tool_call.id,
"output": json.dumps(responses),
})
```
```python
run = client.beta.threads.runs.submit_tool_outputs(
thread_id=thread.id,
run_id=run.id,
tool_outputs=tool_outputs
)
show_json(run)
```
We can now wait for the Run to complete once again, and check our Thread!
```python
run = wait_on_run(run, thread)
pretty_print(get_response(thread))
```
Now let's end the AgentOps session. By default, AgentOps will end the session in the "Intedeterminate" state. You can also end the session in the "Success" or "Failure" state.
We will end the session in the "Success" state.
```python
agentops.end_session(end_state="Success")
```
Woohoo 🎉
## Conclusion
We covered the basics of the Assistants API using OpenAI's Python SDK and AgentOps for observability.
For more information, check out the Assistants API deep [deep dive](https://platform.openai.com/docs/assistants/deep-dive) guide and its [documentation](https://platform.openai.com/docs/api-reference/assistants).
+163
View File
@@ -0,0 +1,163 @@
---
title: 'Recording Events'
description: 'How to record events using spans in your session'
mode: "wide"
---
_View Notebook on <a href={'https://github.com/AgentOps-AI/agentops/blob/main/examples/recording-operations.ipynb'} target={'_blank'}>Github</a>_
{/* SOURCE_FILE: examples/recording-operations.ipynb */}
# Recording Operations with Spans
AgentOps v0.4 uses spans to track different types of operations in your agent workflows.
We automatically instrument your LLM Calls from OpenAI, LiteLLM, Cohere, and more. Just make sure their SDKs are imported before initializing AgentOps like we see below.
First let's install the required packages
```python
%pip install -U openai
%pip install -U agentops
%pip install -U python-dotenv
```
Then import them
```python
from openai import OpenAI
import agentops
from agentops.sdk.decorators import session, agent, operation
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!
```python
load_dotenv()
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") or "<your_openai_key>"
AGENTOPS_API_KEY = os.getenv("AGENTOPS_API_KEY") or "<your_agentops_key>"
```
```python
# Initialize the client
agentops.init()
# Optionally, we can add default tags to all sessions
# agentops.init(tags=['Hello Tracker'])
openai_client = OpenAI()
# Create a session to track all operations
@session
def my_session():
messages = [{"role": "user", "content": "Hello"}]
response = openai_client.chat.completions.create(
model="gpt-3.5-turbo", messages=messages, temperature=0.5
)
print(response.choices[0].message.content)
# Call our operation
result = add(2, 4)
print(f"Addition result: {result}")
# Call our agent
agent = MyAgent()
agent.process_data("test data")
# Run the session
my_session()
```
Click the AgentOps link above to see your session!
## Operations
AgentOps allows you to record operations using the `@operation` decorator:
```python
from agentops.sdk.decorators import operation
@operation
def add(x, y):
return x + y
```
## Agents
You can create agent spans that contain operations using the `@agent` decorator:
```python
from agentops.sdk.decorators import agent, operation
@agent
class MyAgent:
@operation
def process_data(self, data):
print(f"Processing data: {data}")
return f"Processed: {data.upper()}"
```
## Error Handling
Errors are automatically captured by the spans. When an exception occurs within a decorated function, it's recorded in the span:
```python
from agentops.sdk.decorators import operation
@operation
def risky_operation():
# This exception will be recorded in the span
try:
1 / 0 # Ooops! Something went wrong
except Exception as e:
print(f"Error occurred: {e}")
raise
# Create a session that includes the error
@session
def error_session():
try:
risky_operation()
except Exception:
print("Caught the error, but it's still recorded in the span")
# Run the error session
error_session()
```
## Custom Span Attributes
You can add custom attributes to spans for additional context:
```python
from agentops.sdk.decorators import operation
@operation(name="custom-operation")
def custom_operation(data):
# Your operation logic here
return f"Custom: {data}"
# Create a session with custom operation
@session(name="custom-session")
def custom_session():
result = custom_operation("test")
print(result)
# Run the custom session
custom_session()
```
+102
View File
@@ -0,0 +1,102 @@
---
title: 'Fast API'
description: 'Observing agents in a server environment'
mode: "wide"
---
[//]: # (Card for video tutorial)
[//]: # (<Card title="REST Server + AgentOps" icon="computer" href="https://www.loom.com/share/cfcaaef8d4a14cc7a974843bda1076bf">)
[//]: # ( Using agents in a REST server and observing)
[//]: # ( ![thumbnail]&#40;https://cdn.loom.com/sessions/thumbnails/cfcaaef8d4a14cc7a974843bda1076bf-1713568618224-with-play.gif&#41;)
[//]: # (</Card>)
## Adding AgentOps to Crew agents
<Steps>
<Step title="Install the AgentOps SDK">
<CodeGroup>
```bash pip
pip install agentops
```
```bash poetry
poetry add agentops
```
</CodeGroup>
</Step>
<Step title="Install Crew with AgentOps">
<CodeGroup>
```bash pip
pip install 'crewai[agentops]'
```
```bash poetry
poetry add 'crewai[agentops]'
```
</CodeGroup>
</Step>
<Step title="Add 3 lines of code">
1. Before calling the `Crew()` constructor in your code, call `agentops.init()`
2. At the end of your Crew run, call `agentops.end_session("Success")`
<CodeGroup>
```python python
import agentops
# Beginning of program (i.e. main.py, __init__.py)
# IMPORTANT: Must be before calling the `Crew()` constructor
agentops.init(<INSERT YOUR API KEY HERE>)
...
# End of program (e.g. main.py)
agentops.end_session("Success") # Success|Fail|Indeterminate
```
</CodeGroup>
<Check>
Instantiating the AgentOps client will automatically instrument Crew, meaning you will be able to see all
of your sessions on the AgentOps Dashboard along with the full LLM chat histories, cost, token counts, etc.
</Check>
<Tip>
For more features see our [Usage](/v1/usage) section.
</Tip>
</Step>
<Step title="Set your API key">
Retrieve an API Key from your Settings > [Projects & API Keys](https://app.agentops.ai/settings/projects) page.
<Frame type="glass" caption="Settings > Projects & API Keys">
<img height="200" src="/images/api-keys.png" />
</Frame>
<Info>
API keys are tied to individual projects.<br></br>
A Default Project has been created for you, so just click Copy API Key
</Info>
Set this API Key in your [environment variables](/v1/usage/advanced-configuration)
```python .env
AGENTOPS_API_KEY=<YOUR API KEY>
```
</Step>
<Step title="Run your crew">
Execute your program and visit [app.agentops.ai/drilldown](https://app.agentops.ai/drilldown) to observe your Crew! 🕵️
<Tip>
After your run, AgentOps prints a clickable url to console linking directly to your session in the Dashboard
</Tip>
<div/>{/* Intentionally blank div for newline */}
<Frame type="glass" caption="Clickable link to session">
<img height="200" src="https://github.com/AgentOps-AI/agentops/blob/main/docs/images/link-to-session.gif?raw=true" />
</Frame>
</Step>
</Steps>
## Special Considerations with Crew
The Crew framework is capable of determining when all tasks have been accomplished and to halt execution. AgentOps will automatically end your active session
when this determination is made. If you don't want your AgentOps session to end at this time, add an optional parameter to your `agentops.init()` call.
```python
agentops.init(skip_auto_end_session=True)
```
## Crew + AgentOps Examples
<CardGroup cols={3}>
<Card title="Job Posting" icon="briefcase" href="https://github.com/Agentops-AI/crewAI-examples/tree/main/job-posting" />
<Card title="Instagram Post" icon="instagram" href="https://github.com/Agentops-AI/crewAI-examples/tree/main/instagram_post" />
<Card title="Markdown Validator" icon="markdown" href="https://github.com/Agentops-AI/crewAI-examples/tree/main/markdown_validator" />
</CardGroup>
+127
View File
@@ -0,0 +1,127 @@
---
title: 'Simple Agent'
description: 'Most basic usage with OpenAI API'
mode: "wide"
---
_View Notebook on <a href={'https://github.com/AgentOps-AI/agentops/blob/main/examples/openai-gpt.ipynb'} target={'_blank'}>Github</a>_
{/* SOURCE_FILE: examples/openai-gpt.ipynb */}
# AgentOps Basic Monitoring
This is an example of how to use the AgentOps library for basic Agent monitoring with OpenAI's GPT
First let's install the required packages
```python
%pip install -U openai
%pip install -U agentops
%pip install -U python-dotenv
```
Then import them
```python
from openai import OpenAI
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!
```python
load_dotenv()
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") or "<your_openai_key>"
AGENTOPS_API_KEY = os.getenv("AGENTOPS_API_KEY") or "<your_agentops_key>"
```
The AgentOps library is designed to be a plug-and-play replacement for the OpenAI Client, maximizing use with minimal install effort.
```python
openai = OpenAI(api_key=OPENAI_API_KEY)
agentops.init(AGENTOPS_API_KEY, tags=["openai-gpt-notebook"])
```
Now just use OpenAI as you would normally!
## Single Session with ChatCompletion
```python
message = [{"role": "user", "content": "Write a 12 word poem about secret agents."}]
response = openai.chat.completions.create(
model="gpt-3.5-turbo", messages=message, temperature=0.5, stream=False
)
print(response.choices[0].message.content)
```
Make sure to end your session with a `Result` (Success|Fail|Indeterminate) for better tracking
```python
agentops.end_session("Success")
```
Now if you check the AgentOps dashboard, you should see information related to this run!
# Events
Additionally, you can track custom events via AgentOps.
Let's start a new session and record some events
```python
# Create new session
agentops.start_session(tags=["openai-gpt-notebook-events"])
```
The easiest way to record actions is through the use of AgentOps' decorators
```python
from agentops import record_action
@record_action("add numbers")
def add(x, y):
return x + y
add(2, 4)
```
We can also manually craft an event exactly the way we want
```python
from agentops import ActionEvent
message = ({"role": "user", "content": "Hello"},)
response = openai.chat.completions.create(
model="gpt-3.5-turbo", messages=message, temperature=0.5
)
if "hello" in str(response.choices[0].message.content).lower():
agentops.record(
ActionEvent(
action_type="Agent says hello",
logs=str(message),
returns=str(response.choices[0].message.content),
)
)
```
```python
agentops.end_session("Success")
```