Skip to main content
LangChain decorators 是 LangChain 顶层的⼀层,为编写自定义 langchain 提示词和链提供了语法糖 🍭 对于反馈、问题、贡献 - 请在此处提⻅问题: ju-bezdek/langchain-decorators
主要原则和优势:
  • 更pythonic的编写代码方式
  • 编写多⾏提示词,不会因缩进而打断您的代码流
  • 利用 IDE 内置的 提示、类型检查 和 带文档的弹窗 功能,快速查看函数以了解提示词、它消耗的参数等
  • 挥洒所有 🦜🔗 LangChain 生态系统的力量
  • 添加对 可选参数 的支持
  • 通过将参数绑定到类来轻松在提示词之间共享参数
以下是使用 LangChain Decorators ✨ 编写的代码示例

快速入门

安装

示例

如何开始的⽐较好的建议是查看这里的示例:

定义其他参数

这里我们只是使用 llm_prompt 装饰器将函数标记为提示词,将其有效地转换为 LLMChain。而不是运行它 标准 LLMchain 比仅仅输入变量和提示词需要更多的初始化参数… 这里是装饰器中隐藏的这种实现细节。 它的工作原理如下:
  1. 使用 全局设置:
  1. 使用预定义的 提示词类型
  1. 在装饰器中直接定义设置

传递记忆和/或回调:

要传递任何这些,只需在函数中声明它们(或使用 kwargs 传递任何内容)

简化的流式输出

如果我们想利用流式输出:
  • 我们需要将提示词定义为异步函数
  • 在装饰器上打开流式输出,或者我们可以定义带有流式输出的 PromptType
  • 使用 StreamingContext 捕获流
这种方式,我们只需标记哪些提示词应该被流式输出,无需担心我们应⽤ LLM,传递创建和分发流式处理程序到我们链的特定部分… 只需在提示词/提示词类型上打开/关闭流式输出… 只有当我们以流式输出上下文中调用它时,流式输出才会发生… 我们可以定义一个简单的函数来处理流

提示词声明

默认情况下,提示词是整个函数的文档,除非您标记您的提示词

文档化您的提示词

我们可以指定我们的文档中的哪一部分是提示词定义,通过指定带有 <prompt> 语言标签的代码块
Now only to code block above will be used as a prompt, and the rest of the docstring will be used as a description for developers. (It has also a nice benefit that IDE (like VS code) will display the prompt properly (not trying to parse it as markdown, and thus not showing new lines properly)) """ return

human message

(we are using the real role that are enforced by the LLM - GPT supports system, assistant, user)
a reply:
we can also add some history using placeholder
Now only to code block above will be used as a prompt, and the rest of the docstring will be used as a description for developers. (It has also a nice benefit that IDE (like VS code) will display the prompt properly (not trying to parse it as markdown, and thus not showing new lines properly)) """ pass

输出解析器

  • llm_prompt 装饰器原生尝试根据输出类型检测最佳输出解析器。(如果未设置,则返回原始字符串)
  • 列表、字典和 pydantic 输出也原生支持(自动)

更复杂结构

对于字典 / pydantic,您需要指定格式说明… 这可能很繁琐,这就是为什么您可以让输出解析器根据模型(pydantic)为您生成说明

将提示词绑定到对象

""" personality = AssistantPersonality(assistant_name=“John”, assistant_role=“a pirate”) print(personality.introduce_your_self(personality))
Last modified on November 3, 2026