引言
LangChain为开发者提供了强大的工具链来构建复杂的AI应用。在这篇文章中,我们将深入探讨如何将自定义函数作为LangChain中的Runnables使用。这对于需要特定功能的开发场景,或是数据格式化需求尤为重要。本文将引导您通过使用RunnableLambda
构造器和方便的@chain
装饰器来实现这一目标。
主要内容
1. 使用RunnableLambda
构造器创建Runnable
在LangChain中,您可以通过RunnableLambda
构造器将自定义逻辑显式包装为Runnable。这一功能使得单参数函数可以更容易地集成到您的应用链中。
from langchain_core.runnables import RunnableLambda
from langchain_openai import ChatOpenAI
def length_function(text):
return len(text)
model = ChatOpenAI()
prompt = ChatPromptTemplate.from_template("what is the length of {text}")
chain = prompt | model | RunnableLambda(length_function)
chain.invoke({"text": "hello world!"})
2. 通过@chain
装饰器的便利性
通过@chain
装饰器,您可以轻松地将任意函数转换为链。这与RunnableLambda
构造器的功能相当。
from langchain_core.runnables import chain
from langchain_core.output_parsers import StrOutputParser
prompt1 = ChatPromptTemplate.from_template("Tell me a joke about {topic}")
@chain
def custom_chain(topic):
joke = ChatOpenAI().invoke(prompt1.invoke({"topic": topic}))
return joke
custom_chain.invoke("bears")
3. 面向流的自定义函数
当您的应用需要支持流操作时,您可以使用RunnableGenerator
,该构造器允许函数以生成器形式返回数据。
from typing import Iterator
def stream_function(input: Iterator[str]) -> Iterator[str]:
for chunk in input:
yield chunk.upper()
# Use as a part of a chain
代码示例
以下示例展示了如何将自定义函数整合到LangChain中,同时支持流输出:
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableLambda
from langchain_openai import ChatOpenAI
def example_custom_function(text):
return text[::-1]
model = ChatOpenAI()
prompt = ChatPromptTemplate.from_template("Reverse this text: {text}")
chain = prompt | model | RunnableLambda(example_custom_function)
result = chain.invoke({"text": "gnirts tset a si sihT"})
print(result) # 输出: 'This is a test string'
常见问题和解决方案
-
函数需要多个参数时如何处理?
可以创建一个接受字典作为参数的包装函数,并在该函数中解包字典。
-
网络访问限制如何解决?
由于某些地区的网络限制,开发者可能需要考虑使用API代理服务,例如在API调用中使用
{AI_URL}
作为API端点。
总结和进一步学习资源
本文展示了如何在LangChain中使用自定义函数作为Runnables,并讨论了相关的技术细节和挑战。您可以参考以下资源以获取更多信息:
参考资料
- LangChain 官方文档
- OpenAI API 文档
- Python 官方文档
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
—END—