Skip to content

Commit fa4d0e7

Browse files
committed
python scripts with README files with ❤️ for @tcdent
1 parent 1c7e2c0 commit fa4d0e7

43 files changed

Lines changed: 4737 additions & 47 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

examples/README.md

Lines changed: 30 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,65 +1,65 @@
11
# AgentOps Examples
22

3-
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 with detailed explanations and code samples.
3+
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.
44

55
## 📁 Directory Structure
66

77
- **[`ag2/`](./ag2/)** - Examples for AG2 (AutoGen 2.0) multi-agent conversations
8-
- `agentchat_with_memory.ipynb` - Agent chat with persistent memory
9-
- `async_human_input.ipynb` - Asynchronous human input handling
10-
- `tools_wikipedia_search.ipynb` - Wikipedia search tool integration
8+
- `agentchat_with_memory` - Agent chat with persistent memory
9+
- `async_human_input` - Asynchronous human input handling
10+
- `tools_wikipedia_search` - Wikipedia search tool integration
1111

1212
- **[`anthropic/`](./anthropic/)** - Anthropic Claude API integration examples
13-
- `agentops-anthropic-understanding-tools.ipynb` - Deep dive into tool usage
14-
- `anthropic-example-async.ipynb` - Asynchronous API calls
15-
- `anthropic-example-sync.ipynb` - Synchronous API calls
16-
- `antrophic-example-tool.ipynb` - Tool calling examples
13+
- `agentops-anthropic-understanding-tools` - Deep dive into tool usage
14+
- `anthropic-example-async` - Asynchronous API calls
15+
- `anthropic-example-sync` - Synchronous API calls
16+
- `antrophic-example-tool` - Tool calling examples
1717
- `README.md` - Detailed Anthropic integration guide
1818

1919
- **[`autogen/`](./autogen/)** - Microsoft AutoGen framework examples
20-
- `AgentChat.ipynb` - Basic agent chat functionality
21-
- `MathAgent.ipynb` - Mathematical problem-solving agent
20+
- `AgentChat` - Basic agent chat functionality
21+
- `MathAgent` - Mathematical problem-solving agent
2222

2323
- **[`crewai/`](./crewai/)** - CrewAI multi-agent framework examples
24-
- `job_posting.ipynb` - Job posting automation workflow
25-
- `markdown_validator.ipynb` - Markdown validation agent
24+
- `job_posting` - Job posting automation workflow
25+
- `markdown_validator` - Markdown validation agent
2626

2727
- **[`gemini/`](./gemini/)** - Google Gemini API integration
28-
- `gemini_example.ipynb` - Basic Gemini API usage with AgentOps
28+
- `gemini_example` - Basic Gemini API usage with AgentOps
2929

3030
- **[`google_adk/`](./google_adk/)** - Google AI Development Kit examples
31-
- `human_approval.ipynb` - Human-in-the-loop approval workflows
31+
- `human_approval` - Human-in-the-loop approval workflows
3232

3333
- **[`langchain/`](./langchain/)** - LangChain framework integration
34-
- `langchain_examples.ipynb` - Comprehensive LangChain usage examples
34+
- `langchain_examples` - Comprehensive LangChain usage examples
3535

3636
- **[`litellm/`](./litellm/)** - LiteLLM proxy integration
37-
- `litellm_example.ipynb` - Multi-provider LLM access through LiteLLM
37+
- `litellm_example` - Multi-provider LLM access through LiteLLM
3838

3939
- **[`openai/`](./openai/)** - OpenAI API integration examples
40-
- `multi_tool_orchestration.ipynb` - Complex tool orchestration
41-
- `openai_example_async.ipynb` - Asynchronous OpenAI API calls
42-
- `openai_example_sync.ipynb` - Synchronous OpenAI API calls
43-
- `web_search.ipynb` - Web search functionality
40+
- `multi_tool_orchestration` - Complex tool orchestration
41+
- `openai_example_async` - Asynchronous OpenAI API calls
42+
- `openai_example_sync` - Synchronous OpenAI API calls
43+
- `web_search` - Web search functionality
4444

4545
- **[`openai_agents/`](./openai_agents/)** - OpenAI Agents SDK examples
46-
- `agent_patterns.ipynb` - Common agent design patterns
47-
- `agents_tools.ipynb` - Agent tool integration
48-
- `customer_service_agent.ipynb` - Customer service automation
46+
- `agent_patterns` - Common agent design patterns
47+
- `agents_tools` - Agent tool integration
48+
- `customer_service_agent` - Customer service automation
4949

5050
- **[`smolagents/`](./smolagents/)** - SmolAgents framework examples
51-
- `multi_smolagents_system.ipynb` - Multi-agent system coordination
52-
- `text_to_sql.ipynb` - Natural language to SQL conversion
51+
- `multi_smolagents_system` - Multi-agent system coordination
52+
- `text_to_sql` - Natural language to SQL conversion
5353

5454
- **[`watsonx/`](./watsonx/)** - IBM Watsonx AI integration
55-
- `watsonx-streaming.ipynb` - Streaming text generation
56-
- `watsonx-text-chat.ipynb` - Text generation and chat completion
57-
- `watsonx-tokeniation-model.ipynb` - Tokenization and model details
55+
- `watsonx-streaming` - Streaming text generation
56+
- `watsonx-text-chat` - Text generation and chat completion
57+
- `watsonx-tokeniation-model` - Tokenization and model details
5858
- `README.md` - Detailed Watsonx integration guide
5959

6060
- **[`xai/`](./xai/)** - xAI (Grok) API integration
61-
- `grok_examples.ipynb` - Basic Grok API usage
62-
- `grok_vision_examples.ipynb` - Vision capabilities with Grok
61+
- `grok_examples` - Basic Grok API usage
62+
- `grok_vision_examples` - Vision capabilities with Grok
6363

6464
### Utility Scripts
6565

examples/ag2/README.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# AG2 Examples with AgentOps
2+
3+
This directory contains examples of using AG2 (AutoGen 2.0) with AgentOps instrumentation for various multi-agent conversation tasks.
4+
5+
## Prerequisites
6+
7+
- Python >= 3.10 < 3.13
8+
- Install required dependencies:
9+
```
10+
pip install agentops ag2
11+
```
12+
13+
## Examples
14+
15+
### 1. Agent Chat with Memory
16+
17+
Example: `agentchat_with_memory`
18+
This example demonstrates:
19+
- Agent chat with persistent memory
20+
21+
### 2. Asynchronous Human Input
22+
23+
Example: `async_human_input`
24+
25+
This example demonstrates:
26+
- Asynchronous human input handling
27+
28+
### 3. Wikipedia Search Tool
29+
30+
Example: `tools_wikipedia_search`
31+
32+
This example demonstrates:
33+
- Wikipedia search tool integration
34+
35+
## AgentOps Integration
36+
37+
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.
38+
39+
To learn more about AgentOps, visit [https://www.agentops.ai](https://www.agentops.ai)
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
# Observe an Agent with memory powered by Mem0
2+
# This notebook demonstrates an intelligent customer service chatbot system that combines:
3+
#
4+
# - AG2 for conversational agents
5+
# - Mem0 for memory management
6+
#
7+
# [Mem0](https://www.mem0.ai/) provides a smart, self-improving memory layer for Large Language Models (LLMs), enabling developers to create personalized AI experiences that evolve with each user interaction. Refer [docs](https://docs.mem0.ai/overview) for more information.
8+
#
9+
# The implementation showcases how to initialize agents, manage conversation memory, and facilitate multi-agent conversations for enhanced problem-solving in customer support scenarios.
10+
#
11+
# With AgentOps, you can observe the agent's memory and interactions in real-time, providing insights into how the agent learns and adapts over time.
12+
# ## Pre-requisites
13+
# - AgentOps API key from [AgentOps](https://app.agentops.ai/).
14+
# - Mem0 API key from [Mem0 Platform](https://app.mem0.ai/).
15+
# - OpenAI API key from [OpenAI](https://platform.openai.com/).
16+
# # Install required dependencies
17+
# %pip install agentops
18+
# %pip install "ag2[openai]"
19+
# %pip install mem0ai
20+
import os
21+
from dotenv import load_dotenv
22+
import agentops
23+
from mem0 import MemoryClient
24+
from autogen import ConversableAgent
25+
26+
load_dotenv()
27+
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY", "your_api_key_here")
28+
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY", "your_openai_api_key_here")
29+
os.environ["MEM0_API_KEY"] = os.getenv("MEM0_API_KEY", "your_api_key_here")
30+
31+
# ## Initialize Agent and Memory
32+
#
33+
# The conversational agent is set up using the 'gpt-4o' model and a mem0 client. We'll utilize the client's methods for storing and accessing memories.
34+
agentops.init(auto_start_session=False)
35+
tracer = agentops.start_trace(trace_name="AG2 Agent using Mem0", tags=["ag2-mem0-example", "agentops-example"])
36+
37+
agent = ConversableAgent(
38+
"chatbot",
39+
llm_config={"config_list": [{"model": "gpt-4o", "api_key": os.environ.get("OPENAI_API_KEY")}]},
40+
code_execution_config=False,
41+
function_map=None,
42+
human_input_mode="NEVER",
43+
)
44+
45+
memory = MemoryClient()
46+
47+
# Initialize a conversation history for a Best Buy customer service chatbot. It contains a list of message exchanges between the user and the assistant, structured as dictionaries with 'role' and 'content' keys. The entire conversation is then stored in memory using the `memory.add()` method, associated with the identifier "customer_service_bot".
48+
conversation = [
49+
{
50+
"role": "assistant",
51+
"content": "Hi, I'm Best Buy's chatbot!\n\nThanks for being a My Best Buy TotalTM member.\n\nWhat can I help you with?",
52+
},
53+
{
54+
"role": "user",
55+
"content": 'Seeing horizontal lines on our tv. TV model: Sony - 77" Class BRAVIA XR A80K OLED 4K UHD Smart Google TV',
56+
},
57+
{
58+
"role": "assistant",
59+
"content": "Thanks for being a My Best Buy Total™ member. I can connect you to an expert immediately - just one perk of your membership!\n\nSelect the button below when you're ready to chat.",
60+
},
61+
{
62+
"role": "assistant",
63+
"content": "Good evening, thank you for choosing Best Buy, Fnu. My name is Lovely. I hope you are doing well. I'm sorry to hear that you're seeing horizontal lines on your TV.\n\nI'm absolutely committed to exploring all possible ways to assist you to fix this issue.\n\nTo ensure that we are on the right account, may I please have your email address registered with your Best Buy account?",
64+
},
65+
{"role": "user", "content": "dd@gmail.com"},
66+
{
67+
"role": "assistant",
68+
"content": "Perfect! Thank you for providing all the details, surely you have made my job easier by doing this. I really appreciate it.\n\nI also want to take a moment to express our heartfelt appreciation for your trust and loyalty. Thank you for being an amazing customer of BestBuy Total.\n\nCould you please help me with the order number or product's details to check it quickly?\n\nSamsung - 49\" Odyssey OLED G9 (G95SC) DQHD 240Hz 0.03ms G-Sync Compatible Curved Smart Gaming Monitor - Silver - just to confirm this is the item, right?",
69+
},
70+
{"role": "user", "content": "Order number: 112217629"},
71+
{
72+
"role": "assistant",
73+
"content": "Superb! Thank you for confirmation.\n\nThank you for your patience. After exploring all possible solutions, I can help you to arrange a home repair appointment for your device. Our Geek Squad experts will visit your home to inspect and fix your device.\n\nIt's great that you have a protection plan - rest assured, we've got your back! As a valued Total member, you can avail this service at a minimal service fee. This fee, applicable to all repairs, covers the cost of diagnosing the issue and any small parts needed for the repair. It's part of our 24-month free protection plan.\n\nPlease click here to review the service fee and plan coverage details -\n\nhttps://www.bestbuy.com/site/best-buy-membership/best-buy-protection/pcmcat1608643232014.c?id=pcmcat1608643232014#jl-servicefees\n\nFnu - just to confirm shall I proceed to schedule the appointment?",
74+
},
75+
{"role": "user", "content": "Yes please"},
76+
{"role": "assistant", "content": "When should I schedule the appointment?"},
77+
{"role": "user", "content": "Schedule it for tomorrow please"},
78+
]
79+
80+
memory.add(messages=conversation, user_id="customer_service_bot")
81+
82+
# ## Agent Inference
83+
#
84+
# We ask a question to the agent, utilizing mem0 to retrieve relevant memories. The agent then formulates a response based on both the question and the retrieved contextual information.
85+
data = "I forgot the order number, can you quickly tell me?"
86+
relevant_memories = memory.search(data, user_id="customer_service_bot")
87+
flatten_relevant_memories = "\n".join([m["memory"] for m in relevant_memories])
88+
89+
prompt = f"""Answer the user question considering the memories. Keep answers clear and concise.
90+
Memories:
91+
{flatten_relevant_memories}
92+
\n\n
93+
Question: {data}
94+
"""
95+
96+
reply = agent.generate_reply(messages=[{"content": prompt, "role": "user"}])
97+
print(reply)
98+
99+
# ## Multi Agent Conversation
100+
#
101+
# Initialize two AI agents: a "manager" for resolving customer issues and a "customer_bot" for gathering information on customer problems, both using GPT-4. It then retrieves relevant memories for a given question, combining them with the question into a prompt. This prompt can be used by either the manager or customer_bot to generate a contextually informed response.
102+
manager = ConversableAgent(
103+
"manager",
104+
system_message="You are a manager who helps in resolving customer issues.",
105+
llm_config={"config_list": [{"model": "gpt-4o-mini", "api_key": os.environ.get("OPENAI_API_KEY")}]},
106+
human_input_mode="NEVER",
107+
)
108+
109+
customer_bot = ConversableAgent(
110+
"customer_bot",
111+
system_message="You are a customer service bot who gathers information on issues customers are facing. Keep answers clear and concise.",
112+
llm_config={"config_list": [{"model": "gpt-4", "api_key": os.environ.get("OPENAI_API_KEY")}]},
113+
human_input_mode="NEVER",
114+
)
115+
116+
data = "When is the appointment?"
117+
relevant_memories = memory.search(data, user_id="customer_service_bot")
118+
flatten_relevant_memories = "\n".join([m["memory"] for m in relevant_memories])
119+
120+
prompt = f"""
121+
Context:
122+
{flatten_relevant_memories}
123+
\n\n
124+
Question: {data}
125+
"""
126+
127+
result = manager.send(prompt, customer_bot, request_reply=True)
128+
agentops.end_trace(tracer, end_state="Success")

examples/ag2/async_human_input.py

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
# Agent Chat with Async Human Inputs
2+
#
3+
# We are going to create an agent that can chat with a human asynchronously. The agent will be able to respond to messages from the human and will also be able to send messages to the human.
4+
#
5+
# We are going to use AgentOps to monitor the agent's performance and observe its interactions with the human.
6+
# # Install required dependencies
7+
# %pip install agentops
8+
# %pip install ag2
9+
# %pip install chromadb
10+
# %pip install sentence_transformers
11+
# %pip install tiktoken
12+
# %pip install pypdf
13+
# %pip install nest-asyncio
14+
import asyncio
15+
from typing import Dict, Optional, Union
16+
import os
17+
from dotenv import load_dotenv
18+
19+
import nest_asyncio
20+
import agentops
21+
from autogen import AssistantAgent
22+
from autogen.agentchat.user_proxy_agent import UserProxyAgent
23+
24+
load_dotenv()
25+
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY", "your_api_key_here")
26+
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY", "your_openai_api_key_here")
27+
28+
agentops.init(auto_start_session=False)
29+
tracer = agentops.start_trace(
30+
trace_name="AG2 Agent chat with Async Human Inputs", tags=["ag2-chat-async-human-inputs", "agentops-example"]
31+
)
32+
33+
34+
# Define an asynchronous function that simulates some asynchronous task (e.g., I/O operation)
35+
async def my_asynchronous_function():
36+
print("Start asynchronous function")
37+
await asyncio.sleep(2) # Simulate some asynchronous task (e.g., I/O operation)
38+
print("End asynchronous function")
39+
return "input"
40+
41+
42+
# Define a custom class `CustomisedUserProxyAgent` that extends `UserProxyAgent`
43+
class CustomisedUserProxyAgent(UserProxyAgent):
44+
# Asynchronous function to get human input
45+
async def a_get_human_input(self, prompt: str) -> str:
46+
# Call the asynchronous function to get user input asynchronously
47+
user_input = await my_asynchronous_function()
48+
return user_input
49+
50+
# Asynchronous function to receive a message
51+
async def a_receive(
52+
self,
53+
message: Union[Dict, str],
54+
sender,
55+
request_reply: Optional[bool] = None,
56+
silent: Optional[bool] = False,
57+
):
58+
# Call the superclass method to handle message reception asynchronously
59+
await super().a_receive(message, sender, request_reply, silent)
60+
61+
62+
class CustomisedAssistantAgent(AssistantAgent):
63+
# Asynchronous function to get human input
64+
async def a_get_human_input(self, prompt: str) -> str:
65+
# Call the asynchronous function to get user input asynchronously
66+
user_input = await my_asynchronous_function()
67+
return user_input
68+
69+
# Asynchronous function to receive a message
70+
async def a_receive(
71+
self,
72+
message: Union[Dict, str],
73+
sender,
74+
request_reply: Optional[bool] = None,
75+
silent: Optional[bool] = False,
76+
):
77+
# Call the superclass method to handle message reception asynchronously
78+
await super().a_receive(message, sender, request_reply, silent)
79+
80+
81+
nest_asyncio.apply()
82+
83+
84+
async def main():
85+
boss = CustomisedUserProxyAgent(
86+
name="boss",
87+
human_input_mode="ALWAYS",
88+
max_consecutive_auto_reply=0,
89+
code_execution_config=False,
90+
)
91+
92+
assistant = CustomisedAssistantAgent(
93+
name="assistant",
94+
system_message="You will provide some agenda, and I will create questions for an interview meeting. Every time when you generate question then you have to ask user for feedback and if user provides the feedback then you have to incorporate that feedback and generate new set of questions and if user don't want to update then terminate the process and exit",
95+
llm_config={"config_list": [{"model": "gpt-4o-mini", "api_key": os.environ.get("OPENAI_API_KEY")}]},
96+
)
97+
98+
await boss.a_initiate_chat(
99+
assistant,
100+
message="Resume Review, Technical Skills Assessment, Project Discussion, Job Role Expectations, Closing Remarks.",
101+
n_results=3,
102+
)
103+
104+
105+
# await main()
106+
agentops.end_trace(tracer, end_state="Success")

0 commit comments

Comments
 (0)