AI 日报

使用 Redis、Langchain 和 ChatGPT 构建电子商务聊天机器人:分步教程




使用 Redis、Langchain 和 ChatGPT 构建电子商务聊天机器人:分步教程

为什么要在电子商务业务中使用 AI?

在当今快节奏的数字世界中,电子商务已成为我们日常生活的重要组成部分。由于在线提供的产品数量众多,用户很难找到适合他们需求的合适产品。为了解决这个问题,我们可以使用 AI 支持的聊天机器人,利用自然语言处理技术帮助用户找到满足他们需求的完美产品。

在本教程中,我们将引导您完成构建电子商务聊天机器人的过程,该聊天机器人利用亚马逊产品嵌入、ChatGPT API (gpt-3.5-turbo) 和 Langchain 来创建无缝且引人入胜的用户体验。我们的聊天机器人将接受用户输入,从数据集中查找相关产品,并以友好和详细的方式呈现信息。这不仅增强了用户体验,而且使寻找产品的过程更加愉快。

开始吧!

我们将从加载和预处理产品数据开始,然后创建 Redis 索引并将向量加载到索引中。然后,我们将使用 Langchain 创建一个 LLM 链和一个提示模板,用于根据用户输入生成以逗号分隔的产品关键字。接下来,我们将使用生成的关键字在 Redis 中查询产品嵌入,并检索排名靠前的结果。最后,我们将以一种友好且引人入胜的方式向用户展示检索到的产品,让他们可以提出后续问题。

在本教程结束时,您将更好地了解如何构建基于 CLI 的电子商务聊天机器人,该聊天机器人可以查询亚马逊产品嵌入并使用 Langchain 生成用户友好的响应。这不仅有助于改善电子商务领域的整体用户体验,还为未来更先进、更个性化的聊天机器人解决方案铺平了道路。那么,让我们开始构建我们自己的电子商务聊天机器人吧!

以下是与我们的聊天机器人的对话可能是什么样子的简单示例:

User: im looking for some jewelry for my girlfriendBot: Based on your query, I would recommend checking out these Women's Engravable 14k Gold Plated 925 Sterling Silver Polished Disc Charm on 18" Chain Pendant Necklace. They might make a great gift for your girlfriend if she likes elegant and stylish jewelry. However, if you are looking for shoes, you might want to check out Amazon Brand - The Fix Women's Lizzie Block Heel Ruffled Sandal Heeled, Dove Suede, 9 B US. These shoes are great for spring and summer, and perfect for a date night or a fancy event. Another option for shoes could be Amazon Brand - The Fix Women's Giana Open Toe Bootie with Pearl Buckle, which comes in bright white leather and sizes up to 9.5 B US. I hope this helps!User: tell me more about the necklaceBot: The Women's Engravable 14k Gold Plated 925 Sterling Silver Polished Disc Charm on 18" Chain Pendant Necklace is a beautiful and elegant piece of jewelry. The pendant is made of 925 sterling silver and is plated with 14k gold for a luxurious look. The pendant is disc-shaped and can be engraved with a personal message or initials to make it even more special. The chain is 18 inches long and adds a delicate touch to the necklace. This necklace is perfect for everyday wear or for special occasions.User: what's the product idBot: The product ID for the Women's Engravable 14k Gold Plated 925 Sterling Silver Polished Disc Charm on 18" Chain Pendant Necklace is B07CJCSYQF.

先决条件

获取数据集 CSV 文件

从此处获取数据集 CSV 文件。

安装所需的 Python 包

在我们开始之前,请确保您安装了以下 Python 包:

redispandassentence-transformersopenailangchain

您可以使用以下命令安装它们:

pip install redis pandaspip install -U sentence-transformerspip install openaipip install langchain

加载和预处理数据

首先,我们需要从 CSV 文件加载产品数据并截断长文本字段。我们将为我们的聊天机器人使用前 1000 个具有非空项目关键字的产品。

import numpy as npimport pandas as pdimport timefrom redis.commands.search.field import VectorFieldfrom redis.commands.search.field import TextFieldfrom redis.commands.search.field import TagFieldfrom redis.commands.search.query import Queryimport redis
MAX_TEXT_LENGTH=512NUMBER_PRODUCTS=1000def auto_truncate(val):    return val[:MAX_TEXT_LENGTH]#Load Product data and truncate long text fieldsall_prods_df = pd.read_csv("product_data.csv", converters={'bullet_point': auto_truncate,'item_keywords':auto_truncate,'item_name':auto_truncate})all_prods_df['primary_key'] = all_prods_df['item_id'] + '-' + all_prods_df['domain_name']all_prods_df['item_keywords'].replace('', np.nan, inplace=True)all_prods_df.dropna(subset=['item_keywords'], inplace=True)all_prods_df.reset_index(drop=True,inplace=True)#get the first 1000 products with non-empty item keywordsproduct_metadata = all_prods_df.head(NUMBER_PRODUCTS).to_dict(orient='index')all_prods_df.head()

创建 Redis 索引和加载向量

现在,我们将创建一个将向量加载到 Redis 索引的函数和一个创建平面索引的函数。稍后我们将使用这些函数来索引我们的产品数据。

def load_vectors(client, product_metadata, vector_dict, vector_field_name):    p = client.pipeline(transaction=False)    for index in product_metadata.keys():            #hash key        key='product:'+ str(index)+ ':' + product_metadata[index]['primary_key']                #hash values        item_metadata = product_metadata[index]        item_keywords_vector = vector_dict[index].astype(np.float32).tobytes()        item_metadata[vector_field_name]=item_keywords_vector                # HSET        p.hset(key,mapping=item_metadata)                p.execute()def create_flat_index (redis_conn,vector_field_name,number_of_vectors, vector_dimensions=512, distance_metric='L2'):    redis_conn.ft().create_index([        VectorField(vector_field_name, "FLAT", {"TYPE": "FLOAT32", "DIM": vector_dimensions, "DISTANCE_METRIC": distance_metric, "INITIAL_CAP": number_of_vectors, "BLOCK_SIZE":number_of_vectors }),        TagField("product_type"),        TextField("item_name"),        TextField("item_keywords"),        TagField("country")            ]) 

连接到我们的 Redis 数据库

接下来,我们将创建 Redis 连接并将向量加载到 Redis 索引中。

ITEM_KEYWORD_EMBEDDING_FIELD='item_keyword_vector'TEXT_EMBEDDING_DIMENSION=768NUMBER_PRODUCTS=1000print ('Loading and Indexing + ' +  str(NUMBER_PRODUCTS) + ' products')#flush all dataredis_conn.flushall()#create flat index & load vectorscreate_flat_index(redis_conn, ITEM_KEYWORD_EMBEDDING_FIELD,NUMBER_PRODUCTS,TEXT_EMBEDDING_DIMENSION,'COSINE')load_vectors(redis_conn,product_metadata,item_keywords_vectors,ITEM_KEYWORD_EMBEDDING_FIELD)     

创建聊天机器人

我们将结合使用 ChatGPT API (gpt-3.5-turbo) 和 Langchain 来创建对我们问题的回复。如果您想深入了解如何将 ChatGPT API 集成到您的其他项目,我们有专门的教程。

从用户输入字符串到产品关键字

我们将使用 Langchain 为我们的聊天机器人创建一个 LLM 链。首先,我们将创建一个提示模板,以根据用户输入生成以逗号分隔的产品关键字。

from langchain.prompts import PromptTemplatefrom langchain.llms import OpenAIllm = OpenAI(model_name="gpt-3.5-turbo", temperature=0.3, openai_api_key="sk-9xxxxxxxxxx4")prompt = PromptTemplate(    input_variables=["product_description"],    template="Create comma seperated product keywords to perform a query on a amazon dataset for this user input: {product_description}",)from langchain.chains import LLMChainchain = LLMChain(llm=llm, prompt=prompt)

现在,让我们使用我们的链。

userinput = input("Hey im a E-commerce Chatbot, how can i help you today? ")print("User:", userinput)# Run the chain only specifying the input variable.keywords = chain.run(userinput)

查询我们的数据

然后,我们将使用生成的关键字在 Redis 中查询产品嵌入并检索前 3 个结果。

topK = 3# Vectorize the queryquery_vector = model.encode(keywords).astype(np.float32).tobytes()# Prepare the queryq = Query(f'*=>[KNN {topK} @{ITEM_KEYWORD_EMBEDDING_FIELD} $vec_param AS vector_score]').sort_by('vector_score').paging(0, topK).return_fields('vector_score', 'item_name', 'item_id', 'item_keywords').dialect(2)params_dict = {"vec_param": query_vector}# Execute the queryresults = redis_conn.ft().search(q, query_params=params_dict)full_result_string = ''for product in results.docs:    full_result_string += product.item_name + ' ' + product.item_keywords + ' ' + product.item_id + "\n\n\n"

创建聊天机器人

最后,我们将创建另一个 LLM 链,以从检索到的产品中生成良好的响应并将其呈现给用户。用户还可以提出后续问题。请注意,我们在链中添加了内存以跟踪聊天记录。

from langchain.memory import ConversationBufferMemorytemplate = """You are a chatbot. Be kind, detailed and nice. Present the given queried search result in a nice way as answer to the user input. dont ask questions back! just take the given context{chat_history}Human: {user_msg}Chatbot:"""prompt = PromptTemplate(    input_variables=["chat_history", "user_msg"],    template=template)memory = ConversationBufferMemory(memory_key="chat_history")llm_chain = LLMChain(    llm=OpenAI(model_name="gpt-3.5-turbo", temperature=0.8, openai_api_key="sk-9xxxxxxxxxxxxxxxxxxxx4"),    prompt=prompt,    verbose=False,    memory=memory,)answer = llm_chain.predict(user_msg=f"{full_result_string} ---\n\n {userinput}")print("Bot:", answer)time.sleep(0.5)while True:    follow_up = input("Anything else you want to ask about this topic?")    print("User:", follow_up)    answer = llm_chain.predict(        user_msg=follow_up    )    print("Bot:", answer)    time.sleep(0.5)

结论

使用 Redis、Langchain 和 ChatGPT 构建电子商务聊天机器人:分步教程

在本教程中,我们构建了一个电子商务聊天机器人,它可以使用 Redis 查询亚马逊产品嵌入,并使用 Langchain 生成详细且友好的响应。我们已经演示了如何加载和预处理产品数据、创建 Redis 索引以及将向量加载到索引中。我们还展示了如何使用 Langchain 创建 LLM 链来为用户查询生成关键字和响应。

通过利用产品嵌入和语言模型的强大功能,我们的聊天机器人可以高效地搜索相关产品推荐,并以引人入胜且信息丰富的方式呈现它们。这种方法可以进一步扩展以包括更多产品、处理复杂查询,甚至通过结合用户偏好来提供个性化推荐。

我们希望本教程为您构建自己的电子商务聊天机器人或在其他领域实施类似解决方案提供了一个良好的起点。随着 AI 技术的快速发展,创造智能、引人入胜和有用的聊天机器人的可能性无穷无尽,这些聊天机器人可以改善用户体验并推动业务成功。

您可以在 Github 上找到本教程的完整源代码

如果您想尝试新技能并利用尖端技术和我们导师的帮助构建出色的应用程序,请加入我们的 AI 黑客马拉松,用 AI 打造未来。

谢谢你!如果您喜欢本教程,您可以在我们的教程页面上找到更多信息并继续阅读 – Fabian Stehle,New Native 的全栈开发人员