LangChain添加第三条链实现菜品食材与菜谱生成的技术问询
解决LangChain中批量处理菜品获取食材及菜谱的问题
问题核心
当前代码无法将生成的多个菜品逐个传入链中获取对应食材,因为SequentialChain仅能处理单输入输出的线性流程,而生成的menu_items是逗号分隔的字符串列表,无法直接作为单值输入给食材链。此外代码中存在多处拼写错误(如restaurante_name应为restaurant_name、ingrediants应为ingredients、Renturn应为Return),会导致变量传递或模板解析失败。
解决方案
- 修正所有拼写错误,保证变量名和模板内容一致
- 在生成菜单后,将逗号分隔的菜品字符串拆分为列表
- 遍历每个菜品,分别调用食材链获取对应食材
- 新增菜谱生成链,基于菜品和食材生成详细制作步骤
- 整合所有步骤,实现从菜系到餐厅名、菜单、食材、菜谱的完整流程
修正后完整代码
from langchain.llms import OpenAI from langchain.prompts import PromptTemplate from langchain.chains import LLMChain from langchain.chains import SequentialChain openai_key = "你的OpenAI API密钥" # 初始化LLM llm = OpenAI(temperature=0.6, openai_api_key=openai_key) ########## 链1:生成餐厅名称 prompt_template_name = PromptTemplate( input_variables=['cuisine'], template="我想开一家{cuisine}菜餐厅,请推荐一个有格调的餐厅名称。" ) name_chain = LLMChain(llm=llm, prompt=prompt_template_name, output_key="restaurant_name") ########## 链2:生成菜单菜品 prompt_template_items = PromptTemplate( input_variables=['restaurant_name'], template="请为{restaurant_name}餐厅推荐几道招牌菜,用逗号分隔返回。" ) food_items_chain = LLMChain(llm=llm, prompt=prompt_template_items, output_key="menu_items") # 组合前两步的顺序链 name_menu_chain = SequentialChain( chains=[name_chain, food_items_chain], input_variables=['cuisine'], output_variables=['restaurant_name', 'menu_items'] ) ########## 链3:获取单道菜品的食材 prompt_template_ingredients = PromptTemplate( input_variables=['dish_name'], template="请列出制作{dish_name}所需的食材,用逗号分隔返回。" ) ingredients_chain = LLMChain(llm=llm, prompt=prompt_template_ingredients, output_key="ingredients") ########## 链4:生成单道菜品的菜谱 prompt_template_recipe = PromptTemplate( input_variables=['dish_name', 'ingredients'], template="请根据食材{ingredients},生成{dish_name}的详细制作步骤,要求步骤清晰易懂。" ) recipe_chain = LLMChain(llm=llm, prompt=prompt_template_recipe, output_key="recipe") # 完整流程执行 def run_full_cuisine_flow(cuisine): # 生成餐厅名和菜单 name_menu_result = name_menu_chain({'cuisine': cuisine}) restaurant_name = name_menu_result['restaurant_name'] menu_items = [item.strip() for item in name_menu_result['menu_items'].split(',')] # 逐个处理菜品,获取食材和菜谱 dish_details = [] for dish in menu_items: # 获取食材 ingredients_result = ingredients_chain({'dish_name': dish}) ingredients = ingredients_result['ingredients'] # 获取菜谱 recipe_result = recipe_chain({'dish_name': dish, 'ingredients': ingredients}) recipe = recipe_result['recipe'] dish_details.append({ '菜品名称': dish, '所需食材': ingredients, '制作菜谱': recipe }) # 返回最终结果 return { '餐厅名称': restaurant_name, '菜品详情': dish_details } # 测试示例 result = run_full_cuisine_flow('西班牙') print("餐厅名称:", result['餐厅名称']) for idx, dish in enumerate(result['菜品详情'], 1): print(f"\n--- 第{idx}道菜 ---") print(f"菜品:{dish['菜品名称']}") print(f"食材:{dish['所需食材']}") print(f"菜谱:{dish['制作菜谱']}")
关键说明
- 拆分菜单字符串为列表后,通过循环逐个处理菜品,解决了批量输入的问题
- 新增菜谱生成链,结合菜品名称和食材生成完整制作步骤,满足最终需求
- 修正了所有拼写错误,避免因变量名不匹配导致的流程中断
内容的提问来源于stack exchange,提问作者user113156
相关产品推荐
相关产品推荐

