mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-05 16:02:12 +00:00
Merge pull request #1041 from ctermiii/fix/chat-multi-turn-reasoning-bridge
fix(conversation): restore reasoning context in multi-turn chat tool calling
This commit is contained in:
12 files changed
+1374
-25
No files matched your search
@@ -66,8 +66,13 @@ type Adapter struct {
|
||||
fallbackMarker FallbackMarker
|
||||
uploadIssuer VideoUploadIssuer
|
||||
replay *reasoningreplay.ReasoningReplay
|
||||
compaction *gatewayCompactionCodec
|
||||
logger *slog.Logger
|
||||
// conversationReasoningCache bridges Chat/Messages tool calls to the
|
||||
// upstream Responses reasoning proof. It is deliberately separate from
|
||||
// the persistent native Responses replay, and its keys never contain an
|
||||
// account ID: encrypted reasoning is portable across Build accounts.
|
||||
conversationReasoningCache *conversation.ReasoningCache
|
||||
compaction *gatewayCompactionCodec
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func NewAdapter(cfg Config, cipher *security.Cipher) *Adapter {
|
||||
@@ -80,7 +85,9 @@ func NewAdapter(cfg Config, cipher *security.Cipher) *Adapter {
|
||||
agentID := uuid.NewString()
|
||||
adapter := &Adapter{
|
||||
cfg: cfg, http: httpClient, cipher: cipher, base: transport,
|
||||
agentID: agentID, modelsETags: make(map[uint64]string), compaction: newGatewayCompactionCodec(cipher), logger: slog.Default(),
|
||||
agentID: agentID, modelsETags: make(map[uint64]string),
|
||||
conversationReasoningCache: conversation.NewReasoningCache(0, 0),
|
||||
compaction: newGatewayCompactionCodec(cipher), logger: slog.Default(),
|
||||
}
|
||||
adapter.oauth = newOAuthClient(httpClient, func() string { return adapter.config().ClientVersion })
|
||||
return adapter
|
||||
@@ -240,9 +247,16 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
|
||||
var conversationOptions conversation.ResponseOptions
|
||||
cacheRoute := buildPromptCacheRoute{}
|
||||
compactionRequested := false
|
||||
// Resolve the physical inference plane before normalization so Chat and
|
||||
// Anthropic conversion can use the same scope for capture and restoration.
|
||||
// The scope contains the trusted session seed, model, and plane only; it is
|
||||
// intentionally independent of the selected account.
|
||||
primaryBase := a.primaryBaseURL()
|
||||
base := a.inferenceBaseForOperation(request.Credential, request.Billing, request.Method, request.Path)
|
||||
conversationScope := a.conversationReasoningScope(request, base)
|
||||
if request.NormalizeBody {
|
||||
if request.Operation == conversation.OperationChat || request.Operation == conversation.OperationMessages {
|
||||
body, conversationOptions, err = conversation.ConvertRequestWithOptions(body, request.Model, request.Operation)
|
||||
body, conversationOptions, err = conversation.ConvertRequestWithReasoningReplay(body, request.Model, request.Operation, a.conversationReasoningCache, conversationScope)
|
||||
if err == nil && conversationOptions.ReasoningEffortSet && request.NormalizedMetadata != nil {
|
||||
request.NormalizedMetadata.ReasoningEffort = conversationOptions.ReasoningEffort
|
||||
}
|
||||
@@ -276,6 +290,8 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
|
||||
}
|
||||
if request.Operation == conversation.OperationMessages && conversationOptions.AnthropicWebSearch {
|
||||
request.ReasoningReplayKey = ""
|
||||
conversationScope = ""
|
||||
conversationOptions = conversationOptions.WithReasoningReplay(nil, "")
|
||||
}
|
||||
if compactionRequested {
|
||||
body, err = prepareGatewayCompactionSample(body)
|
||||
@@ -312,11 +328,10 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
|
||||
return a.forwardGatewayCompaction(ctx, request, accessToken, body, warnings)
|
||||
}
|
||||
// Explicit mode wins; in auto mode only confirmed Super accounts with bot_flag_source/bfs in {1,2} default to XAI.
|
||||
primaryBase := a.primaryBaseURL()
|
||||
base := a.inferenceBaseForOperation(request.Credential, request.Billing, request.Method, request.Path)
|
||||
// Cache affinity and reasoning replay use separate identities. Replay is bound to the
|
||||
// upstream plane (Build vs XAI) so a blob captured on one API is not injected onto the other.
|
||||
// Encrypted reasoning is portable across accounts, so the cache key is not account-scoped.
|
||||
// Prompt-cache affinity and reasoning replay use separate identities. The
|
||||
// native Responses replay remains account-scoped, while the Chat/Messages
|
||||
// bridge is scoped to the client session, model, and physical plane only;
|
||||
// encrypted reasoning is portable across accounts on that plane.
|
||||
replayBaseBody := body
|
||||
body, replayKey := a.applyReasoningReplay(ctx, request, replayBaseBody, base)
|
||||
call := a.doResponseRequest(ctx, request, accessToken, body, base)
|
||||
@@ -372,6 +387,7 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
|
||||
a.activateBuildAPIFallback(ctx, &request.Credential)
|
||||
call = fallbackCall
|
||||
resp, reqURL, base, body, replayKey = call.response, call.upstreamURL, fallbackBase, fallbackBody, fallbackReplayKey
|
||||
conversationOptions = conversationOptions.WithReasoningReplay(a.conversationReasoningCache, a.conversationReasoningScope(request, base))
|
||||
reasoningRecovery = reasoningRecovery.merge(fallbackRecovery)
|
||||
} else {
|
||||
if fallbackErr == nil && fallbackCall.response != nil {
|
||||
@@ -546,6 +562,20 @@ func (a *Adapter) scopedReasoningReplayKey(request provider.ResponseResourceRequ
|
||||
return hex.EncodeToString(digest[:])
|
||||
}
|
||||
|
||||
func (a *Adapter) conversationReasoningScope(request provider.ResponseResourceRequest, base string) string {
|
||||
seed := strings.TrimSpace(request.ReasoningReplayKey)
|
||||
model := strings.ToLower(strings.TrimSpace(request.Model))
|
||||
if seed == "" || model == "" {
|
||||
return ""
|
||||
}
|
||||
plane := "build"
|
||||
if fallback := a.fallbackBaseURL(); fallback != "" && strings.EqualFold(strings.TrimRight(base, "/"), fallback) {
|
||||
plane = "xai"
|
||||
}
|
||||
digest := sha256.Sum256([]byte(fmt.Sprintf("grok2api:conversation-reasoning:v1:%s:%s:%s", seed, model, plane)))
|
||||
return hex.EncodeToString(digest[:])
|
||||
}
|
||||
|
||||
func isCompactPath(path string) bool {
|
||||
return strings.Contains(strings.ToLower(path), "compact")
|
||||
}
|
||||
|
||||
@@ -519,6 +519,86 @@ func TestReasoningReplayScopeSharesAccountSeparatesPlane(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestConversationReasoningReplaySharesExplicitSessionAcrossAccounts(t *testing.T) {
|
||||
cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
encrypted, err := cipher.Encrypt("access-token")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
adapter := NewAdapter(Config{BaseURL: "https://build.example/v1"}, cipher)
|
||||
var requestCount int
|
||||
var secondRequest map[string]any
|
||||
adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
|
||||
requestCount++
|
||||
body, readErr := io.ReadAll(request.Body)
|
||||
if readErr != nil {
|
||||
return nil, readErr
|
||||
}
|
||||
if requestCount == 2 {
|
||||
if err := json.Unmarshal(body, &secondRequest); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
responseBody := `{"id":"resp_first","model":"grok-4.6","status":"completed","output":[{"id":"rs_first","type":"reasoning","status":"completed","encrypted_content":"portable-proof"},{"id":"fc_first","type":"function_call","call_id":"call_portable","name":"list_dir","arguments":"{}"}]}`
|
||||
if requestCount > 1 {
|
||||
responseBody = `{"id":"resp_second","model":"grok-4.6","status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"done"}]}]}`
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK, Status: "200 OK",
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}},
|
||||
Body: io.NopCloser(strings.NewReader(responseBody)), Request: request,
|
||||
}, nil
|
||||
})
|
||||
firstRequest := provider.ResponseResourceRequest{
|
||||
Credential: account.Credential{ID: 1, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted},
|
||||
Method: http.MethodPost, Path: "/responses", Model: "grok-4.6", Operation: conversation.OperationChat,
|
||||
ReasoningReplayKey: "portable-session", NormalizeBody: true,
|
||||
Body: []byte(`{"model":"public","messages":[{"role":"user","content":"hello"}]}`),
|
||||
}
|
||||
first, err := adapter.ForwardResponse(context.Background(), firstRequest)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := io.ReadAll(first.Body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = first.Body.Close()
|
||||
secondRequestInput := firstRequest
|
||||
secondRequestInput.Credential.ID = 2
|
||||
secondRequestInput.Body = []byte(`{"model":"public","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":null,"tool_calls":[{"id":"call_portable","type":"function","function":{"name":"list_dir","arguments":"{}"}}]},{"role":"tool","tool_call_id":"call_portable","content":"ok"}]}`)
|
||||
second, err := adapter.ForwardResponse(context.Background(), secondRequestInput)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = second.Body.Close()
|
||||
if requestCount != 2 {
|
||||
t.Fatalf("upstream request count = %d, want 2", requestCount)
|
||||
}
|
||||
input, ok := secondRequest["input"].([]any)
|
||||
if !ok {
|
||||
t.Fatalf("second upstream input = %#v", secondRequest["input"])
|
||||
}
|
||||
found := false
|
||||
for _, raw := range input {
|
||||
item, ok := raw.(map[string]any)
|
||||
if ok && item["type"] == "reasoning" && item["encrypted_content"] == "portable-proof" {
|
||||
found = true
|
||||
if _, hasContent := item["content"]; hasContent {
|
||||
t.Fatalf("replayed opaque reasoning contains content: %#v", item)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("portable reasoning was not restored: %#v", input)
|
||||
}
|
||||
if firstScope := adapter.conversationReasoningScope(firstRequest, adapter.primaryBaseURL()); firstScope == "" || firstScope != adapter.conversationReasoningScope(secondRequestInput, adapter.primaryBaseURL()) {
|
||||
t.Fatal("conversation reasoning scope unexpectedly depends on account")
|
||||
}
|
||||
}
|
||||
|
||||
func TestListModelsUsesOfficialMetadataHeaders(t *testing.T) {
|
||||
cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32)))
|
||||
if err != nil {
|
||||
|
||||
@@ -3,11 +3,15 @@ package cli
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"reflect"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func normalizeResponsesTools(payload map[string]json.RawMessage) (*responsesToolCompatibility, error) {
|
||||
if rawTools := payload["tools"]; len(rawTools) > 0 && strings.Contains(string(rawTools), "automation_update") {
|
||||
slog.Info("DEBUG_RAW_AUTOMATION_TOOLS", "tools", string(rawTools))
|
||||
}
|
||||
compatibility := newResponsesToolCompatibility()
|
||||
tools, hasTools, err := decodeOptionalArray(payload["tools"], "tools")
|
||||
if err != nil {
|
||||
@@ -67,6 +71,9 @@ func normalizeResponsesTools(payload map[string]json.RawMessage) (*responsesTool
|
||||
}
|
||||
compatibility.changed = true
|
||||
}
|
||||
if rawTools := payload["tools"]; len(rawTools) > 0 && strings.Contains(string(rawTools), "automation_update") {
|
||||
slog.Info("DEBUG_NORMALIZED_AUTOMATION_TOOLS", "tools", string(rawTools))
|
||||
}
|
||||
if err := compatibility.normalizeToolChoice(payload, normalizedTools); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -172,6 +179,15 @@ func (c *responsesToolCompatibility) normalizeTool(raw any, namespace string, cl
|
||||
return nil, nil
|
||||
}
|
||||
converted := cloneJSONObject(tool)
|
||||
if inputSchema, exists := converted["inputSchema"]; exists {
|
||||
converted["parameters"] = inputSchema
|
||||
delete(converted, "inputSchema")
|
||||
c.changed = true
|
||||
} else if inputSchema, exists := converted["input_schema"]; exists {
|
||||
converted["parameters"] = inputSchema
|
||||
delete(converted, "input_schema")
|
||||
c.changed = true
|
||||
}
|
||||
if parameters, exists := converted["parameters"]; exists {
|
||||
normalized, changed, normalizeErr := normalizeBuildFunctionParametersRootForTool(parameters, param+".parameters", name)
|
||||
if normalizeErr != nil {
|
||||
@@ -411,6 +427,26 @@ func (c *rootObjectLeafCollector) walk(node any, constraints []map[string]any, s
|
||||
constraints = append(cloneRootConstraints(constraints), sibling)
|
||||
}
|
||||
for _, branch := range branches {
|
||||
// Build function parameters may contain a nullable or otherwise
|
||||
// non-object alternative at the root. Such alternatives cannot be
|
||||
// represented by Build's grammar and are intentionally omitted; the
|
||||
// whole schema is rejected below when no object leaf remains.
|
||||
branchSchema, branchOK := branch.(map[string]any)
|
||||
if !branchOK || isNullOnlySchema(branchSchema) {
|
||||
c.changed = true
|
||||
continue
|
||||
}
|
||||
branchKeyword, _, branchErr := rootUnion(branchSchema)
|
||||
if branchErr != nil {
|
||||
return invalidBuildFunctionParametersRoot(c.context)
|
||||
}
|
||||
// A root $ref may point to another union (for example a named
|
||||
// Create schema). Let walk resolve it before deciding whether its
|
||||
// leaves are object schemas.
|
||||
if branchKeyword == "" && branchSchema["$ref"] == nil && !isObjectRootSchema(branchSchema, c.doc, nil) {
|
||||
c.changed = true
|
||||
continue
|
||||
}
|
||||
if err := c.walk(branch, constraints, cloneRefSeen(seen), depth+1, unionDepth+1); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -888,3 +924,20 @@ func (c *responsesToolCompatibility) buildClientSearchFunction() (map[string]any
|
||||
"parameters": cloneJSONValue(parameters),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func dedupeSlice(slice []any) []any {
|
||||
seen := make(map[string]bool)
|
||||
var result []any
|
||||
for _, item := range slice {
|
||||
str, ok := item.(string)
|
||||
if ok {
|
||||
if !seen[str] {
|
||||
seen[str] = true
|
||||
result = append(result, str)
|
||||
}
|
||||
} else {
|
||||
result = append(result, item)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -304,7 +304,7 @@ func TestNormalizeResponsesRequestRejectsNullableNonObjectFunctionRoot(t *testin
|
||||
_, _, err := normalizeResponsesRequest([]byte(`{
|
||||
"model":"public","input":"hello",
|
||||
"tools":[{"type":"function","name":"invalid","parameters":{
|
||||
"anyOf":[{"type":"object"},{"type":"string"},{"type":"null"}]
|
||||
"anyOf":[{"type":"string"},{"type":"null"}]
|
||||
}}]
|
||||
}`), "grok-4.5")
|
||||
requestErr, ok := err.(*responsesRequestError)
|
||||
@@ -313,6 +313,39 @@ func TestNormalizeResponsesRequestRejectsNullableNonObjectFunctionRoot(t *testin
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeResponsesRequestFiltersNonObjectBranchesInAnyOf(t *testing.T) {
|
||||
normalized, compatibility, err := normalizeResponsesRequest([]byte(`{
|
||||
"model":"public","input":"hello",
|
||||
"tools":[{"type":"function","name":"automation_update","parameters":{
|
||||
"anyOf":[
|
||||
{"type":"object","properties":{"task":{"type":"string"}},"required":["task"]},
|
||||
{"type":"string"}
|
||||
]
|
||||
}}]
|
||||
}`), "grok-4.5")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if compatibility == nil {
|
||||
t.Fatal("expected compatibility tracker")
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(normalized, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parameters := payload["tools"].([]any)[0].(map[string]any)["parameters"].(map[string]any)
|
||||
if parameters["type"] != "object" {
|
||||
t.Fatalf("expected parameters.type=object, got %#v", parameters)
|
||||
}
|
||||
if _, exists := parameters["anyOf"]; exists {
|
||||
t.Fatalf("expected anyOf to be hoisted or removed, got %#v", parameters)
|
||||
}
|
||||
props := parameters["properties"].(map[string]any)
|
||||
if props["task"].(map[string]any)["type"] != "string" {
|
||||
t.Fatalf("expected task property, got %#v", props)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeResponsesRequestRemovesNullableLocalRefFunctionRoot(t *testing.T) {
|
||||
normalized, compatibility, err := normalizeResponsesRequest([]byte(`{
|
||||
"model":"public","input":"hello",
|
||||
|
||||
@@ -10,6 +10,10 @@ import (
|
||||
|
||||
// convertChatRequest 将 Chat Completions 请求完整转换为标准 Responses 输入。
|
||||
func convertChatRequest(body []byte, model string) ([]byte, ResponseOptions, error) {
|
||||
return convertChatRequestWithReasoningReplay(body, model, nil, "")
|
||||
}
|
||||
|
||||
func convertChatRequestWithReasoningReplay(body []byte, model string, cache *ReasoningCache, scope string) ([]byte, ResponseOptions, error) {
|
||||
var source map[string]json.RawMessage
|
||||
if err := json.Unmarshal(body, &source); err != nil {
|
||||
return nil, ResponseOptions{}, fmt.Errorf("解析 Chat Completions 请求: %w", err)
|
||||
@@ -18,7 +22,7 @@ func convertChatRequest(body []byte, model string) ([]byte, ResponseOptions, err
|
||||
if err := json.Unmarshal(source["messages"], &messages); err != nil || len(messages) == 0 {
|
||||
return nil, ResponseOptions{}, errors.New("messages 必须是非空数组")
|
||||
}
|
||||
input, err := convertChatMessages(messages)
|
||||
input, err := convertChatMessagesWithReasoningReplay(messages, cache, scope)
|
||||
if err != nil {
|
||||
return nil, ResponseOptions{}, err
|
||||
}
|
||||
@@ -69,7 +73,7 @@ func convertChatRequest(body []byte, model string) ([]byte, ResponseOptions, err
|
||||
target["tool_choice"] = choice
|
||||
}
|
||||
converted, err := json.Marshal(target)
|
||||
return converted, ResponseOptions{StopSequences: stopSequences}, err
|
||||
return converted, ResponseOptions{StopSequences: stopSequences}.WithReasoningReplay(cache, scope), err
|
||||
}
|
||||
|
||||
func parseChatStopSequences(raw json.RawMessage) ([]string, error) {
|
||||
@@ -107,6 +111,10 @@ type chatMessage struct {
|
||||
}
|
||||
|
||||
func convertChatMessages(messages []chatMessage) ([]any, error) {
|
||||
return convertChatMessagesWithReasoningReplay(messages, nil, "")
|
||||
}
|
||||
|
||||
func convertChatMessagesWithReasoningReplay(messages []chatMessage, cache *ReasoningCache, scope string) ([]any, error) {
|
||||
input := make([]any, 0, len(messages))
|
||||
for _, message := range messages {
|
||||
role := strings.ToLower(strings.TrimSpace(message.Role))
|
||||
@@ -124,7 +132,7 @@ func convertChatMessages(messages []chatMessage) ([]any, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
input = append(input, calls...)
|
||||
input = append(input, restoreReasoningForCalls(calls, cache, scope)...)
|
||||
}
|
||||
case "tool":
|
||||
if strings.TrimSpace(message.ToolCallID) == "" {
|
||||
@@ -406,3 +414,107 @@ func convertChatToolChoice(raw json.RawMessage) (json.RawMessage, error) {
|
||||
}
|
||||
return mustJSON(map[string]any{"type": "function", "name": function.Name}), nil
|
||||
}
|
||||
|
||||
func restoreReasoningForCalls(calls []any, cache *ReasoningCache, scope string) []any {
|
||||
if cache == nil || strings.TrimSpace(scope) == "" {
|
||||
return calls
|
||||
}
|
||||
// A cached reasoning item may be inserted before each call, so the final
|
||||
// slice can be larger than calls. Use the input size as a safe initial
|
||||
// capacity and let append grow it; len(calls)+1 is unnecessary and can
|
||||
// overflow for a maximally sized input slice.
|
||||
result := make([]any, 0, len(calls))
|
||||
seenIDs := make(map[string]struct{})
|
||||
seenEncrypted := make(map[string]struct{})
|
||||
for _, raw := range calls {
|
||||
callMap, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
result = append(result, raw)
|
||||
continue
|
||||
}
|
||||
callID, _ := callMap["call_id"].(string)
|
||||
if item, found := cache.GetScoped(scope, callID); found && item.ID != "" && item.Encrypted != "" && !reasoningAlreadyEmitted(seenIDs, seenEncrypted, item) {
|
||||
result = append(result, reasoningInputItem(item))
|
||||
markReasoningEmitted(seenIDs, seenEncrypted, item)
|
||||
}
|
||||
result = append(result, raw)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func reasoningAlreadyEmitted(ids, encrypted map[string]struct{}, item responseItem) bool {
|
||||
if id := strings.TrimSpace(item.ID); id != "" {
|
||||
if _, exists := ids[id]; exists {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if value := strings.TrimSpace(item.Encrypted); value != "" {
|
||||
if _, exists := encrypted[value]; exists {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func markReasoningEmitted(ids, encrypted map[string]struct{}, item responseItem) {
|
||||
if id := strings.TrimSpace(item.ID); id != "" {
|
||||
ids[id] = struct{}{}
|
||||
}
|
||||
if value := strings.TrimSpace(item.Encrypted); value != "" {
|
||||
encrypted[value] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
func reasoningInputItem(item responseItem) map[string]any {
|
||||
payload := map[string]any{
|
||||
"type": "reasoning",
|
||||
"id": item.ID,
|
||||
"status": "completed",
|
||||
}
|
||||
if item.Encrypted != "" {
|
||||
payload["encrypted_content"] = item.Encrypted
|
||||
}
|
||||
if summary := cleanReasoningContents(item.Summary); len(summary) > 0 {
|
||||
payload["summary"] = summary
|
||||
} else if item.Encrypted != "" {
|
||||
// Build's replay schema requires a summary member when an opaque proof is
|
||||
// present. An empty array is the canonical representation for a redacted
|
||||
// or summary-less reasoning item.
|
||||
payload["summary"] = []any{}
|
||||
}
|
||||
// Omit content when it is nil/empty. Build treats content:null as a
|
||||
// mutation of the opaque reasoning/compaction payload.
|
||||
if content := cleanReasoningContents(item.Content); len(content) > 0 {
|
||||
payload["content"] = content
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
// cleanReasoningContents converts the internal response representation back to
|
||||
// the small Responses input shape. responseContent's struct tags intentionally
|
||||
// do not use omitempty because they are also used for decoding upstream output;
|
||||
// assigning the structs directly here would therefore emit refusal:"" and
|
||||
// annotations:null and make an opaque reasoning item look rewritten.
|
||||
func cleanReasoningContents(contents []responseContent) []any {
|
||||
if len(contents) == 0 {
|
||||
return nil
|
||||
}
|
||||
cleaned := make([]any, 0, len(contents))
|
||||
for _, content := range contents {
|
||||
value := make(map[string]any, 4)
|
||||
if content.Type != "" {
|
||||
value["type"] = content.Type
|
||||
}
|
||||
if content.Text != "" || content.Type == "summary_text" || content.Type == "reasoning_text" || content.Type == "output_text" {
|
||||
value["text"] = content.Text
|
||||
}
|
||||
if content.Refusal != "" {
|
||||
value["refusal"] = content.Refusal
|
||||
}
|
||||
if content.Annotations != nil {
|
||||
value["annotations"] = content.Annotations
|
||||
}
|
||||
cleaned = append(cleaned, value)
|
||||
}
|
||||
return cleaned
|
||||
}
|
||||
@@ -10,6 +10,10 @@ import (
|
||||
const anthropicBillingHeaderPrefix = "x-anthropic-billing-header: "
|
||||
|
||||
func convertMessagesRequest(body []byte, model string) ([]byte, ResponseOptions, error) {
|
||||
return convertMessagesRequestWithReasoningReplay(body, model, nil, "")
|
||||
}
|
||||
|
||||
func convertMessagesRequestWithReasoningReplay(body []byte, model string, cache *ReasoningCache, scope string) ([]byte, ResponseOptions, error) {
|
||||
var request anthropicRequest
|
||||
if err := json.Unmarshal(body, &request); err != nil {
|
||||
return nil, ResponseOptions{}, fmt.Errorf("解析 Messages 请求: %w", err)
|
||||
@@ -45,7 +49,18 @@ func convertMessagesRequest(body []byte, model string) ([]byte, ResponseOptions,
|
||||
return nil, ResponseOptions{}, fmt.Errorf("不支持 thinking.type=%q", request.Thinking.Type)
|
||||
}
|
||||
}
|
||||
input, inlineInstructions, err := convertAnthropicMessages(request.Messages, anthropicDeclaredToolNames(request.Tools))
|
||||
// Hosted web search has a separate server-side history contract. The
|
||||
// gateway deliberately does not bridge opaque reasoning for these turns
|
||||
// (see the adapter's web-search isolation below), so disable the bridge
|
||||
// before converting messages rather than trying to remove an already
|
||||
// injected item afterwards.
|
||||
hasWebSearchTool := hasAnthropicWebSearchTool(request.Tools)
|
||||
webSearchEnabled := hasWebSearchTool && (request.ToolChoice == nil || !strings.EqualFold(strings.TrimSpace(request.ToolChoice.Type), "none"))
|
||||
replayCache, replayScope := cache, scope
|
||||
if webSearchEnabled {
|
||||
replayCache, replayScope = nil, ""
|
||||
}
|
||||
input, inlineInstructions, err := convertAnthropicMessagesWithReasoningReplay(request.Messages, anthropicDeclaredToolNames(request.Tools), replayCache, replayScope)
|
||||
if err != nil {
|
||||
return nil, ResponseOptions{}, err
|
||||
}
|
||||
@@ -79,8 +94,6 @@ func convertMessagesRequest(body []byte, model string) ([]byte, ResponseOptions,
|
||||
}
|
||||
target["text"] = map[string]any{"format": map[string]any{"type": "json_schema", "name": "anthropic_output", "schema": request.OutputConfig.Format.Schema}}
|
||||
}
|
||||
hasWebSearchTool := hasAnthropicWebSearchTool(request.Tools)
|
||||
webSearchEnabled := hasWebSearchTool && (request.ToolChoice == nil || !strings.EqualFold(strings.TrimSpace(request.ToolChoice.Type), "none"))
|
||||
webSearchRequired := webSearchEnabled && anthropicWebSearchRequired(request.Tools, request.ToolChoice)
|
||||
webSearchQuery := ""
|
||||
if webSearchEnabled {
|
||||
@@ -138,7 +151,7 @@ func convertMessagesRequest(body []byte, model string) ([]byte, ResponseOptions,
|
||||
AnthropicWebSearchRequired: webSearchRequired,
|
||||
AnthropicWebSearchQuery: webSearchQuery,
|
||||
StopSequences: append([]string(nil), request.StopSequences...),
|
||||
}, err
|
||||
}.WithReasoningReplay(replayCache, replayScope), err
|
||||
}
|
||||
|
||||
type anthropicRequest struct {
|
||||
@@ -181,11 +194,32 @@ type anthropicToolChoice struct {
|
||||
}
|
||||
|
||||
func convertAnthropicMessages(messages []anthropicMessage, declaredTools map[string]struct{}) ([]any, []string, error) {
|
||||
return convertAnthropicMessagesWithReasoningReplay(messages, declaredTools, nil, "")
|
||||
}
|
||||
|
||||
func convertAnthropicMessagesWithReasoningReplay(messages []anthropicMessage, declaredTools map[string]struct{}, cache *ReasoningCache, scope string) ([]any, []string, error) {
|
||||
input := make([]any, 0, len(messages))
|
||||
instructions := make([]string, 0)
|
||||
pendingCalls := make(map[string]struct{})
|
||||
usedCalls := make(map[string]struct{})
|
||||
serverSearches := make(map[string]map[string]any)
|
||||
seenReasoningIDs := make(map[string]struct{})
|
||||
seenReasoningEncrypted := make(map[string]struct{})
|
||||
// A client is allowed to preserve an Anthropic thinking block in a
|
||||
// different order from the tool_use block. Pre-scan explicit signatures so
|
||||
// a cached bridge item is not emitted first and then duplicated when that
|
||||
// explicit block is encountered later in the same history.
|
||||
explicitReasoningEncrypted := anthropicExplicitReasoningProofs(messages)
|
||||
appendCachedReasoning := func(item responseItem) {
|
||||
if item.ID == "" || item.Encrypted == "" || reasoningAlreadyEmitted(seenReasoningIDs, seenReasoningEncrypted, item) {
|
||||
return
|
||||
}
|
||||
if _, exists := explicitReasoningEncrypted[strings.TrimSpace(item.Encrypted)]; exists {
|
||||
return
|
||||
}
|
||||
input = append(input, reasoningInputItem(item))
|
||||
markReasoningEmitted(seenReasoningIDs, seenReasoningEncrypted, item)
|
||||
}
|
||||
for messageIndex, message := range messages {
|
||||
role := strings.ToLower(strings.TrimSpace(message.Role))
|
||||
if role == "system" || role == "developer" {
|
||||
@@ -268,6 +302,11 @@ func convertAnthropicMessages(messages []anthropicMessage, declaredTools map[str
|
||||
return nil, nil, fmt.Errorf("%s 包含重复 tool_use id %q", path, value.ID)
|
||||
}
|
||||
arguments, _ := json.Marshal(value.Input)
|
||||
if cache != nil && strings.TrimSpace(scope) != "" {
|
||||
if reasoning, found := cache.GetScoped(scope, value.ID); found && reasoning.ID != "" && reasoning.Encrypted != "" {
|
||||
appendCachedReasoning(reasoning)
|
||||
}
|
||||
}
|
||||
input = append(input, map[string]any{"type": "function_call", "call_id": value.ID, "name": value.Name, "arguments": string(arguments)})
|
||||
pendingCalls[value.ID] = struct{}{}
|
||||
usedCalls[value.ID] = struct{}{}
|
||||
@@ -312,6 +351,7 @@ func convertAnthropicMessages(messages []anthropicMessage, declaredTools map[str
|
||||
item["encrypted_content"] = signature
|
||||
}
|
||||
input = append(input, item)
|
||||
markReasoningEmitted(seenReasoningIDs, seenReasoningEncrypted, responseItem{Encrypted: signature})
|
||||
case "redacted_thinking":
|
||||
if role != "assistant" {
|
||||
return nil, nil, fmt.Errorf("%s redacted_thinking 只允许出现在 assistant 消息", path)
|
||||
@@ -324,6 +364,7 @@ func convertAnthropicMessages(messages []anthropicMessage, declaredTools map[str
|
||||
// Grok Build requires summary to exist whenever encrypted_content is replayed.
|
||||
// An empty array is the canonical Anthropic redacted_thinking representation.
|
||||
input = append(input, map[string]any{"type": "reasoning", "summary": []any{}, "encrypted_content": data})
|
||||
markReasoningEmitted(seenReasoningIDs, seenReasoningEncrypted, responseItem{Encrypted: data})
|
||||
case "server_tool_use":
|
||||
if role != "assistant" {
|
||||
continue
|
||||
@@ -371,6 +412,34 @@ func convertAnthropicMessages(messages []anthropicMessage, declaredTools map[str
|
||||
return input, instructions, nil
|
||||
}
|
||||
|
||||
func anthropicExplicitReasoningProofs(messages []anthropicMessage) map[string]struct{} {
|
||||
proofs := make(map[string]struct{})
|
||||
for _, message := range messages {
|
||||
if !strings.EqualFold(strings.TrimSpace(message.Role), "assistant") {
|
||||
continue
|
||||
}
|
||||
var blocks []map[string]json.RawMessage
|
||||
if json.Unmarshal(message.Content, &blocks) != nil {
|
||||
continue
|
||||
}
|
||||
for _, block := range blocks {
|
||||
var typeName string
|
||||
_ = json.Unmarshal(block["type"], &typeName)
|
||||
var proof string
|
||||
switch typeName {
|
||||
case "thinking":
|
||||
_ = json.Unmarshal(block["signature"], &proof)
|
||||
case "redacted_thinking":
|
||||
_ = json.Unmarshal(block["data"], &proof)
|
||||
}
|
||||
if proof = strings.TrimSpace(proof); proof != "" {
|
||||
proofs[proof] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
return proofs
|
||||
}
|
||||
|
||||
func applyAnthropicWebSearchResult(call map[string]any, raw json.RawMessage) {
|
||||
var results []map[string]any
|
||||
if json.Unmarshal(raw, &results) == nil {
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
package conversation
|
||||
|
||||
import (
|
||||
"container/list"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultReasoningCacheCapacity = 4096
|
||||
defaultReasoningCacheTTL = 30 * time.Minute
|
||||
)
|
||||
|
||||
type reasoningCacheEntry struct {
|
||||
key string
|
||||
item responseItem
|
||||
createdAt time.Time
|
||||
}
|
||||
|
||||
// ReasoningCache stores only short-lived, scoped reasoning proofs. A scope is
|
||||
// supplied by the caller and must identify the client conversation and the
|
||||
// upstream plane; a call_id by itself is never a sufficient cache key.
|
||||
type ReasoningCache struct {
|
||||
mu sync.Mutex
|
||||
entries map[string]*list.Element
|
||||
order *list.List
|
||||
capacity int
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
func NewReasoningCache(capacity int, ttl time.Duration) *ReasoningCache {
|
||||
if capacity <= 0 {
|
||||
capacity = defaultReasoningCacheCapacity
|
||||
}
|
||||
if ttl <= 0 {
|
||||
ttl = defaultReasoningCacheTTL
|
||||
}
|
||||
return &ReasoningCache{
|
||||
entries: make(map[string]*list.Element, capacity),
|
||||
order: list.New(),
|
||||
capacity: capacity,
|
||||
ttl: ttl,
|
||||
}
|
||||
}
|
||||
|
||||
// newReasoningCache is kept local to the package tests and makes the default
|
||||
// policy explicit without exposing cache internals to providers.
|
||||
func newReasoningCache(capacity int, ttl time.Duration) *ReasoningCache {
|
||||
return NewReasoningCache(capacity, ttl)
|
||||
}
|
||||
|
||||
func scopedReasoningCacheKey(scope, callID string) string {
|
||||
scope = strings.TrimSpace(scope)
|
||||
callID = normalizeReasoningCallID(callID)
|
||||
if scope == "" || callID == "" {
|
||||
return ""
|
||||
}
|
||||
return scope + "\x00" + callID
|
||||
}
|
||||
|
||||
// normalizeReasoningCallID handles the item-id suffix emitted by some
|
||||
// Responses clients while retaining the actual conversation scope.
|
||||
func normalizeReasoningCallID(callID string) string {
|
||||
callID = strings.TrimSpace(callID)
|
||||
if index := strings.IndexByte(callID, '|'); index > 0 {
|
||||
callID = strings.TrimSpace(callID[:index])
|
||||
}
|
||||
return callID
|
||||
}
|
||||
|
||||
func reasoningCallIDCandidates(callID string) []string {
|
||||
callID = strings.TrimSpace(callID)
|
||||
if callID == "" {
|
||||
return nil
|
||||
}
|
||||
result := []string{callID}
|
||||
canonical := normalizeReasoningCallID(callID)
|
||||
if canonical != callID && canonical != "" {
|
||||
result = append(result, canonical)
|
||||
}
|
||||
const anthropicPrefix = "toolu_"
|
||||
if strings.HasPrefix(canonical, anthropicPrefix) {
|
||||
if upstream := strings.TrimPrefix(canonical, anthropicPrefix); upstream != "" {
|
||||
result = append(result, upstream)
|
||||
}
|
||||
} else {
|
||||
result = append(result, anthropicPrefix+canonical)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// SetScoped records one proof under a conversation/plane scope.
|
||||
func (c *ReasoningCache) SetScoped(scope, callID string, item responseItem) {
|
||||
if c == nil || item.Type != "reasoning" || strings.TrimSpace(item.ID) == "" || strings.TrimSpace(item.Encrypted) == "" {
|
||||
return
|
||||
}
|
||||
key := scopedReasoningCacheKey(scope, callID)
|
||||
if key == "" {
|
||||
return
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
now := time.Now()
|
||||
if element, exists := c.entries[key]; exists {
|
||||
entry := element.Value.(*reasoningCacheEntry)
|
||||
entry.item = cloneResponseItem(item)
|
||||
entry.createdAt = now
|
||||
c.order.MoveToFront(element)
|
||||
return
|
||||
}
|
||||
for c.order.Len() >= c.capacity {
|
||||
c.removeExpiredOrOldestLocked(now)
|
||||
if c.order.Len() < c.capacity {
|
||||
break
|
||||
}
|
||||
c.removeElementLocked(c.order.Back())
|
||||
}
|
||||
entry := &reasoningCacheEntry{key: key, item: cloneResponseItem(item), createdAt: now}
|
||||
c.entries[key] = c.order.PushFront(entry)
|
||||
}
|
||||
|
||||
// GetScoped returns a proof only from the requested conversation/plane scope.
|
||||
// Reads refresh recency, making the bounded cache an actual LRU rather than a
|
||||
// FIFO queue.
|
||||
func (c *ReasoningCache) GetScoped(scope, callID string) (responseItem, bool) {
|
||||
if c == nil || strings.TrimSpace(scope) == "" {
|
||||
return responseItem{}, false
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
now := time.Now()
|
||||
for _, candidate := range reasoningCallIDCandidates(callID) {
|
||||
key := scopedReasoningCacheKey(scope, candidate)
|
||||
element, exists := c.entries[key]
|
||||
if !exists {
|
||||
continue
|
||||
}
|
||||
entry := element.Value.(*reasoningCacheEntry)
|
||||
if now.Sub(entry.createdAt) > c.ttl {
|
||||
c.removeElementLocked(element)
|
||||
continue
|
||||
}
|
||||
c.order.MoveToFront(element)
|
||||
return cloneResponseItem(entry.item), true
|
||||
}
|
||||
return responseItem{}, false
|
||||
}
|
||||
|
||||
func (c *ReasoningCache) removeElementLocked(element *list.Element) {
|
||||
if element == nil {
|
||||
return
|
||||
}
|
||||
entry := element.Value.(*reasoningCacheEntry)
|
||||
delete(c.entries, entry.key)
|
||||
c.order.Remove(element)
|
||||
}
|
||||
|
||||
func (c *ReasoningCache) removeExpiredOrOldestLocked(now time.Time) {
|
||||
for element := c.order.Back(); element != nil; {
|
||||
previous := element.Prev()
|
||||
entry := element.Value.(*reasoningCacheEntry)
|
||||
if now.Sub(entry.createdAt) > c.ttl {
|
||||
c.removeElementLocked(element)
|
||||
}
|
||||
element = previous
|
||||
}
|
||||
}
|
||||
|
||||
// RememberReasoningForEnvelope associates each function call with the most
|
||||
// recent preceding reasoning item. A single reasoning item may legitimately
|
||||
// precede several parallel calls; separate reasoning items are never all
|
||||
// collapsed onto the last call.
|
||||
func (c *ReasoningCache) RememberReasoningForEnvelope(scope string, envelope responseEnvelope) {
|
||||
if c == nil || strings.TrimSpace(scope) == "" || len(envelope.Output) == 0 {
|
||||
return
|
||||
}
|
||||
var current *responseItem
|
||||
for _, item := range envelope.Output {
|
||||
switch item.Type {
|
||||
case "reasoning":
|
||||
if item.Encrypted == "" {
|
||||
current = nil
|
||||
continue
|
||||
}
|
||||
copy := cloneResponseItem(item)
|
||||
current = ©
|
||||
case "function_call":
|
||||
if current != nil && item.CallID != "" {
|
||||
c.SetScoped(scope, item.CallID, *current)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func cloneResponseItem(item responseItem) responseItem {
|
||||
clone := item
|
||||
if item.Content != nil {
|
||||
clone.Content = append([]responseContent(nil), item.Content...)
|
||||
}
|
||||
if item.Summary != nil {
|
||||
clone.Summary = append([]responseContent(nil), item.Summary...)
|
||||
}
|
||||
if item.Action != nil {
|
||||
clone.Action = make(map[string]any, len(item.Action))
|
||||
for key, value := range item.Action {
|
||||
clone.Action[key] = value
|
||||
}
|
||||
}
|
||||
return clone
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package conversation
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestReasoningCacheSetAndGet(t *testing.T) {
|
||||
cache := newReasoningCache(10, time.Hour)
|
||||
scope := "session-a/build"
|
||||
sample := responseItem{
|
||||
ID: "rs_123",
|
||||
Type: "reasoning",
|
||||
Status: "completed",
|
||||
Encrypted: "encrypted-content-sample",
|
||||
}
|
||||
|
||||
cache.SetScoped(scope, "call-1", sample)
|
||||
got, found := cache.GetScoped(scope, "call-1")
|
||||
if !found {
|
||||
t.Fatalf("expected call-1 to be found in cache")
|
||||
}
|
||||
if got.Encrypted != sample.Encrypted || got.ID != sample.ID {
|
||||
t.Fatalf("expected %v, got %v", sample, got)
|
||||
}
|
||||
|
||||
_, found2 := cache.GetScoped(scope, "non-existent")
|
||||
if found2 {
|
||||
t.Fatalf("expected non-existent to return false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRememberReasoningForEnvelope(t *testing.T) {
|
||||
cache := newReasoningCache(10, time.Hour)
|
||||
scope := "session-a/build"
|
||||
env := responseEnvelope{
|
||||
Output: []responseItem{
|
||||
{
|
||||
ID: "rs_abc",
|
||||
Type: "reasoning",
|
||||
Status: "completed",
|
||||
Encrypted: "encrypted_abc",
|
||||
},
|
||||
{
|
||||
ID: "fc_1",
|
||||
Type: "function_call",
|
||||
CallID: "call_abc_1",
|
||||
Name: "test_fn",
|
||||
},
|
||||
{
|
||||
ID: "fc_2",
|
||||
Type: "function_call",
|
||||
CallID: "call_abc_2",
|
||||
Name: "test_fn2",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
cache.RememberReasoningForEnvelope(scope, env)
|
||||
|
||||
r1, found1 := cache.GetScoped(scope, "call_abc_1")
|
||||
if !found1 || r1.Encrypted != "encrypted_abc" {
|
||||
t.Fatalf("expected call_abc_1 to be cached, got %v", r1)
|
||||
}
|
||||
|
||||
r2, found2 := cache.GetScoped(scope, "call_abc_2")
|
||||
if !found2 || r2.Encrypted != "encrypted_abc" {
|
||||
t.Fatalf("expected call_abc_2 to be cached, got %v", r2)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReasoningCacheScopesAndLRU(t *testing.T) {
|
||||
cache := newReasoningCache(2, time.Hour)
|
||||
item := func(id string) responseItem {
|
||||
return responseItem{ID: id, Type: "reasoning", Encrypted: id + "-encrypted"}
|
||||
}
|
||||
cache.SetScoped("session-a/build", "call-1", item("one"))
|
||||
cache.SetScoped("session-a/build", "call-2", item("two"))
|
||||
if _, ok := cache.GetScoped("session-b/build", "call-1"); ok {
|
||||
t.Fatal("reasoning leaked across scopes")
|
||||
}
|
||||
if _, ok := cache.GetScoped("session-a/xai", "call-1"); ok {
|
||||
t.Fatal("reasoning leaked across planes")
|
||||
}
|
||||
if _, ok := cache.GetScoped("session-a/build", "call-1"); !ok {
|
||||
t.Fatal("call-1 should be present before LRU access")
|
||||
}
|
||||
cache.SetScoped("session-a/build", "call-3", item("three"))
|
||||
if _, ok := cache.GetScoped("session-a/build", "call-1"); !ok {
|
||||
t.Fatal("recently-read call-1 was evicted; cache is not LRU")
|
||||
}
|
||||
if _, ok := cache.GetScoped("session-a/build", "call-2"); ok {
|
||||
t.Fatal("least-recently-used call-2 was not evicted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRememberReasoningForEnvelopePairsItemsInOrder(t *testing.T) {
|
||||
cache := newReasoningCache(10, time.Hour)
|
||||
scope := "session-a/build"
|
||||
cache.RememberReasoningForEnvelope(scope, responseEnvelope{Output: []responseItem{
|
||||
{ID: "reasoning-a", Type: "reasoning", Encrypted: "enc-a"},
|
||||
{ID: "call-item-a", Type: "function_call", CallID: "call-a"},
|
||||
{ID: "reasoning-b", Type: "reasoning", Encrypted: "enc-b"},
|
||||
{ID: "call-item-b", Type: "function_call", CallID: "call-b"},
|
||||
}})
|
||||
a, ok := cache.GetScoped(scope, "call-a")
|
||||
if !ok || a.ID != "reasoning-a" {
|
||||
t.Fatalf("call-a reasoning = %#v, found=%v", a, ok)
|
||||
}
|
||||
b, ok := cache.GetScoped(scope, "call-b")
|
||||
if !ok || b.ID != "reasoning-b" {
|
||||
t.Fatalf("call-b reasoning = %#v, found=%v", b, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReasoningInputItemOmitsNullContent(t *testing.T) {
|
||||
payload := reasoningInputItem(responseItem{ID: "rs-1", Type: "reasoning", Encrypted: "opaque"})
|
||||
if _, exists := payload["content"]; exists {
|
||||
t.Fatalf("content must be omitted for an opaque item: %#v", payload)
|
||||
}
|
||||
if summary, ok := payload["summary"].([]any); !ok || len(summary) != 0 {
|
||||
t.Fatalf("opaque reasoning must carry an empty summary array: %#v", payload)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReasoningInputItemOmitsSyntheticContentFields(t *testing.T) {
|
||||
payload := reasoningInputItem(responseItem{
|
||||
ID: "rs-2",
|
||||
Type: "reasoning",
|
||||
Encrypted: "opaque",
|
||||
Summary: []responseContent{{Type: "summary_text", Text: "plan"}},
|
||||
Content: []responseContent{{Type: "reasoning_text", Text: "detail"}},
|
||||
})
|
||||
encoded, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
text := string(encoded)
|
||||
for _, unwanted := range []string{`"content":null`, `"refusal":""`, `"annotations":null`} {
|
||||
if strings.Contains(text, unwanted) {
|
||||
t.Fatalf("replay item contains synthetic field %s: %s", unwanted, text)
|
||||
}
|
||||
}
|
||||
var decoded map[string]any
|
||||
if err := json.Unmarshal(encoded, &decoded); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if summary := decoded["summary"].([]any)[0].(map[string]any); summary["type"] != "summary_text" || summary["text"] != "plan" {
|
||||
t.Fatalf("summary fields were not preserved: %#v", decoded["summary"])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
package conversation
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestChatMultiTurnReasoningRestoration(t *testing.T) {
|
||||
// 模拟第一轮:上游返回 Responses 包含 reasoning 和 function_call
|
||||
callID := "call_integration_test_123"
|
||||
cache := newReasoningCache(10, time.Hour)
|
||||
scope := "client-session/build"
|
||||
env := responseEnvelope{
|
||||
Output: []responseItem{
|
||||
{
|
||||
ID: "rs_integ_001",
|
||||
Type: "reasoning",
|
||||
Status: "completed",
|
||||
Encrypted: "encrypted_secret_chain_proof",
|
||||
},
|
||||
{
|
||||
ID: "fc_integ_001",
|
||||
Type: "function_call",
|
||||
CallID: callID,
|
||||
Name: "list_dir",
|
||||
Arguments: `{"path":"/"}`,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// 触发出站记录
|
||||
cache.RememberReasoningForEnvelope(scope, env)
|
||||
|
||||
// 模拟第二轮:下游客户端传回标准的 Chat Completions 历史(带有刚才的 tool_calls 和 tool output)
|
||||
chatReqJSON := []byte(`{
|
||||
"model": "grok-4.6",
|
||||
"messages": [
|
||||
{"role": "user", "content": "hello investigate"},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": null,
|
||||
"tool_calls": [
|
||||
{
|
||||
"id": "` + callID + `",
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "list_dir",
|
||||
"arguments": "{\"path\":\"/\"}"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"role": "tool",
|
||||
"tool_call_id": "` + callID + `",
|
||||
"content": "{\"error\":\"not found\"}"
|
||||
}
|
||||
]
|
||||
}`)
|
||||
|
||||
convertedBody, _, err := ConvertRequestWithReasoningReplay(chatReqJSON, "grok-4.6", OperationChat, cache, scope)
|
||||
if err != nil {
|
||||
t.Fatalf("ConvertRequestWithOptions failed: %v", err)
|
||||
}
|
||||
|
||||
var convertedMap map[string]any
|
||||
if err := json.Unmarshal(convertedBody, &convertedMap); err != nil {
|
||||
t.Fatalf("Unmarshal convertedBody failed: %v", err)
|
||||
}
|
||||
|
||||
inputs, ok := convertedMap["input"].([]any)
|
||||
if !ok || len(inputs) == 0 {
|
||||
t.Fatalf("expected non-empty input array, got: %v", convertedMap["input"])
|
||||
}
|
||||
|
||||
// 验证 input 列表中必须包含我们注入的 reasoning 项!
|
||||
foundReasoning := false
|
||||
for _, itemRaw := range inputs {
|
||||
item, ok := itemRaw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if item["type"] == "reasoning" {
|
||||
if item["id"] == "rs_integ_001" && item["encrypted_content"] == "encrypted_secret_chain_proof" {
|
||||
foundReasoning = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !foundReasoning {
|
||||
t.Fatalf("FAIL: expected reasoning block with id rs_integ_001 to be restored in input, but not found. Inputs: %#v", inputs)
|
||||
}
|
||||
for _, itemRaw := range inputs {
|
||||
item, ok := itemRaw.(map[string]any)
|
||||
if ok && item["type"] == "reasoning" {
|
||||
if _, exists := item["content"]; exists {
|
||||
t.Fatalf("opaque reasoning replay must omit content: %#v", item)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnthropicWebSearchDoesNotInjectCachedReasoning(t *testing.T) {
|
||||
cache := newReasoningCache(10, time.Hour)
|
||||
scope := "client-session/build"
|
||||
cache.SetScoped(scope, "call_search", responseItem{
|
||||
ID: "rs_search", Type: "reasoning", Encrypted: "search-proof",
|
||||
})
|
||||
body := []byte(`{
|
||||
"model":"grok-4.6","max_tokens":128,
|
||||
"messages":[
|
||||
{"role":"assistant","content":[{"type":"tool_use","id":"toolu_call_search","name":"lookup","input":{}}]},
|
||||
{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_call_search","content":"ok"}]}
|
||||
],
|
||||
"tools":[{"type":"web_search_20250305","name":"web_search"}]
|
||||
}`)
|
||||
converted, options, err := ConvertRequestWithReasoningReplay(body, "grok-4.6", OperationMessages, cache, scope)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var payload struct {
|
||||
Input []map[string]any `json:"input"`
|
||||
}
|
||||
if err := json.Unmarshal(converted, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, item := range payload.Input {
|
||||
if item["type"] == "reasoning" {
|
||||
t.Fatalf("web-search request received cached reasoning: %#v", payload.Input)
|
||||
}
|
||||
}
|
||||
if options.reasoningCache != nil || options.reasoningScope != "" {
|
||||
t.Fatalf("web-search options retained reasoning bridge: %#v", options)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnthropicFunctionToolRestoresCachedReasoning(t *testing.T) {
|
||||
cache := newReasoningCache(10, time.Hour)
|
||||
scope := "client-session/build"
|
||||
cache.SetScoped(scope, "call_function", responseItem{
|
||||
ID: "rs_function", Type: "reasoning", Encrypted: "function-proof",
|
||||
})
|
||||
body := []byte(`{
|
||||
"model":"grok-4.6","max_tokens":128,
|
||||
"messages":[
|
||||
{"role":"assistant","content":[{"type":"tool_use","id":"toolu_call_function","name":"lookup","input":{}}]},
|
||||
{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_call_function","content":"ok"}]}
|
||||
],
|
||||
"tools":[{"name":"lookup","input_schema":{"type":"object"}}]
|
||||
}`)
|
||||
converted, options, err := ConvertRequestWithReasoningReplay(body, "grok-4.6", OperationMessages, cache, scope)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var payload struct {
|
||||
Input []map[string]any `json:"input"`
|
||||
}
|
||||
if err := json.Unmarshal(converted, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(payload.Input) < 2 || payload.Input[0]["type"] != "reasoning" || payload.Input[0]["encrypted_content"] != "function-proof" {
|
||||
t.Fatalf("function reasoning was not restored: %#v", payload.Input)
|
||||
}
|
||||
if options.reasoningCache == nil || options.reasoningScope == "" {
|
||||
t.Fatal("ordinary Messages request lost reasoning bridge")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStreamOutputItemDoneFeedsReasoningReplayWhenCompletedOutputIsEmpty(t *testing.T) {
|
||||
cache := newReasoningCache(10, time.Hour)
|
||||
scope := "client-session/build"
|
||||
stream := strings.Join([]string{
|
||||
`event: response.output_item.done`,
|
||||
`data: {"type":"response.output_item.done","item":{"id":"rs_stream","type":"reasoning","status":"completed","encrypted_content":"stream-proof"}}`,
|
||||
``,
|
||||
`event: response.output_item.done`,
|
||||
`data: {"type":"response.output_item.done","item":{"id":"fc_stream","type":"function_call","call_id":"call_stream","name":"list_dir","arguments":"{}"}}`,
|
||||
``,
|
||||
`event: response.completed`,
|
||||
`data: {"type":"response.completed","response":{"id":"resp_stream","status":"completed","output":[]}}`,
|
||||
``,
|
||||
}, "\n")
|
||||
converted := ConvertResponseStreamWithOptions(
|
||||
io.NopCloser(strings.NewReader(stream)),
|
||||
OperationChat,
|
||||
ResponseOptions{}.WithReasoningReplay(cache, scope),
|
||||
)
|
||||
if _, err := io.ReadAll(converted); err != nil {
|
||||
t.Fatalf("stream conversion failed: %v", err)
|
||||
}
|
||||
if _, ok := cache.GetScoped(scope, "call_stream"); !ok {
|
||||
t.Fatal("output_item.done reasoning was not cached")
|
||||
}
|
||||
|
||||
body := []byte(`{"model":"grok-4.6","messages":[{"role":"assistant","content":null,"tool_calls":[{"id":"call_stream","type":"function","function":{"name":"list_dir","arguments":"{}"}}]},{"role":"tool","tool_call_id":"call_stream","content":"ok"}]}`)
|
||||
convertedBody, _, err := ConvertRequestWithReasoningReplay(body, "grok-4.6", OperationChat, cache, scope)
|
||||
if err != nil {
|
||||
t.Fatalf("request conversion failed: %v", err)
|
||||
}
|
||||
var payload struct {
|
||||
Input []map[string]any `json:"input"`
|
||||
}
|
||||
if err := json.Unmarshal(convertedBody, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(payload.Input) < 2 || payload.Input[0]["type"] != "reasoning" || payload.Input[0]["encrypted_content"] != "stream-proof" || payload.Input[1]["type"] != "function_call" {
|
||||
t.Fatalf("restored input = %#v", payload.Input)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStreamCompletedOutputFeedsReasoningReplayWhenItemDoneIsOmitted(t *testing.T) {
|
||||
cache := newReasoningCache(10, time.Hour)
|
||||
scope := "client-session/build"
|
||||
stream := strings.Join([]string{
|
||||
`event: response.completed`,
|
||||
`data: {"type":"response.completed","response":{"id":"resp_terminal","status":"completed","output":[{"id":"rs_terminal","type":"reasoning","status":"completed","encrypted_content":"terminal-proof"},{"id":"fc_terminal","type":"function_call","call_id":"call_terminal","name":"list_dir","arguments":"{}"}]}}`,
|
||||
``,
|
||||
}, "\n")
|
||||
converted := ConvertResponseStreamWithOptions(
|
||||
io.NopCloser(strings.NewReader(stream)),
|
||||
OperationChat,
|
||||
ResponseOptions{}.WithReasoningReplay(cache, scope),
|
||||
)
|
||||
if _, err := io.ReadAll(converted); err != nil {
|
||||
t.Fatalf("stream conversion failed: %v", err)
|
||||
}
|
||||
item, ok := cache.GetScoped(scope, "call_terminal")
|
||||
if !ok || item.Encrypted != "terminal-proof" {
|
||||
t.Fatalf("terminal output was not cached: item=%#v found=%v", item, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStreamReplayPreservesOutputItemDoneOrderWhenTerminalOmitsReasoning(t *testing.T) {
|
||||
cache := newReasoningCache(10, time.Hour)
|
||||
scope := "client-session/build"
|
||||
stream := strings.Join([]string{
|
||||
`event: response.output_item.done`,
|
||||
`data: {"type":"response.output_item.done","item":{"id":"rs_ordered","type":"reasoning","status":"completed","encrypted_content":"ordered-proof"}}`, "",
|
||||
`event: response.output_item.done`,
|
||||
`data: {"type":"response.output_item.done","item":{"id":"fc_ordered","type":"function_call","call_id":"call_ordered","name":"list_dir","arguments":"{}"}}`, "",
|
||||
// The terminal envelope contains only the function call. Some Build
|
||||
// responses do this even though reasoning was sent in item.done.
|
||||
`event: response.completed`,
|
||||
`data: {"type":"response.completed","response":{"id":"resp_ordered","status":"completed","output":[{"id":"fc_ordered","type":"function_call","call_id":"call_ordered","name":"list_dir","arguments":"{}"}]}}`, "",
|
||||
}, "\n")
|
||||
converted := ConvertResponseStreamWithOptions(io.NopCloser(strings.NewReader(stream)), OperationChat, ResponseOptions{}.WithReasoningReplay(cache, scope))
|
||||
if _, err := io.ReadAll(converted); err != nil {
|
||||
t.Fatalf("stream conversion failed: %v", err)
|
||||
}
|
||||
item, ok := cache.GetScoped(scope, "call_ordered")
|
||||
if !ok || item.Encrypted != "ordered-proof" {
|
||||
t.Fatalf("reasoning item.done was not paired with the later function call: item=%#v found=%v", item, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStreamWithoutResponsesTerminalDoesNotCommitReasoningReplay(t *testing.T) {
|
||||
cache := newReasoningCache(10, time.Hour)
|
||||
scope := "client-session/build"
|
||||
// The source ends after item.done without response.completed/incomplete.
|
||||
// Downstream compatibility still emits its normal terminator, but this is
|
||||
// not sufficient evidence that the upstream tool turn completed.
|
||||
stream := strings.Join([]string{
|
||||
`event: response.output_item.done`,
|
||||
`data: {"type":"response.output_item.done","item":{"id":"rs_truncated","type":"reasoning","encrypted_content":"truncated-proof"}}`,
|
||||
``,
|
||||
`event: response.output_item.done`,
|
||||
`data: {"type":"response.output_item.done","item":{"id":"fc_truncated","type":"function_call","call_id":"call_truncated","name":"list_dir","arguments":"{}"}}`,
|
||||
``,
|
||||
}, "\n")
|
||||
converted := ConvertResponseStreamWithOptions(
|
||||
io.NopCloser(strings.NewReader(stream)),
|
||||
OperationChat,
|
||||
ResponseOptions{}.WithReasoningReplay(cache, scope),
|
||||
)
|
||||
if _, err := io.ReadAll(converted); err != nil {
|
||||
t.Fatalf("stream conversion failed: %v", err)
|
||||
}
|
||||
if _, ok := cache.GetScoped(scope, "call_truncated"); ok {
|
||||
t.Fatal("truncated stream polluted reasoning replay cache")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnthropicParallelToolUsesInjectOneReasoningProof(t *testing.T) {
|
||||
cache := newReasoningCache(10, time.Hour)
|
||||
scope := "client-session/build"
|
||||
proof := responseItem{
|
||||
ID: "rs_parallel",
|
||||
Type: "reasoning",
|
||||
Encrypted: "parallel-proof",
|
||||
Summary: []responseContent{{Type: "summary_text", Text: "plan"}},
|
||||
}
|
||||
cache.SetScoped(scope, "call-a", proof)
|
||||
cache.SetScoped(scope, "call-b", proof)
|
||||
|
||||
messages := []anthropicMessage{
|
||||
{Role: "assistant", Content: json.RawMessage(`[
|
||||
{"type":"tool_use","id":"toolu_call-a","name":"first","input":{}},
|
||||
{"type":"tool_use","id":"toolu_call-b","name":"second","input":{}}
|
||||
]`)},
|
||||
{Role: "user", Content: json.RawMessage(`[
|
||||
{"type":"tool_result","tool_use_id":"toolu_call-a","content":"one"},
|
||||
{"type":"tool_result","tool_use_id":"toolu_call-b","content":"two"}
|
||||
]`)},
|
||||
}
|
||||
input, _, err := convertAnthropicMessagesWithReasoningReplay(messages, nil, cache, scope)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reasoningCount := 0
|
||||
functionCount := 0
|
||||
for _, raw := range input {
|
||||
item, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
switch item["type"] {
|
||||
case "reasoning":
|
||||
reasoningCount++
|
||||
if item["encrypted_content"] != "parallel-proof" {
|
||||
t.Fatalf("reasoning = %#v", item)
|
||||
}
|
||||
case "function_call":
|
||||
functionCount++
|
||||
}
|
||||
}
|
||||
if reasoningCount != 1 || functionCount != 2 {
|
||||
t.Fatalf("parallel tool input = %#v", input)
|
||||
}
|
||||
encoded, err := json.Marshal(input)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(string(encoded), `"content":null`) || strings.Contains(string(encoded), `"refusal":""`) || strings.Contains(string(encoded), `"annotations":null`) {
|
||||
t.Fatalf("replayed reasoning contains synthetic null fields: %s", encoded)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnthropicExplicitThinkingSignatureSuppressesCachedDuplicate(t *testing.T) {
|
||||
cache := newReasoningCache(10, time.Hour)
|
||||
scope := "client-session/build"
|
||||
cache.SetScoped(scope, "call-a", responseItem{ID: "rs_cached", Type: "reasoning", Encrypted: "same-proof"})
|
||||
messages := []anthropicMessage{
|
||||
{Role: "assistant", Content: json.RawMessage(`[
|
||||
{"type":"thinking","thinking":"plan","signature":"same-proof"},
|
||||
{"type":"tool_use","id":"toolu_call-a","name":"first","input":{}}
|
||||
]`)},
|
||||
{Role: "user", Content: json.RawMessage(`[{"type":"tool_result","tool_use_id":"toolu_call-a","content":"ok"}]`)},
|
||||
}
|
||||
input, _, err := convertAnthropicMessagesWithReasoningReplay(messages, nil, cache, scope)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reasoningCount := 0
|
||||
for _, raw := range input {
|
||||
item, _ := raw.(map[string]any)
|
||||
if item["type"] == "reasoning" {
|
||||
reasoningCount++
|
||||
}
|
||||
}
|
||||
if reasoningCount != 1 {
|
||||
t.Fatalf("cached proof duplicated explicit thinking: %#v", input)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStreamReasoningReplayCommitsOnlyAfterSuccessfulTerminal(t *testing.T) {
|
||||
cache := newReasoningCache(10, time.Hour)
|
||||
scope := "client-session/build"
|
||||
failed := strings.Join([]string{
|
||||
`event: response.output_item.done`,
|
||||
`data: {"type":"response.output_item.done","item":{"id":"rs_failed","type":"reasoning","encrypted_content":"failed-proof"}}`, "",
|
||||
`event: response.output_item.done`,
|
||||
`data: {"type":"response.output_item.done","item":{"id":"fc_failed","type":"function_call","call_id":"call_failed","name":"first","arguments":"{}"}}`, "",
|
||||
`event: response.failed`,
|
||||
`data: {"type":"response.failed","response":{"error":{"message":"upstream failed"}}}`, "", "",
|
||||
}, "\n")
|
||||
converted := ConvertResponseStreamWithOptions(io.NopCloser(strings.NewReader(failed)), OperationChat, ResponseOptions{}.WithReasoningReplay(cache, scope))
|
||||
if _, err := io.ReadAll(converted); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := cache.GetScoped(scope, "call_failed"); ok {
|
||||
t.Fatal("failed stream left reasoning proof in replay cache")
|
||||
}
|
||||
}
|
||||
@@ -22,11 +22,22 @@ func ConvertRequest(body []byte, model, operation string) ([]byte, error) {
|
||||
|
||||
// ConvertRequestWithOptions 同时返回下游协议特有的响应语义,供 JSON/SSE 转换阶段使用。
|
||||
func ConvertRequestWithOptions(body []byte, model, operation string) ([]byte, ResponseOptions, error) {
|
||||
return convertRequestWithReasoningReplay(body, model, operation, nil, "")
|
||||
}
|
||||
|
||||
// ConvertRequestWithReasoningReplay is used by providers that can establish a
|
||||
// trusted client-session scope. It keeps the public conversion path stateless
|
||||
// when no such scope is available.
|
||||
func ConvertRequestWithReasoningReplay(body []byte, model, operation string, cache *ReasoningCache, scope string) ([]byte, ResponseOptions, error) {
|
||||
return convertRequestWithReasoningReplay(body, model, operation, cache, scope)
|
||||
}
|
||||
|
||||
func convertRequestWithReasoningReplay(body []byte, model, operation string, cache *ReasoningCache, scope string) ([]byte, ResponseOptions, error) {
|
||||
switch operation {
|
||||
case OperationChat:
|
||||
return convertChatRequest(body, model)
|
||||
return convertChatRequestWithReasoningReplay(body, model, cache, scope)
|
||||
case OperationMessages:
|
||||
return convertMessagesRequest(body, model)
|
||||
return convertMessagesRequestWithReasoningReplay(body, model, cache, scope)
|
||||
default:
|
||||
converted, err := replaceModel(body, model)
|
||||
return converted, ResponseOptions{}, err
|
||||
|
||||
@@ -21,6 +21,20 @@ type ResponseOptions struct {
|
||||
Include []string
|
||||
// InlineCitations overrides Include when non-nil.
|
||||
InlineCitations *bool
|
||||
// reasoningCache and reasoningScope are intentionally populated only by a
|
||||
// provider that has a trusted, isolated client-session identity. A raw
|
||||
// call_id is not sufficient to restore encrypted reasoning safely.
|
||||
reasoningCache *ReasoningCache
|
||||
reasoningScope string
|
||||
}
|
||||
|
||||
// WithReasoningReplay attaches a provider-owned, scoped reasoning cache to
|
||||
// the conversion options. The scope must include the client session and the
|
||||
// upstream plane; an empty scope disables the bridge.
|
||||
func (o ResponseOptions) WithReasoningReplay(cache *ReasoningCache, scope string) ResponseOptions {
|
||||
o.reasoningCache = cache
|
||||
o.reasoningScope = scope
|
||||
return o
|
||||
}
|
||||
|
||||
// InlineCitationsEnabled reports whether [[N]](url) markers should be embedded.
|
||||
@@ -128,6 +142,7 @@ func ConvertResponseJSONWithOptions(body []byte, operation string, options Respo
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
options.reasoningCache.RememberReasoningForEnvelope(options.reasoningScope, envelope)
|
||||
parsed := parseResponse(envelope)
|
||||
if operation == OperationMessages || operation == OperationChat {
|
||||
parsed.Text, parsed.StopSequence = applyStopSequences(parsed.Text, options.StopSequences)
|
||||
|
||||
@@ -67,10 +67,6 @@ type streamConverter struct {
|
||||
thinkingIndex int
|
||||
thinkingItemID string
|
||||
chatReasoningMark bool
|
||||
reasoningEvidenceBytes int
|
||||
reasoningItems map[string]*reasoningStreamState
|
||||
reasoningOrder []string
|
||||
activeReasoningID string
|
||||
nextIndex int
|
||||
tools map[string]streamTool
|
||||
webSearch []webSearchCall
|
||||
@@ -82,7 +78,17 @@ type streamConverter struct {
|
||||
stopFilter *anthropicStreamStopFilter
|
||||
stopSequence string
|
||||
refused bool
|
||||
reasoningEvidenceBytes int
|
||||
reasoningItems map[string]*reasoningStreamState
|
||||
reasoningOrder []string
|
||||
activeReasoningID string
|
||||
repeatTracker streamRepeatTracker
|
||||
// terminalEvent distinguishes a normal Responses terminal frame from a
|
||||
// transport EOF. EOF is still converted to the legacy downstream terminator
|
||||
// for compatibility, but it must not make a truncated tool turn replayable.
|
||||
terminalEvent bool
|
||||
outputItems []responseItem
|
||||
outputItemIDs map[string]struct{}
|
||||
}
|
||||
|
||||
// streamRepeatTracker 在协议转换、缓冲和 stop filter 之前跟踪上游增量,
|
||||
@@ -143,6 +149,7 @@ func newStreamConverter(writer io.Writer, operation string, options ResponseOpti
|
||||
return &streamConverter{
|
||||
writer: writer, operation: operation, created: time.Now().Unix(), tools: make(map[string]streamTool),
|
||||
webSearchEmitted: make(map[string]bool),
|
||||
outputItemIDs: make(map[string]struct{}),
|
||||
reasoningItems: make(map[string]*reasoningStreamState),
|
||||
deferSearchText: operation == OperationMessages && options.AnthropicWebSearch,
|
||||
options: options, stopFilter: newAnthropicStreamStopFilter(options.StopSequences),
|
||||
@@ -379,6 +386,7 @@ func (c *streamConverter) handle(event string, data []byte) error {
|
||||
case "response.output_item.done":
|
||||
var item responseItem
|
||||
_ = json.Unmarshal(root["item"], &item)
|
||||
c.recordOutputItem(item)
|
||||
if item.Type == "function_call" {
|
||||
return c.toolArgumentsDone(item.ID, item.Arguments)
|
||||
}
|
||||
@@ -401,6 +409,11 @@ func (c *streamConverter) handle(event string, data []byte) error {
|
||||
case "response.completed", "response.incomplete":
|
||||
var response responseEnvelope
|
||||
_ = json.Unmarshal(root["response"], &response)
|
||||
// Some upstream streams omit output_item.done and put the complete
|
||||
// reasoning/function_call objects only in the terminal envelope. Record
|
||||
// those objects before done() commits the replay cache.
|
||||
c.recordReplayOutput(response.Output)
|
||||
response.Output = c.mergeOutputItems(response.Output)
|
||||
c.setResponse(response)
|
||||
for _, item := range response.Output {
|
||||
if item.Type == "reasoning" {
|
||||
@@ -421,6 +434,7 @@ func (c *streamConverter) handle(event string, data []byte) error {
|
||||
if status == "" && typeName == "response.incomplete" {
|
||||
status = "incomplete"
|
||||
}
|
||||
c.terminalEvent = true
|
||||
return c.done(status)
|
||||
case "error", "response.failed":
|
||||
return c.streamError(data)
|
||||
@@ -428,6 +442,176 @@ func (c *streamConverter) handle(event string, data []byte) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// recordOutputItem retains the authoritative item-done payload. In streamed
|
||||
// Responses, response.completed often contains usage/status only and an empty
|
||||
// output array, while encrypted reasoning is present solely in these events.
|
||||
func (c *streamConverter) recordOutputItem(item responseItem) {
|
||||
if c == nil || (item.Type != "reasoning" && item.Type != "function_call") {
|
||||
return
|
||||
}
|
||||
if c.outputItemIDs == nil {
|
||||
c.outputItemIDs = make(map[string]struct{})
|
||||
}
|
||||
key := replayOutputKey(item)
|
||||
if key != "" {
|
||||
if _, exists := c.outputItemIDs[key]; exists {
|
||||
for index := range c.outputItems {
|
||||
if replayOutputKey(c.outputItems[index]) == key {
|
||||
c.outputItems[index] = mergeResponseItem(c.outputItems[index], item)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
c.outputItemIDs[key] = struct{}{}
|
||||
}
|
||||
c.outputItems = append(c.outputItems, cloneResponseItem(item))
|
||||
}
|
||||
|
||||
func replayOutputKey(item responseItem) string {
|
||||
if id := strings.TrimSpace(item.ID); id != "" {
|
||||
return "id:" + id
|
||||
}
|
||||
if item.Type == "function_call" {
|
||||
if callID := strings.TrimSpace(item.CallID); callID != "" {
|
||||
return "call:" + normalizeReasoningCallID(callID)
|
||||
}
|
||||
}
|
||||
if item.Type == "reasoning" {
|
||||
if encrypted := strings.TrimSpace(item.Encrypted); encrypted != "" {
|
||||
return "proof:" + encrypted
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// recordReplayOutput merges the terminal envelope into the items observed in
|
||||
// output_item.done. The event stream carries the authoritative output order;
|
||||
// the terminal envelope is used to fill richer fields and append items that
|
||||
// were never announced as done.
|
||||
func (c *streamConverter) recordReplayOutput(output []responseItem) {
|
||||
if c == nil || len(output) == 0 {
|
||||
return
|
||||
}
|
||||
merged := make([]responseItem, 0, len(c.outputItems)+len(output))
|
||||
if len(c.outputItems) == 0 {
|
||||
for _, item := range output {
|
||||
if item.Type == "reasoning" || item.Type == "function_call" {
|
||||
merged = append(merged, cloneResponseItem(item))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
terminal := make(map[string]responseItem, len(output))
|
||||
for _, item := range output {
|
||||
if item.Type == "reasoning" || item.Type == "function_call" {
|
||||
if key := replayOutputKey(item); key != "" {
|
||||
terminal[key] = item
|
||||
}
|
||||
}
|
||||
}
|
||||
seen := make(map[string]struct{}, len(c.outputItems)+len(output))
|
||||
for _, item := range c.outputItems {
|
||||
key := replayOutputKey(item)
|
||||
if key != "" {
|
||||
if update, ok := terminal[key]; ok {
|
||||
item = mergeResponseItem(item, update)
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
}
|
||||
merged = append(merged, cloneResponseItem(item))
|
||||
}
|
||||
for _, item := range output {
|
||||
if item.Type != "reasoning" && item.Type != "function_call" {
|
||||
continue
|
||||
}
|
||||
key := replayOutputKey(item)
|
||||
if key != "" {
|
||||
if _, ok := seen[key]; ok {
|
||||
continue
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
}
|
||||
merged = append(merged, cloneResponseItem(item))
|
||||
}
|
||||
}
|
||||
c.outputItems = merged
|
||||
c.outputItemIDs = make(map[string]struct{}, len(merged))
|
||||
for _, item := range merged {
|
||||
if key := replayOutputKey(item); key != "" {
|
||||
c.outputItemIDs[key] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *streamConverter) commitReasoningReplay() {
|
||||
if c == nil || c.options.reasoningCache == nil || strings.TrimSpace(c.options.reasoningScope) == "" || len(c.outputItems) == 0 {
|
||||
return
|
||||
}
|
||||
c.options.reasoningCache.RememberReasoningForEnvelope(c.options.reasoningScope, responseEnvelope{Output: c.outputItems})
|
||||
}
|
||||
|
||||
func (c *streamConverter) mergeOutputItems(output []responseItem) []responseItem {
|
||||
if len(c.outputItems) == 0 {
|
||||
return output
|
||||
}
|
||||
if len(output) == 0 {
|
||||
return append([]responseItem(nil), c.outputItems...)
|
||||
}
|
||||
merged := append([]responseItem(nil), output...)
|
||||
for _, item := range c.outputItems {
|
||||
found := false
|
||||
if key := replayOutputKey(item); key != "" {
|
||||
for index := range merged {
|
||||
if replayOutputKey(merged[index]) == key {
|
||||
merged[index] = mergeResponseItem(merged[index], item)
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
merged = append(merged, item)
|
||||
}
|
||||
}
|
||||
return merged
|
||||
}
|
||||
|
||||
func mergeResponseItem(base, update responseItem) responseItem {
|
||||
if base.ID == "" {
|
||||
base.ID = update.ID
|
||||
}
|
||||
if base.Type == "" {
|
||||
base.Type = update.Type
|
||||
}
|
||||
if base.Status == "" {
|
||||
base.Status = update.Status
|
||||
}
|
||||
if base.Role == "" {
|
||||
base.Role = update.Role
|
||||
}
|
||||
if base.CallID == "" {
|
||||
base.CallID = update.CallID
|
||||
}
|
||||
if base.Name == "" {
|
||||
base.Name = update.Name
|
||||
}
|
||||
if base.Arguments == "" {
|
||||
base.Arguments = update.Arguments
|
||||
}
|
||||
if base.Encrypted == "" {
|
||||
base.Encrypted = update.Encrypted
|
||||
}
|
||||
if len(base.Content) == 0 {
|
||||
base.Content = update.Content
|
||||
}
|
||||
if len(base.Summary) == 0 {
|
||||
base.Summary = update.Summary
|
||||
}
|
||||
if base.Action == nil {
|
||||
base.Action = update.Action
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
func (c *streamConverter) reasoningOutputEnabled() bool {
|
||||
return c.operation == OperationChat || (c.operation == OperationMessages && c.options.AnthropicThinking)
|
||||
}
|
||||
@@ -674,13 +858,23 @@ func (c *streamConverter) done(status string) error {
|
||||
if err := c.start(); err != nil {
|
||||
return err
|
||||
}
|
||||
var err error
|
||||
if err := c.flushPendingReasoning(); err != nil {
|
||||
return err
|
||||
}
|
||||
if c.operation == OperationChat {
|
||||
return c.doneChat(status)
|
||||
err = c.doneChat(status)
|
||||
} else {
|
||||
err = c.doneMessages(status)
|
||||
}
|
||||
return c.doneMessages(status)
|
||||
if err == nil && c.terminalEvent {
|
||||
// Commit only after the downstream terminal event was written. If the
|
||||
// upstream failed, the client abandoned the pipe, or the source ended
|
||||
// without a terminal Responses event, a partially observed tool turn must
|
||||
// not become replayable state.
|
||||
c.commitReasoningReplay()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *streamConverter) streamError(data []byte) error {
|
||||
|
||||
Reference in new issue
Block a user