结构化结果与显式 Function Calling:练习答案
练习解答
python
def stock(sku):return {'sku':sku,'count':{'A':3,'B':0}.get(sku)}
assert stock('A')['count']==3
assert stock('B')['count']==0
assert stock('X')['count'] is None
print('stock contract passed')0 是合法库存,or 会把它当假值覆盖掉;应显式检查 is None。
Interactions 答案
与正文 interactions_lab.py 放在同一目录,保存为 interactions_answers.py 并运行。此处使用 SDK 导出的 Interaction 校验类型,SSE 仍通过真实客户端读取。
python
from google.genai.interactions import Interaction
from interactions_lab import record, results_for, text_stream, stream_client
def interaction(calls):
return Interaction.model_validate(record('exercise','requires_action',calls))
def call(sku, id='c1'):
return {'type':'function_call','id':id,'name':'stock','arguments':{'sku':sku}}
for calls in ([call(True)], [call('A'),call('B')]):
try:results_for(interaction(calls))
except ValueError:pass
else:raise AssertionError('invalid batch accepted')
assert results_for(interaction([call('X')]))[0]['result']=={'sku':'X','count':None,'found':False}
deltas=[{'event_type':'content.delta','index':i,'delta':{'type':'text','text':t}} for i,t in [(1,'B'),(0,'A')]]
final={'event_type':'interaction.complete','interaction':record('s1','completed',[])}
with stream_client(deltas+[final]) as client:
with client.interactions.create(model='fixture-model',input='hello',stream=True) as events:
assert text_stream(events)=='AB'
for status in ('cancelled','requires_action'):
with stream_client(deltas+[{'event_type':'interaction.status_update','status':status}]) as client:
with client.interactions.create(model='fixture-model',input='hello',stream=True) as events:
try:text_stream(events)
except RuntimeError:pass
else:raise AssertionError('non-completion accepted')
# 非文本可以在 content.start 出现,不能只检查增量。
nontext={'event_type':'content.start','index':0,'content':call('A')}
with stream_client([nontext,final]) as client:
with client.interactions.create(model='fixture-model',input='hello',stream=True) as events:
try:text_stream(events)
except ValueError:pass
else:raise AssertionError('nontext start accepted')
print('invalid batch, missing SKU, indexed deltas, terminal states and nontext start passed')重复 ID 破坏结果关联,布尔 SKU 不符合输入契约,二者必须在执行前拒绝。未知商品保留 None;流式文本按内容 index 排序,抵达顺序不能替代内容位置。取消和工具等待都不是文本完成状态。
非文本拒绝还要检查 content.start,而不只检查 content.delta。这里刻意组合非文本开始和 completed,验证适配器的输入契约;不表示在线服务一定产生该组合。