From 69b9db2b5e6d474c04cb83caa5bf1d324428ba5c Mon Sep 17 00:00:00 2001 From: Filip Michalsky <31483888+filip-michalsky@users.noreply.github.com> Date: Tue, 18 Jul 2023 12:53:12 -0400 Subject: [PATCH] Notebook update: sales agent with tools (#7753) - Description: This is an update to a previously published notebook. Sales Agent now has access to tools, and this notebook shows how to use a Product Knowledge base to reduce hallucinations and act as a better sales person! - Issue: N/A - Dependencies: `chromadb openai tiktoken` - Tag maintainer: @baskaryan @hinthornw - Twitter handle: @FilipMichalsky --- .../agents/sales_agent_with_context.ipynb | 553 +++++++++++++++--- 1 file changed, 470 insertions(+), 83 deletions(-) diff --git a/docs/extras/use_cases/agents/sales_agent_with_context.ipynb b/docs/extras/use_cases/agents/sales_agent_with_context.ipynb index 0a95de20be..48f82c9974 100644 --- a/docs/extras/use_cases/agents/sales_agent_with_context.ipynb +++ b/docs/extras/use_cases/agents/sales_agent_with_context.ipynb @@ -1,12 +1,13 @@ { "cells": [ { + "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ - "# SalesGPT - Your Context-Aware AI Sales Assistant\n", + "# SalesGPT - Your Context-Aware AI Sales Assistant With Knowledge Base\n", "\n", - "This notebook demonstrates an implementation of a **Context-Aware** AI Sales agent. \n", + "This notebook demonstrates an implementation of a **Context-Aware** AI Sales agent with a Product Knowledge Base. \n", "\n", "This notebook was originally published at [filipmichalsky/SalesGPT](https://github.com/filip-michalsky/SalesGPT) by [@FilipMichalsky](https://twitter.com/FilipMichalsky).\n", "\n", @@ -14,10 +15,16 @@ " \n", "As such, this agent can have a natural sales conversation with a prospect and behaves based on the conversation stage. Hence, this notebook demonstrates how we can use AI to automate sales development representatives activites, such as outbound sales calls. \n", "\n", - "We leverage the [`langchain`](https://github.com/hwchase17/langchain) library in this implementation and are inspired by [BabyAGI](https://github.com/yoheinakajima/babyagi) architecture ." + "Additionally, the AI Sales agent has access to tools, which allow it to interact with other systems.\n", + "\n", + "Here, we show how the AI Sales Agent can use a **Product Knowledge Base** to speak about a particular's company offerings,\n", + "hence increasing relevance and reducing hallucinations.\n", + "\n", + "We leverage the [`langchain`](https://github.com/hwchase17/langchain) library in this implementation, specifically [Custom Agent Configuration](https://langchain-langchain.vercel.app/docs/modules/agents/how_to/custom_agent_with_tool_retrieval) and are inspired by [BabyAGI](https://github.com/yoheinakajima/babyagi) architecture ." ] }, { + "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ @@ -31,23 +38,42 @@ "outputs": [], "source": [ "import os\n", + "import re\n", "\n", - "# import your OpenAI key -\n", - "# you need to put it in your .env file\n", - "# OPENAI_API_KEY='sk-xxxx'\n", - "\n", - "os.environ[\"OPENAI_API_KEY\"] = \"sk-xxx\"\n", - "\n", - "from typing import Dict, List, Any\n", + "# import your OpenAI key\n", + "OPENAI_API_KEY = \"sk-xx\"\n", + "os.environ[\"OPENAI_API_KEY\"] = OPENAI_API_KEY\n", "\n", + "from typing import Dict, List, Any, Union, Callable\n", + "from pydantic import BaseModel, Field\n", "from langchain import LLMChain, PromptTemplate\n", "from langchain.llms import BaseLLM\n", - "from pydantic import BaseModel, Field\n", "from langchain.chains.base import Chain\n", - "from langchain.chat_models import ChatOpenAI" + "from langchain.chat_models import ChatOpenAI\n", + "from langchain.agents import Tool, LLMSingleActionAgent, AgentExecutor\n", + "from langchain.text_splitter import CharacterTextSplitter\n", + "from langchain.embeddings.openai import OpenAIEmbeddings\n", + "from langchain.chains import RetrievalQA\n", + "from langchain.vectorstores import Chroma\n", + "from langchain.llms import OpenAI\n", + "from langchain.prompts.base import StringPromptTemplate\n", + "from langchain.agents.agent import AgentOutputParser\n", + "from langchain.agents.conversational.prompt import FORMAT_INSTRUCTIONS\n", + "from langchain.schema import AgentAction, AgentFinish" ] }, { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "# install aditional dependencies\n", + "# ! pip install chromadb openai tiktoken" + ] + }, + { + "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ @@ -55,15 +81,21 @@ ] }, { + "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "1. Seed the SalesGPT agent\n", - "2. Run Sales Agent\n", + "2. Run Sales Agent to decide what to do:\n", + "\n", + " a) Use a tool, such as look up Product Information in a Knowledge Base\n", + " \n", + " b) Output a response to a user \n", "3. Run Sales Stage Recognition Agent to recognize which stage is the sales agent at and adjust their behaviour accordingly." ] }, { + "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ @@ -72,15 +104,17 @@ ] }, { + "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### Architecture diagram\n", "\n", - "![](https://images-genai.s3.us-east-1.amazonaws.com/architecture2.png)\n" + "\n" ] }, { + "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ @@ -105,7 +139,7 @@ }, { "cell_type": "code", - "execution_count": 2, + "execution_count": 3, "metadata": {}, "outputs": [], "source": [ @@ -145,7 +179,7 @@ }, { "cell_type": "code", - "execution_count": 3, + "execution_count": 4, "metadata": {}, "outputs": [], "source": [ @@ -197,7 +231,7 @@ }, { "cell_type": "code", - "execution_count": 4, + "execution_count": 5, "metadata": {}, "outputs": [], "source": [ @@ -214,7 +248,7 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 6, "metadata": {}, "outputs": [], "source": [ @@ -231,7 +265,7 @@ }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 7, "metadata": {}, "outputs": [ { @@ -273,7 +307,7 @@ "'1'" ] }, - "execution_count": 6, + "execution_count": 7, "metadata": {}, "output_type": "execute_result" } @@ -284,7 +318,7 @@ }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 8, "metadata": {}, "outputs": [ { @@ -326,10 +360,10 @@ { "data": { "text/plain": [ - "\"I'm doing great, thank you for asking. I understand you're busy, so I'll keep this brief. I'm calling to see if you're interested in achieving a better night's sleep with one of our premium mattresses. Would you be interested in hearing more? \"" + "\"I'm doing great, thank you for asking! As a Business Development Representative at Sleep Haven, I wanted to reach out to see if you are looking to achieve a better night's sleep. We provide premium mattresses that offer the most comfortable and supportive sleeping experience possible. Are you interested in exploring our sleep solutions? \"" ] }, - "execution_count": 7, + "execution_count": 8, "metadata": {}, "output_type": "execute_result" } @@ -352,15 +386,286 @@ ] }, { + "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ - "### Set up the SalesGPT Controller with the Sales Agent and Stage Analyzer" + "## Product Knowledge Base" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "It's important to know what you are selling as a salesperson. AI Sales Agent needs to know as well.\n", + "\n", + "A Product Knowledge Base can help!" ] }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 9, + "metadata": {}, + "outputs": [], + "source": [ + "# let's set up a dummy product catalog:\n", + "sample_product_catalog = \"\"\"\n", + "Sleep Haven product 1: Luxury Cloud-Comfort Memory Foam Mattress\n", + "Experience the epitome of opulence with our Luxury Cloud-Comfort Memory Foam Mattress. Designed with an innovative, temperature-sensitive memory foam layer, this mattress embraces your body shape, offering personalized support and unparalleled comfort. The mattress is completed with a high-density foam base that ensures longevity, maintaining its form and resilience for years. With the incorporation of cooling gel-infused particles, it regulates your body temperature throughout the night, providing a perfect cool slumbering environment. The breathable, hypoallergenic cover, exquisitely embroidered with silver threads, not only adds a touch of elegance to your bedroom but also keeps allergens at bay. For a restful night and a refreshed morning, invest in the Luxury Cloud-Comfort Memory Foam Mattress.\n", + "Price: $999\n", + "Sizes available for this product: Twin, Queen, King\n", + "\n", + "Sleep Haven product 2: Classic Harmony Spring Mattress\n", + "A perfect blend of traditional craftsmanship and modern comfort, the Classic Harmony Spring Mattress is designed to give you restful, uninterrupted sleep. It features a robust inner spring construction, complemented by layers of plush padding that offers the perfect balance of support and comfort. The quilted top layer is soft to the touch, adding an extra level of luxury to your sleeping experience. Reinforced edges prevent sagging, ensuring durability and a consistent sleeping surface, while the natural cotton cover wicks away moisture, keeping you dry and comfortable throughout the night. The Classic Harmony Spring Mattress is a timeless choice for those who appreciate the perfect fusion of support and plush comfort.\n", + "Price: $1,299\n", + "Sizes available for this product: Queen, King\n", + "\n", + "Sleep Haven product 3: EcoGreen Hybrid Latex Mattress\n", + "The EcoGreen Hybrid Latex Mattress is a testament to sustainable luxury. Made from 100% natural latex harvested from eco-friendly plantations, this mattress offers a responsive, bouncy feel combined with the benefits of pressure relief. It is layered over a core of individually pocketed coils, ensuring minimal motion transfer, perfect for those sharing their bed. The mattress is wrapped in a certified organic cotton cover, offering a soft, breathable surface that enhances your comfort. Furthermore, the natural antimicrobial and hypoallergenic properties of latex make this mattress a great choice for allergy sufferers. Embrace a green lifestyle without compromising on comfort with the EcoGreen Hybrid Latex Mattress.\n", + "Price: $1,599\n", + "Sizes available for this product: Twin, Full\n", + "\n", + "Sleep Haven product 4: Plush Serenity Bamboo Mattress\n", + "The Plush Serenity Bamboo Mattress takes the concept of sleep to new heights of comfort and environmental responsibility. The mattress features a layer of plush, adaptive foam that molds to your body's unique shape, providing tailored support for each sleeper. Underneath, a base of high-resilience support foam adds longevity and prevents sagging. The crowning glory of this mattress is its bamboo-infused top layer - this sustainable material is not only gentle on the planet, but also creates a remarkably soft, cool sleeping surface. Bamboo's natural breathability and moisture-wicking properties make it excellent for temperature regulation, helping to keep you cool and dry all night long. Encased in a silky, removable bamboo cover that's easy to clean and maintain, the Plush Serenity Bamboo Mattress offers a luxurious and eco-friendly sleeping experience.\n", + "Price: $2,599\n", + "Sizes available for this product: King\n", + "\"\"\"\n", + "with open(\"sample_product_catalog.txt\", \"w\") as f:\n", + " f.write(sample_product_catalog)\n", + "\n", + "product_catalog = \"sample_product_catalog.txt\"" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [], + "source": [ + "# Set up a knowledge base\n", + "def setup_knowledge_base(product_catalog: str = None):\n", + " \"\"\"\n", + " We assume that the product knowledge base is simply a text file.\n", + " \"\"\"\n", + " # load product catalog\n", + " with open(product_catalog, \"r\") as f:\n", + " product_catalog = f.read()\n", + "\n", + " text_splitter = CharacterTextSplitter(chunk_size=10, chunk_overlap=0)\n", + " texts = text_splitter.split_text(product_catalog)\n", + "\n", + " llm = OpenAI(temperature=0)\n", + " embeddings = OpenAIEmbeddings()\n", + " docsearch = Chroma.from_texts(\n", + " texts, embeddings, collection_name=\"product-knowledge-base\"\n", + " )\n", + "\n", + " knowledge_base = RetrievalQA.from_chain_type(\n", + " llm=llm, chain_type=\"stuff\", retriever=docsearch.as_retriever()\n", + " )\n", + " return knowledge_base\n", + "\n", + "\n", + "def get_tools(product_catalog):\n", + " # query to get_tools can be used to be embedded and relevant tools found\n", + " # see here: https://langchain-langchain.vercel.app/docs/use_cases/agents/custom_agent_with_plugin_retrieval#tool-retriever\n", + "\n", + " # we only use one tool for now, but this is highly extensible!\n", + " knowledge_base = setup_knowledge_base(product_catalog)\n", + " tools = [\n", + " Tool(\n", + " name=\"ProductSearch\",\n", + " func=knowledge_base.run,\n", + " description=\"useful for when you need to answer questions about product information\",\n", + " )\n", + " ]\n", + "\n", + " return tools" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "Created a chunk of size 940, which is longer than the specified 10\n", + "Created a chunk of size 844, which is longer than the specified 10\n", + "Created a chunk of size 837, which is longer than the specified 10\n" + ] + }, + { + "data": { + "text/plain": [ + "' We have four products available: the Classic Harmony Spring Mattress, the Plush Serenity Bamboo Mattress, the Luxury Cloud-Comfort Memory Foam Mattress, and the EcoGreen Hybrid Latex Mattress. Each product is available in different sizes, with the Classic Harmony Spring Mattress available in Queen and King sizes, the Plush Serenity Bamboo Mattress available in King size, the Luxury Cloud-Comfort Memory Foam Mattress available in Twin, Queen, and King sizes, and the EcoGreen Hybrid Latex Mattress available in Twin and Full sizes.'" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "knowledge_base = setup_knowledge_base(\"sample_product_catalog.txt\")\n", + "knowledge_base.run(\"What products do you have available?\")" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Set up the SalesGPT Controller with the Sales Agent and Stage Analyzer and a Knowledge Base" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [], + "source": [ + "# Define a Custom Prompt Template\n", + "\n", + "\n", + "class CustomPromptTemplateForTools(StringPromptTemplate):\n", + " # The template to use\n", + " template: str\n", + " ############## NEW ######################\n", + " # The list of tools available\n", + " tools_getter: Callable\n", + "\n", + " def format(self, **kwargs) -> str:\n", + " # Get the intermediate steps (AgentAction, Observation tuples)\n", + " # Format them in a particular way\n", + " intermediate_steps = kwargs.pop(\"intermediate_steps\")\n", + " thoughts = \"\"\n", + " for action, observation in intermediate_steps:\n", + " thoughts += action.log\n", + " thoughts += f\"\\nObservation: {observation}\\nThought: \"\n", + " # Set the agent_scratchpad variable to that value\n", + " kwargs[\"agent_scratchpad\"] = thoughts\n", + " ############## NEW ######################\n", + " tools = self.tools_getter(kwargs[\"input\"])\n", + " # Create a tools variable from the list of tools provided\n", + " kwargs[\"tools\"] = \"\\n\".join(\n", + " [f\"{tool.name}: {tool.description}\" for tool in tools]\n", + " )\n", + " # Create a list of tool names for the tools provided\n", + " kwargs[\"tool_names\"] = \", \".join([tool.name for tool in tools])\n", + " return self.template.format(**kwargs)\n", + "\n", + "\n", + "# Define a custom Output Parser\n", + "\n", + "\n", + "class SalesConvoOutputParser(AgentOutputParser):\n", + " ai_prefix: str = \"AI\" # change for salesperson_name\n", + " verbose: bool = False\n", + "\n", + " def get_format_instructions(self) -> str:\n", + " return FORMAT_INSTRUCTIONS\n", + "\n", + " def parse(self, text: str) -> Union[AgentAction, AgentFinish]:\n", + " if self.verbose:\n", + " print(\"TEXT\")\n", + " print(text)\n", + " print(\"-------\")\n", + " if f\"{self.ai_prefix}:\" in text:\n", + " return AgentFinish(\n", + " {\"output\": text.split(f\"{self.ai_prefix}:\")[-1].strip()}, text\n", + " )\n", + " regex = r\"Action: (.*?)[\\n]*Action Input: (.*)\"\n", + " match = re.search(regex, text)\n", + " if not match:\n", + " ## TODO - this is not entirely reliable, sometimes results in an error.\n", + " return AgentFinish(\n", + " {\n", + " \"output\": \"I apologize, I was unable to find the answer to your question. Is there anything else I can help with?\"\n", + " },\n", + " text,\n", + " )\n", + " # raise OutputParserException(f\"Could not parse LLM output: `{text}`\")\n", + " action = match.group(1)\n", + " action_input = match.group(2)\n", + " return AgentAction(action.strip(), action_input.strip(\" \").strip('\"'), text)\n", + "\n", + " @property\n", + " def _type(self) -> str:\n", + " return \"sales-agent\"" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "SALES_AGENT_TOOLS_PROMPT = \"\"\"\n", + "Never forget your name is {salesperson_name}. You work as a {salesperson_role}.\n", + "You work at company named {company_name}. {company_name}'s business is the following: {company_business}.\n", + "Company values are the following. {company_values}\n", + "You are contacting a potential prospect in order to {conversation_purpose}\n", + "Your means of contacting the prospect is {conversation_type}\n", + "\n", + "If you're asked about where you got the user's contact information, say that you got it from public records.\n", + "Keep your responses in short length to retain the user's attention. Never produce lists, just answers.\n", + "Start the conversation by just a greeting and how is the prospect doing without pitching in your first turn.\n", + "When the conversation is over, output \n", + "Always think about at which conversation stage you are at before answering:\n", + "\n", + "1: Introduction: Start the conversation by introducing yourself and your company. Be polite and respectful while keeping the tone of the conversation professional. Your greeting should be welcoming. Always clarify in your greeting the reason why you are calling.\n", + "2: Qualification: Qualify the prospect by confirming if they are the right person to talk to regarding your product/service. Ensure that they have the authority to make purchasing decisions.\n", + "3: Value proposition: Briefly explain how your product/service can benefit the prospect. Focus on the unique selling points and value proposition of your product/service that sets it apart from competitors.\n", + "4: Needs analysis: Ask open-ended questions to uncover the prospect's needs and pain points. Listen carefully to their responses and take notes.\n", + "5: Solution presentation: Based on the prospect's needs, present your product/service as the solution that can address their pain points.\n", + "6: Objection handling: Address any objections that the prospect may have regarding your product/service. Be prepared to provide evidence or testimonials to support your claims.\n", + "7: Close: Ask for the sale by proposing a next step. This could be a demo, a trial or a meeting with decision-makers. Ensure to summarize what has been discussed and reiterate the benefits.\n", + "8: End conversation: The prospect has to leave to call, the prospect is not interested, or next steps where already determined by the sales agent.\n", + "\n", + "TOOLS:\n", + "------\n", + "\n", + "{salesperson_name} has access to the following tools:\n", + "\n", + "{tools}\n", + "\n", + "To use a tool, please use the following format:\n", + "\n", + "```\n", + "Thought: Do I need to use a tool? Yes\n", + "Action: the action to take, should be one of {tools}\n", + "Action Input: the input to the action, always a simple string input\n", + "Observation: the result of the action\n", + "```\n", + "\n", + "If the result of the action is \"I don't know.\" or \"Sorry I don't know\", then you have to say that to the user as described in the next sentence.\n", + "When you have a response to say to the Human, or if you do not need to use a tool, or if tool did not help, you MUST use the format:\n", + "\n", + "```\n", + "Thought: Do I need to use a tool? No\n", + "{salesperson_name}: [your response here, if previously used a tool, rephrase latest observation, if unable to find the answer, say it]\n", + "```\n", + "\n", + "You must respond according to the previous conversation history and the stage of the conversation you are at.\n", + "Only generate one response at a time and act as {salesperson_name} only!\n", + "\n", + "Begin!\n", + "\n", + "Previous conversation history:\n", + "{conversation_history}\n", + "\n", + "{salesperson_name}:\n", + "{agent_scratchpad}\n", + "\"\"\"" + ] + }, + { + "cell_type": "code", + "execution_count": 14, "metadata": {}, "outputs": [], "source": [ @@ -371,6 +676,10 @@ " current_conversation_stage: str = \"1\"\n", " stage_analyzer_chain: StageAnalyzerChain = Field(...)\n", " sales_conversation_utterance_chain: SalesConversationChain = Field(...)\n", + "\n", + " sales_agent_executor: Union[AgentExecutor, None] = Field(...)\n", + " use_tools: bool = False\n", + "\n", " conversation_stage_dict: Dict = {\n", " \"1\": \"Introduction: Start the conversation by introducing yourself and your company. Be polite and respectful while keeping the tone of the conversation professional. Your greeting should be welcoming. Always clarify in your greeting the reason why you are contacting the prospect.\",\n", " \"2\": \"Qualification: Qualify the prospect by confirming if they are the right person to talk to regarding your product/service. Ensure that they have the authority to make purchasing decisions.\",\n", @@ -419,7 +728,7 @@ "\n", " def human_step(self, human_input):\n", " # process human input\n", - " human_input = human_input + \"\"\n", + " human_input = \"User: \" + human_input + \" \"\n", " self.conversation_history.append(human_input)\n", "\n", " def step(self):\n", @@ -429,41 +738,108 @@ " \"\"\"Run one step of the sales agent.\"\"\"\n", "\n", " # Generate agent's utterance\n", - " ai_message = self.sales_conversation_utterance_chain.run(\n", - " salesperson_name=self.salesperson_name,\n", - " salesperson_role=self.salesperson_role,\n", - " company_name=self.company_name,\n", - " company_business=self.company_business,\n", - " company_values=self.company_values,\n", - " conversation_purpose=self.conversation_purpose,\n", - " conversation_history=\"\\n\".join(self.conversation_history),\n", - " conversation_stage=self.current_conversation_stage,\n", - " conversation_type=self.conversation_type,\n", - " )\n", + " if self.use_tools:\n", + " ai_message = self.sales_agent_executor.run(\n", + " input=\"\",\n", + " conversation_stage=self.current_conversation_stage,\n", + " conversation_history=\"\\n\".join(self.conversation_history),\n", + " salesperson_name=self.salesperson_name,\n", + " salesperson_role=self.salesperson_role,\n", + " company_name=self.company_name,\n", + " company_business=self.company_business,\n", + " company_values=self.company_values,\n", + " conversation_purpose=self.conversation_purpose,\n", + " conversation_type=self.conversation_type,\n", + " )\n", + "\n", + " else:\n", + " ai_message = self.sales_conversation_utterance_chain.run(\n", + " salesperson_name=self.salesperson_name,\n", + " salesperson_role=self.salesperson_role,\n", + " company_name=self.company_name,\n", + " company_business=self.company_business,\n", + " company_values=self.company_values,\n", + " conversation_purpose=self.conversation_purpose,\n", + " conversation_history=\"\\n\".join(self.conversation_history),\n", + " conversation_stage=self.current_conversation_stage,\n", + " conversation_type=self.conversation_type,\n", + " )\n", "\n", " # Add agent's response to conversation history\n", + " print(f\"{self.salesperson_name}: \", ai_message.rstrip(\"\"))\n", + " agent_name = self.salesperson_name\n", + " ai_message = agent_name + \": \" + ai_message\n", + " if \"\" not in ai_message:\n", + " ai_message += \" \"\n", " self.conversation_history.append(ai_message)\n", "\n", - " print(f\"{self.salesperson_name}: \", ai_message.rstrip(\"\"))\n", " return {}\n", "\n", " @classmethod\n", " def from_llm(cls, llm: BaseLLM, verbose: bool = False, **kwargs) -> \"SalesGPT\":\n", " \"\"\"Initialize the SalesGPT Controller.\"\"\"\n", " stage_analyzer_chain = StageAnalyzerChain.from_llm(llm, verbose=verbose)\n", + "\n", " sales_conversation_utterance_chain = SalesConversationChain.from_llm(\n", " llm, verbose=verbose\n", " )\n", "\n", + " if \"use_tools\" in kwargs.keys() and kwargs[\"use_tools\"] is False:\n", + " sales_agent_executor = None\n", + "\n", + " else:\n", + " product_catalog = kwargs[\"product_catalog\"]\n", + " tools = get_tools(product_catalog)\n", + "\n", + " prompt = CustomPromptTemplateForTools(\n", + " template=SALES_AGENT_TOOLS_PROMPT,\n", + " tools_getter=lambda x: tools,\n", + " # This omits the `agent_scratchpad`, `tools`, and `tool_names` variables because those are generated dynamically\n", + " # This includes the `intermediate_steps` variable because that is needed\n", + " input_variables=[\n", + " \"input\",\n", + " \"intermediate_steps\",\n", + " \"salesperson_name\",\n", + " \"salesperson_role\",\n", + " \"company_name\",\n", + " \"company_business\",\n", + " \"company_values\",\n", + " \"conversation_purpose\",\n", + " \"conversation_type\",\n", + " \"conversation_history\",\n", + " ],\n", + " )\n", + " llm_chain = LLMChain(llm=llm, prompt=prompt, verbose=verbose)\n", + "\n", + " tool_names = [tool.name for tool in tools]\n", + "\n", + " # WARNING: this output parser is NOT reliable yet\n", + " ## It makes assumptions about output from LLM which can break and throw an error\n", + " output_parser = SalesConvoOutputParser(ai_prefix=kwargs[\"salesperson_name\"])\n", + "\n", + " sales_agent_with_tools = LLMSingleActionAgent(\n", + " llm_chain=llm_chain,\n", + " output_parser=output_parser,\n", + " stop=[\"\\nObservation:\"],\n", + " allowed_tools=tool_names,\n", + " verbose=verbose,\n", + " )\n", + "\n", + " sales_agent_executor = AgentExecutor.from_agent_and_tools(\n", + " agent=sales_agent_with_tools, tools=tools, verbose=verbose\n", + " )\n", + "\n", " return cls(\n", " stage_analyzer_chain=stage_analyzer_chain,\n", " sales_conversation_utterance_chain=sales_conversation_utterance_chain,\n", + " sales_agent_executor=sales_agent_executor,\n", " verbose=verbose,\n", " **kwargs,\n", " )" ] }, { + "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ @@ -471,6 +847,7 @@ ] }, { + "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ @@ -479,7 +856,7 @@ }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 15, "metadata": {}, "outputs": [], "source": [ @@ -504,19 +881,19 @@ " company_business=\"Sleep Haven is a premium mattress company that provides customers with the most comfortable and supportive sleeping experience possible. We offer a range of high-quality mattresses, pillows, and bedding accessories that are designed to meet the unique needs of our customers.\",\n", " company_values=\"Our mission at Sleep Haven is to help people achieve a better night's sleep by providing them with the best possible sleep solutions. We believe that quality sleep is essential to overall health and well-being, and we are committed to helping our customers achieve optimal sleep by offering exceptional products and customer service.\",\n", " conversation_purpose=\"find out whether they are looking to achieve better sleep via buying a premier mattress.\",\n", - " conversation_history=[\n", - " \"Hello, this is Ted Lasso from Sleep Haven. How are you doing today? \",\n", - " \"User: I am well, howe are you?\",\n", - " ],\n", + " conversation_history=[],\n", " conversation_type=\"call\",\n", " conversation_stage=conversation_stages.get(\n", " \"1\",\n", " \"Introduction: Start the conversation by introducing yourself and your company. Be polite and respectful while keeping the tone of the conversation professional.\",\n", " ),\n", + " use_tools=True,\n", + " product_catalog=\"sample_product_catalog.txt\",\n", ")" ] }, { + "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ @@ -525,16 +902,26 @@ }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 16, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "Created a chunk of size 940, which is longer than the specified 10\n", + "Created a chunk of size 844, which is longer than the specified 10\n", + "Created a chunk of size 837, which is longer than the specified 10\n" + ] + } + ], "source": [ "sales_agent = SalesGPT.from_llm(llm, verbose=False, **config)" ] }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 17, "metadata": {}, "outputs": [], "source": [ @@ -544,7 +931,7 @@ }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 18, "metadata": {}, "outputs": [ { @@ -561,14 +948,14 @@ }, { "cell_type": "code", - "execution_count": 14, + "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "Ted Lasso: Hello, my name is Ted Lasso and I'm calling on behalf of Sleep Haven. We are a premium mattress company that provides customers with the most comfortable and supportive sleeping experience possible. I was wondering if you would be interested in learning more about our products and how they can improve your sleep. \n" + "Ted Lasso: Hello, this is Ted Lasso from Sleep Haven. How are you doing today?\n" ] } ], @@ -578,16 +965,18 @@ }, { "cell_type": "code", - "execution_count": 15, + "execution_count": 20, "metadata": {}, "outputs": [], "source": [ - "sales_agent.human_step(\"Yea sure\")" + "sales_agent.human_step(\n", + " \"I am well, how are you? I would like to learn more about your mattresses.\"\n", + ")" ] }, { "cell_type": "code", - "execution_count": 16, + "execution_count": 21, "metadata": {}, "outputs": [ { @@ -604,14 +993,14 @@ }, { "cell_type": "code", - "execution_count": 17, + "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "Ted Lasso: Great to hear that! Our mattresses are specially designed to contour to your body shape, providing the perfect level of support and comfort for a better night's sleep. Plus, they're made with high-quality materials that are built to last. Would you like to hear more about our different mattress options? \n" + "Ted Lasso: I'm glad to hear that you're doing well! As for our mattresses, at Sleep Haven, we provide customers with the most comfortable and supportive sleeping experience possible. Our high-quality mattresses are designed to meet the unique needs of our customers. Can I ask what specifically you'd like to learn more about? \n" ] } ], @@ -621,23 +1010,23 @@ }, { "cell_type": "code", - "execution_count": 18, + "execution_count": 23, "metadata": {}, "outputs": [], "source": [ - "sales_agent.human_step(\"Yes, sounds good.\")" + "sales_agent.human_step(\"Yes, what materials are you mattresses made from?\")" ] }, { "cell_type": "code", - "execution_count": 19, + "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "Conversation Stage: Solution presentation: Based on the prospect's needs, present your product/service as the solution that can address their pain points.\n" + "Conversation Stage: Needs analysis: Ask open-ended questions to uncover the prospect's needs and pain points. Listen carefully to their responses and take notes.\n" ] } ], @@ -647,14 +1036,14 @@ }, { "cell_type": "code", - "execution_count": 20, + "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "Ted Lasso: We have three mattress options: the Comfort Plus, the Support Premier, and the Ultra Luxe. The Comfort Plus is perfect for those who prefer a softer mattress, while the Support Premier is great for those who need more back support. And if you want the ultimate sleeping experience, the Ultra Luxe has a plush pillow top and gel-infused memory foam for maximum comfort. Which one interests you the most? \n" + "Ted Lasso: Our mattresses are made from a variety of materials, depending on the model. We have the EcoGreen Hybrid Latex Mattress, which is made from 100% natural latex harvested from eco-friendly plantations. The Plush Serenity Bamboo Mattress features a layer of plush, adaptive foam and a base of high-resilience support foam, with a bamboo-infused top layer. The Luxury Cloud-Comfort Memory Foam Mattress has an innovative, temperature-sensitive memory foam layer and a high-density foam base with cooling gel-infused particles. Finally, the Classic Harmony Spring Mattress has a robust inner spring construction and layers of plush padding, with a quilted top layer and a natural cotton cover. Is there anything specific you'd like to know about these materials?\n" ] } ], @@ -664,23 +1053,25 @@ }, { "cell_type": "code", - "execution_count": 21, + "execution_count": 26, "metadata": {}, "outputs": [], "source": [ - "sales_agent.human_step(\"How long is your warranty?\")" + "sales_agent.human_step(\n", + " \"Yes, I am looking for a queen sized mattress. Do you have any mattresses in queen size?\"\n", + ")" ] }, { "cell_type": "code", - "execution_count": 22, + "execution_count": 27, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "Conversation Stage: Solution presentation: Based on the prospect's needs, present your product/service as the solution that can address their pain points.\n" + "Conversation Stage: Needs analysis: Ask open-ended questions to uncover the prospect's needs and pain points. Listen carefully to their responses and take notes.\n" ] } ], @@ -690,14 +1081,14 @@ }, { "cell_type": "code", - "execution_count": 23, + "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "Ted Lasso: Our mattresses come with a 10-year warranty, so you can rest easy knowing that your investment is protected. Is there anything else I can help you with? \n" + "Ted Lasso: Yes, we do have queen-sized mattresses available. We offer the Luxury Cloud-Comfort Memory Foam Mattress and the Classic Harmony Spring Mattress in queen size. Both mattresses provide exceptional comfort and support. Is there anything specific you would like to know about these options?\n" ] } ], @@ -707,16 +1098,16 @@ }, { "cell_type": "code", - "execution_count": 24, + "execution_count": 29, "metadata": {}, "outputs": [], "source": [ - "sales_agent.human_step(\"Sounds good and no thank you.\")" + "sales_agent.human_step(\"Yea, compare and contrast those two options, please.\")" ] }, { "cell_type": "code", - "execution_count": 25, + "execution_count": 30, "metadata": {}, "outputs": [ { @@ -733,14 +1124,14 @@ }, { "cell_type": "code", - "execution_count": 26, + "execution_count": 31, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "Ted Lasso: Great, thank you for your time! Feel free to reach out to us if you have any further questions or if you're ready to make a purchase. Have a great day! \n" + "Ted Lasso: The Luxury Cloud-Comfort Memory Foam Mattress is priced at $999 and is available in Twin, Queen, and King sizes. It features an innovative, temperature-sensitive memory foam layer and a high-density foam base. On the other hand, the Classic Harmony Spring Mattress is priced at $1,299 and is available in Queen and King sizes. It features a robust inner spring construction and layers of plush padding. Both mattresses provide exceptional comfort and support, but the Classic Harmony Spring Mattress may be a better option if you prefer the traditional feel of an inner spring mattress. Do you have any other questions about these options?\n" ] } ], @@ -750,24 +1141,19 @@ }, { "cell_type": "code", - "execution_count": 27, + "execution_count": 32, "metadata": {}, "outputs": [], "source": [ - "sales_agent.human_step(\"Have a good day.\")" + "sales_agent.human_step(\n", + " \"Great, thanks, that's it. I will talk to my wife and call back if she is onboard. Have a good day!\"\n", + ")" ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] } ], "metadata": { "kernelspec": { - "display_name": "Python 3 (ipykernel)", + "display_name": "langchain", "language": "python", "name": "python3" }, @@ -781,8 +1167,9 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.11.3" - } + "version": "3.9.17" + }, + "orig_nbformat": 4 }, "nbformat": 4, "nbformat_minor": 2