fix(openai): 도구 호출 effort를 Responses로 보존한다

GPT Chat wire는 함수 도구와 reasoning effort를 함께 지원하지 않는다. caller-workspace 내부 단계가 선택된 프로필의 Responses operation으로 전환해 두 요구를 모두 보존하도록 한다.
This commit is contained in:
toki 2026-08-15 05:30:42 +09:00
parent 0110ca1af8
commit 4368a31ea6
6 changed files with 96 additions and 5 deletions

View file

@ -267,7 +267,7 @@ Provider-pool raw passthrough route는 위 목록을 provider request allowlist
Chat Completions의 실행 경로는 caller가 보낸 `model`의 route/provider capability로 결정한다.
- provider-pool model group route(`models[]`)는 candidate를 선택한 뒤 selected provider가 OpenAI-compatible 호출 방식을 지원하면 provider HTTP status/header/body를 Node가 열어 기존 Edge-Node tunnel로 relay하고, Edge가 caller에게 쓴다. 요청 body는 라우팅에 필요한 envelope만 읽고 `model` alias를 selected provider의 served target으로 rewrite하는 것을 기본으로 하며, provider가 지원하는 OpenAI-compatible field와 provider extension field를 보존한다.
- Provider-pool Chat과 unmarked caller-workspace의 selector/Work/Review Chat 요청은 모두 selected protocol profile이 선언한 출력 상한 wire spelling을 사용한다. OpenAI Chat wire는 `max_completion_tokens`, Gemini Chat wire는 `max_tokens`로 정규화하며 caller/agent identity로 분기하지 않는다.
- Provider-pool Chat과 unmarked caller-workspace의 selector/Work/Review 요청은 selected protocol profile이 선언한 출력 상한 wire spelling을 사용한다. OpenAI Chat wire는 `max_completion_tokens`, Gemini Chat wire는 `max_tokens`로 정규화한다. Unmarked 내부 stage가 function tools와 reasoning effort를 함께 요구하고 selected OpenAI profile의 Chat wire가 이를 지원하지 않으면, 같은 profile의 Responses operation이 두 요구를 보존할 때 내부 wire만 Responses로 전환한다. 결과는 기존 hot-path 공통 stage shape로 복원하며 caller-visible Chat surface와 caller/agent identity로 분기하지 않는다.
- selected provider가 Ollama/native provider처럼 normalized execution을 요구하면 Edge는 normalized `RunRequest` path를 사용한다. 이 경로는 OpenAI-compatible 표면을 입력/출력 compatibility layer로 제공하되, backend 호출은 normalized adapter 계약을 따른다.
- `metadata`는 경로 선택자가 아니다. Edge는 route 결정 뒤 인증 principal, usage/observability 등 IOP가 아는 bounded metadata key만 발췌한다. 이 발췌 정보는 provider body를 바꾸는 selector가 아니며, passthrough 응답 body에 IOP marker/event/envelope를 섞지 않는다.
- Chat Completions 성공 응답의 top-level `model` echo가 provider-served model이면 caller가 요청한 IOP model alias로 정규화할 수 있다. reasoning/content/tool_calls 같은 provider payload field는 보존한다.

View file

@ -208,7 +208,7 @@ Edge가 OpenAI-compatible HTTP 요청을 받아 내부 `adapter + target` 실행
| managed projection auth | `credential_plane.enabled=true` uses the fresh Control Plane projection for inbound token auth and principal route discovery. Static principal/bearer fallback is disabled. |
| managed slot route | Public model id/alias resolves to one projected route, exact slot/profile/upstream model/resource selector, and immutable revisions/generation. Unknown, cross-principal, stale, revoked, or ambiguous bindings fail closed. |
| marked preset single-request admission | An authorized fixed single-request preset compiles one service-owned admission value at request start: requested public model, canonical plan/work/review bindings resolved through managed authorization, opaque workspace capability, and absolute resource caps. Later refresh cannot mutate the admitted shape. No private binding is echoed to the caller. Compiled only after every canonical reference is verified through its catalog binding for the authenticated principal; missing, duplicate, unauthorized, dynamically selected, or option-inconsistent inputs are rejected without fallback. |
| unmarked caller-workspace light route | An unmarked `light` preset binds only admitted caller `workspace_tools`; it never accepts a raw caller path. Edge derives a phase-specific selector instruction from the locked artifact frontier. A non-parent-creating write binding first receives `prepare-only` for exactly one admitted `.iop/job/<request_id>` prepare call with PLAN/REVIEW writes prohibited; its successful receipt resumes the same selector with `pair-write` for exactly the PLAN/REVIEW writes and accepted grammar. A parent-creating binding receives `pair-write` immediately. The instruction is the final leading Chat `system` message or final Anthropic top-level `system` text block, does not mutate the retained caller snapshot or add a public field, and is absent from Work, Review, cleanup, and marked `single_request` bodies. Selector/Work/Review Chat bodies normalize `max_tokens`/`max_completion_tokens` to the selected profile wire; target-native values win when both aliases exist. A selector upstream HTTP 400 becomes one non-retryable caller HTTP 400 `invalid_request_error`, while provider details remain private. The selector's lightweight PLAN and pending REVIEW seed are validated before caller writes. Work reads PLAN, executes/verifies in the caller workspace, and replaces REVIEW with a completed `P1..Pn` handoff. Review reads both artifacts, successfully inspects an ordinary caller result, repairs/re-verifies in the same binding when needed, and owns the non-empty final output without rewriting REVIEW. Cleanup removes only the request `.iop/job/<request_id>` directory. Marked `single_request` presets bypass this route and retain the operator-owned Node workspace. |
| unmarked caller-workspace light route | An unmarked `light` preset binds only admitted caller `workspace_tools`; it never accepts a raw caller path. Edge derives a phase-specific selector instruction from the locked artifact frontier. A non-parent-creating write binding first receives `prepare-only` for exactly one admitted `.iop/job/<request_id>` prepare call with PLAN/REVIEW writes prohibited; its successful receipt resumes the same selector with `pair-write` for exactly the PLAN/REVIEW writes and accepted grammar. A parent-creating binding receives `pair-write` immediately. The instruction is the final leading Chat `system` message or final Anthropic top-level `system` text block, does not mutate the retained caller snapshot or add a public field, and is absent from Work, Review, cleanup, and marked `single_request` bodies. Selector/Work/Review Chat bodies normalize `max_tokens`/`max_completion_tokens` to the selected profile wire; target-native values win when both aliases exist. When tools plus reasoning effort are not representable on the selected OpenAI Chat wire, the internal stage alone uses that profile's lossless Responses operation and restores the common hot-path stage shape. A selector upstream HTTP 400 becomes one non-retryable caller HTTP 400 `invalid_request_error`, while provider details remain private. The selector's lightweight PLAN and pending REVIEW seed are validated before caller writes. Work reads PLAN, executes/verifies in the caller workspace, and replaces REVIEW with a completed `P1..Pn` handoff. Review reads both artifacts, successfully inspects an ordinary caller result, repairs/re-verifies in the same binding when needed, and owns the non-empty final output without rewriting REVIEW. Cleanup removes only the request `.iop/job/<request_id>` directory. Marked `single_request` presets bypass this route and retain the operator-owned Node workspace. |
| marked single-request provider normalization | Plan/Work/Review derive caller-neutral effort/tool/structured-output requirements and let the selected protocol profile choose Chat Completions or Responses. Effort exact misses fall only to the nearest declared lower grade (`max` → `xhigh` when `max` is absent). Explicit resource selectors keep exact provider-ID verification; a `default` selector leaves provider choice to the pool while model group, profile, upstream model, credential slot/revision, and tunnel path remain frozen. Both Chat and Responses results are converted into the private common Chat-shaped stage codec before Plan/Work/Review validation. Chat conversion discards only bounded standard/provider bookkeeping (`service_tier`, `system_fingerprint`, provider `timings`, choice `logprobs`, message `annotations`, null `refusal`) and rejects a non-null refusal or unknown/duplicate fields. |
| marked single-request internal templates | The admission also freezes the operator-configured effective Plan/Review Markdown templates. They are internal artifact shapes only: the Plan stage first performs a bounded read/list-only workspace inspection and requires one successful result in the same request-local conversation, then obtains a strict one-line `goal` plus bounded one-line `steps`/`verification` arrays. Edge owns the bullet formatting and renders `plan.md`; no separate analysis artifact is created. The Review template shapes the private `review.md` artifact. Callers cannot supply, name, or select a template, and template paths, contents, and digests never appear in a response, error, log, or metric label. The caller-visible Messages request/response schema is unchanged and the final text stays the model's `decision.output`. |
| marked single-request ingress | One validated and authorized Messages POST enters the separate service coordinator capability before legacy provider/caller continuation and increments `iop_anthropic_single_request_ingress_total` once. Non-streaming returns one buffered final-only message. Streaming keeps one envelope across the coordinator lifetime, exposes only fixed plan/work/review/repair text blocks plus `event: ping`, and commits one final text/error terminal. Internal reasoning/tool wire never becomes caller `tool_use`; success is acknowledged only after the complete terminal write succeeds. |
@ -371,7 +371,7 @@ sequenceDiagram
## 변경 기록
- 2026-08-15: Normalized Chat output-token aliases by selected protocol profile across provider-pool and unmarked caller-workspace selector/Work/Review calls. OpenAI Chat uses `max_completion_tokens`, Gemini Chat uses `max_tokens`, target-native values win, and selector upstream HTTP 400 now terminates once as caller `invalid_request_error` instead of retryable 502. Command-mode workspace execution also carries the admitted containment guard in the actual outgoing command.
- 2026-08-15: Normalized Chat output-token aliases by selected protocol profile across provider-pool and unmarked caller-workspace selector/Work/Review calls. OpenAI Chat uses `max_completion_tokens`, Gemini Chat uses `max_tokens`, target-native values win, and unmarked internal stages use the selected OpenAI profile's Responses operation when tools plus effort cannot be represented by Chat. Selector upstream HTTP 400 now terminates once as caller `invalid_request_error` instead of retryable 502. Command-mode workspace execution also carries the admitted containment guard in the actual outgoing command.
- 2026-08-14: Split the unmarked selector instruction into frontier-derived `prepare-only` and `pair-write` operations. Non-parent-creating bindings prepare the request job directory first and receive the exact artifact-pair grammar only after the successful receipt; parent-creating bindings receive the pair operation immediately.
- 2026-08-14: Added the Edge-owned provider-side selector instruction for unmarked caller-workspace initial/resume turns. Actual Chat/Messages bodies now carry the exact request-local relative paths and accepted PLAN/pending REVIEW grammar without changing caller snapshots or public schemas.
- 2026-08-14: Added the restored unmarked caller-workspace light route, including template-validated PLAN/pending REVIEW creation, worker-owned completed REVIEW handoff, reviewer reads/result inspection/repair, reviewer-owned non-empty terminal, and strict separation from marked Node-owned `single_request` presets.

View file

@ -393,6 +393,13 @@ func (s *Server) handleChatCompletionsProviderPool(w http.ResponseWriter, dc *ch
if err != nil {
return tunnelReq, err
}
if strings.TrimSpace(selectorInstruction) != "" {
prepared, err = prepareHotPathSelectorProviderInstruction(prepared, selectorInstruction)
if err != nil {
return tunnelReq, err
}
return prepareHotPathChatProviderOperation(prepared, selected, chatProviderRequirements(req))
}
prepared, err = prepareProviderChatRequestNormalization(prepared, selected)
if err != nil {
return tunnelReq, err
@ -401,7 +408,7 @@ func (s *Server) handleChatCompletionsProviderPool(w http.ResponseWriter, dc *ch
if err != nil {
return tunnelReq, err
}
return prepareHotPathSelectorProviderInstruction(prepared, selectorInstruction)
return prepared, nil
}
// strict-output output policy only applies to normalized dispatch,

View file

@ -1556,7 +1556,13 @@ func (s *Server) prepareHotPathStageTunnel(r *http.Request, snapshot hotPathDisp
prepared.BuildBody = func(target string) ([]byte, error) {
return hotPathChatStageBody(snapshot, prompt, target)
}
return prepareProviderChatRequestNormalization(prepared, selected)
requirements := providerRequestRequirements{
HasTools: len(snapshot.Tools) > 0, Stream: snapshot.Stream,
}
if effort, ok := snapshot.Stage.Options["reasoning_effort"].(string); ok {
requirements.Effort = strings.TrimSpace(effort)
}
return prepareHotPathChatProviderOperation(prepared, selected, requirements)
case config.ProtocolDriverAnthropicMessages:
request := r.Clone(r.Context())
if strings.TrimSpace(request.Header.Get(anthropicVersionHeader)) == "" {

View file

@ -567,6 +567,46 @@ func prepareProviderChatRequestNormalization(tunnel edgeservice.SubmitProviderTu
return tunnel, nil
}
// prepareHotPathChatProviderOperation lets an internal caller-workspace stage
// use the closest provider wire without changing the caller-facing Chat
// surface. In particular, OpenAI Chat cannot combine reasoning effort with
// function tools, while the same profile's Responses operation can. The
// internal stage result is already decoded into the common hot-path shape, so
// this operation switch remains private to IOP.
func prepareHotPathChatProviderOperation(
tunnel edgeservice.SubmitProviderTunnelRequest,
selected edgeservice.ProviderPoolCandidate,
requirements providerRequestRequirements,
) (edgeservice.SubmitProviderTunnelRequest, error) {
if selected.ProtocolProfile == nil || tunnel.BuildBody == nil {
return tunnel, errProviderStageMissingBinding
}
prepared, err := singleRequestProviderTunnelPreparer(requirements, tunnel.BuildBody)(tunnel, selected)
if err != nil {
return tunnel, err
}
if prepared.Operation != string(config.OperationChatCompletions) {
return prepared, nil
}
prepared, err = prepareProviderChatRequestNormalization(prepared, selected)
if err != nil {
return tunnel, err
}
return prepareProviderChatToolCallNormalization(prepared, selected)
}
func chatProviderRequirements(req chatCompletionRequest) providerRequestRequirements {
requirements := providerRequestRequirements{
HasTools: len(req.Tools) > 0,
Stream: req.Stream,
StructuredOutput: req.ResponseFormat != nil,
}
if req.ReasoningEffort != nil {
requirements.Effort = strings.TrimSpace(*req.ReasoningEffort)
}
return requirements
}
func normalizeChatTokenLimitField(body []byte, targetField string) ([]byte, error) {
var limits struct {
MaxTokens json.RawMessage `json:"max_tokens"`

View file

@ -189,6 +189,44 @@ func TestOpenAIChatProviderHTTPNormalizesGenericTokenLimit(t *testing.T) {
}
}
func TestHotPathOpenAIToolsAndEffortUseResponsesOperation(t *testing.T) {
profile, err := config.ResolveProtocolProfile("openai", "", config.BuiltInProtocolProfileCatalog())
if err != nil {
t.Fatal(err)
}
tunnel := edgeservice.SubmitProviderTunnelRequest{
Operation: string(config.OperationChatCompletions),
Path: "/v1/chat/completions",
BuildBody: func(target string) ([]byte, error) {
return []byte(`{"model":"` + target + `","messages":[{"role":"system","content":"inspect"},{"role":"user","content":"work"}],"tools":[{"type":"function","function":{"name":"bash","parameters":{"type":"object"}}}],"max_tokens":32000,"reasoning_effort":"high","stream":true}`), nil
},
}
prepared, err := prepareHotPathChatProviderOperation(tunnel, edgeservice.ProviderPoolCandidate{ProtocolProfile: &profile}, providerRequestRequirements{
HasTools: true, Stream: true, Effort: "high",
})
if err != nil {
t.Fatal(err)
}
if prepared.Operation != string(config.OperationResponses) || prepared.Path != "/v1/responses" {
t.Fatalf("operation=%q path=%q", prepared.Operation, prepared.Path)
}
body, err := prepared.BuildBody("gpt-5.6-terra")
if err != nil {
t.Fatal(err)
}
var request map[string]any
if err := json.Unmarshal(body, &request); err != nil {
t.Fatal(err)
}
if request["max_output_tokens"] != float64(32000) || request["messages"] != nil || request["max_tokens"] != nil {
t.Fatalf("Responses token/message conversion mismatch: %+v", request)
}
reasoning, _ := request["reasoning"].(map[string]any)
if reasoning["effort"] != "high" || len(anySlice(request["tools"])) != 1 {
t.Fatalf("Responses effort/tools conversion mismatch: %+v", request)
}
}
func TestGeminiChatProviderHTTPToolContinuationRoundTrip(t *testing.T) {
var providerRequests []map[string]any
provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {