检查结果
本课属于 Coddy AI Engineering 学习旅程的“在代码中调用模型”单元。第 18 课,共 22 课。
挑战
中等现在每个工单在 results 中都是一个字典,原生的 Python 就可以对今天的数据进行统计报告了。保留你目前编写的所有代码,并在循环后添加以下代码行:
- 对于每个类别,按照
SCHEMA中枚举的顺序,打印<category>: <count>。跳过没有工单的类别。 - 打印
Urgent:和紧急工单的编号,每个编号写作#<number>,并用逗号加空格分隔。当没有紧急工单时,打印Urgent: none。
在经过 json.loads 解析后,urgent 是一个真正的布尔值,因此可以使用 if data["urgent"]: 来进行判断。例如,对于两个类别都是 billing 且都不紧急的工单,程序结尾如下:
billing: 2
Urgent: none亲手试试
import coddy_ai as anthropic # 生产环境中:import anthropic
import json
client = anthropic.Anthropic()
SCHEMA = {
"type": "object",
"properties": {
"category": {"type": "string", "enum": ["billing", "shipping", "account", "technical", "other"]},
"urgent": {"type": "boolean"},
"summary": {"type": "string"},
},
"required": ["category", "urgent", "summary"],
"additionalProperties": False,
}
count = int(input())
tickets = [input() for _ in range(count)]
print(f"Tickets: {count}")
results = []
for number, ticket in enumerate(tickets, start=1):
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=200,
output_config={"format": {"type": "json_schema", "schema": SCHEMA}},
messages=[{"role": "user", "content": ticket}],
)
for block in response.content:
if block.type == "text":
data = json.loads(block.text)
results.append(data)
urgent = "yes" if data["urgent"] else "no"
print(f"#{number} {data['category']} | urgent: {urgent} | {data['summary']}")
在代码中调用模型中的所有课
自己练习: Python 在线编译器