LangChain系列文章
有时我们希望在一个Runnable
序列内调用一个Runnable
,其常量参数不是前一个Runnable
的输出的一部分,也不是用户输入的一部分。我们可以使用Runnable.bind()
轻松传递这些参数。
假设我们有一个简单的提示 + 模型序列:
# 从 'operator' 模块导入 'itemgetter' 函数,用于项查找
from operator import itemgetter
# 从 langchain 和 langchain_core 包中导入各种类和函数
from langchain_core.runnables import RunnablePassthrough
from langchain.prompts import ChatPromptTemplate
from langchain.chat_models import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser
from dotenv import load_dotenv # 导入从 .env 文件加载环境变量的函数
load_dotenv() # 调用函数实际加载环境变量
from langchain.globals import set_debug # 导入在 langchain 中设置调试模式的函数
set_debug(True) # 启用 langchain 的调试模式
prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"Write out the following equation using algebraic symbols then solve it. Use the format\n\nEQUATION:...\nSOLUTION:...\n\n",
),
("human", "{equation_statement}"),
]
)
model = ChatOpenAI(temperature=0)
runnable = (
{"equation_statement": RunnablePassthrough()}
| prompt
| model
| StrOutputParser()
)
print(runnable.invoke("x raised to the third plus seven equals 12"))
输出
EQUATION: x^3 + 7 = 12
SOLUTION:
Subtracting 7 from both sides of the equation, we get:
x^3 = 12 - 7
x^3 = 5
Taking the cube root of both sides, we get:
x = ?5
Therefore, the solution to the equation x^3 + 7 = 12 is x = ?5.
想要用一些特定的stop
词来调用模型, 使其输出提前停止在"SOLUTION":
runnable = (
{"equation_statement": RunnablePassthrough()}
| prompt
| model.bind(stop="SOLUTION")
| StrOutputParser()
)
print(runnable.invoke("x raised to the third plus seven equals 12"))
输出
EQUATION: x^3 + 7 = 12
https://github.com/zgpeace/pets-name-langchain/tree/develop
https://python.langchain.com/docs/expression_language/how_to/functions