ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

LangChain--2--invoke、batch、stream、ainvoke、abatch、astream

2026/9/4 12:40:18 拓冰建站 浏览量
LangChain--2--invoke、batch、stream、ainvoke、abatch、astream 环境本地使用ollama部署的deepseek-r1:1.5b模型1 invoke、batch、stream代码示例frompydanticimportBaseModel,Fieldfromlangchain_community.llmsimportOllamafromlangchain.promptsimportPromptTemplatefromlangchain.schema.runnableimportRunnablePassthroughclassAdd(BaseModel):a:intField(description第一个整数)b:intField(description第二个整数)result:intField(description两个整数的求和结果)# 初始化LLMllmOllama(modeldeepseek-r1:1.5b,base_urlhttp://localhost:11434,temperature0)fromlangchain_core.output_parsersimportJsonOutputParser json_parserJsonOutputParser(pydantic_objectAdd)prompt_templatePromptTemplate(template计算两个整数的和。\n用户输入{query}\n{format_instructions},input_variables[query],partial_variables{format_instructions:json_parser.get_format_instructions()})chain{query:RunnablePassthrough()}|prompt_template|llm|json_parser# 1 invoke 同步单任务 参数直接传递字符串print(1 invoke 同步单任务 参数直接传递字符串)outputchain.invoke(5 加 3 等于几)print(output)# 2 invoke 同步单任务 参数也可以传递列表print(2 invoke 同步单任务 参数也可以传递列表)outputchain.invoke([5 加 3 等于几])print(output)# 3 invoke 同步单任务 传参多个列表中有多个任务时只会执行第一个任务后边的任务不会执行批量执行需要使用batchprint(3 invoke 同步单任务 传参多个列表中有多个任务时只会执行第一个任务后边的任务不会执行批量执行需要使用batch)outputchain.invoke([5 加 3 等于几,10 8 ?])print(output)# 4 batch 同步多任务批量执行 执行多个任务print(4 batch 同步多任务批量执行 执行多个任务)outputchain.batch([5 加 3 等于几,10 8 ?])print(output)# 5 stream 同步单任务参数可以是字符串可以是单任务列表所任务列别时只会执行第一个任务stream流式输出不仅可以是字符串流式输出也可以是其它数据格式比如json、pydantic...print(5 stream 同步单任务参数可以是字符串可以是单任务列表所任务列别时只会执行第一个任务stream流式输出不仅可以是字符串流式输出也可以是其它数据格式比如json、pydantic..)forchunkinchain.stream(5 加 3 等于几):print(chunk)print(aaaaaaa)执行结果1 invoke 同步单任务 参数直接传递字符串 {a: 5, b: 3, result: 8} 2 invoke 同步单任务 参数也可以传递列表 {a: 5, b: 3, result: 8} # 3 invoke 同步单任务 传参多个列表中有多个任务时只会执行第一个任务后边的任务不会执行批量执行需要使用batch {a: 5, b: 3, result: 8} 4 batch 同步多任务批量执行 执行多个任务 [{a: 5, b: 3, result: 8}, {a: 10, b: 8, result: 18}] 5 stream 同步单任务参数可以是字符串可以是单任务列表所任务列别时只会执行第一个任务stream流式输出不仅可以是字符串流式输出也可以是其它数据格式比如json、pydantic.. {} aaaaaaa {a: 5} aaaaaaa {a: 5, b: 3} aaaaaaa {a: 5, b: 3, result: 8} aaaaaaa Process finished with exit code 02 ainvoke、abatch、astream