使用 Cohere 获取结构化输出,附带 instructor 的完整指南¶
本指南演示了如何将 Cohere 与 Instructor 结合使用以生成结构化输出。您将学习如何使用 Cohere 的 command 模型来创建类型安全的响应。
现在您可以将 Cohere 的任意 命令模型 与 `instructor` 库结合使用,以获取结构化输出。
您需要一个 Cohere API 密钥,可以通过此处注册获得,注册后即可获得免费、速率受限的使用权,用于学习和原型开发。
设置¶
导出您的密钥
示例¶
from pydantic import BaseModel, Field
from typing import List
import cohere
import instructor
# Patching the Cohere client with the instructor for enhanced capabilities
client = instructor.from_cohere(
cohere.Client(),
max_tokens=1000,
model="command-r-plus",
)
class Person(BaseModel):
name: str = Field(description="name of the person")
country_of_origin: str = Field(description="country of origin of the person")
class Group(BaseModel):
group_name: str = Field(description="name of the group")
members: List[Person] = Field(description="list of members in the group")
task = """\
Given the following text, create a Group object for 'The Beatles' band
Text:
The Beatles were an English rock band formed in Liverpool in 1960. With a line-up comprising John Lennon, Paul McCartney, George Harrison and Ringo Starr, they are regarded as the most influential band of all time. The group were integral to the development of 1960s counterculture and popular music's recognition as an art form.
"""
group = client.messages.create(
response_model=Group,
messages=[{"role": "user", "content": task}],
temperature=0,
)
print(group.model_dump_json(indent=2))
"""
{
"group_name": "The Beatles",
"members": [
{
"name": "John Lennon",
"country_of_origin": "England"
},
{
"name": "Paul McCartney",
"country_of_origin": "England"
},
{
"name": "George Harrison",
"country_of_origin": "England"
},
{
"name": "Ringo Starr",
"country_of_origin": "England"
}
]
}
"""