Skip to content

Tool Use、流式与结构化契约:练习答案 ​

练习解答 ​

python
def matched(calls,results):
    wanted=[c['id'] for c in calls]
    got=[r['tool_use_id'] for r in results]
    return len(wanted)==len(set(wanted)) and sorted(wanted)==sorted(got)
calls=[{'id':'a'},{'id':'b'}]
assert not matched(calls,[{'tool_use_id':'a'}])
assert matched(calls,[{'tool_use_id':'b'},{'tool_use_id':'a'}])
assert not matched(calls,[{'tool_use_id':'a'},{'tool_use_id':'a'}])
print('pairing passed')

数量相同仍可能绑定错 ID,集合相同仍可能有重复;比较带重复的排序列表并保证调用 ID 唯一。

原生结构化与文件变体 ​

先按正文保存native.py与pdf.py,再将下列保存为同目录answer_native.py运行。不联网,PDF字节仅用于输入门测试,不声称为可解析PDF。

python
from native import fixture,checked
from pdf import document
for text in ('{"sku":"A","count":2,"price":9}','{"sku":"missing","count":2}'):
    try:checked(fixture('end_turn',text))
    except ValueError:pass
    else:raise AssertionError('invalid order accepted')
assert document(b'%PDF-1.7 test')['source']['media_type']=='application/pdf'
for data,mime in ((b'PNG','application/pdf'),(b'%PDF-1.7','image/png')):
    try:document(data,mime)
    except ValueError:pass
    else:raise AssertionError('invalid media accepted')
print('schema, business and media failures rejected')

额外字段违反模型契约,未知SKU违反业务契约;二者都不能入库。头部只检查前几个字节,截断文档同样可以具有该头,完整解析与资源限制需要独立处理。

用心记录每一步成长