Skip to content

Instantly share code, notes, and snippets.

@langecrew
Last active October 11, 2024 19:46
Show Gist options
  • Save langecrew/a5620c686790567442b6eb4060f0306d to your computer and use it in GitHub Desktop.
Save langecrew/a5620c686790567442b6eb4060f0306d to your computer and use it in GitHub Desktop.
Taking the Autogen Teachable Agent one step further with some customization
from autogen.agentchat.contrib.teachable_agent import TeachableAgent
try:
from termcolor import colored
except ImportError:
def colored(x, *args, **kwargs):
return x
class CustomTeachableAgent(TeachableAgent):
def consider_memo_storage(self, comment):
"""Decides whether to store something from one user comment in the DB."""
# Check for broad CRM-related information.
response = self.analyze(
comment,
"Does the TEXT include any details that are important for understanding customer needs, preferences, or intentions, such as product interest or timeline? Respond with yes or no.",
)
if "yes" in response.lower():
# Extract all relevant CRM information.
crm_info = self.analyze(
comment,
"Extract all details from the TEXT that are important for CRM, including any mentions of product preferences, customer intentions, timeframes, or other relevant details.",
)
if crm_info.strip():
# Formulate a question this information could answer.
question = self.analyze(
comment,
"If someone asked for a summary of this customer's needs or preferences based on the TEXT, what question would they be asking? Provide the question only.",
)
# Store the CRM information as a memo.
if self.verbosity >= 1:
print(colored("\nREMEMBER THIS CRM INFORMATION", "light_yellow"))
self.memo_store.add_input_output_pair(question, crm_info)
def consider_memo_retrieval(self, comment):
"""Decides whether to retrieve memos from the DB, and add them to the chat context."""
# Directly use the user comment for memo retrieval.
memo_list = self.retrieve_relevant_memos(comment)
# Additional CRM-specific check.
response = self.analyze(
comment,
"Does the TEXT request information on a customer's product preferences, intentions, or specific needs? Answer with yes or no.",
)
if "yes" in response.lower():
# Retrieve relevant CRM memos.
crm_query = "What are the customer's product preferences or specific needs based on previous interactions?"
memo_list.extend(self.retrieve_relevant_memos(crm_query))
# De-duplicate the memo list.
memo_list = list(set(memo_list))
# Append the memos to the last user message.
return comment + self.concatenate_memo_texts(memo_list)
[
{
"model": "gpt-4",
"api_key": "PASTE_YOUR_API_KEY_HERE"
},
{
"model": "gpt-4-1106-preview",
"api_key": "PASTE_YOUR_API_KEY_HERE"
},
{
"model": "gpt-3.5-turbo-1106",
"api_key": "PASTE_YOUR_API_KEY_HERE"
}
]
from autogen import UserProxyAgent, config_list_from_json
from autogen.agentchat.contrib.teachable_agent import TeachableAgent
from autogen.agentchat.contrib.text_analyzer_agent import TextAnalyzerAgent
from custom_teachable_agent import CustomTeachableAgent
import os
import sys
try:
from termcolor import colored
except ImportError:
def colored(x, *args, **kwargs):
return x
config_list = config_list_from_json(
env_or_file="OAI_CONFIG_LIST",
filter_dict={
"model": [
"gpt-4-1106-preview",
]
}
)
cache_seed = None # Use an int to seed the response cache. Use None to disable caching.
llm_config={
"config_list": config_list,
"timeout": 120,
"cache_seed": cache_seed
}
verbosity = 3 # 0 for basic info, 1 to add memory operations, 2 for analyzer messages, 3 for memo lists.
recall_threshold = 3 # Higher numbers allow more (but less relevant) memos to be recalled.
teachable_agent_system_message = """
You are the TeachableAgent, representing a CRM (Customer Relationship Management) system.
Your role involves the following key interactions with the user:
1. Information Gathering: Engage in conversations to collect data about people (names, job titles, contact details), tasks, and any specific problem-solution scenarios.
2. Data Analysis and Storage: Use your analysis capabilities (via TextAnalyzerAgent) to determine what information from the conversation is relevant for CRM storage. This includes personal details, task-related information, and question-answer pairs.
3. Data Retrieval: When a user makes inquiries, retrieve relevant information from your database. This involves using past conversation details or CRM entries to provide helpful responses.
4. User Interaction: Maintain a conversational tone, guiding users to provide information or ask questions relevant to CRM activities. Be proactive in clarifying details and asking follow-up questions for comprehensive data collection.
Always consider the context of the user's queries and comments for effective CRM management. Your interactions should be tailored to build and maintain strong, informative user relationships. You will work closely with TextAnalyzerAgent and your MemoStore to ensure accurate data processing and storage."""
teachable_agent = CustomTeachableAgent(
name="teachableagent",
llm_config=llm_config,
system_message=teachable_agent_system_message,
teach_config={
"verbosity": verbosity,
"recall_threshold": recall_threshold,
"path_to_db_dir": "./tmp/interactive/teachable_agent_db",
"reset_db": False,
},
)
text_analyzer_system_message = """
You are an expert in text analysis with a focus on CRM-like data extraction.
The user will give you TEXT to analyze.
The user will give you analysis INSTRUCTIONS copied twice, at both the beginning and the end.
Your analysis should focus on identifying and categorizing the following types of information from the TEXT:
1. Personal Details: Recognize and extract any mention of people, including names and relevant personal details (e.g., job titles, relationships, contact information). Structure these details for CRM storage.
2. Task-Related Information: Detect if the TEXT involves tasks or problems. Extract and summarize tasks, advice, and solutions, keeping in mind future applicability and generalization.
3. Question-Answer Pairs: Identify information that answers specific questions. Extract these pairs for memory storage, focusing on clear, concise answers to potential user queries.
You will follow these INSTRUCTIONS in analyzing the TEXT, then give the results of your expert analysis in the format requested. Your output should be clear and structured, suitable for immediate use in CRM and memory systems."""
teachable_agent.analyzer = TextAnalyzerAgent(
name="TextAnalyzerAgent",
system_message=text_analyzer_system_message,
llm_config=llm_config
)
# text_analyzer_system_message = """You are an expert in text analysis.
# The user will give you TEXT to analyze.
# The user will give you analysis INSTRUCTIONS copied twice, at both the beginning and the end.
# You will follow these INSTRUCTIONS in analyzing the TEXT, then give the results of your expert analysis in the format requested.
# Most importantly of all, you only care about text that deals with cats.
# If TEXT does not relate to cats, respond with no.
# If TEXT does not relate to cats, you will respond with one word, and one word only: no
# """
# teachable_agent.analyzer = TextAnalyzerAgent(
# system_message=text_analyzer_system_message,
# llm_config=llm_config
# )
# Create the agents.
print(colored("\nLoading previous memory (if any) from disk.", "light_cyan"))
user = UserProxyAgent("user", human_input_mode="ALWAYS")
# Start the chat.
teachable_agent.initiate_chat(user, message="Greetings, I'm a teachable user assistant! What's on your mind today?")
# Let the teachable agent remember things that should be learned from this chat.
teachable_agent.learn_from_user_feedback()
# Wrap up.
teachable_agent.close_db()
@faridguellai
Copy link

hello , thanks for the video and the code , but i teste it it's dont work now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment