一.agent+Conversation
通过用户问题,来选择
import json
import os
import re
from langchain import FAISS, PromptTemplate, LLMChain
from langchain.agents import initialize_agent, Tool, AgentType
from langchain.chains import RetrievalQA
from langchain.chat_models import ChatOpenAI
from langchain.document_loaders import TextLoader
from langchain.embeddings import OpenAIEmbeddings
from langchain.memory import ConversationBufferMemory
from langchain.text_splitter import SpacyTextSplitter
from langchain.tools import tool
"""
pip install spacy
python -m spacy download zh_core_web_sm
"""
os.environ["OPENAI_API_KEY"] = ''
llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo-16k", max_tokens=10240) # type: ignore
file_path = "faq.txt"
loader = TextLoader(file_path, encoding="utf-8")
documents = loader.load()
text_splitter = SpacyTextSplitter(chunk_size=500, chunk_overlap=0, pipeline="zh_core_web_sm", separator="\n\n")
texts = text_splitter.split_documents(documents)
embeddings = OpenAIEmbeddings()
docsearch = FAISS.from_documents(texts, embeddings)
faq_chain = RetrievalQA.from_chain_type(llm=llm, retriever=docsearch.as_retriever(), verbose=True)
order_1_num = "20230926001"
order_2_num = "20230927002"
order_1 = {
"order_number": order_1_num,
"statu": "已发货",
"shipping_date": "2023-09-26",
"estimated_delivered_date": "2023-09-31"
}
order_2 = {
"order_number": order_2_num,
"statu": "未发货",
"shipping_date": None,
"estimated_delivered_date": None
}
answer_order_info = PromptTemplate(template="请把下面的订单信息回复给用户:\n{order}?", input_variables=["order"])
answer_order_llm = LLMChain(llm=ChatOpenAI(temperature=0), prompt=answer_order_info)
# 模拟订单
@tool("searchOrder", return_direct=True)
def search_order(input: str) -> str:
"""userful for when you need to answer questions about customers orders"""
pattern = r"\d{11}"
match = re.search(pattern, input)
order_number = input
if match:
order_number = match.group(0)
else:
return f"""请提供订单号"""
if order_number == order_1_num:
return answer_order_llm.run(json.dumps(order_1))
elif order_number == order_2_num:
return answer_order_llm.run(json.dumps(order_2))
else:
return f"""根据{input}没有找到订单"""
# 模拟推荐商品
def recommend_product(input: str) -> str:
if "male".lower() == input.lower():
return "红色衣服,衣服的商品编号为999"
elif "female".lower() == input.lower():
return "黄色衣服,衣服的商品编号为888"
else:
return "蓝色衣服,衣服的商品编号为777"
# 模拟推荐商品
@tool("productPrice", return_direct=True)
def product_price(input: str) -> str:
"""userful for when you need to answer questions about product price.
the user needs to provide the item number to query product price
Answer users' questions in Chinese
"""
print(str)
pattern = r"\d{3}"
match = re.search(pattern, input)
product_number = input
if match:
product_number = match.group(0)
else:
return f"""请提供商品编号"""
if "999" == product_number:
return "价格为1080"
elif "888" == product_number:
return "价格为2080"
elif "777" == product_number:
return "价格为3080"
else:
return "价格不知道"
# 模拟问电商faq
@tool("FAQ", return_direct=True)
def faq(input: str) -> str:
"""userful for when you need to answer questions about shopping policies,like return policy
Answer users' questions in Chinese
"""
return faq_chain.run(input)
tools = [
Tool(
name="recommend product", func=recommend_product,
description="""userful for when you need to answer questions about product recommendations,
"if question about male ,input value is male,
if question about female ,input value is female
""",
return_direct=True
),
faq,
search_order,
product_price
]
memory = ConversationBufferMemory(memory_key="chat_history", return_message=True)
# 当没有相关答案,不需要一直重试,最大次数max_iterations=2
agent = initialize_agent(tools, llm, agent=AgentType.CONVERSATIONAL_REACT_DESCRIPTION, memory=memory, verbose=True)
# question = "我有一个订单20230926002的购买日期是多久?一直没有收到,啥时候发货,帮我查下"
# print(agent.run(question))
def query_answer(question: str) -> str:
# question = "我要查询一个订单啥时候送到?"
res = agent.run(question)
print(res)
return res
if __name__ == '__main__':
query_answer("我的订单到哪了?")
faq.txt
Q:如果更改收获地址?
A:在订单发货前,登录账号,进行修改,如果已经发货,联系客服协助处理
Q:如何查询发票?
A:进入"我的发票"页面,在此页面上查看详细信息
Q:为什么我的订单被取消?
A:订单可能因为库存不足,支付异常,用户要求等原因被取消,联系客服
Q:如何使用优惠券?
A:在购物车页面,输入优惠券代码后,点击"应用"。优惠券折扣将自动应用你的订单
Q:物流时效是多久?
A:一般情况下,大部分城市的订单在2-3个工作日,偏远地区是5-7个工作日,具体的配货时间可能因为订单的商品,物流公司而异