diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index 05e2261f..947a043f 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -918,6 +918,7 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string EventID: eventID, RequestID: input.RequestID, ClientKeyID: input.ClientKey.ID, ClientKeyName: input.ClientKey.Name, ModelRouteID: route.ID, ModelPublicID: publicModel, ModelUpstreamModel: modeldomain.DisplayUpstreamModel(route.Provider, route.UpstreamModel), Provider: string(route.Provider), Operation: operation, UsageSource: audit.UsageSourceNone, Streaming: input.Streaming, + ReasoningEffort: audit.ExtractReasoningEffort(input.Body), MediaInputImages: mediaSummary.InputImages, } if errors.Is(routeErr, clientkeyapp.ErrModelNotAllowed) { diff --git a/backend/internal/application/gateway/service_test.go b/backend/internal/application/gateway/service_test.go index 6be8cc6c..38936fa3 100644 --- a/backend/internal/application/gateway/service_test.go +++ b/backend/internal/application/gateway/service_test.go @@ -202,7 +202,7 @@ func TestGatewayFailsOverBeforeReturningBody(t *testing.T) { clientService := clientkeyapp.NewService(nil, nil, nil, 60, 4, nil) selector := NewSelector(accountRepo, concurrency, sticky, registry, time.Hour, time.Second, time.Minute) service := NewService(modelRepo, auditRepo, accountService, clientService, registry, selector, responseRepo, 3) - result, err := service.CreateResponse(ctx, Input{RequestID: "req-1", ClientKey: clientKey, PublicModel: "grok-test", Body: []byte(`{"model":"grok-test"}`), PromptCacheSeed: "claude-session", GrokTurnIndex: "3"}) + result, err := service.CreateResponse(ctx, Input{RequestID: "req-1", ClientKey: clientKey, PublicModel: "grok-test", Body: []byte(`{"model":"grok-test","reasoning":{"effort":"high"}}`), PromptCacheSeed: "claude-session", GrokTurnIndex: "3"}) if err != nil { t.Fatal(err) } @@ -237,7 +237,7 @@ func TestGatewayFailsOverBeforeReturningBody(t *testing.T) { t.Fatalf("observed account = %#v, err = %v", observedAccount, err) } logs, total, err := auditRepo.List(ctx, 0, 10) - if err != nil || total != 1 || logs[0].AccountID == nil || *logs[0].AccountID != second.ID || logs[0].ClientKeyName != "test-key" || logs[0].ModelPublicID != "grok-test" || logs[0].ModelUpstreamModel != "Build/grok-test" || logs[0].AccountName != "second" || logs[0].CachedInputTokens != 80 || logs[0].UsageSource != audit.UsageSourceUpstream || logs[0].StatusCode != http.StatusOK || logs[0].AttemptCount != 1 { + if err != nil || total != 1 || logs[0].AccountID == nil || *logs[0].AccountID != second.ID || logs[0].ClientKeyName != "test-key" || logs[0].ModelPublicID != "grok-test" || logs[0].ModelUpstreamModel != "Build/grok-test" || logs[0].ReasoningEffort != "high" || logs[0].AccountName != "second" || logs[0].CachedInputTokens != 80 || logs[0].UsageSource != audit.UsageSourceUpstream || logs[0].StatusCode != http.StatusOK || logs[0].AttemptCount != 1 { t.Fatalf("audit = %#v, %d, %v", logs, total, err) } detail, err := auditRepo.Get(ctx, logs[0].ID) diff --git a/backend/internal/domain/audit/audit.go b/backend/internal/domain/audit/audit.go index 1cbb1a54..18882586 100644 --- a/backend/internal/domain/audit/audit.go +++ b/backend/internal/domain/audit/audit.go @@ -82,6 +82,7 @@ type Record struct { Provider string Operation Operation UsageSource UsageSource + ReasoningEffort string AccountID *uint64 AccountName string EgressNodeID *uint64 diff --git a/backend/internal/domain/audit/reasoning_effort.go b/backend/internal/domain/audit/reasoning_effort.go new file mode 100644 index 00000000..8c05aeda --- /dev/null +++ b/backend/internal/domain/audit/reasoning_effort.go @@ -0,0 +1,91 @@ +package audit + +import ( + "encoding/json" + "strconv" + "strings" +) + +// ExtractReasoningEffort reads the client-facing reasoning setting used by +// Responses, Chat Completions, and Anthropic Messages requests. +func ExtractReasoningEffort(body []byte) string { + if len(body) == 0 { + return "" + } + var root map[string]any + if json.Unmarshal(body, &root) != nil || root == nil { + return "" + } + if value := normalizeReasoningEffort(root["reasoning_effort"]); value != "" { + return value + } + if nested, ok := root["reasoning"].(map[string]any); ok { + if value := normalizeReasoningEffort(nested["effort"]); value != "" { + return value + } + } + if nested, ok := root["output_config"].(map[string]any); ok { + if value := normalizeReasoningEffort(nested["effort"]); value != "" { + return value + } + } + if nested, ok := root["thinking"].(map[string]any); ok { + if value := normalizeReasoningEffort(nested["effort"]); value != "" { + return value + } + typeName := strings.ToLower(strings.TrimSpace(reasoningString(nested["type"]))) + if typeName == "enabled" || typeName == "adaptive" { + if budget, ok := reasoningNumber(nested["budget_tokens"]); ok && budget > 0 { + return "thinking:" + strconv.FormatInt(int64(budget), 10) + } + return typeName + } + if typeName == "disabled" { + return "none" + } + } + return "" +} + +func normalizeReasoningEffort(raw any) string { + value := strings.ToLower(strings.TrimSpace(reasoningString(raw))) + if value == "" || value == "null" { + return "" + } + runes := []rune(value) + if len(runes) > 32 { + return string(runes[:32]) + } + return value +} + +func reasoningString(value any) string { + switch typed := value.(type) { + case string: + return typed + case float64: + if typed == float64(int64(typed)) { + return strconv.FormatInt(int64(typed), 10) + } + return strconv.FormatFloat(typed, 'f', -1, 64) + case json.Number: + return typed.String() + default: + return "" + } +} + +func reasoningNumber(value any) (float64, bool) { + switch typed := value.(type) { + case float64: + return typed, true + case json.Number: + number, err := typed.Float64() + return number, err == nil + case string: + number, err := strconv.ParseFloat(strings.TrimSpace(typed), 64) + return number, err == nil + default: + return 0, false + } +} diff --git a/backend/internal/domain/audit/reasoning_effort_test.go b/backend/internal/domain/audit/reasoning_effort_test.go new file mode 100644 index 00000000..30e4ff8d --- /dev/null +++ b/backend/internal/domain/audit/reasoning_effort_test.go @@ -0,0 +1,30 @@ +package audit + +import ( + "strings" + "testing" +) + +func TestExtractReasoningEffort(t *testing.T) { + tests := []struct { + name string + body string + want string + }{ + {name: "chat", body: `{"model":"grok-4.6","reasoning_effort":"XHIGH"}`, want: "xhigh"}, + {name: "responses", body: `{"reasoning":{"effort":"high"}}`, want: "high"}, + {name: "messages output config", body: `{"output_config":{"effort":"medium"},"thinking":{"type":"adaptive"}}`, want: "medium"}, + {name: "thinking budget", body: `{"thinking":{"type":"enabled","budget_tokens":32000}}`, want: "thinking:32000"}, + {name: "thinking disabled", body: `{"thinking":{"type":"disabled"}}`, want: "none"}, + {name: "missing", body: `{"model":"grok-4.6"}`, want: ""}, + {name: "malformed", body: `{`, want: ""}, + {name: "bounded", body: `{"reasoning_effort":"` + strings.Repeat("x", 40) + `"}`, want: strings.Repeat("x", 32)}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := ExtractReasoningEffort([]byte(test.body)); got != test.want { + t.Fatalf("got %q, want %q", got, test.want) + } + }) + } +} diff --git a/backend/internal/infra/persistence/relational/audit_repository.go b/backend/internal/infra/persistence/relational/audit_repository.go index b908ce71..bbb78e64 100644 --- a/backend/internal/infra/persistence/relational/audit_repository.go +++ b/backend/internal/infra/persistence/relational/audit_repository.go @@ -351,7 +351,8 @@ func toAuditModels(value audit.Record) (requestAuditModel, []requestAuditAttempt EventID: truncate(eventID, 64), RequestID: truncate(value.RequestID, 64), ClientKeyID: value.ClientKeyID, ClientKeyName: truncate(value.ClientKeyName, 160), ModelRouteID: value.ModelRouteID, ModelPublicID: truncate(value.ModelPublicID, 255), ModelUpstreamModel: truncate(value.ModelUpstreamModel, 255), Provider: truncate(provider, 32), Operation: string(operation), UsageSource: string(usageSource), - AccountID: value.AccountID, AccountName: truncate(value.AccountName, 160), + ReasoningEffort: truncate(value.ReasoningEffort, 32), + AccountID: value.AccountID, AccountName: truncate(value.AccountName, 160), EgressNodeID: value.EgressNodeID, EgressNodeName: truncate(value.EgressNodeName, 160), EgressScope: truncate(value.EgressScope, 32), EgressMode: string(value.EgressMode), StatusCode: value.StatusCode, Streaming: value.Streaming, MediaInputImages: nonNegative(value.MediaInputImages), MediaOutputImages: nonNegative(value.MediaOutputImages), MediaOutputSeconds: nonNegative(value.MediaOutputSeconds), diff --git a/backend/internal/infra/persistence/relational/audit_repository_test.go b/backend/internal/infra/persistence/relational/audit_repository_test.go index 5525b12b..b8a4a735 100644 --- a/backend/internal/infra/persistence/relational/audit_repository_test.go +++ b/backend/internal/infra/persistence/relational/audit_repository_test.go @@ -61,7 +61,7 @@ func TestAuditRepositoryBatchAndCursor(t *testing.T) { {RequestID: "cursor-old", ClientKeyID: 1, ModelRouteID: 1, StatusCode: 200, CreatedAt: now.Add(-48 * time.Hour)}, {RequestID: "cursor-1", ClientKeyID: 1, ModelRouteID: 1, StatusCode: 200, CreatedAt: now.Add(-3 * time.Minute)}, {RequestID: "cursor-2", ClientKeyID: 1, ModelRouteID: 1, StatusCode: 200, CreatedAt: now.Add(-2 * time.Minute)}, - {RequestID: "cursor-3", ClientKeyID: 1, ClientKeyName: "production", ModelRouteID: 1, ModelPublicID: "grok-test", ModelUpstreamModel: "grok-test-upstream", AccountName: "primary", EgressNodeID: uint64Pointer(42), EgressNodeName: "proxy-shanghai", EgressScope: "grok_web", EgressMode: audit.EgressModeProxy, StatusCode: 200, CreatedAt: now.Add(-time.Minute)}, + {RequestID: "cursor-3", ClientKeyID: 1, ClientKeyName: "production", ModelRouteID: 1, ModelPublicID: "grok-test", ModelUpstreamModel: "grok-test-upstream", ReasoningEffort: "xhigh", AccountName: "primary", EgressNodeID: uint64Pointer(42), EgressNodeName: "proxy-shanghai", EgressScope: "grok_web", EgressMode: audit.EgressModeProxy, StatusCode: 200, CreatedAt: now.Add(-time.Minute)}, } if err := repository.CreateBatch(ctx, values); err != nil { t.Fatal(err) @@ -74,7 +74,7 @@ func TestAuditRepositoryBatchAndCursor(t *testing.T) { if len(first) != 2 || !hasMore || first[0].ID <= first[1].ID { t.Fatalf("first page = %#v, hasMore = %v", first, hasMore) } - if first[0].ClientKeyName != "production" || first[0].ModelPublicID != "grok-test" || first[0].ModelUpstreamModel != "grok-test-upstream" || first[0].AccountName != "primary" || first[0].EgressNodeID == nil || *first[0].EgressNodeID != 42 || first[0].EgressNodeName != "proxy-shanghai" || first[0].EgressMode != audit.EgressModeProxy { + if first[0].ClientKeyName != "production" || first[0].ModelPublicID != "grok-test" || first[0].ModelUpstreamModel != "grok-test-upstream" || first[0].ReasoningEffort != "xhigh" || first[0].AccountName != "primary" || first[0].EgressNodeID == nil || *first[0].EgressNodeID != 42 || first[0].EgressNodeName != "proxy-shanghai" || first[0].EgressMode != audit.EgressModeProxy { t.Fatalf("audit snapshots = %#v", first[0]) } matched, _, err := repository.ListCursor(ctx, repositorypkg.AuditCursorQuery{Limit: 10, Search: "proxy-shanghai", Sort: sort}) diff --git a/backend/internal/infra/persistence/relational/mapping.go b/backend/internal/infra/persistence/relational/mapping.go index f37d6931..52db977d 100644 --- a/backend/internal/infra/persistence/relational/mapping.go +++ b/backend/internal/infra/persistence/relational/mapping.go @@ -254,7 +254,8 @@ func toAuditDomain(value requestAuditModel) audit.Record { ID: value.ID, EventID: value.EventID, RequestID: value.RequestID, ClientKeyID: value.ClientKeyID, ClientKeyName: value.ClientKeyName, ModelRouteID: value.ModelRouteID, ModelPublicID: value.ModelPublicID, ModelUpstreamModel: value.ModelUpstreamModel, Provider: value.Provider, Operation: audit.Operation(value.Operation), UsageSource: audit.UsageSource(value.UsageSource), - AccountID: value.AccountID, AccountName: value.AccountName, + ReasoningEffort: value.ReasoningEffort, + AccountID: value.AccountID, AccountName: value.AccountName, EgressNodeID: value.EgressNodeID, EgressNodeName: value.EgressNodeName, EgressScope: value.EgressScope, EgressMode: audit.EgressMode(value.EgressMode), StatusCode: value.StatusCode, Streaming: value.Streaming, MediaInputImages: value.MediaInputImages, MediaOutputImages: value.MediaOutputImages, MediaOutputSeconds: value.MediaOutputSeconds, diff --git a/backend/internal/infra/persistence/relational/models.go b/backend/internal/infra/persistence/relational/models.go index 966fd6e4..676ca6d0 100644 --- a/backend/internal/infra/persistence/relational/models.go +++ b/backend/internal/infra/persistence/relational/models.go @@ -299,6 +299,7 @@ type requestAuditModel struct { Provider string `gorm:"size:32;not null;check:chk_request_audits_provider,provider IN ('grok_build','grok_web','grok_console')"` Operation string `gorm:"size:32;not null;check:chk_request_audits_operation,operation IN ('responses','compaction','chat','messages','image','image_edit','video','tts','stt','realtime','voice')"` UsageSource string `gorm:"size:16;not null;check:chk_request_audits_usage_source,usage_source IN ('upstream','estimated','none')"` + ReasoningEffort string `gorm:"size:32;not null;default:'';check:chk_request_audits_reasoning_effort,length(reasoning_effort) <= 32"` AccountID *uint64 `gorm:"check:chk_request_audits_account_id,account_id IS NULL OR account_id > 0"` AccountName string `gorm:"size:160;check:chk_request_audits_account_name,length(account_name) <= 160"` EgressNodeID *uint64 `gorm:"check:chk_request_audits_egress_node_id,egress_node_id IS NULL OR egress_node_id > 0"` diff --git a/backend/internal/transport/http/audit/handler.go b/backend/internal/transport/http/audit/handler.go index 580c75b5..0c22e741 100644 --- a/backend/internal/transport/http/audit/handler.go +++ b/backend/internal/transport/http/audit/handler.go @@ -94,6 +94,7 @@ type auditResponse struct { Provider string `json:"provider"` Operation string `json:"operation"` UsageSource string `json:"usageSource"` + ReasoningEffort string `json:"reasoningEffort,omitempty"` AccountID *uint64 `json:"accountId,string,omitempty"` AccountName string `json:"accountName,omitempty"` EgressNodeID *uint64 `json:"egressNodeId,string,omitempty"` @@ -474,7 +475,8 @@ func newAuditResponse(value auditdomain.Record) auditResponse { ID: value.ID, RequestID: value.RequestID, ClientKeyID: value.ClientKeyID, ClientKeyName: value.ClientKeyName, ModelRouteID: value.ModelRouteID, ModelPublicID: value.ModelPublicID, ModelUpstreamModel: value.ModelUpstreamModel, Provider: value.Provider, Operation: string(value.Operation), UsageSource: string(value.UsageSource), - AccountID: value.AccountID, AccountName: value.AccountName, + ReasoningEffort: value.ReasoningEffort, + AccountID: value.AccountID, AccountName: value.AccountName, EgressNodeID: value.EgressNodeID, EgressNodeName: value.EgressNodeName, EgressScope: value.EgressScope, EgressMode: string(value.EgressMode), StatusCode: value.StatusCode, Streaming: value.Streaming, MediaInputImages: value.MediaInputImages, MediaOutputImages: value.MediaOutputImages, MediaOutputSeconds: value.MediaOutputSeconds, diff --git a/backend/internal/transport/http/audit/handler_test.go b/backend/internal/transport/http/audit/handler_test.go index d5a270dc..d2e8d06d 100644 --- a/backend/internal/transport/http/audit/handler_test.go +++ b/backend/internal/transport/http/audit/handler_test.go @@ -84,8 +84,8 @@ func TestAuditDetailReturnsCompleteTextAndBinaryBodies(t *testing.T) { func TestAuditResponseDerivesOutputThroughput(t *testing.T) { firstTokenMS := int64(250) - response := newAuditResponse(auditdomain.Record{StatusCode: http.StatusOK, Streaming: true, FirstTokenMS: &firstTokenMS, DurationMS: 1250, OutputTokens: 80}) - if response.FirstTokenMS == nil || *response.FirstTokenMS != 250 || response.OutputTokensPerSecond == nil || *response.OutputTokensPerSecond != 80 { + response := newAuditResponse(auditdomain.Record{StatusCode: http.StatusOK, Streaming: true, ReasoningEffort: "high", FirstTokenMS: &firstTokenMS, DurationMS: 1250, OutputTokens: 80}) + if response.ReasoningEffort != "high" || response.FirstTokenMS == nil || *response.FirstTokenMS != 250 || response.OutputTokensPerSecond == nil || *response.OutputTokensPerSecond != 80 { t.Fatalf("response = %#v", response) } diff --git a/frontend/src/features/audits/request-audit-detail-dialog.tsx b/frontend/src/features/audits/request-audit-detail-dialog.tsx index d52efb48..f81810e4 100644 --- a/frontend/src/features/audits/request-audit-detail-dialog.tsx +++ b/frontend/src/features/audits/request-audit-detail-dialog.tsx @@ -43,6 +43,7 @@ export function RequestAuditDetailDialog({ audit, open, onOpenChange }: { audit: {t("audits.detailTitle")} {audit?.requestId} + {audit?.reasoningEffort ? {t("audits.reasoningEffort")}: {audit.reasoningEffort} : null} {audit ? {formatDateTime(audit.createdAt, i18n.language)} : null} diff --git a/frontend/src/features/audits/request-audits-api.ts b/frontend/src/features/audits/request-audits-api.ts index ffe4d976..d2f35541 100644 --- a/frontend/src/features/audits/request-audits-api.ts +++ b/frontend/src/features/audits/request-audits-api.ts @@ -34,6 +34,7 @@ export type AuditDTO = { provider: "grok_build" | "grok_web" | "grok_console"; operation: "responses" | "compaction" | "chat" | "messages" | "image" | "image_edit" | "video" | "tts" | "stt" | "realtime" | "voice"; usageSource: "upstream" | "estimated" | "none"; + reasoningEffort?: string; accountId?: string; accountName?: string; egressNodeId?: string; @@ -142,6 +143,7 @@ const auditValidator = hasShape({ id: isString, requestId: isString, clientKeyId: isString, clientKeyName: isOptional(isString), modelRouteId: isString, modelPublicId: isOptional(isString), modelUpstreamModel: isOptional(isString), provider: isOneOf("grok_build", "grok_web", "grok_console"), operation: isOneOf("responses", "compaction", "chat", "messages", "image", "image_edit", "video", "tts", "stt", "realtime", "voice"), usageSource: isOneOf("upstream", "estimated", "none"), + reasoningEffort: isOptional(isString), accountId: isOptional(isString), accountName: isOptional(isString), egressNodeId: isOptional(isString), egressNodeName: isOptional(isString), egressScope: isOptional(isOneOf("grok_build", "grok_web", "grok_console", "grok_web_asset", "grok_console_asset")), egressMode: isOptional(isOneOf("direct", "proxy")), diff --git a/frontend/src/features/audits/request-audits-page.tsx b/frontend/src/features/audits/request-audits-page.tsx index 19cc5077..0196a43c 100644 --- a/frontend/src/features/audits/request-audits-page.tsx +++ b/frontend/src/features/audits/request-audits-page.tsx @@ -371,10 +371,14 @@ function splitDuration(value: string): { value: string; unit: string } { function RequestValue({ audit }: { audit: AuditDTO }) { const { t } = useTranslation(); + const effort = audit.reasoningEffort?.trim(); return (
{providerLabel(audit.provider)} · {t(`audits.operations.${audit.operation}`)} - {audit.requestId} + + {audit.requestId} + {effort ? {effort} : null} + {audit.numSourcesUsed > 0 ? ( {t("audits.sources", { count: audit.numSourcesUsed })} ) : null} diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index 7a2f9c76..d193c006 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -872,6 +872,7 @@ const resources = { createdAt: "时间", stream: "流式", nonStream: "非流式", + reasoningEffort: "思考强度", cursorPage: "第 {{page}} 页", key: "密钥", keyFilterPlaceholder: "输入密钥名称或 ID", @@ -1584,6 +1585,7 @@ const resources = { createdAt: "Time", stream: "Streaming", nonStream: "Non-streaming", + reasoningEffort: "Reasoning effort", cursorPage: "Page {{page}}", key: "Key", keyFilterPlaceholder: "Enter key name or ID",