使用 Anthropic 进行结构化输出¶
特别感谢 Shreya 为 anthropic 支持做出的贡献。截至目前,除流式传输支持外,所有功能均可正常使用。
对于那些渴望尝试的人,只需使用 ANTHROPIC_JSON
修补客户端,即可利用 anthropic
客户端发起请求。
缺少的功能
需要说明的是,我们知道目前缺少部分流式传输和对 XML 的更好重问支持。我们正在努力解决,很快就会推出。
from pydantic import BaseModel
from typing import List
import anthropic
import instructor
# Patching the Anthropics client with the instructor for enhanced capabilities
anthropic_client = instructor.from_openai(
create=anthropic.Anthropic().messages.create,
mode=instructor.Mode.ANTHROPIC_JSON
)
class Properties(BaseModel):
name: str
value: str
class User(BaseModel):
name: str
age: int
properties: List[Properties]
user_response = anthropic_client(
model="claude-3-haiku-20240307",
max_tokens=1024,
max_retries=0,
messages=[
{
"role": "user",
"content": "Create a user for a model with a name, age, and properties.",
}
],
response_model=User,
) # type: ignore
print(user_response.model_dump_json(indent=2))
"""
{
"name": "John",
"age": 25,
"properties": [
{
"key": "favorite_color",
"value": "blue"
}
]
}
我们在处理深度嵌套类型时遇到挑战,热切邀请社区进行测试、提供反馈并提出必要的改进建议,以便我们增强对 anthropic 客户端的支持。