mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-05 16:02:12 +00:00
Merge branch 'main' into fix/hold-tools-schema
This commit is contained in:
8 files changed
+475
-78
No files matched your search
@@ -50,12 +50,16 @@ type QualityRetryRuntime struct {
|
||||
// QualityStreamSignals is the hold classifier input. Tests drive this
|
||||
// directly and via ObserveQualityChunk on SSE fixtures.
|
||||
type QualityStreamSignals struct {
|
||||
HasThinking bool
|
||||
VisibleTokens int64
|
||||
ReasoningTokens int64
|
||||
OutputTokens int64
|
||||
Terminal bool
|
||||
HoldExpired bool
|
||||
HasThinking bool
|
||||
// ReasoningStarted is an empty reasoning item or the Chat SSE stub
|
||||
// `: grok2api-reasoning-start`. That is not proof of thinking: 降智
|
||||
// still emits the stub, then dumps visible tokens with usage 0.
|
||||
ReasoningStarted bool
|
||||
VisibleTokens int64
|
||||
ReasoningTokens int64
|
||||
OutputTokens int64
|
||||
Terminal bool
|
||||
HoldExpired bool
|
||||
}
|
||||
|
||||
// QualityVerdict is the hold decision for one upstream stream.
|
||||
@@ -110,23 +114,37 @@ func (s *Service) qualityRetryConfig() QualityRetryRuntime {
|
||||
}
|
||||
|
||||
// ClassifyQualityHold decides whether a held stream may be forwarded.
|
||||
// Thinking (or reasoning tokens) always delivers. A finished or expired
|
||||
// sample with enough visible output and no reasoning is 降智 and withheld.
|
||||
// Streamed thinking always delivers: reasoning/summary deltas, or a
|
||||
// reasoning item with encrypted_content. Usage.reasoning_tokens alone
|
||||
// does not — degraded upstreams fill that field without ciphertext or
|
||||
// deltas. A finished sample with enough visible output and no streamed
|
||||
// thinking is withheld.
|
||||
// Short replies below minOutput are delivered so "ok"/"yes" is not retried.
|
||||
// A hold timeout with no visible output is not fail-open: keep waiting for
|
||||
// more bytes or a stream abort so an empty hang is not flushed as HTTP 200.
|
||||
//
|
||||
// An empty reasoning stub is not thinking. Wait for usage/terminal so
|
||||
// encrypted thinking (tokens arrive at the end) is not withheld, and so
|
||||
// 200 + 推理·高 + reasoning=0 is not delivered the moment the stub appears.
|
||||
func ClassifyQualityHold(sig QualityStreamSignals, minOutput int64) QualityVerdict {
|
||||
if minOutput <= 0 {
|
||||
minOutput = defaultQualityMinOutput
|
||||
}
|
||||
if sig.HasThinking || sig.ReasoningTokens > 0 {
|
||||
if sig.HasThinking {
|
||||
return QualityDeliver
|
||||
}
|
||||
output := sig.OutputTokens
|
||||
if output < sig.VisibleTokens {
|
||||
output = sig.VisibleTokens
|
||||
// Prefer observed/derived visible output. Total output includes reasoning
|
||||
// tokens, which are deliberately not trusted as quality evidence above. If
|
||||
// the stream exposed no visible count at all, retain OutputTokens as a
|
||||
// compatibility fallback for terminal usage-only responses.
|
||||
output := sig.VisibleTokens
|
||||
if output <= 0 {
|
||||
output = sig.OutputTokens
|
||||
}
|
||||
enough := output >= minOutput
|
||||
if sig.ReasoningStarted && !sig.Terminal && !sig.HoldExpired {
|
||||
return QualityWait
|
||||
}
|
||||
if sig.Terminal {
|
||||
if output <= 0 {
|
||||
return QualityWait
|
||||
@@ -143,6 +161,9 @@ func ClassifyQualityHold(sig QualityStreamSignals, minOutput int64) QualityVerdi
|
||||
if output <= 0 {
|
||||
return QualityWait
|
||||
}
|
||||
if enough {
|
||||
return QualityWithhold
|
||||
}
|
||||
return QualityDeliver
|
||||
}
|
||||
return QualityWait
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
@@ -13,23 +14,25 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
qualityProtocolChat = "chat"
|
||||
qualityProtocolResponses = "responses"
|
||||
qualityProtocolAnthropic = "anthropic"
|
||||
qualityReasoningSSEComment = ": grok2api-reasoning-start"
|
||||
qualityHoldMaxBufferBytes = 4 << 20
|
||||
qualityProtocolChat = "chat"
|
||||
qualityProtocolResponses = "responses"
|
||||
qualityProtocolAnthropic = "anthropic"
|
||||
qualityReasoningSSEComment = ": grok2api-reasoning-start"
|
||||
qualityReasoningEvidenceSSEComment = ": grok2api-reasoning-evidence"
|
||||
qualityHoldMaxBufferBytes = 4 << 20
|
||||
)
|
||||
|
||||
type qualityScanState struct {
|
||||
protocol string
|
||||
pending []byte
|
||||
hasThinking bool
|
||||
visibleRunes int
|
||||
reasoningTokens int64
|
||||
outputTokens int64
|
||||
usage Usage
|
||||
responseID string
|
||||
terminal bool
|
||||
protocol string
|
||||
pending []byte
|
||||
hasThinking bool
|
||||
reasoningStarted bool
|
||||
visibleRunes int
|
||||
reasoningTokens int64
|
||||
outputTokens int64
|
||||
usage Usage
|
||||
responseID string
|
||||
terminal bool
|
||||
}
|
||||
|
||||
type qualityReadResult struct {
|
||||
@@ -135,12 +138,16 @@ func (s *qualityScanState) signals() QualityStreamSignals {
|
||||
if s.usage.Reported && s.usage.OutputTokens > output {
|
||||
output = s.usage.OutputTokens
|
||||
}
|
||||
// Usage.reasoning_tokens is not proof of thinking. 降智 accounts report
|
||||
// hundreds of reasoning tokens on completed while the stream never sent
|
||||
// reasoning_text / reasoning_summary deltas (TUI shows no thoughts).
|
||||
return QualityStreamSignals{
|
||||
HasThinking: s.hasThinking || s.reasoningTokens > 0 || s.usage.ReasoningTokens > 0,
|
||||
VisibleTokens: visible,
|
||||
ReasoningTokens: max(s.reasoningTokens, s.usage.ReasoningTokens),
|
||||
OutputTokens: output,
|
||||
Terminal: s.terminal,
|
||||
HasThinking: s.hasThinking,
|
||||
ReasoningStarted: s.reasoningStarted || s.hasThinking,
|
||||
VisibleTokens: visible,
|
||||
ReasoningTokens: max(s.reasoningTokens, s.usage.ReasoningTokens),
|
||||
OutputTokens: output,
|
||||
Terminal: s.terminal,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,6 +172,14 @@ func ObserveQualityChunk(state *qualityScanState, chunk []byte) {
|
||||
continue
|
||||
}
|
||||
if bytes.Equal(line, []byte(qualityReasoningSSEComment)) {
|
||||
// Timing stub only. 降智 still emits this, then usage.reasoning_tokens=0.
|
||||
state.reasoningStarted = true
|
||||
continue
|
||||
}
|
||||
if bytes.Equal(line, []byte(qualityReasoningEvidenceSSEComment)) {
|
||||
// Protocol converters cannot expose encrypted_content in every public
|
||||
// JSON contract. This internal SSE comment preserves that evidence.
|
||||
state.reasoningStarted = true
|
||||
state.hasThinking = true
|
||||
continue
|
||||
}
|
||||
@@ -228,13 +243,10 @@ func observeQualityChat(state *qualityScanState, payload []byte) {
|
||||
state.usage.ResponseModel = event.Model
|
||||
state.outputTokens = event.Usage.CompletionTokens
|
||||
state.reasoningTokens = event.Usage.CompletionTokensDetails.ReasoningTokens
|
||||
if state.reasoningTokens > 0 {
|
||||
state.hasThinking = true
|
||||
}
|
||||
}
|
||||
for _, choice := range event.Choices {
|
||||
delta := choice.Delta
|
||||
if delta.Reasoning != "" || delta.ReasoningContent != "" || delta.ThinkingContent != "" {
|
||||
if strings.TrimSpace(delta.Reasoning) != "" || strings.TrimSpace(delta.ReasoningContent) != "" || strings.TrimSpace(delta.ThinkingContent) != "" {
|
||||
state.hasThinking = true
|
||||
}
|
||||
if delta.Content != "" {
|
||||
@@ -246,18 +258,34 @@ func observeQualityChat(state *qualityScanState, payload []byte) {
|
||||
}
|
||||
}
|
||||
|
||||
type qualityReasoningItem struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
EncryptedContent string `json:"encrypted_content"`
|
||||
}
|
||||
|
||||
func noteResponsesReasoningItem(state *qualityScanState, item qualityReasoningItem) {
|
||||
if !strings.EqualFold(strings.TrimSpace(item.Type), "reasoning") {
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(item.ID) != "" {
|
||||
state.reasoningStarted = true
|
||||
}
|
||||
if strings.TrimSpace(item.EncryptedContent) != "" {
|
||||
state.hasThinking = true
|
||||
}
|
||||
}
|
||||
|
||||
func observeQualityResponses(state *qualityScanState, payload []byte) {
|
||||
var event struct {
|
||||
Type string `json:"type"`
|
||||
Delta string `json:"delta"`
|
||||
Item struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
} `json:"item"`
|
||||
Type string `json:"type"`
|
||||
Delta string `json:"delta"`
|
||||
Item qualityReasoningItem
|
||||
Response *struct {
|
||||
ID string `json:"id"`
|
||||
Model string `json:"model"`
|
||||
Usage *struct {
|
||||
ID string `json:"id"`
|
||||
Model string `json:"model"`
|
||||
Output []qualityReasoningItem `json:"output"`
|
||||
Usage *struct {
|
||||
OutputTokens int64 `json:"output_tokens"`
|
||||
InputTokens int64 `json:"input_tokens"`
|
||||
TotalTokens int64 `json:"total_tokens"`
|
||||
@@ -274,13 +302,11 @@ func observeQualityResponses(state *qualityScanState, payload []byte) {
|
||||
case "response.completed", "response.incomplete", "response.failed":
|
||||
state.terminal = true
|
||||
case "response.reasoning_text.delta", "response.reasoning_summary_text.delta":
|
||||
if event.Delta != "" {
|
||||
state.hasThinking = true
|
||||
}
|
||||
case "response.output_item.added":
|
||||
if event.Item.Type == "reasoning" && event.Item.ID != "" {
|
||||
if strings.TrimSpace(event.Delta) != "" {
|
||||
state.hasThinking = true
|
||||
}
|
||||
case "response.output_item.added", "response.output_item.done":
|
||||
noteResponsesReasoningItem(state, event.Item)
|
||||
case "response.output_text.delta":
|
||||
if event.Delta != "" {
|
||||
noteVisibleContent(state, event.Delta)
|
||||
@@ -290,6 +316,9 @@ func observeQualityResponses(state *qualityScanState, payload []byte) {
|
||||
if state.responseID == "" {
|
||||
state.responseID = event.Response.ID
|
||||
}
|
||||
for _, item := range event.Response.Output {
|
||||
noteResponsesReasoningItem(state, item)
|
||||
}
|
||||
if event.Response.Usage != nil {
|
||||
state.usage.Reported = true
|
||||
state.usage.InputTokens = event.Response.Usage.InputTokens
|
||||
@@ -299,9 +328,6 @@ func observeQualityResponses(state *qualityScanState, payload []byte) {
|
||||
state.usage.ResponseModel = event.Response.Model
|
||||
state.outputTokens = event.Response.Usage.OutputTokens
|
||||
state.reasoningTokens = event.Response.Usage.OutputTokensDetails.ReasoningTokens
|
||||
if state.reasoningTokens > 0 {
|
||||
state.hasThinking = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -313,9 +339,10 @@ func observeQualityAnthropic(state *qualityScanState, payload []byte) {
|
||||
Type string `json:"type"`
|
||||
} `json:"content_block"`
|
||||
Delta struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
Thinking string `json:"thinking"`
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
Thinking string `json:"thinking"`
|
||||
Signature string `json:"signature"`
|
||||
} `json:"delta"`
|
||||
Usage *struct {
|
||||
OutputTokens int64 `json:"output_tokens"`
|
||||
@@ -332,10 +359,16 @@ func observeQualityAnthropic(state *qualityScanState, payload []byte) {
|
||||
state.terminal = true
|
||||
case "content_block_start":
|
||||
if event.ContentBlock.Type == "thinking" {
|
||||
state.hasThinking = true
|
||||
state.reasoningStarted = true
|
||||
}
|
||||
case "content_block_delta":
|
||||
if event.Delta.Type == "thinking_delta" && event.Delta.Thinking != "" {
|
||||
if event.Delta.Type == "thinking_delta" && strings.TrimSpace(event.Delta.Thinking) != "" {
|
||||
state.hasThinking = true
|
||||
}
|
||||
if event.Delta.Type == "signature_delta" && strings.TrimSpace(event.Delta.Signature) != "" {
|
||||
// Anthropic Messages represents Responses encrypted_content as a
|
||||
// signature delta. A non-empty signature is encrypted thinking proof.
|
||||
state.reasoningStarted = true
|
||||
state.hasThinking = true
|
||||
}
|
||||
if event.Delta.Type == "text_delta" && event.Delta.Text != "" {
|
||||
@@ -348,9 +381,6 @@ func observeQualityAnthropic(state *qualityScanState, payload []byte) {
|
||||
state.usage.ReasoningTokens = event.Usage.OutputTokensDetails.ThinkingTokens
|
||||
state.outputTokens = event.Usage.OutputTokens
|
||||
state.reasoningTokens = event.Usage.OutputTokensDetails.ThinkingTokens
|
||||
if state.reasoningTokens > 0 {
|
||||
state.hasThinking = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ import (
|
||||
modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/persistence/relational"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/provider/conversation"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/runtime/memory"
|
||||
neterrorpkg "github.com/chenyme/grok2api/backend/internal/pkg/neterror"
|
||||
)
|
||||
@@ -32,12 +33,15 @@ func TestClassifyQualityHold(t *testing.T) {
|
||||
want QualityVerdict
|
||||
}{
|
||||
{name: "thinking delivers", sig: QualityStreamSignals{HasThinking: true, VisibleTokens: 10}, want: QualityDeliver},
|
||||
{name: "reasoning tokens deliver", sig: QualityStreamSignals{ReasoningTokens: 40, VisibleTokens: 80, Terminal: true}, want: QualityDeliver},
|
||||
{name: "usage reasoning tokens alone withhold", sig: QualityStreamSignals{ReasoningTokens: 40, VisibleTokens: 80, Terminal: true}, want: QualityWithhold},
|
||||
{name: "visible 32 no think withhold", sig: QualityStreamSignals{VisibleTokens: 32, Terminal: true}, want: QualityWithhold},
|
||||
{name: "output 40 no think withhold", sig: QualityStreamSignals{OutputTokens: 40, Terminal: true}, want: QualityWithhold},
|
||||
{name: "short visible output ignores inflated total", sig: QualityStreamSignals{VisibleTokens: 1, OutputTokens: 80, Terminal: true}, want: QualityDeliver},
|
||||
{name: "short no think delivers", sig: QualityStreamSignals{VisibleTokens: 10, Terminal: true}, want: QualityDeliver},
|
||||
{name: "empty terminal waits for transport handling", sig: QualityStreamSignals{Terminal: true}, want: QualityWait},
|
||||
{name: "midstream enough content withhold", sig: QualityStreamSignals{VisibleTokens: 64}, want: QualityWithhold},
|
||||
{name: "stub midstream waits even with enough visible", sig: QualityStreamSignals{ReasoningStarted: true, VisibleTokens: 64}, want: QualityWait},
|
||||
{name: "stub terminal enough withhold", sig: QualityStreamSignals{ReasoningStarted: true, VisibleTokens: 64, Terminal: true}, want: QualityWithhold},
|
||||
{name: "wait for more", sig: QualityStreamSignals{VisibleTokens: 8}, want: QualityWait},
|
||||
{name: "hold expired short delivers", sig: QualityStreamSignals{VisibleTokens: 8, HoldExpired: true}, want: QualityDeliver},
|
||||
{name: "hold expired empty waits", sig: QualityStreamSignals{HoldExpired: true}, want: QualityWait},
|
||||
@@ -263,16 +267,191 @@ func TestObserveQualityChunkShortNoThink(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestObserveQualityChunkShortNoThinkIgnoresFakeReasoningUsage(t *testing.T) {
|
||||
t.Parallel()
|
||||
state := qualityScanState{protocol: qualityProtocolChat}
|
||||
ObserveQualityChunk(&state, []byte(sse(
|
||||
": grok2api-reasoning-start",
|
||||
`data: {"choices":[{"delta":{"content":"OK"}}]}`,
|
||||
`data: {"usage":{"completion_tokens":80,"completion_tokens_details":{"reasoning_tokens":79}}}`,
|
||||
"data: [DONE]",
|
||||
)))
|
||||
sig := state.signals()
|
||||
if sig.VisibleTokens >= 32 || sig.OutputTokens != 80 || sig.ReasoningTokens != 79 {
|
||||
t.Fatalf("fake-usage short reply signals = %#v", sig)
|
||||
}
|
||||
if got := ClassifyQualityHold(sig, 32); got != QualityDeliver {
|
||||
t.Fatalf("short visible reply must not be withheld by inflated usage: %s (%#v)", got, sig)
|
||||
}
|
||||
}
|
||||
|
||||
func TestObserveQualityConvertedEncryptedThinking(t *testing.T) {
|
||||
t.Parallel()
|
||||
source := sse(
|
||||
`data: {"type":"response.created","response":{"id":"resp_1","model":"grok-4.6"}}`,
|
||||
`data: {"type":"response.output_item.added","item":{"id":"rs_1","type":"reasoning"}}`,
|
||||
`data: {"type":"response.output_item.done","item":{"id":"rs_1","type":"reasoning","encrypted_content":"gAAAA-cipher"}}`,
|
||||
`data: {"type":"response.output_text.delta","delta":"`+strings.Repeat("word ", 40)+`"}`,
|
||||
`data: {"type":"response.completed","response":{"id":"resp_1","model":"grok-4.6","usage":{"output_tokens":90,"output_tokens_details":{"reasoning_tokens":60}}}}`,
|
||||
)
|
||||
tests := []struct {
|
||||
name string
|
||||
operation string
|
||||
protocol string
|
||||
options conversation.ResponseOptions
|
||||
}{
|
||||
{name: "chat", operation: conversation.OperationChat, protocol: qualityProtocolChat},
|
||||
{name: "messages", operation: conversation.OperationMessages, protocol: qualityProtocolAnthropic, options: conversation.ResponseOptions{AnthropicThinking: true}},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
converted, err := io.ReadAll(conversation.ConvertResponseStreamWithOptions(
|
||||
io.NopCloser(strings.NewReader(source)), test.operation, test.options,
|
||||
))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state := qualityScanState{protocol: test.protocol}
|
||||
ObserveQualityChunk(&state, converted)
|
||||
sig := state.signals()
|
||||
if !sig.HasThinking {
|
||||
t.Fatalf("converted encrypted thinking evidence was lost:\n%s", converted)
|
||||
}
|
||||
if got := ClassifyQualityHold(sig, 32); got != QualityDeliver {
|
||||
t.Fatalf("converted encrypted thinking verdict = %s (%#v)", got, sig)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestObserveQualityChunkWhitespaceIsNotThinking(t *testing.T) {
|
||||
t.Parallel()
|
||||
tests := []struct {
|
||||
name string
|
||||
protocol string
|
||||
fixture string
|
||||
}{
|
||||
{name: "chat", protocol: qualityProtocolChat, fixture: sse(`data: {"choices":[{"delta":{"reasoning_content":" \n\t"}}]}`)},
|
||||
{name: "responses", protocol: qualityProtocolResponses, fixture: sse(`data: {"type":"response.reasoning_summary_text.delta","delta":" \n\t"}`)},
|
||||
{name: "messages", protocol: qualityProtocolAnthropic, fixture: sse(`data: {"type":"content_block_delta","delta":{"type":"thinking_delta","thinking":" \n\t"}}`)},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
state := qualityScanState{protocol: test.protocol}
|
||||
ObserveQualityChunk(&state, []byte(test.fixture))
|
||||
if sig := state.signals(); sig.HasThinking {
|
||||
t.Fatalf("whitespace-only reasoning counted as thinking: %#v", sig)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestObserveQualityChunkAnthropicSignatureIsThinking(t *testing.T) {
|
||||
t.Parallel()
|
||||
state := qualityScanState{protocol: qualityProtocolAnthropic}
|
||||
ObserveQualityChunk(&state, []byte(sse(
|
||||
`data: {"type":"content_block_delta","delta":{"type":"signature_delta","signature":"gAAAA-cipher"}}`,
|
||||
)))
|
||||
if sig := state.signals(); !sig.HasThinking || !sig.ReasoningStarted {
|
||||
t.Fatalf("non-empty Anthropic signature must count as encrypted thinking: %#v", sig)
|
||||
}
|
||||
}
|
||||
|
||||
func TestObserveQualityChunkResponsesReasoningItem(t *testing.T) {
|
||||
t.Parallel()
|
||||
state := qualityScanState{protocol: qualityProtocolResponses}
|
||||
ObserveQualityChunk(&state, []byte(sse(
|
||||
fake := qualityScanState{protocol: qualityProtocolResponses}
|
||||
ObserveQualityChunk(&fake, []byte(sse(
|
||||
`data: {"type":"response.output_item.added","item":{"id":"rs_1","type":"reasoning"}}`,
|
||||
`data: {"type":"response.output_text.delta","delta":"`+strings.Repeat("hello ", 40)+`"}`,
|
||||
`data: {"type":"response.completed","response":{"id":"resp_1","usage":{"output_tokens":90,"output_tokens_details":{"reasoning_tokens":60}}}}`,
|
||||
)))
|
||||
fakeSig := fake.signals()
|
||||
if fakeSig.HasThinking {
|
||||
t.Fatalf("usage-only reasoning tokens must not count as thinking: %#v", fakeSig)
|
||||
}
|
||||
if !fakeSig.ReasoningStarted || fakeSig.ReasoningTokens != 60 {
|
||||
t.Fatalf("usage-only signals = %#v", fakeSig)
|
||||
}
|
||||
if ClassifyQualityHold(fakeSig, 32) != QualityWithhold {
|
||||
t.Fatalf("usage-only reasoning with no deltas must withhold: %#v", fakeSig)
|
||||
}
|
||||
|
||||
real := qualityScanState{protocol: qualityProtocolResponses}
|
||||
ObserveQualityChunk(&real, []byte(sse(
|
||||
`data: {"type":"response.reasoning_summary_text.delta","delta":"plan the fix"}`,
|
||||
`data: {"type":"response.output_text.delta","delta":"hello"}`,
|
||||
`data: {"type":"response.completed","response":{"id":"resp_1","usage":{"output_tokens":90,"output_tokens_details":{"reasoning_tokens":60}}}}`,
|
||||
)))
|
||||
if ClassifyQualityHold(state.signals(), 32) != QualityDeliver {
|
||||
t.Fatalf("responses reasoning item should deliver: %#v", state.signals())
|
||||
realSig := real.signals()
|
||||
if !realSig.HasThinking || realSig.ReasoningTokens != 60 {
|
||||
t.Fatalf("streamed summary must count as thinking: %#v", realSig)
|
||||
}
|
||||
if ClassifyQualityHold(realSig, 32) != QualityDeliver {
|
||||
t.Fatalf("streamed reasoning summary should deliver: %#v", realSig)
|
||||
}
|
||||
|
||||
encrypted := qualityScanState{protocol: qualityProtocolResponses}
|
||||
ObserveQualityChunk(&encrypted, []byte(sse(
|
||||
`data: {"type":"response.output_item.added","item":{"id":"rs_1","type":"reasoning"}}`,
|
||||
`data: {"type":"response.output_item.done","item":{"id":"rs_1","type":"reasoning","encrypted_content":"gAAAA-cipher"}}`,
|
||||
`data: {"type":"response.output_text.delta","delta":"hello hello hello hello hello hello hello hello"}`,
|
||||
`data: {"type":"response.completed","response":{"id":"resp_1","usage":{"output_tokens":90,"output_tokens_details":{"reasoning_tokens":60}}}}`,
|
||||
)))
|
||||
encSig := encrypted.signals()
|
||||
if !encSig.HasThinking || encSig.ReasoningTokens != 60 {
|
||||
t.Fatalf("encrypted reasoning item must count as thinking: %#v", encSig)
|
||||
}
|
||||
if ClassifyQualityHold(encSig, 32) != QualityDeliver {
|
||||
t.Fatalf("encrypted thinking should deliver: %#v", encSig)
|
||||
}
|
||||
}
|
||||
|
||||
func TestObserveQualityChunkEmptyReasoningStubIsNotThinking(t *testing.T) {
|
||||
t.Parallel()
|
||||
content := strings.Repeat("word ", 40)
|
||||
chat := qualityScanState{protocol: qualityProtocolChat}
|
||||
ObserveQualityChunk(&chat, []byte(sse(
|
||||
": grok2api-reasoning-start",
|
||||
`data: {"choices":[{"delta":{"content":"`+content+`"}}]}`,
|
||||
`data: {"usage":{"completion_tokens":45,"completion_tokens_details":{"reasoning_tokens":0}}}`,
|
||||
"data: [DONE]",
|
||||
)))
|
||||
chatSig := chat.signals()
|
||||
if chatSig.HasThinking {
|
||||
t.Fatalf("chat SSE stub must not count as thinking: %#v", chatSig)
|
||||
}
|
||||
if !chatSig.ReasoningStarted || !chatSig.Terminal || chatSig.ReasoningTokens != 0 {
|
||||
t.Fatalf("chat stub signals = %#v", chatSig)
|
||||
}
|
||||
if ClassifyQualityHold(chatSig, 32) != QualityWithhold {
|
||||
t.Fatalf("chat stub + 0 reasoning must withhold, got %s (%#v)", ClassifyQualityHold(chatSig, 32), chatSig)
|
||||
}
|
||||
|
||||
mid := qualityScanState{protocol: qualityProtocolChat}
|
||||
ObserveQualityChunk(&mid, []byte(sse(
|
||||
": grok2api-reasoning-start",
|
||||
`data: {"choices":[{"delta":{"content":"`+content+`"}}]}`,
|
||||
)))
|
||||
midSig := mid.signals()
|
||||
if midSig.HasThinking || !midSig.ReasoningStarted || midSig.Terminal {
|
||||
t.Fatalf("midstream stub signals = %#v", midSig)
|
||||
}
|
||||
if ClassifyQualityHold(midSig, 32) != QualityWait {
|
||||
t.Fatalf("midstream stub must wait for usage, got %s (%#v)", ClassifyQualityHold(midSig, 32), midSig)
|
||||
}
|
||||
|
||||
responses := qualityScanState{protocol: qualityProtocolResponses}
|
||||
ObserveQualityChunk(&responses, []byte(sse(
|
||||
`data: {"type":"response.output_item.added","item":{"id":"rs_1","type":"reasoning"}}`,
|
||||
`data: {"type":"response.output_text.delta","delta":"`+content+`"}`,
|
||||
`data: {"type":"response.completed","response":{"id":"resp_1","usage":{"output_tokens":45,"output_tokens_details":{"reasoning_tokens":0}}}}`,
|
||||
)))
|
||||
respSig := responses.signals()
|
||||
if respSig.HasThinking {
|
||||
t.Fatalf("empty responses reasoning item must not count as thinking: %#v", respSig)
|
||||
}
|
||||
if ClassifyQualityHold(respSig, 32) != QualityWithhold {
|
||||
t.Fatalf("empty reasoning item + 0 tokens must withhold, got %s (%#v)", ClassifyQualityHold(respSig, 32), respSig)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -928,6 +928,50 @@ func TestConvertResponsesStreamMarksChatReasoningStart(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertResponsesStreamMarksEncryptedChatReasoningEvidence(t *testing.T) {
|
||||
stream := strings.Join([]string{
|
||||
`event: response.created`,
|
||||
`data: {"type":"response.created","response":{"id":"resp_1","model":"grok-4.6"}}`, "",
|
||||
`event: response.output_item.added`,
|
||||
`data: {"type":"response.output_item.added","item":{"id":"rs_1","type":"reasoning"}}`, "",
|
||||
`event: response.output_item.done`,
|
||||
`data: {"type":"response.output_item.done","item":{"id":"rs_1","type":"reasoning","encrypted_content":"signature"}}`, "",
|
||||
`event: response.completed`,
|
||||
`data: {"type":"response.completed","response":{"status":"completed"}}`, "", "",
|
||||
}, "\n")
|
||||
converted, err := io.ReadAll(ConvertResponseStream(io.NopCloser(strings.NewReader(stream)), OperationChat))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
text := string(converted)
|
||||
if strings.Count(text, ": grok2api-reasoning-start\n\n") != 1 || strings.Count(text, ": grok2api-reasoning-evidence\n\n") != 1 {
|
||||
t.Fatalf("encrypted reasoning markers missing or duplicated: %s", text)
|
||||
}
|
||||
if strings.Contains(text, "signature") || strings.Contains(text, "encrypted_content") {
|
||||
t.Fatalf("encrypted reasoning leaked into Chat JSON: %s", text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertResponsesStreamMarksFinalEnvelopeReasoningEvidence(t *testing.T) {
|
||||
stream := strings.Join([]string{
|
||||
`event: response.created`,
|
||||
`data: {"type":"response.created","response":{"id":"resp_1","model":"grok-4.6"}}`, "",
|
||||
`event: response.completed`,
|
||||
`data: {"type":"response.completed","response":{"status":"completed","output":[{"id":"rs_1","type":"reasoning","encrypted_content":"signature"}]}}`, "", "",
|
||||
}, "\n")
|
||||
converted, err := io.ReadAll(ConvertResponseStream(io.NopCloser(strings.NewReader(stream)), OperationChat))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
text := string(converted)
|
||||
if strings.Count(text, ": grok2api-reasoning-evidence\n\n") != 1 {
|
||||
t.Fatalf("final-envelope reasoning evidence missing or duplicated: %s", text)
|
||||
}
|
||||
if strings.Contains(text, "signature") || strings.Contains(text, "encrypted_content") {
|
||||
t.Fatalf("final-envelope encrypted reasoning leaked into Chat JSON: %s", text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertResponsesStreamChatPrefersRawReasoningOverSummary(t *testing.T) {
|
||||
stream := strings.Join([]string{
|
||||
`event: response.created`,
|
||||
|
||||
@@ -53,6 +53,7 @@ type streamConverter struct {
|
||||
thinkingIndex int
|
||||
thinkingItemID string
|
||||
chatReasoningMark bool
|
||||
evidenceMarked bool
|
||||
reasoningItems map[string]*reasoningStreamState
|
||||
reasoningOrder []string
|
||||
activeReasoningID string
|
||||
@@ -95,6 +96,23 @@ func newStreamConverter(writer io.Writer, operation string, options ResponseOpti
|
||||
}
|
||||
}
|
||||
|
||||
// markReasoningEvidence preserves non-empty upstream encrypted_content for the
|
||||
// request-path quality scanner after protocol conversion. SSE clients ignore
|
||||
// comments, so Chat and Messages public event payloads remain unchanged.
|
||||
func (c *streamConverter) markReasoningEvidence() error {
|
||||
if c.evidenceMarked {
|
||||
return nil
|
||||
}
|
||||
if err := c.start(); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := io.WriteString(c.writer, ": grok2api-reasoning-evidence\n\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
c.evidenceMarked = true
|
||||
return nil
|
||||
}
|
||||
|
||||
// noteWebSearch records a Build web_search_call. Emission is deferred to doneMessages
|
||||
// so we always use the completed action.sources payload from the final envelope when available.
|
||||
// For progressive UI we still emit server_tool_use as soon as we see the call.
|
||||
@@ -314,6 +332,11 @@ func (c *streamConverter) handle(event string, data []byte) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(item.Encrypted) != "" {
|
||||
if err := c.markReasoningEvidence(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return c.thinkingDone(item)
|
||||
}
|
||||
if item.Type == "web_search_call" && c.operation == OperationMessages && c.options.AnthropicWebSearch {
|
||||
@@ -325,6 +348,13 @@ func (c *streamConverter) handle(event string, data []byte) error {
|
||||
var response responseEnvelope
|
||||
_ = json.Unmarshal(root["response"], &response)
|
||||
c.setResponse(response)
|
||||
for _, item := range response.Output {
|
||||
if item.Type == "reasoning" && strings.TrimSpace(item.Encrypted) != "" {
|
||||
if err := c.markReasoningEvidence(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if c.operation == OperationMessages && c.options.AnthropicWebSearch {
|
||||
parsed := parseResponse(response)
|
||||
for _, call := range parsed.WebSearch {
|
||||
|
||||
@@ -1288,7 +1288,7 @@ type responseMetadata struct {
|
||||
|
||||
func copyStream(writer gin.ResponseWriter, source io.Reader, protocol streamProtocol, onFirstToken func()) (responseMetadata, error) {
|
||||
inspector := &responseInspector{protocol: protocol, onFirstToken: onFirstToken}
|
||||
markerFilter := internalSSEMarkerFilter{enabled: protocol == streamProtocolChat}
|
||||
markerFilter := internalSSEMarkerFilter{enabled: protocol == streamProtocolChat || protocol == streamProtocolAnthropic}
|
||||
var compat responsesCompatState
|
||||
buffer := make([]byte, responseCopyBufferBytes)
|
||||
received := 0
|
||||
@@ -1466,13 +1466,13 @@ func (f *internalSSEMarkerFilter) Filter(chunk []byte, final bool) []byte {
|
||||
if !f.enabled {
|
||||
return chunk
|
||||
}
|
||||
marker := []byte(reasoningStartSSEComment + "\n\n")
|
||||
f.pending = append(f.pending, chunk...)
|
||||
result := make([]byte, 0, len(f.pending))
|
||||
for {
|
||||
if index := bytes.Index(f.pending, marker); index >= 0 {
|
||||
index, markerLength := nextInternalSSEMarker(f.pending)
|
||||
if index >= 0 {
|
||||
result = append(result, f.pending[:index]...)
|
||||
f.pending = f.pending[index+len(marker):]
|
||||
f.pending = f.pending[index+markerLength:]
|
||||
continue
|
||||
}
|
||||
if final {
|
||||
@@ -1481,11 +1481,13 @@ func (f *internalSSEMarkerFilter) Filter(chunk []byte, final bool) []byte {
|
||||
return result
|
||||
}
|
||||
keep := 0
|
||||
limit := min(len(f.pending), len(marker)-1)
|
||||
for size := limit; size > 0; size-- {
|
||||
if bytes.Equal(f.pending[len(f.pending)-size:], marker[:size]) {
|
||||
keep = size
|
||||
break
|
||||
for _, marker := range internalSSEMarkers {
|
||||
limit := min(len(f.pending), len(marker)-1)
|
||||
for size := limit; size > keep; size-- {
|
||||
if bytes.Equal(f.pending[len(f.pending)-size:], marker[:size]) {
|
||||
keep = size
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
result = append(result, f.pending[:len(f.pending)-keep]...)
|
||||
@@ -1494,6 +1496,19 @@ func (f *internalSSEMarkerFilter) Filter(chunk []byte, final bool) []byte {
|
||||
}
|
||||
}
|
||||
|
||||
func nextInternalSSEMarker(value []byte) (int, int) {
|
||||
index := -1
|
||||
length := 0
|
||||
for _, marker := range internalSSEMarkers {
|
||||
candidate := bytes.Index(value, marker)
|
||||
if candidate >= 0 && (index < 0 || candidate < index) {
|
||||
index = candidate
|
||||
length = len(marker)
|
||||
}
|
||||
}
|
||||
return index, length
|
||||
}
|
||||
|
||||
func copyJSON(writer gin.ResponseWriter, source io.Reader, protocol streamProtocol) (responseMetadata, error) {
|
||||
buffer := make([]byte, responseCopyBufferBytes)
|
||||
metadataBody := make([]byte, 0, responseCopyBufferBytes)
|
||||
@@ -1545,7 +1560,15 @@ type responseInspector struct {
|
||||
terminalFailure bool
|
||||
}
|
||||
|
||||
const reasoningStartSSEComment = ": grok2api-reasoning-start"
|
||||
const (
|
||||
reasoningStartSSEComment = ": grok2api-reasoning-start"
|
||||
reasoningEvidenceSSEComment = ": grok2api-reasoning-evidence"
|
||||
)
|
||||
|
||||
var internalSSEMarkers = [][]byte{
|
||||
[]byte(reasoningStartSSEComment + "\n\n"),
|
||||
[]byte(reasoningEvidenceSSEComment + "\n\n"),
|
||||
}
|
||||
|
||||
func (i *responseInspector) Inspect(chunk []byte) {
|
||||
i.pending = append(i.pending, chunk...)
|
||||
|
||||
@@ -927,8 +927,8 @@ func TestStreamInspectorMarksChatReasoningComment(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestInternalSSEMarkerFilterAcrossChunkBoundaries(t *testing.T) {
|
||||
marker := reasoningStartSSEComment + "\n\n"
|
||||
input := []byte("data: before\n\n" + marker + "data: after\n\n")
|
||||
markers := reasoningStartSSEComment + "\n\n" + reasoningEvidenceSSEComment + "\n\n"
|
||||
input := []byte("data: before\n\n" + markers + "data: after\n\n")
|
||||
want := "data: before\n\ndata: after\n\n"
|
||||
for split := 0; split <= len(input); split++ {
|
||||
filter := internalSSEMarkerFilter{enabled: true}
|
||||
@@ -948,6 +948,7 @@ func TestCopyStreamConsumesInternalReasoningMarker(t *testing.T) {
|
||||
context, _ := gin.CreateTestContext(recorder)
|
||||
body := `data: {"choices":[{"delta":{"role":"assistant"}}]}` + "\n\n" +
|
||||
": grok2api-reasoning-start\n\n" +
|
||||
": grok2api-reasoning-evidence\n\n" +
|
||||
`data: {"choices":[{"delta":{"content":"hello"}}]}` + "\n\n" +
|
||||
"data: [DONE]\n\n"
|
||||
marked := 0
|
||||
@@ -957,7 +958,7 @@ func TestCopyStreamConsumesInternalReasoningMarker(t *testing.T) {
|
||||
if marked != 1 {
|
||||
t.Fatalf("first token marked %d times", marked)
|
||||
}
|
||||
if strings.Contains(recorder.Body.String(), "grok2api-reasoning-start") {
|
||||
if strings.Contains(recorder.Body.String(), "grok2api-reasoning-") {
|
||||
t.Fatalf("internal marker leaked to client: %q", recorder.Body.String())
|
||||
}
|
||||
if !strings.Contains(recorder.Body.String(), `"content":"hello"`) {
|
||||
@@ -965,6 +966,26 @@ func TestCopyStreamConsumesInternalReasoningMarker(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCopyStreamConsumesAnthropicReasoningEvidenceMarker(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
recorder := httptest.NewRecorder()
|
||||
context, _ := gin.CreateTestContext(recorder)
|
||||
body := ": grok2api-reasoning-evidence\n\n" +
|
||||
"event: content_block_delta\n" +
|
||||
`data: {"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"sig"}}` + "\n\n" +
|
||||
"event: message_stop\n" +
|
||||
`data: {"type":"message_stop"}` + "\n\n"
|
||||
if _, err := copyStream(context.Writer, strings.NewReader(body), streamProtocolAnthropic, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(recorder.Body.String(), "grok2api-reasoning-evidence") {
|
||||
t.Fatalf("internal Anthropic marker leaked to client: %q", recorder.Body.String())
|
||||
}
|
||||
if !strings.Contains(recorder.Body.String(), `"signature":"sig"`) {
|
||||
t.Fatalf("Anthropic signature delta missing: %q", recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCopyStreamPreservesBufferedTailOnReadError(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
recorder := httptest.NewRecorder()
|
||||
@@ -1166,6 +1187,26 @@ func TestSanitizeResponsesDoesNotAddResponseIDToErrorEvent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizeResponsesFillsMissingOutputTextAnnotations(t *testing.T) {
|
||||
state := &responsesCompatState{}
|
||||
added := rewriteResponsesDataLine([]byte(`data: {"type":"response.output_item.added","item":{"type":"message","content":[{"type":"output_text","text":"hi"}]}}`+"\n"), state)
|
||||
if !bytes.Contains(added, []byte(`"annotations":[]`)) {
|
||||
t.Fatalf("item output_text missing annotations: %s", added)
|
||||
}
|
||||
completed := rewriteResponsesDataLine([]byte(`data: {"type":"response.completed","response":{"id":"resp_1","output":[{"type":"message","content":[{"type":"output_text","text":"hi"}]}]}}`+"\n"), state)
|
||||
if !bytes.Contains(completed, []byte(`"annotations":[]`)) {
|
||||
t.Fatalf("completed output_text missing annotations: %s", completed)
|
||||
}
|
||||
part := rewriteResponsesDataLine([]byte(`data: {"type":"response.content_part.added","part":{"type":"output_text","text":"hi"}}`+"\n"), state)
|
||||
if !bytes.Contains(part, []byte(`"annotations":[]`)) {
|
||||
t.Fatalf("content_part output_text missing annotations: %s", part)
|
||||
}
|
||||
kept := rewriteResponsesDataLine([]byte(`data: {"type":"response.output_item.done","item":{"type":"message","content":[{"type":"output_text","text":"hi","annotations":[{"type":"url_citation","url":"https://x.test"}]}]}}`+"\n"), state)
|
||||
if !bytes.Contains(kept, []byte(`"url":"https://x.test"`)) || bytes.Contains(kept, []byte(`"annotations":[]`)) {
|
||||
t.Fatalf("existing annotations were replaced: %s", kept)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResponsesCompatBoundsUnterminatedLineBuffer(t *testing.T) {
|
||||
state := &responsesCompatState{}
|
||||
chunk := bytes.Repeat([]byte{'x'}, maxStreamEventInspectionBytes+1)
|
||||
|
||||
@@ -221,6 +221,35 @@ func sanitizeResponsesEvent(event map[string]any, state *responsesCompatState) b
|
||||
}
|
||||
}
|
||||
}
|
||||
if ensureOutputTextAnnotations(event) {
|
||||
changed = true
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
// Grok CLI serde requires output_text.annotations even when there are no
|
||||
// citations. Missing the field makes a retry fail with
|
||||
// "serialization error: missing field `annotations`".
|
||||
func ensureOutputTextAnnotations(node any) bool {
|
||||
changed := false
|
||||
switch typed := node.(type) {
|
||||
case map[string]any:
|
||||
if stringAny(typed["type"]) == "output_text" && typed["annotations"] == nil {
|
||||
typed["annotations"] = []any{}
|
||||
changed = true
|
||||
}
|
||||
for _, key := range []string{"item", "part", "response", "content", "output", "delta"} {
|
||||
if ensureOutputTextAnnotations(typed[key]) {
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
case []any:
|
||||
for _, child := range typed {
|
||||
if ensureOutputTextAnnotations(child) {
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user