引言
在现代编程中,能够灵活地组合和执行自定义函数是提升开发效率的关键。LangChain提供了一种强大的方式来将自定义函数作为可运行项(Runnable)进行处理。本篇文章将详细介绍如何在LangChain中使用自定义函数,包括创建runnable、处理流式数据等功能。通过学习这些技巧,开发者可以实现更多样化的功能并更具扩展性。
主要内容
创建Runnable
LangChain中的自定义函数可以通过RunnableLambda构造器显式地创建为runnable。这对于需要特定功能或格式化的场景非常有用。注意,所有输入必须是一个单一参数。如果函数需要多个参数,可以通过封装成接受dict的函数来实现。
from langchain_core.runnables import RunnableLambda
from operator import itemgetter
def length_function(text):
return len(text)
def _multiple_length_function(text1, text2):
return len(text1) * len(text2)
def multiple_length_function(_dict):
return _multiple_length_function(_dict["text1"], _dict["text2"])
chain = {
"a": itemgetter("foo") | RunnableLambda(length_function),
"b": {"text1": itemgetter("foo"), "text2": itemgetter("bar")} | RunnableLambda(multiple_length_function),
}
使用@chain装饰器
通过@chain装饰器可以将任意函数转换为链条式结构,等效于使用RunnableLambda包装函数。
from langchain_core.runnables import chain
from langchain_core.output_parsers import StrOutputParser
@chain
def custom_chain(text):
prompt_val1 = prompt1.invoke({"topic": text})
output1 = ChatOpenAI().invoke(prompt_val1)
parsed_output1 = StrOutputParser().invoke(output1)
chain2 = prompt2 | ChatOpenAI() | StrOutputParser()
return chain2.invoke({"joke": parsed_output1})
custom_chain.invoke("bears")
自动强制转换
在链中使用自定义函数时,可以通过管道操作符自动进行强制转换,无需显式包装。
prompt = ChatPromptTemplate.from_template("tell me a story about {topic}")
model = ChatOpenAI()
chain_with_coerced_function = prompt | model | (lambda x: x.content[:5])
chain_with_coerced_function.invoke({"topic": "bears"})
传递运行元数据
Runnable lambdas可以接收RunnableConfig参数,用于传递回调、标签等信息给嵌套运行。
from langchain_core.runnables import RunnableConfig
import json
def parse_or_fix(text: str, config: RunnableConfig):
# 示例代码
实现流式处理
使用生成器函数实现流式处理,支持对输入和输出进行批量操作。
from typing import Iterator, List
def split_into_list(input: Iterator[str]) -> Iterator[List[str]]:
buffer = ""
for chunk in input:
buffer += chunk
while "," in buffer:
comma_index = buffer.index(",")
yield [buffer[:comma_index].strip()]
buffer = buffer[comma_index + 1 :]
yield [buffer.strip()]
代码示例
以下是一个完整的示例,展示了如何使用上述概念:
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langchain_core.runnables import RunnableLambda
# 定义自定义函数
def custom_length_function(text):
return len(text)
# 创建模型与提示模板
model = ChatOpenAI()
prompt = ChatPromptTemplate.from_template("Analyze this text: {text}")
# 创建可运行链条
chain = (prompt | RunnableLambda(custom_length_function) | model)
# 调用链条
result = chain.invoke({"text": "Hello, world!"})
print(result) # 输出分析结果
常见问题和解决方案
-
多参数函数如何转换? 封装为接受dict的单参数函数。
-
如何处理流式数据? 使用生成器函数,可选用
RunnableGenerator实现。
总结和进一步学习资源
LangChain提供了丰富的工具来处理可运行项和流式数据。掌握这些技巧可以极大提升程序的扩展能力。建议继续深入阅读LangChain的官方文档和相关教程,以获取更全面的理解。
参考资料
- LangChain官方文档 # 使用API代理服务提高访问稳定性
- LangChain GitHub仓库
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---