流式、结构化输出与工具执行:练习答案
练习解答
以下是完整离线文件,保存为answer.py后运行python answer.py;先建立与正文一致的初始状态,再验证变体。
使用正文 consume 定义:
python
def consume(events):
draft='';done=False
for e in events:
if done:raise ValueError('event after terminal')
if e['type']=='delta':draft+=e['text']
elif e['type']=='complete':done=True
elif e['type']=='failed':raise RuntimeError('provider failed')
else:raise ValueError('unknown event')
return {'draft':draft,'committable':done}
assert consume([{'type':'delta','text':'hello'}])['committable'] is False
assert consume([{'type':'delta','text':'hello'},{'type':'complete'}])['committable'] is True
print('terminal boundary passed')
assert consume([])=={'draft':'','committable':False}
try:consume([{'type':'complete'},{'type':'delta','text':'late'}])
except ValueError:pass
else:raise AssertionError('late event accepted')
print('late event rejected')终态后仍接受文字会让已经提交的结果与展示不一致。跨请求迟到事件还需在调用层用业务 ID 过滤。
深化页面练习解答
事件生命周期
usage 只改变统计字段,不能改变 status。tool_call 建立待执行的 call ID,tool_result 必须匹配同一 ID;committable 同时要求终态为 completed、结构化校验为真,并且不存在未完成的工具调用。
结构化契约
quantity=0 和超大整数属于业务范围错误,浮点数属于 schema 错误;金额与币种应在业务层做跨字段校验。错误列表至少包含层级、字段、机器可读代码和可展示消息。截断响应应标记为 truncated 或 incomplete,禁止转换成空对象。
工具执行
只读查询仍需租户校验;写操作的确认摘要必须包含动作、资源、关键参数和有效期。工具超时要区分尚未开始、执行状态未知和明确失败;状态未知时查询或人工接管,不能自动重放有副作用的请求。步数、deadline、单工具超时和重复调用检测任一触发,都应终止循环并留下审计事件。