Skip to content

fix(anthropic): 映射 refusal 与 model_context_window_exceeded 两个 stop_reason - #70

Merged
HoneyBBQ merged 1 commit into
mainfrom
fix/anthropic-stop-reasons
Sep 30, 2026
Merged

HoneyBBQ merged 1 commit into
mainfrom
fix/anthropic-stop-reasons

Conversation

@HoneyBBQ

Copy link
Copy Markdown
Collaborator

问题

mapFinishReason 没有处理 Anthropic 的 model_context_window_exceeded 和 refusal 两个 stop_reason,两者都映射为 FinishReasonUnknown。

model_context_window_exceeded 表示响应写满了模型的上下文窗口,官方文档要求按截断处理。Sonnet 4.5 及更新的模型不加 beta 头也会返回这个值。refusal 表示安全分类器中止了响应,接口以 200 正常返回,不是错误。调用方按 FinishReasonLength 判断截断、按 FinishReasonContentFilter 判断拦截时,这两种情况都判断不出来。

改动

  • model_context_window_exceeded 映射为 FinishReasonLength,与 max_tokens 相同。
  • refusal 映射为 FinishReasonContentFilter。Google、Completions 和 Responses 的内容过滤也报告这个值。
  • RawFinishReason 仍是原始的 stop_reason。
  • docs/api-reference.md 中 FinishReasonLength 的说明加上上下文窗口。

验证

  • go build ./...、go vet ./...、go vet -tags integration ./...、go test ./... -short -count=1 -race 和 golangci-lint run ./... 均通过,go mod tidy 无 diff。
  • 新增 TestFinishReasonMapping。对每个已映射的 stop_reason,检查 DoGenerate 的结果以及 DoStream 的 FinishStepPart 和 FinishPart,并断言 RawFinishReason。改回原来的映射,model_context_window_exceeded 和 refusal 两个用例失败。
  • 没有在真实 API 上触发这两个 stop_reason。取值和含义依据官方文档 Handling stop reasons 和 anthropic-sdk-go 的 StopReason 枚举。

⚠️ No human QA

…p reasons

Both stop reasons came out as FinishReasonUnknown. A response that filled
the context window is truncated, as with max_tokens, so it is now
FinishReasonLength. A refusal is a response the safety classifiers
stopped; it is now FinishReasonContentFilter, which is what the Google,
Completions and Responses providers report for their content filters.
RawFinishReason is unchanged.
@HoneyBBQ
HoneyBBQ marked this pull request as ready for review September 30, 2026 06:53
@HoneyBBQ
HoneyBBQ merged commit 17bbdf5 into main Sep 30, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant