先补齐必要概念
适合:需要把示例接入服务端或替换模型供应商。
- 模型请求
- 包含模型 ID、任务指令、用户输入及可用工具;凭据与真实用户身份由调用端管理。
- 候选动作
- 模型给出的工具名与参数。它表达建议,执行端还要核对格式、权限和业务条件。
- 调用关联
- call_id 把某次函数请求与它的返回结果关联;业务幂等键需由业务另外定义。
- 完成状态
- HTTP、生成过程和业务任务各有状态;只有业务验收能说明任务完成。
- 响应样本
- 本实验由作者编写的 Responses 形状样本,用于检查程序分支;真实 API 以当次返回和官方契约为准。
原理怎样一步步成立?
- 组装完整请求
任务指令说明允许行为,用户输入描述目标,工具定义提供局部参数契约。
- 分类接口结果
先检查 HTTP 结果,再检查生成状态和 output 的条目类型,保留拒绝与不完整原因。
- 执行受限动作
从可信会话绑定身份,独立校验参数、访问权限和调用预算;本实验只允许读取订单。
- 回传与核对
保留原始输出条目,把函数结果以对应 call_id 回传,最后对照工具回执核对候选答案。
资深 · 解释取舍
用稳定响应类型隔离接口变化
本层目标:定义适配契约、信任边界与可核对的完成条件,并说明此最小应用的生产缺口。
把业务代码依赖的结果做成稳定类型
业务层需要候选文本、候选工具、拒绝、不完整、可重试接口错误和不可恢复错误。适配器把目标接口映射到这些内部类型,保留原始类型、模型版本、响应关联与用量。遇到未知条目显式报告不支持;每次升级增加样本并回归,避免接口变化悄悄改变业务判断。
本课的分类器绑定一个有限的非流式形状。它适合解释边界和起步实现。完整产品还需流事件组装、取消、超时、错误体、消息并发、请求大小和隐私处理。先根据业务需要选择支持范围,再说明哪些输入会得到明确拒绝。
三份身份和三个标识
调用模型的服务凭据授权访问模型接口;当前业务用户身份决定可以读哪些订单;外部工具凭据约束执行服务。它们分别受控。响应 ID 用于生成关联,call_id 用于候选与结果关联,业务操作 ID 用于去重及账本。不要让某个传输标识承担未约定的业务唯一性保证。
在同一任务集比较供应商
固定正常、拒绝、截断、未知工具、越权和循环耗尽样本。比较内部类型映射、结构校验、工具结果关联、实际用量和业务验收。支持相似字段不代表所有能力一致;采样参数、结构约束、token 口径和模型限制要按实际接口核对。温度较低也不能保证跨运行完全相同。
升级路径与发布条件
第一阶段只读查询可以靠可信回执和预算闭环验收;第二阶段接入政策文档,用 RAG 证据检查解释;第三阶段才考虑有副作用的动作,接入批准对象、版本绑定、幂等和未知结果核对。增加写权限前,应让正确拒绝和故障恢复成为发布门槛。
本实验的两个静态订单与作者响应不代表身份系统、在线模型质量或并发可靠性。交付设计时逐项列出已运行部分、目标服务契约和待验证条件。下一步可沿工具契约、RAG 实作及研究恢复实验补齐证据。
运行实验,观察反例
使用作者编写的非流式 Responses 形状样本、教学订单与可信身份模拟,验证请求组装、只读校验、call_id 回传、预算和答案核对。程序不调用在线模型或真实订单服务。
Python 3.10+ · 默认运行只使用标准库 · 在你的电脑运行
- 下载本页的 Agent 应用入门实验包,解压后进入 agent-application-lab-v1 目录。
- 使用 Python 3.10+ 执行上方命令;默认回放只需标准库与包内数据。
- 对照输出与检查点,再运行 python3 -m unittest test_application -v,并完成当前层任务。
python3 model_response_contract.py查看本入口脚本
"""A bounded read-only tool loop using authored Responses-shaped fixtures.
This file makes no API requests. The course separately documents the real API request.
The fixture response shape is deliberately limited to the non-streaming cases below.
"""
import json
ORDERS = {
"o-1": {"tenant": "shop-a", "user": "u-1", "status": "delivered"},
"o-2": {"tenant": "shop-b", "user": "u-2", "status": "processing"},
}
PRINCIPAL = {"tenant": "shop-a", "user": "u-1"}
TOOL = {
"type": "function", "name": "read_order", "description": "Read an authorized order status.",
"strict": True, "parameters": {"type": "object", "properties": {"order_id": {"type": "string"}},
"required": ["order_id"], "additionalProperties": False},
}
def build_request(order_id, model="reader-selected-model"):
return {"model": model, "input": [
{"role": "developer", "content": "Use read_order for order facts. Tool access is checked by the application. Return an object with order_id, status and source. Do not perform writes."},
{"role": "user", "content": "What is the status of order " + order_id + "?"},
], "tools": [TOOL], "max_output_tokens": 500}
def classify_response(response, http_status=200):
if http_status != 200:
return {"kind": "http_error", "retryable": http_status == 429 or 500 <= http_status < 600}
if not isinstance(response, dict):
return {"kind": "unsupported"}
status = response.get("status")
if status == "incomplete":
return {"kind": "incomplete", "reason": response.get("incomplete_details")}
if status in ("failed", "cancelled"):
return {"kind": status}
if status != "completed" or not isinstance(response.get("output"), list):
return {"kind": "unsupported"}
calls, texts = [], []
for item in response["output"]:
if not isinstance(item, dict):
return {"kind": "unsupported"}
if item.get("type") == "function_call":
if not all(isinstance(item.get(key), str) and item[key] for key in ("call_id", "name", "arguments")):
return {"kind": "invalid_tool_call"}
calls.append(item)
elif item.get("type") == "message":
if item.get("status") not in (None, "completed") or not isinstance(item.get("content"), list):
return {"kind": "unsupported"}
for content in item["content"]:
if not isinstance(content, dict):
return {"kind": "unsupported"}
if content.get("type") == "refusal":
return {"kind": "refused"}
if content.get("type") != "output_text" or not isinstance(content.get("text"), str):
return {"kind": "unsupported"}
texts.append(content["text"])
elif item.get("type") != "reasoning":
return {"kind": "unsupported"}
if calls:
return {"kind": "tool_requests", "calls": calls}
return {"kind": "text", "text": "".join(texts)} if texts else {"kind": "empty"}
def execute_read(call, principal):
if call["name"] != "read_order":
raise ValueError("unknown_tool")
try:
args = json.loads(call["arguments"])
except (ValueError, TypeError):
raise ValueError("invalid_arguments") from None
if not isinstance(args, dict) or set(args) != {"order_id"} or not isinstance(args["order_id"], str):
raise ValueError("invalid_arguments")
order = ORDERS.get(args["order_id"])
if not order or order["tenant"] != principal["tenant"] or order["user"] != principal["user"]:
# No protected resource fields are returned when access is denied.
raise ValueError("permission_denied")
return {"order_id": args["order_id"], "status": order["status"], "source": "read_order"}
def run_loop(responses, principal=None, max_turns=3, max_calls=2):
principal = principal or PRINCIPAL
trace, results, seen_ids, calls_used = [], [], set(), 0
transcript = build_request("o-1")["input"]
for turn, response in enumerate(responses, 1):
if turn > max_turns:
break
event = classify_response(response)
trace.append({"turn": turn, "kind": event["kind"]})
if event["kind"] == "tool_requests":
# Preserve output items, including reasoning items when present, before
# appending call-correlated tool results to the next request input.
transcript.extend(response["output"])
if calls_used + len(event["calls"]) > max_calls:
return {"status": "budget_exhausted", "trace": trace, "results": results, "calls": calls_used}
for call in event["calls"]:
if call["call_id"] in seen_ids:
return {"status": "duplicate_call_id", "trace": trace, "results": results, "calls": calls_used}
seen_ids.add(call["call_id"])
calls_used += 1
try:
result = execute_read(call, principal)
except ValueError as error:
return {"status": str(error), "trace": trace, "results": results, "calls": calls_used}
result_item = {"type": "function_call_output", "call_id": call["call_id"], "output": json.dumps(result, sort_keys=True)}
results.append(result_item)
transcript.append(result_item)
trace[-1]["nextInputTypes"] = [item.get("type", "message") for item in transcript]
elif event["kind"] == "text":
try:
candidate = json.loads(event["text"])
except ValueError:
candidate = None
confirmed = isinstance(candidate, dict) and set(candidate) == {"order_id", "status", "source"} and any(candidate == json.loads(result["output"]) for result in results)
return {"status": "answer_ready" if confirmed else "unverified_answer", "trace": trace, "results": results, "calls": calls_used}
else:
return {"status": event["kind"], "trace": trace, "results": results, "calls": calls_used}
return {"status": "budget_exhausted", "trace": trace, "results": results, "calls": calls_used}
def tool_response(order_id="o-1", call_id="call-1", name="read_order"):
return {"status": "completed", "output": [{"type": "function_call", "call_id": call_id, "name": name, "arguments": json.dumps({"order_id": order_id})}]}
def text_response(candidate):
return {"status": "completed", "output": [{"type": "message", "role": "assistant", "status": "completed", "content": [{"type": "output_text", "text": json.dumps(candidate)}]}]}
def demo():
normal = run_loop([tool_response(), text_response({"order_id": "o-1", "status": "delivered", "source": "read_order"})])
denied = run_loop([tool_response("o-2")])
loop = run_loop([tool_response(call_id="c-" + str(i)) for i in range(5)], max_turns=2)
refused = {"status": "completed", "output": [{"type": "message", "content": [{"type": "refusal", "refusal": "fixture refusal"}]}]}
return {"normal": normal["status"], "toolResultCallId": normal["results"][0]["call_id"],
"crossTenant": denied["status"], "deniedResults": len(denied["results"]),
"boundedLoop": loop["status"], "boundedCalls": loop["calls"],
"refusal": classify_response(refused)["kind"],
"incomplete": classify_response({"status": "incomplete", "incomplete_details": {"reason": "max_output_tokens"}})["kind"],
"scope": "authored_responses_fixtures_no_api"}
if __name__ == "__main__":
print(json.dumps(demo(), ensure_ascii=False, sort_keys=True))
本地运行的预期输出
{"boundedCalls": 2, "boundedLoop": "budget_exhausted", "crossTenant": "permission_denied", "deniedResults": 0, "incomplete": "incomplete", "normal": "answer_ready", "refusal": "refused", "scope": "authored_responses_fixtures_no_api", "toolResultCallId": "call-1"}- normal=answer_ready,最终对象与该次 read_order 回执一致。
- crossTenant=permission_denied 且 deniedResults=0。
- boundedLoop=budget_exhausted 且 boundedCalls=2。
- refusal 与 incomplete 使用独立处理路径。
本层验收任务
为订单与政策助手设计接口适配表和信任边界图,列出正常、拒绝、不完整、越权、升级与写入未知六组验收。
完成后逐条核对
- 模型、业务身份与工具凭据分别标出。
- 内部响应类型和未知类型处理有定义。
- call_id 与业务操作 ID 的责任明确。
- 供应商替换比较同一任务与业务验收。
- 上线条件区分离线样本、真实联调和外部动作保证。
保存自己的过程、代码与结果。这里提供验收要求,暂不自动评分或保存课程掌握状态。
收起答案,检查理解
供应商接口字段与 OpenAI 相似,是否可以直接沿用全部状态处理?
展开参考推导
需要验证工具条目、拒绝、不完整、消息关联、结构约束与 usage 的实际行为,再映射成内部类型。用同一组正常和故障样本比较业务结果,保留版本和原始证据;表面字段相似不能替代能力验证。
延伸原理与知识练习
遇到不熟悉的原理,先阅读实现、连续追问和迁移案例,再独立说明前提与边界。作答与笔记保存到原有账号记录。
本专题的全部关联解析与练习(2 道)
依据与验证范围
原理依据来自公开资料;数字、案例和任务是本站教学设计。离线实验验证本页注明的范围,学习效果仍需通过独立任务与反馈判断。