In today’s fast-paced digital world, businesses are constantly looking for innovative ways to provide customized customer experiences that stand out. AI agents play a crucial role in personalizing these experiences by understanding customer behavior and tailoring interactions in real-time. In this article, we’ll explore how AI agents work to deliver customized customer experiences, examine the technologies behind them, and discuss practical applications across various industries to help businesses enhance their customer engagement and satisfaction.
This article was published as a part of the Data Science Blogathon.
AI agents are specialized programs or models designed to perform tasks autonomously using artificial intelligence techniques, often mimicking human decision-making, reasoning, and learning. They interact with users or systems, learn from data, adapt to new information, and execute specific functions within a defined scope, like customer support, process automation, or complex data analysis.
In the real world, tasks rarely have single-step solutions. Instead, they typically involve a series of interconnected and standalone steps to be carried out. For example, for a question like –
“Which coffee had the highest sales in our Manhattan based store?” might have a single step answer.
However, for a question like –
“Which 3 coffee types would be liked by our customer Emily who works at Google, NYC office? She prefers low calories coffee and likes Lattes more than Cappuccinos. Also could you send a mail to her with a promotional campaign for these 3 coffee types mentioning the nearest location of our store to her office where she can grab these?”
A single LLM would not be able to handle such a complex query by itself and this is where the need for an AI agent consisting of multiple LLMs arises.
For handling such complex tasks, instead of prompting a single LLM, multiple LLMs can be combined together acting as AI agents to break the complex task into multiple independent tasks.
We will now learn about key features of AI agents in detail below:
AI agents are made up of certain building blocks. Let us go through them:
Let us consider a use case in which a coffee chain like Starbucks wants to build an AI agent for drafting and mailing personalized promotional campaigns recommending 3 types of coffee for their customers based on their coffee preferences. The promotional campaign should also include the location of the coffee store which is nearest to the customer’s location where the customer can easily grab these coffees.
Start by installing the necessary libraries.
!pip install llama-index-core
!pip install llama-index-readers-file
!pip install llama-index-embeddings-openai
!pip install llama-index-llms-llama-api
!pip install 'crewai[tools]'
!pip install llama-index-llms-langchain
We will create the multi agent system here using CrewAI. This framework enables creation of a collaborative group of AI agents working together to accomplish a shared objective.
import os
from crewai import Agent, Task, Crew, Process
from crewai_tools import LlamaIndexTool
from llama_index.core import SimpleDirectoryReader, VectorStoreIndex
from llama_index.llms.openai import OpenAI
from langchain_openai import ChatOpenAI
openai_api_key = ''
os.environ['OPENAI_API_KEY']=openai_api_key
We will be using OpenAI LLMs to query with our CSV data in the next steps. Hence defining the OpenAI key here as an environment variable is necessary here.
We will be using the Starbucks Data here which has information on different types of Starbucks Coffee along with their nutritional information.
reader = SimpleDirectoryReader(input_files=["starbucks.csv"])
docs = reader.load_data()
#we have used gpt-4o model here as the LLM. Other OpenAI models can also be used
llm = ChatOpenAI(temperature=0, model="gpt-4o", max_tokens=1000)
#creates a VectorStoreIndex from a list of documents (docs)
index = VectorStoreIndex.from_documents(docs)
#The vector store is transformed into a query engine.
#Setting similarity_top_k=5 limits the results to the top 5 documents that are most similar to the query,
#llm specifies that the LLM should be used to process and refine the query results
query_engine = index.as_query_engine(similarity_top_k=5, llm=llm)
query_tool = LlamaIndexTool.from_query_engine(
query_engine,
name="Coffee Promo Campaign",
description="Use this tool to lookup the Starbucks Coffee Dataset",
)
def create_crew(taste):
#Agent For Choosing 3 Types of Coffee Based on Customer Preferences
researcher = Agent(
role="Coffee Chooser",
goal="Choose Starbucks Coffee based on customer preferences",
backstory="""You work at Starbucks.
Your goal is to recommend 3 Types of Coffee FROM THE GIVEN DATA ONLY based on a given customer's lifestyle tastes %s. DO NOT USE THE WEB to recommend the coffee types."""%(taste),
verbose=True,
allow_delegation=False,
tools=[query_tool],
)
#Agent For Drafting Promotional Campaign based on Chosen Coffee
writer = Agent(
role="Product Content Specialist",
goal="""Craft a Promotional Campaign that can mailed to customer based on the 3 Types of the Coffee suggested by the previous agent.Also GIVE ACCURATE Starbucks Location in the given location in the query %s using 'web_search_tool' from the WEB where the customer can enjoy these coffees in the writeup"""%(taste),
backstory="""You are a renowned Content Specialist, known for writing to customers for promotional campaigns""",
verbose=True,
allow_delegation=False)
#Task For Choosing 3 Types of Coffee Based on Customer Preferences
task1 = Task(
description="""Recommend 3 Types of Coffee FROM THE GIVEN DATA ONLY based on a given customer's lifestyle tastes %s. DO NOT USE THE WEB to recommend the coffee types."""%(taste),
expected_output="List of 3 Types of Coffee",
agent=researcher,
)
#Task For Drafting Promotional Campaign based on Chosen Coffee
task2 = Task(
description="""Using ONLY the insights provided, develop a Promotional Campaign that can mailed to customer based on 3 Types of the Coffee suggested by the previous agent.
Also GIVE ACCURATE Starbucks Location in the given location in the query %s using 'web_search_tool' from the WEB where the customer can enjoy these coffees in the writeup. Your writing should be accurate and to the point. Make it respectful and customer friendly"""%(taste),
expected_output="Full Response to customer on how to resolve the issue .",
agent=writer
)
#Define the crew based on the defined agents and tasks
crew = Crew(
agents=[researcher,writer],
tasks=[task1,task2],
verbose=True, # You can set it to 1 or 2 to different logging levels
)
result = crew.kickoff()
return result
In the above code, we have set up a two-agent system where:
The tasks are coordinated within a Crew, and the process kicks off with the crew.kickoff() function, returning the final result of the task execution.
text = create_crew("Emily is from Gurgaon, India and likes High calorie coffees and prefers Latte more than Cappuccino.")
print(text)
As we can see, we want to check the output of the MultiAgent system we created for a sample customer ‘Emily’ who stays in Gurgaon, India and and likes High calorie coffees and prefers Latte more than Cappuccino.
# Agent: Coffee Chooser
## Task: Recommend 3 Types of Coffee FROM THE GIVEN DATA ONLY based on a given customer's lifestyle tastes Name - Emily, Location - Gurgaon, Tastes - likes High calorie coffees and prefers Latte more than Cappuccino.. DO NOT USE THE WEB to recommend the coffee types.
# Agent: Coffee Chooser
## Thought: I need to gather coffee options that match Emily's preferences for high calorie coffees, with a preference for lattes over cappuccinos.
## Using tool: Coffee Promo Campaign
## Tool Input:
"{\"query\": \"high calorie lattes\"}"
## Tool Output:
The high-calorie lattes include the Caffè Latte with 2% Milk, which has 240 calories, and the Caffè Latte with Soymilk, which has 190 calories.
# Agent: Coffee Chooser
## Thought: Thought: I need to perform another search to find more latte options that are high in calories to meet Emily's preferences.
## Using tool: Coffee Promo Campaign
## Tool Input:
"{\"query\": \"high calorie coffees with latte base\"}"
## Tool Output:
High-calorie coffee options with a latte base include:
1. Vanilla Latte (Or Other Flavoured Latte) with 2% Milk, Venti size, which has 320 calories.
2. Vanilla Latte (Or Other Flavoured Latte) with Soymilk, which has 270 calories.
# Agent: Coffee Chooser
## Final Answer:
1. Caffè Latte with 2% Milk (240 calories)
2. Vanilla Latte with 2% Milk, Venti size (320 calories)
3. Caffè Latte with Soymilk (190 calories)
# Agent: Product Content Specialist
## Task: Using ONLY the insights provided, develop a Promotional Campaign that can mailed to customer based on 3 Types of the Coffee suggested by the previous agent.
Also GIVE ACCURATE Starbucks Location in the given location in the query Name - Emily, Location - Gurgaon, Tastes - likes High calorie coffees and prefers Latte more than Cappuccino. using 'web_search_tool' from the WEB where the customer can enjoy these coffees in the writeup. Your writing should be accurate and to the point. Make it respectful and customer friendly
# Agent: Product Content Specialist
## Final Answer:
Dear Emily,
We're thrilled to connect with you and share an exciting lineup of coffees tailored to your love for high-calorie drinks and preference for lattes! Treat yourself to our carefully crafted selections, perfect for your taste buds.
1. **Caffè Latte with 2% Milk (240 calories)**: This classic option combines rich espresso with steamed 2% milk for a wonderfully creamy experience. Enjoy the perfect balance of flavors while indulging in those calories!
2. **Vanilla Latte with 2% Milk, Venti Size (320 calories)**: Elevate your day with our delightful Vanilla Latte! The infusion of vanilla syrup adds a sweet touch to the robust espresso and creamy milk, making it a luscious choice that checks all your boxes.
3. **Caffè Latte with Soymilk (190 calories)**: For a slightly lighter yet satisfying variant, try our Caffè Latte with soymilk. This drink maintains the creamy goodness while being a tad lower on calories, perfect for a mid-day refreshment!
To experience these luxurious lattes, visit us at:
**Starbucks Location**:
Starbucks at **Galleria Market, DLF Phase 4, Gurgaon**
Address: Shop No. 32, Ground Floor, Galleria Market, DLF Phase 4, Gurugram, Haryana 122002, India.
We can't wait for you to dive into the delightful world of our lattes! Stop by and savor these beautifully crafted beverages that will surely brighten your day.
We're here to make your coffee moments memorable.
Warm regards,
[Your Name]
Product Content Specialist
Starbucks
from langchain.agents.agent_toolkits import GmailToolkit
from langchain import OpenAI
from langchain.agents import initialize_agent, AgentType
toolkit = GmailToolkit()
llm = OpenAI(temperature=0, max_tokens=1000)
agent = initialize_agent(
tools=toolkit.get_tools(),
llm=llm,
agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,
)
print(agent.run("Send a mail to [email protected] with the following text %s"%(text)))
We have utilized Langchain’s GmailToolKit (Reference Document) here to send mail to our customer, Emily’s mail id ([email protected]) with the previously generated text. To use Langchain’s GmailToolKit, you will need to set up your credentials explained in the Gmail API docs. Once you’ve downloaded the credentials.json file, you can start using the Gmail API.
You can select the Internal user type only if the GCP project belongs to an organization and the connector users are members of the same organization.
The External user type causes the authentication to expire in seven days. If you choose this type, you need to renew authentication weekly.
Provide the following information:
For External user type:
To finish configuration, select Save and continue » Back to dashboard.
The following procedure describes how to configure the OAuth Client ID:
Post clicking on “Create”, the above window will pop out that will give the Client ID and Client Secret. This can be saved in a JSON format using the “DOWNLOAD JSON” option. Post downloading, we can save this JSON file in our project folder with the name “credentials.json”. Once you have this credentials.json in the local folder, only then you would be able to use the GmailToolKit.
Sample Mail Output on Promotional Campaign (sent using the above code on AI Agent)
With this, we can fully automate the process of creating and sending personalized promotional campaigns, taking into account customers’ unique lifestyles, preferences, and geographical locations. By analyzing data from customer interactions, past purchases, and demographic information, this multi agent AI system can craft tailored recommendations that are highly relevant to each individual. This level of personalization ensures that marketing content resonates with customers, improving the chances of engagement and conversion.
For marketing teams managing large customer bases, AI agents eliminate the complexity of targeting individuals based on their personal tastes, allowing for efficient and scalable marketing efforts. As a result, businesses can deliver more effective campaigns while saving time and resources.
We will now discuss the challenges of AI agents below:
AI agents are advanced programs designed to perform tasks autonomously by leveraging AI techniques to mimic human decision-making and learning. They excel at managing complex and ambiguous tasks by breaking them into simpler subtasks. Modern AI agents are multimodal, capable of processing diverse input types such as text, images, and voice. The core building blocks of an AI agent include perception, decision-making, action, and learning capabilities. However, these systems face challenges such as limited context processing, output instability, prompt sensitivity, and high resource demands.
For instance, a multi-agent system was developed in Python for Starbucks to create personalized coffee recommendations and promotional campaigns. This system utilized multiple agents: one focused on selecting coffees based on customer preferences, while another handled the creation of targeted promotional campaigns. This innovative approach allowed for efficient, scalable marketing with highly personalized content.
A. AI agents are specialized programs that perform tasks autonomously using AI techniques, mimicking human decision-making and learning. Unlike traditional AI models that often focus on single tasks, AI agents can handle complex, multi-step processes by interacting with users or systems and adapting to new information.
A. AI agents encounter difficulties such as limited context processing, output instability, prompt sensitivity, and high resource requirements. These challenges can impact their ability to deliver consistent and accurate results in certain scenarios.
A. AI agents use specialized tools like API requests, online searches, and other task-specific utilities to perform actions. These tools have clear purposes, ensuring efficient task completion.
A. AI agents are necessary for complex tasks because real-world problems often involve interconnected steps that cannot be solved in one go. AI agents, especially multi-agent systems, break these tasks into smaller, manageable subtasks, each handled independently.
The media shown in this article is not owned by Analytics Vidhya and is used at the Author’s discretion.