Promptic 是一个基于 Python 的轻量级库,旨在简化与大型语言模型(LLMs)的交互。它通过提供简洁的装饰器 API 和强大的功能,帮助开发者高效地构建 LLM 应用程序。Promptic 的设计理念是提供 90% 的 LLM 应用开发所需功能,同时保持代码的简洁和易用性。
1. Promptic 的核心功能
1.1 简化 LLM 交互 Promptic 提供了一个装饰器 @llm
,用于定义与 LLM 交互的函数。通过装饰器,你可以直接在函数的 docstring 中定义提示(prompt),并自动将函数参数插入到提示中。
Python复制
python">from promptic import llm
@llm
def translate(text, language="Chinese"):
"""Translate '{text}' to {language}"""
print(translate("Hello world!"))
# 输出:您好,世界!
1.2 支持 Pydantic 模型 Promptic 支持使用 Pydantic 模型定义 LLM 的输出结构,确保 LLM 的响应符合预定义的模式。
Python复制
python">from pydantic import BaseModel
from promptic import llm
class Forecast(BaseModel):
location: str
temperature: float
units: str
@llm
def get_weather(location, units: str = "fahrenheit") -> Forecast:
"""What's the weather for {location} in {units}?"""
print(get_weather("San Francisco", units="celsius"))
# 输出:location='San Francisco' temperature=16.0 units='Celsius'
1.3 流式响应 Promptic 支持流式响应,允许实时接收 LLM 的输出,适用于长文本内容或交互式应用。
Python复制
python">from promptic import llm
@llm(stream=True)
def write_poem(topic):
"""Write a haiku about {topic}."""
print("".join(write_poem(