langchain--1--prompt、output格式、LCEL示例

环境:本地使用ollama部署的deepseek-r1:1.5b模型

本文示例包含:

  • 1\] 非LCEL的调用方法

  • 3\] prompt template的简单使用,除了PromptTemplate模板,还有一些其它模板,可去查看官网

示例代码:

python 复制代码
from pydantic import BaseModel, Field
from langchain_community.llms import Ollama
from langchain.prompts import PromptTemplate
from langchain.schema.runnable import RunnablePassthrough


class 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
)


# 1 非LCEL 输出json
print("============1 非LCEL 输出json===========")
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()}
)
query = "5 加 3 等于几"
prompt = prompt_template.format_prompt(query=query)
output = llm.invoke(prompt)
print(json_parser.invoke(output))


# 2 非LCEL 输出pydantic对象
print("============2 非LCEL 输出pydantic对象===========")
from langchain_core.output_parsers import  PydanticOutputParser
pydantic_parser = PydanticOutputParser(pydantic_object=Add)
prompt_template = PromptTemplate(
    template="计算两个整数的和。\n用户输入:{query}\n{format_instructions}",
    input_variables=["query"],
    partial_variables={"format_instructions": pydantic_parser.get_format_instructions()}
)
query = "5 加 3 等于几"
prompt = prompt_template.format_prompt(query=query)
output = llm.invoke(prompt)
res = pydantic_parser.invoke(output)
print(res, "|", res.a, res.b, res.result)


# 3 LCEL 字符串流式输出 带有json字符串
print("============3 LCEL 字符串流式输出 带有json字符串===========")
from langchain.schema.output_parser import StrOutputParser
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 | StrOutputParser()
for chunk in chain.stream("5 加 3 等于几"):
    print(chunk, end="")
# output = chain.invoke("5 加 3 等于几")
# print(output)


# 4 LCEL 字符串流式输出 不带有json字符串
print("============4 LCEL 字符串流式输出 不带有json字符串===========")
from langchain.schema.output_parser import StrOutputParser
prompt_template = PromptTemplate(
    template="计算两个整数的和。\n用户输入:{query}\n",
    input_variables=["query"],
)
chain = {"query": RunnablePassthrough()} | prompt_template | llm | StrOutputParser()
for chunk in chain.stream("5 加 3 等于几"):
    print(chunk, end="")
print() # 为了流式输出完后换行而已
# output = chain.invoke("5 加 3 等于几")
# print(output)


# 5 LCEL 输出json
print("============5 LCEL 输出json===========")
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
output = chain.invoke("5 加 3 等于几")
print(output)


# 6 LCEL 输出pydantic对象
print("============6 LCEL 输出pydantic对象===========")
from langchain_core.output_parsers import  PydanticOutputParser
pydantic_parser = PydanticOutputParser(pydantic_object=Add)
prompt_template = PromptTemplate(
    template="计算两个整数的和。\n用户输入:{query}\n{format_instructions}",
    input_variables=["query"],
    partial_variables={"format_instructions": pydantic_parser.get_format_instructions()}
)
chain = {"query": RunnablePassthrough()} | prompt_template | llm | pydantic_parser
output = chain.invoke("5 加 3 等于几")
print(output, "|", output.a, output.b, output.result)

结果输出:

复制代码
============1 非LCEL 输出json===========
{'a': 5, 'b': 3, 'result': 8}
============2 非LCEL 输出pydantic对象===========
a=5 b=3 result=8 | 5 3 8
============3 LCEL 字符串流式输出 带有json字符串===========
<think>
嗯,用户让我计算两个整数的和。输入是5加3等于几。首先,我需要确认这两个数字是否正确输入了。看起来没问题,都是整数。

接下来,我要按照用户的要求,生成一个JSON对象,并且确保它符合指定的格式。根据输出 schema,我需要定义三个属性:a、b和result。每个属性都有特定的描述和类型。

对于a,应该是第一个整数5;b是第二个整数3;result则是它们的和8。这样填写的话,整个结构就完整了。

然后,我要检查一下JSON格式是否正确。确保逗号的位置没有错误,特别是分隔符部分。同时,每个属性的名称也必须准确无误地对应到输入中的变量名。

最后,确认输出结果是否符合要求,比如类型是否都是整数,以及结构是否正确。这样用户就能得到一个正确的JSON对象作为输出了。
</think>

要计算两个整数的和,请按照以下步骤操作:

1. 输入第一个整数:5
2. 输入第二个整数:3
3. 计算它们的和:5 + 3 = 8

根据要求,生成的JSON对象应如下:

```json
{
  "a": 5,
  "b": 3,
  "result": 8
}
```

请将上述内容作为输出。============4 LCEL 字符串流式输出 不带有json字符串===========
<think>
首先,我需要明确用户的要求。用户希望计算两个整数的和,并且提供一个简短的输出。

接下来,我会将输入的两个整数分别提取出来。这里给出的是5和3。

然后,我会进行加法运算:5加上3等于8。

最后,我会将结果以清晰的方式呈现给用户。
</think>

要计算两个整数的和,按照以下步骤进行:

1. **输入两个整数**:
   - 输入的第一个整数是 \( 5 \)
   - 输入的第二个整数是 \( 3 \)

2. **进行加法运算**:
   \[
   5 + 3 = 8
   \]

3. **输出结果**:

\boxed{8}
============5 LCEL 输出json===========
{'a': 5, 'b': 3, 'result': 8}
============6 LCEL 输出pydantic对象===========
a=5 b=3 result=8 | 5 3 8

Process finished with exit code 0
相关推荐
Jack___Xue31 分钟前
LangChain实战快速入门笔记(五)--LangChain使用之Tools
笔记·microsoft·langchain
爱写Bug的小孙4 小时前
Agent 和ReAct Agent区别
ai·langchain·agent·springai
爬点儿啥16 小时前
[Ai Agent] 10 MCP基础:快速编写你自己的MCP服务器(Server)
人工智能·ai·langchain·agent·transport·mcp
猫头虎18 小时前
又又又双叒叕一款AI IDE发布,国内第五款国产AI IDE Qoder来了
ide·人工智能·langchain·prompt·aigc·intellij-idea·ai编程
树獭叔叔1 天前
Langgraph: Human-in-the-Loop 实现机制
后端·langchain·aigc
JH灰色1 天前
【大模型】-LangChain--stream流式同步异步
服务器·前端·langchain
JH灰色1 天前
【大模型】-LangChain--Agent
windows·microsoft·langchain
JH灰色1 天前
【大模型】-LangChain多模态输入和自定义输出
java·前端·langchain
JH灰色1 天前
【大模型】-LangChain自定义工具调用
数据库·langchain
minhuan1 天前
大模型应用:LlamaIndex、LangChain 与 LangGraph 细节深度、协同应用.24
langchain·llamaindex·大模型应用·langgraph