使用 Promptic 进行对话管理是一个高效且灵活的过程,它通过装饰器模式、动态提示生成、状态管理等功能,帮助开发者快速构建基于 LLM 的对话系统。以下是详细的全过程分析:
1. 安装 Promptic
首先,需要通过 pip 安装 Promptic:
bash复制
pip install promptic
2. 基本用法
Promptic 使用 @llm
装饰器将普通函数转换为由 LLM 驱动的函数。函数的文档字符串将作为提示模板,与函数参数结合生成提示并发送给 LLM。
示例:基本翻译功能
Python复制
from promptic import llm@llm
def translate(text, language="Chinese"):"""Translate '{text}' to {language}"""print(translate("Hello world!")) # 输出:您好,世界!
print(translate("Hello world!", language="Spanish")) # 输出:¡Hola, mundo!
3. 对话记忆与状态管理
默认情况下,每次函数调用是独立且无状态的。通过设置 memory=True
,可以启用内置的对话记忆功能,让 LLM 在多次交互中保持上下文。
示例:启用对话记忆
Python复制
from promptic import llm@llm(memory=True)
def assistant(message):"""{message}"""response1 = assistant("Tell me about AI.")
response2 = assistant("What are the latest advancements?")