Bind runtime args | 🦜️🔗 Langchain
1、有时,我们希望使用常量参数调用Runnable序列中的Runnable,这些参数不是序列中前一个Runnable的输出的一部分,也不是用户的输入,这时可以用Runnable.bind()
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_openai import ChatOpenAI
prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"用代数符号写出下面的方程,然后求解。 格式EQUATION:...换行SOLUTION:...换行",
),
("human", "{equation_statement}"),
]
)
model = ChatOpenAI(temperature=0)
runnable = (
{"equation_statement": RunnablePassthrough()} | prompt | model | StrOutputParser()
)
print(runnable.invoke("x的三次方加7等于12"))
# 使用model.bind,此处限制输入某些字
runnable = (
{"equation_statement": RunnablePassthrough()}
| prompt
| model.bind(stop="SOLUTION")
| StrOutputParser()
)
print('model.bind:',runnable.invoke("x的三次方加7等于12"))
2、通过bind给openAI模型绑定openAI函数、openAI工具
注意以下的方程求解需要GPT4才能给出正确答案,奇怪的是上面不用bind function的gpt3.5可以回答正确
注意name的key不能为中文
function = {
"name": "solver",
"description": "Formulates and solves an equation",
"parameters": {
"type": "object",
"properties": {
"equation": {
"type": "string",
"description": "The algebraic expression of the equation",
},
"solution": {
"type": "string",
"description": "The solution to the equation",
},
},
"required": ["equation", "solution"],
},
}
prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"Write out the following equation using algebraic symbols then solve it.",
),
("human", "{equation_statement}"),
]
)
model=model="gpt-3.5-turbo".bind(
function_call={"name": "solver"}, functions=[function]
)
runnable = {"equation_statement": RunnablePassthrough()} | prompt | model
print(runnable.invoke("x raised to the third plus seven equals 12"))