langchain--2--invoke、batch、stream、ainvoke、abatch、astream
环境:本地使用ollama部署的deepseek-r1:1.5b模型
1 invoke、batch、stream
代码示例:
from pydantic import BaseModel, Field
from langchain_community.llms import Ollama
from langchain.prompts import PromptTemplate
from langchain.schema.runnable import RunnablePassthroughclass Add(BaseModel):a: int = Field(description="第一个整数")b: int = Field(description="第二个整数")result: int = Field(description="两个整数的求和结果")# 初始化LLM
llm = Ollama(model="deepseek-r1:1.5b",base_url="http://localhost:11434",temperature=0
)from langchain_core.output_parsers import JsonOutputParser
json_parser = JsonOutputParser(pydantic_object=Add)
prompt_template = PromptTemplate(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 同步;单任务 参数直接传递字符串=============")
output = chain.invoke("5 加 3 等于几")
print(output)# 2 invoke 同步;单任务 参数也可以传递列表
print("==========2 invoke 同步;单任务 参数也可以传递列表=============")
output = chain.invoke(["5 加 3 等于几"])
print(output)# 3 invoke 同步;单任务 传参多个列表中有多个任务时,只会执行第一个任务,后边的任务不会执行,批量执行需要使用batch
print("==========3 invoke 同步;单任务 传参多个列表中有多个任务时,只会执行第一个任务,后边的任务不会执行,批量执行需要使用batch=============")
output = chain.invoke(["5 加 3 等于几", "10 + 8 = ?"])
print(output)# 4 batch 同步;多任务批量执行 执行多个任务
print("==========4 batch 同步;多任务批量执行 执行多个任务=============")
output = chain.batch(["5 加 3 等于几", "10 + 8 = ?"])
print(output)# 5 stream 同步;单任务,参数可以是字符串可以是单任务列表,所任务列别时只会执行第一个任务;stream流式输出不仅可以是字符串流式输出,也可以是其它数据格式比如:json、pydantic...
print("==========5 stream 同步;单任务,参数可以是字符串可以是单任务列表,所任务列别时只会执行第一个任务;stream流式输出不仅可以是字符串流式输出,也可以是其它数据格式比如:json、pydantic..=============")
for chunk in chain.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}
aaaaaaaProcess finished with exit code 0