how-tos

GPT-6.2 API 用于编码智能体:函数工具、流式输出、长上下文与缓存

Poyo.ai Team
5 min read
Share:

驱动编码智能体循环的 GPT-6.2 API

GPT-6.2 API 是 OpenAI 目前推荐用于智能体工作的模型:API 更新日志推荐 gpt-6.2-sol 用于“日常编码和智能体工作流”,gpt-6.2-astra 用于“复杂的推理和编码任务”。本指南通过 PoYo 的 Responses 接口把任一模型接入编码智能体,包括函数工具、有界循环、流式进度、大型代码仓库上下文,以及让长会话成本可控的缓存。从 GPT-6.2 Sol 模型页开始,把 GPT-6.2 Astra 留作升级之用。

如果你还没发出过第一个请求,请先阅读 GPT-6.2 API 指南。

这个 API 能为编码智能体提供什么

项目PoYo 上的 GPT-6.2
模型 IDgpt-6.2-sol(默认)、gpt-6.2-astra(升级)
智能体接口POST https://api.poyo.ai/v1/responses(OpenAI SDK,base_url="https://api.poyo.ai/v1")
工具调用仅限 Responses;OpenAI:“工具调用需要使用 Responses”
上下文 / 最大输入 / 最大输出1,050,000 / 922,000 / 128,000 token
流式输出"stream": true;response.completed 携带最终输出和 usage
推理reasoning.effort;不接受 none,从 medium 开始
每 1M 价格(Sol)输入 $1.60 / 输出 $8 / 缓存读取 $0.08 / 缓存写入 $2
每 1M 价格(Astra)输入 $6.40 / 输出 $32 / 缓存读取 $0.32 / 缓存写入 $8
错误400 字段无效、401 密钥错误、402 积分不足、404 未知模型;429 / 5xx 用退避重试

PoYo 的 Responses 文档说明了 tools、tool_choice、parallel_tool_calls、reasoning、include、store、previous_response_id 和 truncation,并说明工具支持取决于模型。OpenAI 的模型页为 GPT-6.2 列出了函数调用和一组托管工具。PoYo 文档只给出了 web_search_preview 这一个托管工具示例,所以这个智能体使用你自己的函数工具,由你端到端掌控。

定义函数工具

工具集要小而安全。模型只能请求你实现了的操作:

import json, os, subprocess
from pathlib import Path
from openai import OpenAI

client = OpenAI(base_url="https://api.poyo.ai/v1", api_key=os.environ["POYO_API_KEY"])
REPO = Path("/srv/checkout").resolve()

TOOLS = [
    {"type": "function", "name": "read_file",
     "description": "Read a UTF-8 text file from the repository.",
     "parameters": {"type": "object", "properties": {"path": {"type": "string"}},
                    "required": ["path"], "additionalProperties": False}},
    {"type": "function", "name": "write_file",
     "description": "Replace a file in the repository with new content.",
     "parameters": {"type": "object",
                    "properties": {"path": {"type": "string"}, "content": {"type": "string"}},
                    "required": ["path", "content"], "additionalProperties": False}},
    {"type": "function", "name": "run_tests",
     "description": "Run the test suite and return the last 200 lines of output.",
     "parameters": {"type": "object", "properties": {}, "additionalProperties": False}},
]

def safe_path(p: str) -> Path:
    full = (REPO / p).resolve()
    if not full.is_relative_to(REPO):
        raise ValueError("path escapes the repository")
    return full

def call_tool(name: str, args: dict) -> str:
    try:
        if name == "read_file":
            return safe_path(args["path"]).read_text(encoding="utf-8")[:200_000]
        if name == "write_file":
            safe_path(args["path"]).write_text(args["content"], encoding="utf-8")
            return "ok"
        if name == "run_tests":
            r = subprocess.run(["pytest", "-q"], cwd=REPO, capture_output=True, text=True, timeout=600)
            return "\n".join((r.stdout + r.stderr).splitlines()[-200:])
        return f"unknown tool {name}"
    except Exception as e:  # return errors to the model instead of crashing the loop
        return f"error: {e}"

让智能体在一次性的检出副本或容器中运行,绝不要在你的工作目录中运行。

有界智能体循环

循环发送对话,执行每个 function_call 条目,追加一个带相同 call_id 的 function_call_output,然后重复,直到模型不再调用工具而直接给出回答。它在达到轮数上限或美元预算时停止。

PRICES = {"gpt-6.2-sol": (1.60, 8.00, 0.08, 2.00), "gpt-6.2-astra": (6.40, 32.00, 0.32, 8.00)}

def cost(model, u) -> float:
    p_in, p_out, p_read, p_write = PRICES[model]
    d = getattr(u, "input_tokens_details", None)
    read = getattr(d, "cached_tokens", 0) or 0
    write = getattr(d, "cache_write_tokens", 0) or 0
    return ((u.input_tokens - read - write) * p_in + read * p_read
            + write * p_write + u.output_tokens * p_out) / 1e6

DEVELOPER = ("You are a coding agent working in a Python repository. "
             "Read files before editing. Run the tests after every change. "
             "When the tests pass, reply with a short summary and no tool call.")

def run_agent(task: str, model="gpt-6.2-sol", max_turns=30, budget_usd=3.00):
    items = [{"role": "developer", "content": DEVELOPER},
             {"role": "user", "content": task}]
    spent = 0.0
    for turn in range(max_turns):
        resp = client.responses.create(
            model=model, input=items, tools=TOOLS,
            reasoning={"effort": "medium"}, max_output_tokens=16000,
            store=False, include=["reasoning.encrypted_content"],
        )
        spent += cost(model, resp.usage)
        items += [o.model_dump(exclude_none=True) for o in resp.output]
        calls = [o for o in resp.output if o.type == "function_call"]
        if not calls:
            return resp.output_text, spent, turn + 1
        for c in calls:
            items.append({"type": "function_call_output", "call_id": c.call_id,
                          "output": call_tool(c.name, json.loads(c.arguments))})
        if spent >= budget_usd:
            break
    raise RuntimeError(f"stopped after {turn + 1} turns, ${spent:.3f} spent")

循环为什么这样设计:

  • 输出条目按顺序回传,包括推理条目。 对于 store 为 false 的请求(例如在零数据保留下),OpenAI 的 GPT-6.2 指南要求“按顺序回传之前的输出条目,包括加密的推理条目”。include=["reasoning.encrypted_content"] 用来请求返回这些条目。另一种做法是使用存储的响应配合 previous_response_id,PoYo 也有文档说明。
  • 历史只追加不修改。 OpenAI 警告,对话中途的编辑可能让 Responses API 丢弃推理条目,这“可能降低回答质量并增加 token 用量”;而且编辑还会破坏已缓存的前缀。
  • 每轮都检查预算, 使用的是与账单相同的价格表。

为写这篇文章,我们没有在 PoYo 上端到端运行过这个循环。请先在一个小任务上运行,确认工具调用和 usage 符合预期。

向用户流式展示进度

没有反馈时,智能体的长轮次会显得很慢。对每一轮使用流式输出,展示文本增量,并从 response.completed 获取最终输出。以下是 PoYo 文档中的事件类型:

def stream_turn(model, items):
    final = None
    with client.responses.create(model=model, input=items, tools=TOOLS,
                                 reasoning={"effort": "medium"}, max_output_tokens=16000,
                                 store=False, include=["reasoning.encrypted_content"],
                                 stream=True) as stream:
        for event in stream:
            if event.type == "response.output_text.delta":
                print(event.delta, end="", flush=True)
            elif event.type == "response.completed":
                final = event.response
            elif event.type == "response.failed":
                raise RuntimeError(event.response)
    return final  # same object as the non-streaming call: .output, .usage

在循环中用 stream_turn 替换 responses.create。工具调用仍像之前一样从 final.output 中读取。

长上下文:922K 输入,128K 输出

GPT-6.2 每个请求最多接受 922,000 个输入 token。智能体可以预先加载代码仓库的很大一部分,而不是逐个读取文件。有三个限制会影响这个选择:

  • 每一轮都会重发历史。 一个 200K token 的快照经过 20 轮,至少是 4M 输入 token。按 Sol 的 $1.60 计算,不走缓存是 $6.40。如果快照写入缓存一次($0.40),再以 $0.08 读取 19 次($0.30),则约为 $0.70。
  • OpenAI 的长上下文价格档从超过 272K 输入 token 开始。 超过这条线后,OpenAI 价格页对整个请求把输入和缓存价格翻倍,输出按 1.5× 计费。除非任务确实需要,否则让智能体请求保持在 272K 以下,并在模型页查看适用的 PoYo 价格。
  • 推理共享输出预算。 max_output_tokens 限制的是可见文本加推理。让每次 write_file 调用只写一个文件,而不是重写整个仓库。

在追加工具输出之前先做裁剪:返回测试运行的最后 200 行,而不是 20,000 行。这样每轮的增长以及账单都能保持线性且较小。

智能体会话的提示缓存

OpenAI 的缓存指南为 GPT-6.2 设定了以下规则:

规则值
缓存读取价格输入的 0.05×(PoYo 上 Sol 每 1M $0.08,Astra $0.32)
缓存写入价格默认 30 分钟保留期下为输入的 1.25×(PoYo 上每 1M $2 / $8)
最小可缓存前缀1,024 个可见输入 token
隐式断点最新一条符合条件的消息末尾
用量字段usage.input_tokens_details.cached_tokens(读取)、cache_write_tokens(写入)

要提高缓存命中率:

  1. 稳定内容放在最前。 先是 developer 消息,然后是工具定义,再是代码仓库快照,最后是任务。
  2. 使用 developer 消息,而不是顶层 instructions。 GPT-6.2 会把 instructions 追加到 input 之后,因此它们会落在前缀之外。
  3. 绝不编辑之前的条目。 追加工具输出;不要改写历史。
  4. 会话内保持设置稳定。 OpenAI 的指南说,在两次响应之间修改设置时要保持前缀不变。

OpenAI 还说明了 prompt_cache_options(显式断点和 12 小时保留期)。PoYo 的 Responses schema 没有列出该字段,并声明不接受额外字段(additionalProperties: false),所以不要传它,依靠隐式缓存即可。在 Sol 上,一个最佳情况的 25 轮会话从不走缓存的 $3.82 降到约 $0.74;计算过程见 GPT-6.2 API 价格。

何时把运行交给 Astra

每次运行都从 gpt-6.2-sol 开始。如果它在达到轮数上限时测试仍失败,就用一个全新的条目列表在 gpt-6.2-astra 上重新开始任务。不要在同一个对话里切换模型,因为 OpenAI 表示模型切换可能会丢弃推理条目。路由的计算方法和一个路由器实现见 GPT-6.2 Sol API vs GPT-6.2 Astra API。想看另一家厂商对同一循环的做法,可以对比 Gemini 4 Carbon API 用于编码智能体。

常见问题

GPT-6.2 API 支持函数调用吗?

支持,在 /v1/responses 上。用 type: "function" 定义工具,从 output 中读取 function_call 条目,并把结果作为带相同 call_id 的 function_call_output 条目回传。

可以在 Chat Completions 上使用 GPT-6.2 API 的工具吗?

不可以。OpenAI 表示 GPT-6.2 支持 Chat Completions,但工具调用需要使用 Responses。

如何流式输出 GPT-6.2 API 智能体的一轮?

在 Responses 上设置 stream: true,打印 response.output_text.delta 事件,并从 response.completed 事件中读取工具调用和 usage。

如何降低长智能体会话中的 GPT-6.2 API 成本?

把稳定前缀(developer 消息、工具、快照)放在开头,只追加不编辑,裁剪工具输出,并尽可能让每个请求的输入保持在 272K token 以下。

我的编码智能体该用哪个 GPT-6.2 模型?

从 gpt-6.2-sol 开始,它每 token 的价格是 Astra 的四分之一;失败的运行再在 gpt-6.2-astra 上重新开始。

Share: