跳到内容

Anthropic 的结构化输出和提示词缓存

Anthropic 的生态系统现在为 AI 开发者提供了两个强大的功能:结构化输出和提示词缓存。这些进展使得大型语言模型 (LLM) 的使用更加高效。本指南演示了如何利用 Instructor 库结合这些功能来增强您的 AI 应用。

使用 Anthropic 和 Instructor 的结构化输出

Instructor 现在与 Anthropic 强大的语言模型无缝集成,允许开发者使用 Pydantic 模型轻松创建结构化输出。这种集成简化了从 AI 生成的响应中提取特定信息的流程。

开始之前,您需要安装支持 Anthropic 的 Instructor

pip install instructor[anthropic]

以下是一个使用 Instructor 与 Anthropic 集成的基本示例

from pydantic import BaseModel
from typing import List
import anthropic
import instructor

# Patch the Anthropic client with Instructor
anthropic_client = instructor.from_anthropic(create=anthropic.Anthropic())


# Define your Pydantic models
class Properties(BaseModel):
    name: str
    value: str


class User(BaseModel):
    name: str
    age: int
    properties: List[Properties]


# Use the patched client to generate structured output
user_response = anthropic_client(
    model="claude-3-7-sonnet-latest",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": "Create a user for a model with a name, age, and properties.",
        }
    ],
    response_model=User,
)

print(user_response.model_dump_json(indent=2))
"""
{
  "name": "John Doe",
  "age": 30,
  "properties": [
    { "name": "favorite_color", "value": "blue" }
  ]
}
"""

这种方法让您可以轻松地从 Claude 的响应中提取结构化数据,从而更简单地将 AI 生成的内容集成到您的应用中。

提示词缓存:提升性能并降低成本

Anthropic 引入了一项新的提示词缓存功能,可以显著改善处理大型上下文窗口的应用的响应时间并降低成本。当随着时间推移多次调用相似的大型上下文时,此功能特别有用。

以下是如何使用 Instructor 和 Anthropic 实现提示词缓存的方法

from anthropic import Anthropic
from pydantic import BaseModel

# Set up the client with prompt caching
client = instructor.from_anthropic(Anthropic())


# Define your Pydantic model
class Character(BaseModel):
    name: str
    description: str


# Load your large context
with open("./book.txt") as f:
    book = f.read()

# Make multiple calls using the cached context
for _ in range(2):
    resp, completion = client.chat.completions.create_with_completion(
        model="claude-3-7-sonnet-latest",
        messages=[
            {
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        "text": "<book>" + book + "</book>",
                        "cache_control": {"type": "ephemeral"},
                    },
                    {
                        "type": "text",
                        "text": "Extract a character from the text given above",
                    },
                ],
            },
        ],
        response_model=Character,
        max_tokens=1000,
    )

在此示例中,大型上下文(书籍内容)在第一次请求后被缓存,并在后续请求中重复使用。这可以显著节省时间和成本,尤其是在处理大量上下文时。

结论

通过结合 Anthropic 的 Claude、Instructor 的结构化输出能力以及利用提示词缓存,开发者可以创建更高效、更具成本效益且功能强大的 AI 应用。这些功能为构建能够轻松处理复杂任务的精密 AI 系统开辟了新的可能性。

随着 AI 格局的不断演变,及时了解最新的工具和技术至关重要。我们鼓励您探索这些功能,并与社区分享您的经验。编码愉快!