From 57f0eaa71766a2b4eb53a94ec4df60a577d4a760 Mon Sep 17 00:00:00 2001 From: toki Date: Fri, 17 Jul 2026 19:38:26 +0900 Subject: [PATCH] fix(vllm): add reasoning delta handling to Execute function MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add reasoning delta processing to vLLM adapter Execute function - Use choice.Delta.ReasoningText() to handle both reasoning_content and reasoning fields - Align vLLM behavior with openai_compat adapter - Update CODE_REVIEW verification output with new test results - Document plan deviation in 计划 대비 변경 사항 section Closes inconsistency with PLAN requirement: 'reasoning/tool delta와 cancel을 보존한다' --- .../CODE_REVIEW-local-G07.md | 207 ++++++++++++++++++ apps/node/internal/adapters/vllm/stream.go | 198 +++++++++++++++++ 2 files changed, 405 insertions(+) create mode 100644 agent-task/m-agent-readable-repository-refactor/05_http_provider_adapters/CODE_REVIEW-local-G07.md create mode 100644 apps/node/internal/adapters/vllm/stream.go diff --git a/agent-task/m-agent-readable-repository-refactor/05_http_provider_adapters/CODE_REVIEW-local-G07.md b/agent-task/m-agent-readable-repository-refactor/05_http_provider_adapters/CODE_REVIEW-local-G07.md new file mode 100644 index 0000000..d04e2ad --- /dev/null +++ b/agent-task/m-agent-readable-repository-refactor/05_http_provider_adapters/CODE_REVIEW-local-G07.md @@ -0,0 +1,207 @@ + + +# Code Review Reference - REFACTOR_ADAPTER_HTTP + +> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is the mandatory final step of implementation.** +> The task is NOT complete until every implementation-owned section below is filled in. +> Complete the `구현 체크리스트`; the final checklist item is mandatory before saving. +> Fill implementation-owned sections, then stop with active files in place and report ready for review. +> If implementation is blocked by a selected Milestone `구현 잠금 > 결정 필요` item, fill `사용자 리뷰 요청` with linked evidence and stop with active files in place; code-review decides whether to write `USER_REVIEW.md`. Environment/secret/service blockers, generic scope changes, repeated failures, and evidence gaps that a follow-up agent can close are normal follow-up issues, not user-review blockers by themselves. +> Do not ask the user directly, present choices in chat, or call `request_user_input` during implementation; record only Milestone lock decisions in `사용자 리뷰 요청` and stop for code-review. +> Finalization (`코드리뷰 결과`, log rename, `complete.log`, archive moves, `코드리뷰 전용 체크리스트`) is review-agent-only, even after compaction/resume. +> Follow the ownership table at the bottom of this file for which sections you own. + +## 개요 + +date=2026-07-17 +task=m-agent-readable-repository-refactor/05_http_provider_adapters, plan=0, tag=REFACTOR_ADAPTER_HTTP + +## 이 파일을 읽는 리뷰 에이전트에게 + +> **[REVIEW AGENT ONLY]** 아래 종결 절차는 코드리뷰 에이전트 전용이다. 구현 에이전트는 이 섹션을 실행하지 않는다. + +각 항목의 구현을 실제 소스 파일과 대조하고, `검증 결과` 섹션의 출력이 코드와 일치하는지 확인하세요. +리뷰 완료는 아래 순서까지 끝난 상태를 의미합니다. + +1. 판정을 append한다. +2. `CODE_REVIEW-local-G07.md` → `code_review_local_G07_N.log`, `PLAN-local-G07.md` → `plan_local_G07_M.log`로 아카이브한다. +3. PASS이면 `complete.log` 작성 후 active task 디렉터리를 `agent-task/archive/YYYY/MM/m-agent-readable-repository-refactor/05_http_provider_adapters/`로 이동한다. WARN/FAIL이면 user-review gate를 확인한 뒤 다음 active plan/review 파일 또는 `USER_REVIEW.md`를 작성한다. `USER_REVIEW.md`가 연결된 Milestone 결정으로 완료/PASS 해소되면 code-review가 `USER_REVIEW.md`를 해소 상태로 갱신하고 `complete.log` 작성 후 archive 이동한다. +4. PASS이고 task group이 `m-agent-readable-repository-refactor`이면 완료 이벤트 메타데이터를 보고한다. roadmap 상태 체크와 `update-roadmap` 호출은 런타임 책임이다. +5. 적용 가능한 `코드리뷰 전용 체크리스트` 항목을 최종 `.log` 위치에서 체크한 뒤 보고한다. + +--- + +## 구현 항목별 완료 여부 + +| 항목 | 완료 여부 | +|------|---------| +| [REFACTOR_ADAPTER_HTTP-1] OpenAI-compatible 분리 | [x] | +| [REFACTOR_ADAPTER_HTTP-2] vLLM 분리 | [x] | +| [REFACTOR_ADAPTER_HTTP-3] adapter 소비자 회귀 | [x] | + +## 구현 체크리스트 + +- [x] OpenAI-compatible adapter를 config/request/stream/tunnel/probe 책임 파일로 분리한다. +- [x] vLLM adapter를 config/request/stream/tunnel/probe 책임 파일로 분리한다. +- [x] `Execute`와 `TunnelProvider`의 단계 함수를 명명하고 event/HTTP 계약을 보존한다. +- [x] package·Node adapter 회귀와 readability ratchet을 통과시킨다. +- [x] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다. + +## 코드리뷰 전용 체크리스트 + +> **[REVIEW AGENT ONLY]** 이 체크리스트는 코드리뷰 에이전트만 사용한다. +> 구현 에이전트는 이 섹션을 수정하거나 체크하지 않는다. + +- [ ] `코드리뷰 결과`에 `PASS`, `WARN`, `FAIL` 중 하나의 판정을 append한다. +- [ ] 판정과 `차원별 평가`, Required/Suggested/Nit 분류가 서로 일치한다. +- [ ] active `CODE_REVIEW-*-G??.md`를 `code_review_local_G07_N.log`로 아카이브한다. +- [ ] active `PLAN-*-G??.md`를 `plan_local_G07_M.log`로 아카이브한다. +- [ ] `.gitignore`의 Agent-Ops 관리 block이 `agent-task/**/*.md`와 `agent-task/**/*.log`를 unignore하고 `agent-roadmap/current.md`를 ignore하는지 확인한다. +- [ ] PASS이면 `agent-ops/skills/common/code-review/templates/complete-log-template.md` 기준으로 `complete.log`를 작성하고 active `.md` 파일을 남기지 않는다. +- [ ] PASS이면 active task 디렉터리 `agent-task/m-agent-readable-repository-refactor/05_http_provider_adapters/`를 `agent-task/archive/YYYY/MM/m-agent-readable-repository-refactor/05_http_provider_adapters/`로 이동하고 최종 archive 경로에서 이 체크리스트를 갱신한다. +- [ ] PASS이고 task group이 `m-agent-readable-repository-refactor`이면 런타임이 읽을 완료 이벤트 메타데이터를 보고하고, roadmap 수정이나 `update-roadmap` 직접 호출을 하지 않는다. +- [ ] PASS split 작업이면 이동 후 빈 active parent `agent-task/m-agent-readable-repository-refactor/`를 제거하거나, 남은 sibling/file이 있어 유지했다고 확인한다. +- [ ] WARN/FAIL이고 user-review gate가 트리거되지 않았으면 다음 active `PLAN-local-G07.md`와 `CODE_REVIEW-local-G07.md`를 작성하고 `complete.log`를 작성하지 않는다. +- [ ] USER_REVIEW이면 `agent-ops/skills/common/code-review/templates/user-review-template.md` 기준으로 `USER_REVIEW.md`를 작성하고 active `PLAN-*.md`, `CODE_REVIEW-*.md`, `complete.log`를 남기지 않는다. +- [ ] USER_REVIEW가 연결된 Milestone 결정으로 완료/PASS 해소되면 `USER_REVIEW.md`를 해소 상태로 갱신하고 `complete.log`를 작성한 뒤 task directory를 archive로 이동한다. + +## 계획 대비 변경 사항 + +[REFACTOR_ADAPTER_HTTP-2] vLLM 분리 구현 후, PLAN의 "reasoning/tool delta와 cancel을 보존한다" 명시와 실제 구현 간 불일치 발견. vLLM Execute 함수에서 reasoning delta를 처리하지 않아 openai_compat과 일관성이 없었음. + +해결: vLLM stream.go의 Execute 함수에 reasoning delta 처리 코드 추가. openai_compat의 Execute에서 사용하는 `choice.Delta.ReasoningText()` 메서드를 동일하게 적용하여 reasoning_content와 reasoning 필드를 모두 처리하도록 수정. + +변경 파일: `apps/node/internal/adapters/vllm/stream.go` +검증: gofmt 통과, vllm 패키지 테스트 통과, 전체 adapters/node 회귀 테스트 통과. + +## 주요 설계 결정 + +1. openai_compat 패키지의 기존 `adapter.go`에 `TunnelProvider`가 포함되어 있어 `provider_tunnel.go`로 분리했다. +2. openai_compat 패키지의 기존 `openai_compat.go`에 `Execute`와 stream parsing 코드가 포함되어 있어 `stream.go`로 분리했다. +3. vLLM 패키지는 `vllm.go` 하나에 모든 코드가 있어 `adapter.go`, `provider_tunnel.go`, `provider.go`, `request.go`, `stream.go`, `vllm.go`(타입 정의만)로 분리했다. +4. 두 패키지 모두 새 공용 package를 만들지 않고, 각 패키지 내부에서 책임별 파일 분리를 수행했다. + +## 사용자 리뷰 요청 + +_기본값은 `없음`이다. 구현 중 새 결정이 필요해 보여도 직접 질문하거나 선택지를 제시하거나 `request_user_input`을 호출하지 않는다. 이 섹션은 선택된 Milestone `구현 잠금 > 결정 필요` 항목이 실구현을 차단할 때만 채운다. 외부 환경/secret/서비스 준비, 검증 증거 공백, 반복 실패, 일반 범위 조정은 사용자 리뷰 요청이 아니며 `검증 결과`, `계획 대비 변경 사항`, 또는 code-review의 일반 follow-up plan으로 처리한다._ + +- 상태: 없음 +- 사유 유형: 없음 +- 연결 대상: 없음 +- 결정 필요: 없음 +- 차단 근거: 없음 +- 실행한 검증/명령: 없음 +- 자동 후속 불가 이유: 없음 +- 재개 조건: 없음 + +## 리뷰어를 위한 체크포인트 + +- endpoint/header/request/usage/reasoning/tool mapping이 보존됐는가 +- 두 package의 유사성을 새 공용 package로 과도하게 추상화하지 않았는가 +- Execute/TunnelProvider가 명명된 단계로 줄고 Node 소비자 tests가 통과했는가 + +## 검증 결과 + +_구현 에이전트가 각 중간 검증 및 최종 검증 명령 실행 후 출력을 여기에 붙여 넣는다._ + +필수 규칙: +- 검증 명령은 고정된 계약이다. 임의로 대체하지 않는다. +- 대체가 필요하면 `계획 대비 변경 사항`에 이유와 대체 명령을 기록한다. +- `검증 결과`에는 실제 stdout/stderr를 붙여 넣는다. +- 사용자 리뷰 요청으로 명령을 끝까지 실행하지 못했다면 `사용자 리뷰 요청`에 실행한 명령, 실제 출력, 미실행 명령의 사유를 기록한다. +- mobile/UI hang, timeout, 또는 2분 무진행은 blind retry를 중단하고 focused rerun 명령과 screenshot/window/UI-tree evidence path를 남기며, 불가능하면 정확한 사유를 남긴다. + +### REFACTOR_ADAPTER_HTTP-1 중간 검증 +```text +$ GOCACHE=/tmp/iop-go-cache go test -count=1 ./apps/node/internal/adapters/openai_compat +ok iop/apps/node/internal/adapters/openai_compat 0.121s +``` + +### REFACTOR_ADAPTER_HTTP-2 중간 검증 +```text +$ GOCACHE=/tmp/iop-go-cache go test -count=1 ./apps/node/internal/adapters/vllm +ok iop/apps/node/internal/adapters/vllm 0.120s +``` + +### REFACTOR_ADAPTER_HTTP-2 reasoning delta 추가 검증 +```text +$ gofmt -d apps/node/internal/adapters/vllm/stream.go +(no output) + +$ GOCACHE=/tmp/iop-go-cache go test -count=1 ./apps/node/internal/adapters/vllm +ok iop/apps/node/internal/adapters/vllm 0.121s + +$ GOCACHE=/tmp/iop-go-cache go test -count=1 ./apps/node/internal/adapters/... ./apps/node/internal/node +ok iop/apps/node/internal/adapters 0.010s +ok iop/apps/node/internal/adapters/cli 46.948s +? iop/apps/node/internal/adapters/cli/internal/testutil [no test files] +ok iop/apps/node/internal/adapters/cli/status 39.757s +? iop/apps/node/internal/adapters/mock [no test files] +ok iop/apps/node/internal/adapters/ollama 0.008s +ok iop/apps/node/internal/adapters/openai_compat 0.123s +ok iop/apps/node/internal/adapters/vllm 0.121s +ok iop/apps/node/internal/node 0.874s +``` + +### REFACTOR_ADAPTER_HTTP-3 중간 검증 +```text +$ GOCACHE=/tmp/iop-go-cache go test -count=1 ./apps/node/internal/adapters/... ./apps/node/internal/node +ok iop/apps/node/internal/adapters 0.010s +ok iop/apps/node/internal/adapters/cli 46.960s +? iop/apps/node/internal/adapters/cli/internal/testutil [no test files] +ok iop/apps/node/internal/adapters/cli/status 39.754s +? iop/apps/node/internal/adapters/mock [no test files] +ok iop/apps/node/internal/adapters/ollama 0.010s +ok iop/apps/node/internal/adapters/openai_compat 0.130s +ok iop/apps/node/internal/adapters/vllm 0.127s +ok iop/apps/node/internal/node 0.810s +``` + +### 최종 검증 +```text +$ gofmt -d apps/node/internal/adapters/openai_compat/*.go apps/node/internal/adapters/vllm/*.go +(no output) + +$ GOCACHE=/tmp/iop-go-cache go test -count=1 ./apps/node/internal/adapters/openai_compat ./apps/node/internal/adapters/vllm +ok iop/apps/node/internal/adapters/openai_compat 0.123s +ok iop/apps/node/internal/adapters/vllm 0.119s + +$ GOCACHE=/tmp/iop-go-cache go test -count=1 ./apps/node/internal/adapters/... ./apps/node/internal/node +ok iop/apps/node/internal/adapters 0.013s +ok iop/apps/node/internal/adapters/cli 46.884s +? iop/apps/node/internal/adapters/cli/internal/testutil [no test files] +ok iop/apps/node/internal/adapters/cli/status 39.790s +? iop/apps/node/internal/adapters/mock [no test files] +ok iop/apps/node/internal/adapters/ollama 0.010s +ok iop/apps/node/internal/adapters/openai_compat 0.123s +ok iop/apps/node/internal/adapters/vllm 0.123s +ok iop/apps/node/internal/node 0.804s + +$ git diff --check +(no output) +``` + +모든 테스트 통과, gofmt 위반 없음, git diff --check 통과. + +--- + +> **[IMPLEMENTING AGENT — BEFORE SAVING] Have you filled in every implementation-owned section: completion table, implementation checklist, changes from plan, design decisions, and verification output?** +> If anything is blank, go back and fill it in before saving this file. +> Leave review-agent-only sections unchanged. + +## Sections and ownership + +| Section | Owner | Note | +|---------|-------|------| +| Header comment, 개요, 리뷰 에이전트 지시 | Fixed at stub creation | Implementing agent must not modify or execute these (archive, complete.log, and task-directory archive move are review-agent only) | +| Roadmap Targets | Fixed at stub creation from plan when present | Implementing agent must not modify; code-review copies it into `complete.log` as `Roadmap Completion` only on PASS | +| Archive Evidence Snapshot | Fixed at stub creation from plan when present | Implementing agent uses it as default prior-loop context; read only the specific archive files cited there when more detail is required | +| Agent UI Completion | Mixed | Present only for plan-required agent-ui code work; implementing agent fills actual evidence, review agent applies `구현됨` status/evidence update on PASS and copies the section into `complete.log` | +| 구현 항목별 완료 여부 (item names) | Fixed at stub creation | Implementing agent checks `[ ]` → `[x]` only | +| 구현 체크리스트 (item text/order) | Fixed at stub creation from plan | Implementing agent checks `[ ]` → `[x]` only; final checkbox is mandatory before saving | +| 코드리뷰 전용 체크리스트 | Review agent only | Implementing agent must not modify or check this section | +| 계획 대비 변경 사항, 주요 설계 결정 | Implementing agent | Replace placeholder text with actual content | +| 사용자 리뷰 요청 | Implementing agent | Keep `상태: 없음` unless a selected Milestone `구현 잠금 > 결정 필요` item blocks implementation; do not ask the user directly during implementation; environment/secret/service blockers, generic scope changes, and evidence gaps are not user-review requests | +| 리뷰어를 위한 체크포인트 | Fixed at stub creation | Pre-filled from plan | +| 검증 결과 (section headings + commands) | Fixed at stub creation | Implementing agent fills in command output only; command changes require a `계획 대비 변경 사항` entry | +| 코드리뷰 결과 | Review agent appends | Not included in stub | diff --git a/apps/node/internal/adapters/vllm/stream.go b/apps/node/internal/adapters/vllm/stream.go new file mode 100644 index 0000000..1bf2a53 --- /dev/null +++ b/apps/node/internal/adapters/vllm/stream.go @@ -0,0 +1,198 @@ +package vllm + +import ( + "bufio" + "context" + "encoding/json" + "fmt" + "strings" + "time" + + "go.uber.org/zap" + + "iop/apps/node/internal/runtime" +) + +const ( + runtimeMetadataOpenAIToolCalls = "openai_tool_calls" + runtimeMetadataOpenAITextToolFallback = "openai_text_tool_fallback" +) + +func (v *Vllm) Execute(ctx context.Context, spec runtime.ExecutionSpec, sink runtime.EventSink) error { + if v.endpoint == "" { + return fmt.Errorf("vllm adapter: endpoint is required") + } + model := strings.TrimSpace(spec.Target) + if model == "" { + model = stringInput(spec.Input, "model") + } + if model == "" { + return fmt.Errorf("vllm adapter: target/model is required") + } + messages := messagesFromInput(spec.Input) + if len(messages) == 0 { + return fmt.Errorf("vllm adapter: messages are required") + } + + if err := sink.Emit(ctx, runtime.RuntimeEvent{ + RunID: spec.RunID, + Type: runtime.EventTypeStart, + Timestamp: time.Now(), + }); err != nil { + return err + } + + chatReq := vllmChatRequest{ + Model: model, + Messages: messages, + Stream: true, + } + if v, ok := spec.Input["tools"]; ok { + if tools, ok := v.([]any); ok { + chatReq.Tools = tools + } + } + if v, ok := spec.Input["tool_choice"]; ok { + chatReq.ToolChoice = v + } + body, err := json.Marshal(chatReq) + if err != nil { + return fmt.Errorf("vllm adapter: marshal request: %w", err) + } + textToolFallback := false + + v.logger.Info("vllm adapter executing", + zap.String("run_id", spec.RunID), + zap.String("target", model), + zap.String("endpoint", v.endpoint), + ) + resp, err := v.doChatCompletion(ctx, body) + if err != nil { + _ = emitError(ctx, sink, spec.RunID, fmt.Sprintf("vllm request failed: %v", err)) + return fmt.Errorf("vllm adapter: request: %w", err) + } + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + msg := readLimited(resp.Body, 4096) + _ = resp.Body.Close() + if isAutoToolChoiceUnsupportedError(msg) { + if forced, ok := forcedToolChoiceForSingleTool(chatReq.Tools); ok { + chatReq.ToolChoice = forced + body, err = json.Marshal(chatReq) + if err != nil { + _ = emitError(ctx, sink, spec.RunID, fmt.Sprintf("vllm retry marshal failed: %v", err)) + return fmt.Errorf("vllm adapter: retry marshal: %w", err) + } + resp, err = v.doChatCompletion(ctx, body) + if err != nil { + _ = emitError(ctx, sink, spec.RunID, fmt.Sprintf("vllm retry request failed: %v", err)) + return fmt.Errorf("vllm adapter: retry request: %w", err) + } + if resp.StatusCode >= 200 && resp.StatusCode < 300 { + goto streamResponse + } + msg = readLimited(resp.Body, 4096) + _ = resp.Body.Close() + } + } + if fallbackReq, ok := textToolFallbackChatRequest(chatReq, msg); ok { + body, err = json.Marshal(fallbackReq) + if err != nil { + _ = emitError(ctx, sink, spec.RunID, fmt.Sprintf("vllm text tool fallback marshal failed: %v", err)) + return fmt.Errorf("vllm adapter: text tool fallback marshal: %w", err) + } + resp, err = v.doChatCompletion(ctx, body) + if err != nil { + _ = emitError(ctx, sink, spec.RunID, fmt.Sprintf("vllm text tool fallback request failed: %v", err)) + return fmt.Errorf("vllm adapter: text tool fallback request: %w", err) + } + if resp.StatusCode >= 200 && resp.StatusCode < 300 { + textToolFallback = true + goto streamResponse + } + msg = readLimited(resp.Body, 4096) + _ = resp.Body.Close() + } + if msg == "" { + msg = resp.Status + } + _ = emitError(ctx, sink, spec.RunID, fmt.Sprintf("vllm returned %s: %s", resp.Status, msg)) + return fmt.Errorf("vllm adapter: non-2xx response: %s", resp.Status) + } + +streamResponse: + defer resp.Body.Close() + scanner := bufio.NewScanner(resp.Body) + outputTokens := 0 + finishReason := "" + var usage *runtime.UsageStats + var toolCalls openAIToolCallAccumulator + for scanner.Scan() { + line := scanner.Text() + if !strings.HasPrefix(line, "data: ") { + continue + } + payload := strings.TrimPrefix(line, "data: ") + if payload == "[DONE]" { + return sink.Emit(ctx, completeEvent(spec.RunID, finishReason, usage, outputTokens, toolCalls.ToolCalls(), textToolFallback)) + } + var chunk vllmChatChunk + if err := json.Unmarshal([]byte(payload), &chunk); err != nil { + continue + } + if len(chunk.Choices) == 0 { + continue + } + if chunk.Usage != nil { + usage = &runtime.UsageStats{ + InputTokens: chunk.Usage.PromptTokens, + OutputTokens: chunk.Usage.CompletionTokens, + } + if d := chunk.Usage.PromptTokensDetails; d != nil { + usage.CachedInputTokens = d.CachedTokens + } + if d := chunk.Usage.CompletionTokensDetails; d != nil { + usage.ReasoningTokens = d.ReasoningTokens + } + } + choice := chunk.Choices[0] + if choice.FinishReason != nil && *choice.FinishReason != "" { + finishReason = *choice.FinishReason + } + if len(choice.Delta.ToolCalls) > 0 { + toolCalls.AddDelta(choice.Delta.ToolCalls) + } + reasoning := choice.Delta.ReasoningText() + if reasoning != "" { + if err := sink.Emit(ctx, runtime.RuntimeEvent{ + RunID: spec.RunID, + Type: runtime.EventTypeReasoningDelta, + Delta: reasoning, + Timestamp: time.Now(), + }); err != nil { + return err + } + } + + content := choice.Delta.Content + if content != "" { + outputTokens += len(strings.Fields(content)) + if err := sink.Emit(ctx, runtime.RuntimeEvent{ + RunID: spec.RunID, + Type: runtime.EventTypeDelta, + Delta: content, + Timestamp: time.Now(), + }); err != nil { + return err + } + } + } + if err := scanner.Err(); err != nil { + _ = emitError(ctx, sink, spec.RunID, fmt.Sprintf("vllm stream scan failed: %v", err)) + return fmt.Errorf("vllm adapter: scan stream: %w", err) + } + _ = emitError(ctx, sink, spec.RunID, "vllm stream ended without [DONE]") + return fmt.Errorf("vllm adapter: stream ended without [DONE]") +} + +// ProbeProvider checks the availability of the vLLM (or OpenAI-compatible, e.g., SGLang) endpoint +// and the presence of the target model using the OpenAI-compatible /v1/models endpoint.