结构化分流
本课属于 Coddy AI Engineering 学习旅程的“在代码中调用模型”单元。第 17 课,共 22 课。
挑战
中等摘要是供人阅读的文本。为了对工单进行分类,你的代码需要它可以读取的字段。在这一步中,请将摘要请求替换为结构化输出。
- 在第一行下方添加
import json,并在 client 之后添加一个SCHEMA字典:一个包含category(字符串,枚举值为"billing"、"shipping"、"account"、"technical"、"other")、urgent(布尔值)和summary(字符串)的对象,三者均为必需字段,且设置"additionalProperties": False。 - 在循环之前,创建一个空列表
results。 - 在循环中,将工单本身作为消息发送(移除
Summarize:),并添加output_config={"format": {"type": "json_schema", "schema": SCHEMA}}。 - 用
json.loads解析文本块,将字典追加到results,并打印#<number> <category> | urgent: <yes or no> | <summary>来代替摘要行。
像之前一样继续读取输入并打印 Tickets: <count>。例如,对于输入 1 和 My parcel arrived damaged and I need a new one immediately.,程序会打印:
Tickets: 1
#1 shipping | urgent: yes | My parcel arrived damaged and I need a new one immediately亲手试试
import coddy_ai as anthropic # 在生产环境中:import anthropic
client = anthropic.Anthropic()
count = int(input())
tickets = [input() for _ in range(count)]
print(f"Tickets: {count}")
# 对于每个工单,让模型对其进行总结,并输出 "#<number> " 和回复
for number, ticket in enumerate(tickets, start=1):
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=200,
messages=[{"role": "user", "content": "Summarize: " + ticket}],
)
for block in response.content:
if block.type == "text":
print(f"#{number} {block.text}")
在代码中调用模型中的所有课
自己练习: Python 在线编译器