mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-06 08:02:14 +00:00
feat(audit): record reasoning effort
This commit is contained in:
1 parent
57746fc702
commit
b91bdbdbcc
15 files changed
+147
-10
No files matched your search
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -82,6 +82,7 @@ type Record struct {
|
||||
Provider string
|
||||
Operation Operation
|
||||
UsageSource UsageSource
|
||||
ReasoningEffort string
|
||||
AccountID *uint64
|
||||
AccountName string
|
||||
EgressNodeID *uint64
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
|
||||
@@ -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})
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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"`
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@ export function RequestAuditDetailDialog({ audit, open, onOpenChange }: { audit:
|
||||
<DialogTitle>{t("audits.detailTitle")}</DialogTitle>
|
||||
<DialogDescription className="flex min-w-0 flex-wrap gap-x-4 gap-y-0.5">
|
||||
<span className="truncate" title={audit?.requestId}>{audit?.requestId}</span>
|
||||
{audit?.reasoningEffort ? <Badge variant="secondary">{t("audits.reasoningEffort")}: {audit.reasoningEffort}</Badge> : null}
|
||||
{audit ? <span>{formatDateTime(audit.createdAt, i18n.language)}</span> : null}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
@@ -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")),
|
||||
|
||||
@@ -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 (
|
||||
<div className="min-w-0">
|
||||
<span className="block truncate text-xs font-medium">{providerLabel(audit.provider)} · {t(`audits.operations.${audit.operation}`)}</span>
|
||||
<span className="mt-0.5 block truncate font-mono text-[10px] text-muted-foreground" title={audit.requestId}>{audit.requestId}</span>
|
||||
<span className="mt-0.5 flex min-w-0 items-center gap-1.5">
|
||||
<span className="block min-w-0 truncate font-mono text-[10px] text-muted-foreground" title={audit.requestId}>{audit.requestId}</span>
|
||||
{effort ? <span className="shrink-0 rounded bg-violet-500/10 px-1.5 py-0.5 text-[10px] font-medium text-violet-700 dark:text-violet-300" title={t("audits.reasoningEffort")}>{effort}</span> : null}
|
||||
</span>
|
||||
{audit.numSourcesUsed > 0 ? (
|
||||
<span className="mt-0.5 block truncate text-[10px] text-muted-foreground">{t("audits.sources", { count: audit.numSourcesUsed })}</span>
|
||||
) : null}
|
||||
|
||||
@@ -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",
|
||||
|
||||
Reference in new issue
Block a user