我为什么放弃了 LangChain?( 四 )

- If the user input is not related to food, do not answer their query and correct the user."""prompt = ChatPromptTemplate.from_messages([SystemMessagePromptTemplate.from_template(system_prompt.strip()),
我们还将使用一个玩具矢量存储,该存储由来自数据集的 1000 个食谱组成,并使用编码为 384D 矢量 。为了实现这一点,我们创建了一个函数来获取输入查询的最近邻,并将查询格式化为 Agent 可以用来向用户展示的文本 。这就是 Agent 可以选择使用的工具,或者只是返回正常生成的文本 。
def similar_recipes(query):query_embedding = embeddings_encoder.encode(query)scores, recipes = recipe_vs.get_nearest_examples("embeddings", query_embedding, k=3)return recipesdef get_similar_recipes(query):recipe_dict = similar_recipes(query)recipes_formatted = [f"Recipe ID: recipe|{recipe_dict['id'][i]}\nRecipe Name: {recipe_dict['name'][i]}"for i in range(3)]return "\n---\n".join(recipes_formatted)print(get_similar_recipes("yummy dessert"))# Recipe ID: recipe|167188# Recipe Name: Creamy Strawberry Pie# ---# Recipe ID: recipe|1488243# Recipe Name: Summer Strawberry Pie Recipe# ---# Recipe ID: recipe|299514# Recipe Name: Pudding Cake
你会注意到这个ID,这与我的用例相关,因为在最终应用中向终端用户显示的最终结果需要获取元数据(照片缩略图、URL) 。遗憾的是,没有简单的方法保证模型在最终输出中输出食谱 ID,也没有方法在生成的输出之外返回结构化的中间元数据 。
将指定为一个工具是很简单的,尽管你需要指定一个名称和描述,这实际上是一种微妙的提示工程,因为可能会因为指定的名称和描述不正确而无法选择一个工具 。
tools = [Tool(func=get_similar_recipes,name="Similar Recipes",description="Useful to get similar recipes in response to a user query about food.",),]
最后,是示例中的 Agent 构建代码,以及新的系统提示 。
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)llm = ChatOpenAI(temperature=0)agent_chain = initialize_agent(tools, llm, prompt=prompt, agent=AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION, verbose=True, memory=memory)
没有错误 。现在运行 Agent,看看会发生什么:
agent_chain.run(input="Hi!")
> Entering newchain...{"action": "Final Answer","action_input": "Hello! How can I assist you today?"}> Finished chain.Hello! How can I assist you today?

我为什么放弃了 LangChain?

文章插图
什么?它完全忽略了我的系统提示!检查内存变量证实了这一点 。
在 mory 的文档中,甚至在代码本身中都没有关于系统提示的内容,甚至在使其成为主流的几个月之后 。
在 Agent 中使用系统提示的方法是在中添加一个参数,我只是在一个月前发布的一个不相关的文档页面中发现了这一点 。
agent_kwargs = {"system_message": system_prompt.strip()}
使用此新参数重新创建 Agent 并再次运行,会导致。
好消息是,系统提示这次应该是起作用了 。
OutputParserException: Could not parse LLM output: Hello there, my culinary companion! How delightful to have you here in my whimsical kitchen. What delectable dish can I assist you with today?