diff --git a/core/schemas/bifrost.go b/core/schemas/bifrost.go
index a58f407f34c..0e632058282 100644
--- a/core/schemas/bifrost.go
+++ b/core/schemas/bifrost.go
@@ -335,6 +335,8 @@ const (
BifrostContextKeyRoutingAllowedProviders BifrostContextKey = "bifrost-routing-allowed-providers" // []ModelProvider; when set, downstream routing layers (enterprise LB, model-catalog-resolver) must intersect their candidate providers with this set. Plugins set this when they have an opinion about which providers are valid for the request — even if they couldn't pick one themselves. Empty slice means "no provider is permitted" (fail-closed).
BifrostContextKeyAllowPerRequestStorageOverride BifrostContextKey = "bifrost-allow-per-request-storage-override" // bool (set by transport from config — gates whether x-bf-disable-content-logging and x-bf-store-raw-request-response per-request overrides are honored)
BifrostContextKeyAllowPerRequestRawOverride BifrostContextKey = "bifrost-allow-per-request-raw-override" // bool (set by transport from config — gates whether x-bf-send-back-raw-request and x-bf-send-back-raw-response per-request overrides are honored)
+ BifrostContextKeyGuardrailDebug BifrostContextKey = "bifrost-guardrail-debug" // *BifrostGuardrailDebug (set by enterprise guardrails plugin - DO NOT SET THIS MANUALLY)
+ BifrostContextKeyCacheDebug BifrostContextKey = "bifrost-cache-debug" // *BifrostCacheDebug (set by semantic cache plugin - DO NOT SET THIS MANUALLY)
BifrostContextKeyRedactionData BifrostContextKey = "bifrost-redaction-data" // RedactionData (set by enterprise guardrails plugin - DO NOT SET THIS MANUALLY)
BifrostContextKeyDisableContentLogging BifrostContextKey = "x-bf-disable-content-logging" // bool (per-request override for content logging; only honored when BifrostContextKeyAllowPerRequestStorageOverride is true. When retain_content_in_object_storage is on, disabled content is still offloaded to object storage as hidden instead of dropped)
BifrostContextKeySkipListModelsGovernanceFiltering BifrostContextKey = "bifrost-skip-list-models-governance-filtering" // bool (set by bifrost - DO NOT SET THIS MANUALLY))
@@ -1700,27 +1702,28 @@ type BifrostResponseExtraFields struct {
// matched (i.e. RoutingInfo.ResolvedKeyAlias != nil), otherwise
// RoutingInfo.Model. Still populated for backward compatibility; new
// consumers should read from RoutingInfo.
- ResolvedModelUsed string `json:"resolved_model_used,omitempty"`
- Latency int64 `json:"latency"` // in milliseconds (for streaming responses this will be each chunk latency, and the last chunk latency will be the total latency)
+ ResolvedModelUsed string `json:"resolved_model_used,omitempty"`
+ Latency int64 `json:"latency"` // in milliseconds (for streaming responses this will be each chunk latency, and the last chunk latency will be the total latency)
// UpstreamLatency is the total time spent blocked on upstream sockets across
// every attempt, in milliseconds. Unlike Latency it survives retries and
// fallbacks, so total-UpstreamLatency is Bifrost's own cost. Nil when the
// request never accumulated one; nil means unknown, not zero.
UpstreamLatency *int64 `json:"upstream_latency,omitempty"`
- ChunkIndex int `json:"chunk_index"` // used for streaming responses to identify the chunk index, will be 0 for non-streaming responses
- RawRequest interface{} `json:"raw_request,omitempty"`
- RawResponse interface{} `json:"raw_response,omitempty"`
- CacheDebug *BifrostCacheDebug `json:"cache_debug,omitempty"`
- ParseErrors []BatchError `json:"parse_errors,omitempty"` // errors encountered while parsing JSONL batch results
- ConvertedRequestType RequestType `json:"converted_request_type,omitempty"`
- DroppedCompatPluginParams []string `json:"dropped_compat_plugin_params,omitempty"` // params dropped by the compat plugin based on model catalog
+ ChunkIndex int `json:"chunk_index"` // used for streaming responses to identify the chunk index, will be 0 for non-streaming responses
+ RawRequest interface{} `json:"raw_request,omitempty"`
+ RawResponse interface{} `json:"raw_response,omitempty"`
+ CacheDebug *BifrostCacheDebug `json:"cache_debug,omitempty"`
+ GuardrailDebug *BifrostGuardrailDebug `json:"guardrail_debug,omitempty"`
+ ParseErrors []BatchError `json:"parse_errors,omitempty"` // errors encountered while parsing JSONL batch results
+ ConvertedRequestType RequestType `json:"converted_request_type,omitempty"`
+ DroppedCompatPluginParams []string `json:"dropped_compat_plugin_params,omitempty"` // params dropped by the compat plugin based on model catalog
// DroppedUnsupportedTools lists tool type strings silently stripped from the
// request because the target provider/model doesn't support them (e.g.
// web_search requested against a non-Nova Bedrock model). Currently populated
// only by the Bedrock provider.
DroppedUnsupportedTools []string `json:"dropped_unsupported_tools,omitempty"`
- ProviderResponseHeaders map[string]string `json:"provider_response_headers,omitempty"` // HTTP response headers from the provider (filtered to exclude transport-level headers)
- PassthroughPath string `json:"passthrough_path,omitempty"` // Stripped provider path for passthrough requests, e.g. "/v1/chat/completions"
+ ProviderResponseHeaders map[string]string `json:"provider_response_headers,omitempty"` // HTTP response headers from the provider (filtered to exclude transport-level headers)
+ PassthroughPath string `json:"passthrough_path,omitempty"` // Stripped provider path for passthrough requests, e.g. "/v1/chat/completions"
}
type RoutingInfo struct {
diff --git a/core/schemas/cachedebug.go b/core/schemas/cachedebug.go
new file mode 100644
index 00000000000..decef104097
--- /dev/null
+++ b/core/schemas/cachedebug.go
@@ -0,0 +1,77 @@
+package schemas
+
+// Clone returns an owned snapshot of cache debug data.
+func (d *BifrostCacheDebug) Clone() *BifrostCacheDebug {
+ if d == nil {
+ return nil
+ }
+ clone := *d
+ clone.CacheID = cloneString(d.CacheID)
+ clone.HitType = cloneString(d.HitType)
+ clone.RequestedProvider = cloneString(d.RequestedProvider)
+ clone.RequestedModel = cloneString(d.RequestedModel)
+ clone.ProviderUsed = cloneString(d.ProviderUsed)
+ clone.ModelUsed = cloneString(d.ModelUsed)
+ clone.InputTokens = cloneInt(d.InputTokens)
+ clone.Threshold = cloneFloat64(d.Threshold)
+ clone.Similarity = cloneFloat64(d.Similarity)
+ clone.CacheHitLatency = cloneInt64(d.CacheHitLatency)
+ return &clone
+}
+
+// CacheDebugFromContext returns typed cache debug data stored on ctx.
+func CacheDebugFromContext(ctx *BifrostContext) (*BifrostCacheDebug, bool) {
+ if ctx == nil {
+ return nil, false
+ }
+ debug, ok := ctx.Value(BifrostContextKeyCacheDebug).(*BifrostCacheDebug)
+ if !ok || debug == nil || debug.ProviderUsed == nil || debug.ModelUsed == nil || debug.InputTokens == nil {
+ return nil, false
+ }
+ return debug.Clone(), true
+}
+
+// SetCacheDebugOnContext stores semantic cache debug data on ctx.
+func SetCacheDebugOnContext(ctx *BifrostContext, debug *BifrostCacheDebug) bool {
+ if ctx == nil || debug == nil || debug.ProviderUsed == nil || debug.ModelUsed == nil || debug.InputTokens == nil {
+ return false
+ }
+ ctx.SetValue(BifrostContextKeyCacheDebug, debug.Clone())
+ return true
+}
+
+// cloneString returns an owned copy of value.
+func cloneString(value *string) *string {
+ if value == nil {
+ return nil
+ }
+ clone := *value
+ return &clone
+}
+
+// cloneInt returns an owned copy of value.
+func cloneInt(value *int) *int {
+ if value == nil {
+ return nil
+ }
+ clone := *value
+ return &clone
+}
+
+// cloneFloat64 returns an owned copy of value.
+func cloneFloat64(value *float64) *float64 {
+ if value == nil {
+ return nil
+ }
+ clone := *value
+ return &clone
+}
+
+// cloneInt64 returns an owned copy of value.
+func cloneInt64(value *int64) *int64 {
+ if value == nil {
+ return nil
+ }
+ clone := *value
+ return &clone
+}
diff --git a/core/schemas/cachedebug_test.go b/core/schemas/cachedebug_test.go
new file mode 100644
index 00000000000..cdafcf53bee
--- /dev/null
+++ b/core/schemas/cachedebug_test.go
@@ -0,0 +1,29 @@
+package schemas
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// TestCacheDebugContextReturnsOwnedSnapshot verifies semantic cache metadata survives without aliases.
+func TestCacheDebugContextReturnsOwnedSnapshot(t *testing.T) {
+ ctx := NewBifrostContext(nil, NoDeadline)
+ provider := "openai"
+ model := "text-embedding-3-small"
+ inputTokens := 12
+ require.True(t, SetCacheDebugOnContext(ctx, &BifrostCacheDebug{
+ ProviderUsed: &provider,
+ ModelUsed: &model,
+ InputTokens: &inputTokens,
+ }))
+
+ first, ok := CacheDebugFromContext(ctx)
+ require.True(t, ok)
+ *first.InputTokens = 999
+
+ second, ok := CacheDebugFromContext(ctx)
+ require.True(t, ok)
+ assert.Equal(t, 12, *second.InputTokens)
+}
diff --git a/core/schemas/chatcompletions.go b/core/schemas/chatcompletions.go
index 451afb03e4a..f666e601aa7 100644
--- a/core/schemas/chatcompletions.go
+++ b/core/schemas/chatcompletions.go
@@ -92,6 +92,7 @@ func (cr *BifrostChatResponse) ToTextCompletionResponse() *BifrostTextCompletion
Latency: cr.ExtraFields.Latency,
RawResponse: cr.ExtraFields.RawResponse,
CacheDebug: cr.ExtraFields.CacheDebug,
+ GuardrailDebug: cr.ExtraFields.GuardrailDebug,
ProviderResponseHeaders: cr.ExtraFields.ProviderResponseHeaders,
},
}
@@ -126,6 +127,7 @@ func (cr *BifrostChatResponse) ToTextCompletionResponse() *BifrostTextCompletion
Latency: cr.ExtraFields.Latency,
RawResponse: cr.ExtraFields.RawResponse,
CacheDebug: cr.ExtraFields.CacheDebug,
+ GuardrailDebug: cr.ExtraFields.GuardrailDebug,
ProviderResponseHeaders: cr.ExtraFields.ProviderResponseHeaders,
},
}
@@ -163,6 +165,7 @@ func (cr *BifrostChatResponse) ToTextCompletionResponse() *BifrostTextCompletion
Latency: cr.ExtraFields.Latency,
RawResponse: cr.ExtraFields.RawResponse,
CacheDebug: cr.ExtraFields.CacheDebug,
+ GuardrailDebug: cr.ExtraFields.GuardrailDebug,
ProviderResponseHeaders: cr.ExtraFields.ProviderResponseHeaders,
},
}
@@ -184,6 +187,7 @@ func (cr *BifrostChatResponse) ToTextCompletionResponse() *BifrostTextCompletion
Latency: cr.ExtraFields.Latency,
RawResponse: cr.ExtraFields.RawResponse,
CacheDebug: cr.ExtraFields.CacheDebug,
+ GuardrailDebug: cr.ExtraFields.GuardrailDebug,
ProviderResponseHeaders: cr.ExtraFields.ProviderResponseHeaders,
},
}
diff --git a/core/schemas/guardraildebug.go b/core/schemas/guardraildebug.go
new file mode 100644
index 00000000000..c5c90db6b37
--- /dev/null
+++ b/core/schemas/guardraildebug.go
@@ -0,0 +1,110 @@
+package schemas
+
+// BifrostGuardrailDebug carries request-scoped guardrail execution metadata.
+type BifrostGuardrailDebug struct {
+ JudgeCalls []BifrostGuardrailJudgeCall `json:"judge_calls,omitempty"`
+}
+
+// BifrostGuardrailJudgeCall records one billable guardrail judge invocation.
+type BifrostGuardrailJudgeCall struct {
+ Phase string `json:"phase,omitempty"`
+ RuleID *uint `json:"rule_id,omitempty"`
+ RuleName string `json:"rule_name,omitempty"`
+ GuardrailName string `json:"guardrail_name,omitempty"`
+ GuardrailProvider string `json:"guardrail_provider,omitempty"`
+ Action string `json:"action,omitempty"`
+ Reason string `json:"reason,omitempty"`
+ JudgeProvider ModelProvider `json:"judge_provider,omitempty"`
+ JudgeModel string `json:"judge_model,omitempty"`
+ JudgeRequestType RequestType `json:"judge_request_type,omitempty"`
+ PromptTokens int `json:"prompt_tokens,omitempty"`
+ PromptTokensDetails *ChatPromptTokensDetails `json:"prompt_tokens_details,omitempty"`
+ CompletionTokens int `json:"completion_tokens,omitempty"`
+ CompletionTokensDetails *ChatCompletionTokensDetails `json:"completion_tokens_details,omitempty"`
+ TotalTokens int `json:"total_tokens,omitempty"`
+}
+
+// Clone returns an owned snapshot of the guardrail debug data.
+func (d *BifrostGuardrailDebug) Clone() *BifrostGuardrailDebug {
+ if d == nil || len(d.JudgeCalls) == 0 {
+ return nil
+ }
+ clone := &BifrostGuardrailDebug{
+ JudgeCalls: make([]BifrostGuardrailJudgeCall, len(d.JudgeCalls)),
+ }
+ for index, call := range d.JudgeCalls {
+ clone.JudgeCalls[index] = call
+ clone.JudgeCalls[index].RuleID = cloneUint(call.RuleID)
+ clone.JudgeCalls[index].PromptTokensDetails = cloneChatPromptTokensDetails(call.PromptTokensDetails)
+ clone.JudgeCalls[index].CompletionTokensDetails = cloneChatCompletionTokensDetails(call.CompletionTokensDetails)
+ }
+ return clone
+}
+
+// cloneChatPromptTokensDetails returns an owned copy of nested prompt token details.
+func cloneChatPromptTokensDetails(details *ChatPromptTokensDetails) *ChatPromptTokensDetails {
+ if details == nil {
+ return nil
+ }
+ clone := *details
+ if details.CachedWriteTokenDetails != nil {
+ cachedWriteClone := *details.CachedWriteTokenDetails
+ clone.CachedWriteTokenDetails = &cachedWriteClone
+ }
+ return &clone
+}
+
+// cloneChatCompletionTokensDetails returns an owned copy of completion token details.
+func cloneChatCompletionTokensDetails(details *ChatCompletionTokensDetails) *ChatCompletionTokensDetails {
+ if details == nil {
+ return nil
+ }
+ clone := *details
+ clone.CitationTokens = cloneInt(details.CitationTokens)
+ clone.NumSearchQueries = cloneInt(details.NumSearchQueries)
+ clone.ImageTokens = cloneInt(details.ImageTokens)
+ return &clone
+}
+
+// cloneUint returns an owned copy of value.
+func cloneUint(value *uint) *uint {
+ if value == nil {
+ return nil
+ }
+ clone := *value
+ return &clone
+}
+
+// GuardrailDebugFromContext returns typed guardrail debug data stored on ctx.
+func GuardrailDebugFromContext(ctx *BifrostContext) (*BifrostGuardrailDebug, bool) {
+ if ctx == nil {
+ return nil, false
+ }
+ debug, ok := ctx.Value(BifrostContextKeyGuardrailDebug).(*BifrostGuardrailDebug)
+ if !ok || debug == nil || len(debug.JudgeCalls) == 0 {
+ return nil, false
+ }
+ return debug.Clone(), true
+}
+
+// SetGuardrailDebugOnContext stores non-empty guardrail debug data on ctx.
+func SetGuardrailDebugOnContext(ctx *BifrostContext, debug *BifrostGuardrailDebug) bool {
+ if ctx == nil || debug == nil || len(debug.JudgeCalls) == 0 {
+ return false
+ }
+ ctx.SetValue(BifrostContextKeyGuardrailDebug, debug.Clone())
+ return true
+}
+
+// AppendGuardrailJudgeCallOnContext appends one guardrail judge call to ctx.
+func AppendGuardrailJudgeCallOnContext(ctx *BifrostContext, call BifrostGuardrailJudgeCall) bool {
+ if ctx == nil || call.TotalTokens == 0 && call.PromptTokens == 0 && call.CompletionTokens == 0 {
+ return false
+ }
+ current, _ := GuardrailDebugFromContext(ctx)
+ if current == nil {
+ current = &BifrostGuardrailDebug{}
+ }
+ current.JudgeCalls = append(current.JudgeCalls, call)
+ return SetGuardrailDebugOnContext(ctx, current)
+}
diff --git a/core/schemas/guardraildebug_test.go b/core/schemas/guardraildebug_test.go
new file mode 100644
index 00000000000..4c2037d6133
--- /dev/null
+++ b/core/schemas/guardraildebug_test.go
@@ -0,0 +1,82 @@
+package schemas
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// TestGuardrailDebugContextRoundTrip verifies typed guardrail debug context storage.
+func TestGuardrailDebugContextRoundTrip(t *testing.T) {
+ ctx := NewBifrostContext(nil, NoDeadline)
+ call := BifrostGuardrailJudgeCall{
+ Phase: "input",
+ RuleName: "pii",
+ JudgeProvider: OpenAI,
+ JudgeModel: "gpt-4o-mini",
+ PromptTokens: 12,
+ TotalTokens: 12,
+ }
+
+ require.True(t, AppendGuardrailJudgeCallOnContext(ctx, call))
+ debug, ok := GuardrailDebugFromContext(ctx)
+ require.True(t, ok)
+ require.Len(t, debug.JudgeCalls, 1)
+ assert.Equal(t, call, debug.JudgeCalls[0])
+}
+
+// TestGuardrailDebugContextReturnsOwnedSnapshot verifies callers cannot mutate context state.
+func TestGuardrailDebugContextReturnsOwnedSnapshot(t *testing.T) {
+ ctx := NewBifrostContext(nil, NoDeadline)
+ require.True(t, AppendGuardrailJudgeCallOnContext(ctx, BifrostGuardrailJudgeCall{
+ JudgeProvider: OpenAI,
+ JudgeModel: "gpt-4o-mini",
+ TotalTokens: 10,
+ }))
+
+ first, ok := GuardrailDebugFromContext(ctx)
+ require.True(t, ok)
+ first.JudgeCalls[0].TotalTokens = 999
+
+ second, ok := GuardrailDebugFromContext(ctx)
+ require.True(t, ok)
+ assert.Equal(t, 10, second.JudgeCalls[0].TotalTokens)
+}
+
+// TestGuardrailDebugContextClonesUsageDetails verifies nested pricing details cannot alias context state.
+func TestGuardrailDebugContextClonesUsageDetails(t *testing.T) {
+ ctx := NewBifrostContext(nil, NoDeadline)
+ citationTokens := 3
+ require.True(t, AppendGuardrailJudgeCallOnContext(ctx, BifrostGuardrailJudgeCall{
+ JudgeProvider: OpenAI,
+ JudgeModel: "gpt-4o-mini",
+ PromptTokens: 10,
+ PromptTokensDetails: &ChatPromptTokensDetails{
+ CachedWriteTokenDetails: &ChatCachedWriteTokenDetails{CachedWriteTokens5m: 4},
+ },
+ CompletionTokens: 5,
+ CompletionTokensDetails: &ChatCompletionTokensDetails{
+ CitationTokens: &citationTokens,
+ },
+ TotalTokens: 15,
+ }))
+
+ first, ok := GuardrailDebugFromContext(ctx)
+ require.True(t, ok)
+ first.JudgeCalls[0].PromptTokensDetails.CachedWriteTokenDetails.CachedWriteTokens5m = 999
+ *first.JudgeCalls[0].CompletionTokensDetails.CitationTokens = 999
+
+ second, ok := GuardrailDebugFromContext(ctx)
+ require.True(t, ok)
+ assert.Equal(t, 4, second.JudgeCalls[0].PromptTokensDetails.CachedWriteTokenDetails.CachedWriteTokens5m)
+ assert.Equal(t, 3, *second.JudgeCalls[0].CompletionTokensDetails.CitationTokens)
+}
+
+// TestAppendGuardrailJudgeCallRejectsEmptyUsage verifies non-billable calls are omitted.
+func TestAppendGuardrailJudgeCallRejectsEmptyUsage(t *testing.T) {
+ ctx := NewBifrostContext(nil, NoDeadline)
+ assert.False(t, AppendGuardrailJudgeCallOnContext(ctx, BifrostGuardrailJudgeCall{}))
+ _, ok := GuardrailDebugFromContext(ctx)
+ assert.False(t, ok)
+}
diff --git a/core/schemas/mux.go b/core/schemas/mux.go
index 13bc789b29c..3212d079e2e 100644
--- a/core/schemas/mux.go
+++ b/core/schemas/mux.go
@@ -2627,6 +2627,7 @@ func (cr *BifrostChatResponse) ToBifrostTextCompletionResponse() *BifrostTextCom
Latency: cr.ExtraFields.Latency,
RawResponse: cr.ExtraFields.RawResponse,
CacheDebug: cr.ExtraFields.CacheDebug,
+ GuardrailDebug: cr.ExtraFields.GuardrailDebug,
ProviderResponseHeaders: cr.ExtraFields.ProviderResponseHeaders,
},
}
@@ -2661,6 +2662,7 @@ func (cr *BifrostChatResponse) ToBifrostTextCompletionResponse() *BifrostTextCom
Latency: cr.ExtraFields.Latency,
RawResponse: cr.ExtraFields.RawResponse,
CacheDebug: cr.ExtraFields.CacheDebug,
+ GuardrailDebug: cr.ExtraFields.GuardrailDebug,
ProviderResponseHeaders: cr.ExtraFields.ProviderResponseHeaders,
},
}
@@ -2711,6 +2713,7 @@ func (cr *BifrostChatResponse) ToBifrostTextCompletionResponse() *BifrostTextCom
Latency: cr.ExtraFields.Latency,
RawResponse: cr.ExtraFields.RawResponse,
CacheDebug: cr.ExtraFields.CacheDebug,
+ GuardrailDebug: cr.ExtraFields.GuardrailDebug,
ProviderResponseHeaders: cr.ExtraFields.ProviderResponseHeaders,
},
}
@@ -2732,6 +2735,7 @@ func (cr *BifrostChatResponse) ToBifrostTextCompletionResponse() *BifrostTextCom
Latency: cr.ExtraFields.Latency,
RawResponse: cr.ExtraFields.RawResponse,
CacheDebug: cr.ExtraFields.CacheDebug,
+ GuardrailDebug: cr.ExtraFields.GuardrailDebug,
ProviderResponseHeaders: cr.ExtraFields.ProviderResponseHeaders,
},
}
diff --git a/core/schemas/tracer.go b/core/schemas/tracer.go
index 3a1a006a4b0..1787fc27464 100644
--- a/core/schemas/tracer.go
+++ b/core/schemas/tracer.go
@@ -25,6 +25,7 @@ type StreamAccumulatorResult struct {
TokenUsage *BifrostLLMUsage // Token usage
Cost *float64 // Cost in dollars
CacheDebug *BifrostCacheDebug // Semantic cache debug info if available
+ GuardrailDebug *BifrostGuardrailDebug // Guardrail debug info if available
ErrorDetails *BifrostError // Error details if any
AudioOutput *BifrostSpeechResponse // For speech streaming
TranscriptionOutput *BifrostTranscriptionResponse // For transcription streaming
diff --git a/framework/logstore/migrations.go b/framework/logstore/migrations.go
index 7a335bd6c97..d3976e2e046 100644
--- a/framework/logstore/migrations.go
+++ b/framework/logstore/migrations.go
@@ -217,6 +217,7 @@ var logstoreMigrationSteps = []migrationStep{
{IDs: []string{"logs_init_add_parent_request_id_column"}, run: migrationAddParentRequestIDColumn},
{IDs: []string{"logs_init_add_responses_output_column"}, run: migrationAddResponsesOutputColumn},
{IDs: []string{"logs_init_add_cost_and_cache_debug_column"}, run: migrationAddCostAndCacheDebugColumn},
+ {IDs: []string{"logs_add_guardrail_debug_column"}, run: migrationAddGuardrailDebugColumn},
{IDs: []string{"logs_init_add_responses_input_history_column"}, run: migrationAddResponsesInputHistoryColumn},
{IDs: []string{"logs_init_add_number_of_retries_and_fallback_index_and_selected_key_and_virtual_key_columns"}, run: migrationAddNumberOfRetriesAndFallbackIndexAndSelectedKeyAndVirtualKeyColumns},
{IDs: []string{"logs_add_performance_indexes"}, run: migrationAddPerformanceIndexes},
@@ -611,6 +612,30 @@ func migrationAddCostAndCacheDebugColumn(ctx context.Context, db *gorm.DB, logge
return nil
}
+// migrationAddGuardrailDebugColumn adds the guardrail_debug column to the logs table.
+func migrationAddGuardrailDebugColumn(ctx context.Context, db *gorm.DB, logger schemas.Logger) error {
+ migrationName := "logs_add_guardrail_debug_column"
+ logger.Info("[logstore] starting migration %s", migrationName)
+ defer logger.Info("[logstore] finished migration %s", migrationName)
+ opts := *migrator.DefaultOptions
+ opts.UseTransaction = true
+ m := migrator.New(db, &opts, []*migrator.Migration{{
+ ID: migrationName,
+ Migrate: func(tx *gorm.DB) error {
+ tx = tx.WithContext(ctx)
+ return addColumnIfNotExists(tx, logger, &Log{}, "guardrail_debug")
+ },
+ Rollback: func(tx *gorm.DB) error {
+ tx = tx.WithContext(ctx)
+ return dropColumnIfExists(tx, logger, &Log{}, "guardrail_debug")
+ },
+ }})
+ if err := m.Migrate(); err != nil {
+ return fmt.Errorf("error while adding guardrail_debug column: %s", err.Error())
+ }
+ return nil
+}
+
// migrationAddResponsesInputHistoryColumn adds the responses_input_history column to the logs table.
func migrationAddResponsesInputHistoryColumn(ctx context.Context, db *gorm.DB, logger schemas.Logger) error {
migrationName := "logs_init_add_responses_input_history_column"
diff --git a/framework/logstore/payload.go b/framework/logstore/payload.go
index cd5568f3d88..d4129cc28d9 100644
--- a/framework/logstore/payload.go
+++ b/framework/logstore/payload.go
@@ -43,6 +43,7 @@ var payloadFields = []string{
"video_list_output",
"video_delete_output",
"cache_debug",
+ "guardrail_debug",
"token_usage",
"error_details",
"raw_request",
@@ -83,6 +84,7 @@ func ExtractPayload(l *Log) map[string]string {
m["video_list_output"] = l.VideoListOutput
m["video_delete_output"] = l.VideoDeleteOutput
m["cache_debug"] = l.CacheDebug
+ m["guardrail_debug"] = l.GuardrailDebug
m["token_usage"] = l.TokenUsage
m["error_details"] = l.ErrorDetails
m["raw_request"] = l.RawRequest
@@ -186,6 +188,7 @@ func ClearPayload(l *Log) {
l.VideoListOutput = ""
l.VideoDeleteOutput = ""
l.CacheDebug = ""
+ l.GuardrailDebug = ""
l.TokenUsage = ""
l.ErrorDetails = ""
l.RawRequest = ""
@@ -222,6 +225,7 @@ func ClearPayload(l *Log) {
l.VideoListOutputParsed = nil
l.VideoDeleteOutputParsed = nil
l.CacheDebugParsed = nil
+ l.GuardrailDebugParsed = nil
l.TokenUsageParsed = nil
l.ErrorDetailsParsed = nil
}
@@ -315,6 +319,9 @@ func MergePayloadFromJSON(l *Log, data []byte) error {
if v, ok := m["cache_debug"]; ok && v != "" {
l.CacheDebug = v
}
+ if v, ok := m["guardrail_debug"]; ok && v != "" {
+ l.GuardrailDebug = v
+ }
if v, ok := m["token_usage"]; ok && v != "" {
l.TokenUsage = v
}
@@ -870,6 +877,9 @@ func clearPayloadField(l *Log, name string) {
case "cache_debug":
l.CacheDebug = ""
l.CacheDebugParsed = nil
+ case "guardrail_debug":
+ l.GuardrailDebug = ""
+ l.GuardrailDebugParsed = nil
case "token_usage":
l.TokenUsage = ""
l.TokenUsageParsed = nil
diff --git a/framework/logstore/payload_test.go b/framework/logstore/payload_test.go
index 32ddd4f1504..f3e6c641b3a 100644
--- a/framework/logstore/payload_test.go
+++ b/framework/logstore/payload_test.go
@@ -39,6 +39,7 @@ func TestExtractPayload_RoundTrip(t *testing.T) {
VideoListOutput: `{"videos":[]}`,
VideoDeleteOutput: `{"deleted":true}`,
CacheDebug: `{"hit":true}`,
+ GuardrailDebug: `{"judge_calls":[{"total_tokens":18}]}`,
TokenUsage: `{"total_tokens":100}`,
ErrorDetails: `{"error":"bad"}`,
RawRequest: `{"method":"POST"}`,
@@ -53,6 +54,7 @@ func TestExtractPayload_RoundTrip(t *testing.T) {
assert.Equal(t, len(payloadFields)+1, len(payload), "payload map should have all payload fields plus metadata")
assert.Equal(t, `[{"role":"user","content":"hello"}]`, payload["input_history"])
assert.Equal(t, `{"role":"assistant","content":"world"}`, payload["output_message"])
+ assert.Equal(t, `{"judge_calls":[{"total_tokens":18}]}`, payload["guardrail_debug"])
assert.Equal(t, `routing log`, payload["routing_engine_logs"])
assert.Equal(t, metadata, payload["metadata"], "metadata must be written to the snapshot for object consumers")
@@ -61,6 +63,7 @@ func TestExtractPayload_RoundTrip(t *testing.T) {
assert.Empty(t, log.InputHistory)
assert.Empty(t, log.OutputMessage)
assert.Empty(t, log.RawRequest)
+ assert.Empty(t, log.GuardrailDebug)
assert.Empty(t, log.RoutingEngineLogs)
require.NotNil(t, log.Metadata)
assert.Equal(t, metadata, *log.Metadata)
@@ -80,6 +83,7 @@ func TestExtractPayload_RoundTrip(t *testing.T) {
require.NoError(t, err)
assert.Equal(t, `[{"role":"user","content":"hello"}]`, log.InputHistory)
assert.Equal(t, `{"role":"assistant","content":"world"}`, log.OutputMessage)
+ assert.Equal(t, `{"judge_calls":[{"total_tokens":18}]}`, log.GuardrailDebug)
assert.Equal(t, `routing log`, log.RoutingEngineLogs)
require.NotNil(t, log.Metadata)
assert.Equal(t, dbMetadata, *log.Metadata, "merge must not override DB-authoritative metadata with the snapshot")
diff --git a/framework/logstore/tables.go b/framework/logstore/tables.go
index b872164c791..5ec3e4a1052 100644
--- a/framework/logstore/tables.go
+++ b/framework/logstore/tables.go
@@ -238,6 +238,7 @@ type Log struct {
VideoListOutput string `gorm:"type:text" json:"-"` // JSON serialized *schemas.BifrostVideoListResponse
VideoDeleteOutput string `gorm:"type:text" json:"-"` // JSON serialized *schemas.BifrostVideoDeleteResponse
CacheDebug string `gorm:"type:text" json:"-"` // JSON serialized *schemas.BifrostCacheDebug
+ GuardrailDebug string `gorm:"type:text" json:"-"` // JSON serialized *schemas.BifrostGuardrailDebug
Latency *float64 `gorm:"index:idx_logs_latency" json:"latency,omitempty"`
TokenUsage string `gorm:"type:text" json:"-"` // JSON serialized *schemas.LLMUsage
Cost *float64 `gorm:"index" json:"cost,omitempty"` // Cost in dollars (total cost of the request - includes cache lookup cost)
@@ -317,6 +318,7 @@ type Log struct {
TranscriptionOutputParsed *schemas.BifrostTranscriptionResponse `gorm:"-" json:"transcription_output,omitempty"`
ImageGenerationOutputParsed *schemas.BifrostImageGenerationResponse `gorm:"-" json:"image_generation_output,omitempty"`
CacheDebugParsed *schemas.BifrostCacheDebug `gorm:"-" json:"cache_debug,omitempty"`
+ GuardrailDebugParsed *schemas.BifrostGuardrailDebug `gorm:"-" json:"guardrail_debug,omitempty"`
ListModelsOutputParsed []schemas.Model `gorm:"-" json:"list_models_output,omitempty"`
MetadataParsed map[string]interface{} `gorm:"-" json:"metadata,omitempty"`
VideoGenerationInputParsed *schemas.VideoGenerationInput `gorm:"-" json:"video_generation_input,omitempty"`
@@ -648,6 +650,14 @@ func (l *Log) SerializeFields() error {
}
}
+ if l.GuardrailDebugParsed != nil {
+ if data, err := sonic.Marshal(l.GuardrailDebugParsed); err != nil {
+ return err
+ } else {
+ l.GuardrailDebug = string(data)
+ }
+ }
+
if len(l.AttemptTrailParsed) > 0 {
if data, err := sonic.Marshal(l.AttemptTrailParsed); err != nil {
return err
@@ -961,6 +971,13 @@ func (l *Log) DeserializeFields() error {
}
}
+ if l.GuardrailDebug != "" {
+ if err := sonic.Unmarshal([]byte(l.GuardrailDebug), &l.GuardrailDebugParsed); err != nil {
+ // Log error but don't fail the operation - initialize as nil
+ l.GuardrailDebugParsed = nil
+ }
+ }
+
if l.AttemptTrail != "" {
if err := sonic.Unmarshal([]byte(l.AttemptTrail), &l.AttemptTrailParsed); err != nil {
l.AttemptTrailParsed = nil
diff --git a/framework/modelcatalog/datasheet/cost.go b/framework/modelcatalog/datasheet/cost.go
index 8873cc7e285..acdb3bd9e03 100644
--- a/framework/modelcatalog/datasheet/cost.go
+++ b/framework/modelcatalog/datasheet/cost.go
@@ -11,7 +11,7 @@ import (
)
// CalculateCost calculates the cost of a Bifrost response.
-// It handles all request types, cache debug billing, and tiered pricing.
+// It handles all request types, cache and guardrail billing, and tiered pricing.
// If scopes is nil, an empty LookupScopes is used; global and provider-scoped
// overrides may still apply since the provider is derived from the response.
func (s *Store) CalculateCost(result *schemas.BifrostResponse, scopes *LookupScopes) float64 {
@@ -24,13 +24,22 @@ func (s *Store) CalculateCost(result *schemas.BifrostResponse, scopes *LookupSco
lookupScopes = *scopes
}
+ extraFields := result.GetExtraFields()
+
// Handle semantic cache billing
- cacheDebug := result.GetExtraFields().CacheDebug
+ cacheDebug := extraFields.CacheDebug
+ var requestCost float64
if cacheDebug != nil {
- return s.calculateCostWithCache(result, cacheDebug, lookupScopes)
+ requestCost = s.calculateCostWithCache(result, cacheDebug, lookupScopes)
+ } else {
+ requestCost = s.calculateBaseCost(result, lookupScopes)
}
- return s.calculateBaseCost(result, lookupScopes)
+ // Handle guardrail judge-call billing
+ if extraFields.GuardrailDebug == nil {
+ return requestCost
+ }
+ return requestCost + s.CalculateGuardrailCost(extraFields.GuardrailDebug, &lookupScopes)
}
// CalculateCostForUsage computes the dollar cost from a bare usage object plus
@@ -72,6 +81,57 @@ func (s *Store) CalculateCostForUsage(usage *schemas.BifrostLLMUsage, provider s
)
}
+// CalculateGuardrailCost computes judge cost when no parent response is available.
+//
+// CalculateCost uses this for normal responses. Logging also calls it directly
+// for input guardrail blocks, where the main provider call never produced a
+// BifrostResponse.
+func (s *Store) CalculateGuardrailCost(debug *schemas.BifrostGuardrailDebug, scopes *LookupScopes) float64 {
+ if debug == nil || len(debug.JudgeCalls) == 0 {
+ return 0
+ }
+
+ var total float64
+ for _, call := range debug.JudgeCalls {
+ total += s.computeGuardrailJudgeCost(call, scopes)
+ }
+ return total
+}
+
+// computeGuardrailJudgeCost computes one internal judge chat-completion cost.
+func (s *Store) computeGuardrailJudgeCost(call schemas.BifrostGuardrailJudgeCall, scopes *LookupScopes) float64 {
+ if call.JudgeProvider == "" || call.JudgeModel == "" {
+ return 0
+ }
+
+ // Price the judge call using its own provider/model. Keep virtual-key
+ // attribution for the caller, but do not reuse the main request's selected
+ // provider key: the judge may use a different configured key.
+ judgeScopes := LookupScopes{Provider: string(call.JudgeProvider)}
+ if scopes != nil {
+ judgeScopes.VirtualKeyID = scopes.VirtualKeyID
+ }
+
+ usage := &schemas.BifrostLLMUsage{
+ PromptTokens: call.PromptTokens,
+ PromptTokensDetails: call.PromptTokensDetails,
+ CompletionTokens: call.CompletionTokens,
+ CompletionTokensDetails: call.CompletionTokensDetails,
+ TotalTokens: call.TotalTokens,
+ }
+ requestType := call.JudgeRequestType
+ if requestType == "" {
+ requestType = schemas.ChatCompletionRequest
+ }
+ return s.CalculateCostForUsage(
+ usage,
+ call.JudgeProvider,
+ call.JudgeModel,
+ requestType,
+ &judgeScopes,
+ )
+}
+
// calculateCostWithCache handles cost calculation when semantic cache debug info is present.
func (s *Store) calculateCostWithCache(result *schemas.BifrostResponse, cacheDebug *schemas.BifrostCacheDebug, scopes LookupScopes) float64 {
if cacheDebug.CacheHit {
@@ -113,6 +173,15 @@ func (s *Store) computeCacheEmbeddingCost(cacheDebug *schemas.BifrostCacheDebug,
return float64(*cacheDebug.InputTokens) * tieredInputRate(pricing, *cacheDebug.InputTokens, serviceTier{})
}
+// CalculateCacheEmbeddingCost computes the semantic-cache embedding lookup cost.
+func (s *Store) CalculateCacheEmbeddingCost(cacheDebug *schemas.BifrostCacheDebug, scopes *LookupScopes) float64 {
+ var lookupScopes LookupScopes
+ if scopes != nil {
+ lookupScopes = *scopes
+ }
+ return s.computeCacheEmbeddingCost(cacheDebug, lookupScopes)
+}
+
// computeContainerCreationCost returns the cost for creating a container from an already-resolved pricing entry.
func computeContainerCreationCost(pricing *configstoreTables.TableModelPricing) float64 {
if pricing == nil || pricing.CodeInterpreterCostPerSession == nil {
diff --git a/framework/modelcatalog/datasheet/cost_test.go b/framework/modelcatalog/datasheet/cost_test.go
index a4cc984ebde..d1b988a57ce 100644
--- a/framework/modelcatalog/datasheet/cost_test.go
+++ b/framework/modelcatalog/datasheet/cost_test.go
@@ -1712,6 +1712,148 @@ func TestCalculateCost_SemanticCacheHitNoEmbeddingInfo(t *testing.T) {
assert.Equal(t, 0.0, cost)
}
+// TestCalculateCostAddsGuardrailJudgeCost verifies judge cost is additive to the main request.
+func TestCalculateCostAddsGuardrailJudgeCost(t *testing.T) {
+ s := testStoreWithPricing(map[string]configstoreTables.TableModelPricing{
+ makeKey("gpt-4o", "openai", "chat"): {
+ Model: "gpt-4o", Provider: "openai", Mode: "chat",
+ InputCostPerToken: bifrost.Ptr(0.000001), OutputCostPerToken: bifrost.Ptr(0.000002),
+ },
+ makeKey("claude-judge", "anthropic", "chat"): {
+ Model: "claude-judge", Provider: "anthropic", Mode: "chat",
+ InputCostPerToken: bifrost.Ptr(0.000003), OutputCostPerToken: bifrost.Ptr(0.000004),
+ },
+ })
+ resp := makeChatResponse(schemas.OpenAI, "gpt-4o", &schemas.BifrostLLMUsage{
+ PromptTokens: 100,
+ CompletionTokens: 50,
+ TotalTokens: 150,
+ })
+ resp.GetExtraFields().GuardrailDebug = &schemas.BifrostGuardrailDebug{
+ JudgeCalls: []schemas.BifrostGuardrailJudgeCall{{
+ JudgeProvider: schemas.Anthropic,
+ JudgeModel: "claude-judge",
+ PromptTokens: 20,
+ CompletionTokens: 5,
+ TotalTokens: 25,
+ }},
+ }
+
+ // Main: 100*0.000001 + 50*0.000002 = 0.0002.
+ // Judge: 20*0.000003 + 5*0.000004 = 0.00008.
+ assert.InDelta(t, 0.00028, s.CalculateCost(resp, nil), 1e-12)
+}
+
+// TestCalculateGuardrailCostPreservesUsageDetails verifies cache-aware judge pricing uses detailed usage.
+func TestCalculateGuardrailCostPreservesUsageDetails(t *testing.T) {
+ pricing := chatPricing(0.00001, 0)
+ pricing.Model = "gpt-judge"
+ pricing.Provider = "openai"
+ pricing.Mode = "chat"
+ pricing.CacheReadInputTokenCost = bifrost.Ptr(0.000001)
+ s := testStoreWithPricing(map[string]configstoreTables.TableModelPricing{
+ makeKey("gpt-judge", "openai", "chat"): pricing,
+ })
+
+ cost := s.CalculateGuardrailCost(&schemas.BifrostGuardrailDebug{
+ JudgeCalls: []schemas.BifrostGuardrailJudgeCall{{
+ JudgeProvider: schemas.OpenAI,
+ JudgeModel: "gpt-judge",
+ PromptTokens: 10,
+ PromptTokensDetails: &schemas.ChatPromptTokensDetails{
+ CachedReadTokens: 8,
+ },
+ TotalTokens: 10,
+ }},
+ }, nil)
+
+ // Two uncached tokens at $10/M plus eight cached reads at $1/M.
+ assert.InDelta(t, 0.000028, cost, 1e-12)
+}
+
+// TestCalculateCostDirectCacheHitStillBillsGuardrail verifies cache hits do not hide judge spend.
+func TestCalculateCostDirectCacheHitStillBillsGuardrail(t *testing.T) {
+ s := testStoreWithPricing(map[string]configstoreTables.TableModelPricing{
+ makeKey("gpt-4o-mini", "openai", "chat"): {
+ Model: "gpt-4o-mini", Provider: "openai", Mode: "chat",
+ InputCostPerToken: bifrost.Ptr(0.000001), OutputCostPerToken: bifrost.Ptr(0.000002),
+ },
+ })
+ hitType := "direct"
+ resp := makeChatResponse(schemas.OpenAI, "cached-model", nil)
+ resp.GetExtraFields().CacheDebug = &schemas.BifrostCacheDebug{CacheHit: true, HitType: &hitType}
+ resp.GetExtraFields().GuardrailDebug = &schemas.BifrostGuardrailDebug{
+ JudgeCalls: []schemas.BifrostGuardrailJudgeCall{{
+ JudgeProvider: schemas.OpenAI,
+ JudgeModel: "gpt-4o-mini",
+ PromptTokens: 10,
+ CompletionTokens: 5,
+ TotalTokens: 15,
+ }},
+ }
+
+ assert.InDelta(t, 0.00002, s.CalculateCost(resp, nil), 1e-12)
+}
+
+// TestCalculateGuardrailCostUsesJudgeProviderWithoutCallerSelectedKey verifies
+// judge pricing retains virtual-key attribution while excluding the caller's
+// selected provider key from scoped override matching.
+func TestCalculateGuardrailCostUsesJudgeProviderWithoutCallerSelectedKey(t *testing.T) {
+ s := testStoreWithPricing(map[string]configstoreTables.TableModelPricing{
+ makeKey("claude-judge", "anthropic", "chat"): {
+ Model: "claude-judge",
+ Provider: "anthropic",
+ Mode: "chat",
+ InputCostPerToken: bifrost.Ptr(1.0),
+ OutputCostPerToken: bifrost.Ptr(0.0),
+ },
+ })
+
+ virtualKeyID := "vk-caller"
+ callerSelectedKeyID := "openai-key"
+ judgeProviderID := "anthropic"
+ require.NoError(t, s.SetOverrides([]configstoreTables.TablePricingOverride{
+ {
+ ID: "judge-vk-provider",
+ ScopeKind: string(ScopeKindVirtualKeyProvider),
+ VirtualKeyID: &virtualKeyID,
+ ProviderID: &judgeProviderID,
+ MatchType: string(MatchTypeExact),
+ Pattern: "claude-judge",
+ RequestTypes: []schemas.RequestType{schemas.ChatCompletionRequest},
+ PricingPatchJSON: `{"input_cost_per_token":3}`,
+ },
+ {
+ ID: "caller-vk-provider-key",
+ ScopeKind: string(ScopeKindVirtualKeyProviderKey),
+ VirtualKeyID: &virtualKeyID,
+ ProviderID: &judgeProviderID,
+ ProviderKeyID: &callerSelectedKeyID,
+ MatchType: string(MatchTypeExact),
+ Pattern: "claude-judge",
+ RequestTypes: []schemas.RequestType{schemas.ChatCompletionRequest},
+ PricingPatchJSON: `{"input_cost_per_token":99}`,
+ },
+ }))
+
+ cost := s.CalculateGuardrailCost(&schemas.BifrostGuardrailDebug{
+ JudgeCalls: []schemas.BifrostGuardrailJudgeCall{{
+ JudgeProvider: schemas.Anthropic,
+ JudgeModel: "claude-judge",
+ PromptTokens: 10,
+ TotalTokens: 10,
+ }},
+ }, &LookupScopes{
+ VirtualKeyID: virtualKeyID,
+ SelectedKeyID: callerSelectedKeyID,
+ Provider: "openai",
+ })
+
+ // The virtual-key + Anthropic override applies (10 * 3). Reusing the
+ // caller's selected key would instead select the 99/token override.
+ assert.InDelta(t, 30.0, cost, 1e-12)
+}
+
// =========================================================================
// 11. CalculateCost integration — end-to-end
// =========================================================================
diff --git a/framework/modelcatalog/pricing.go b/framework/modelcatalog/pricing.go
index d06585d6a9d..1b2dd6e4bdc 100644
--- a/framework/modelcatalog/pricing.go
+++ b/framework/modelcatalog/pricing.go
@@ -56,6 +56,16 @@ func (mc *ModelCatalog) CalculateCostForUsage(usage *schemas.BifrostLLMUsage, pr
return mc.datasheet.CalculateCostForUsage(usage, provider, model, requestType, (*datasheet.LookupScopes)(scopes))
}
+// CalculateGuardrailCost computes the aggregate cost of guardrail judge calls.
+func (mc *ModelCatalog) CalculateGuardrailCost(debug *schemas.BifrostGuardrailDebug, scopes *PricingLookupScopes) float64 {
+ return mc.datasheet.CalculateGuardrailCost(debug, (*datasheet.LookupScopes)(scopes))
+}
+
+// CalculateCacheEmbeddingCost computes the semantic-cache embedding lookup cost.
+func (mc *ModelCatalog) CalculateCacheEmbeddingCost(debug *schemas.BifrostCacheDebug, scopes *PricingLookupScopes) float64 {
+ return mc.datasheet.CalculateCacheEmbeddingCost(debug, (*datasheet.LookupScopes)(scopes))
+}
+
// UpsertModelPricingAttributes writes additional_attributes for every row
// matching (model, provider) and reloads the pricing cache.
func (mc *ModelCatalog) UpsertModelPricingAttributes(ctx context.Context, model string, provider schemas.ModelProvider, attrs map[string]string) (int64, error) {
diff --git a/framework/streaming/chat.go b/framework/streaming/chat.go
index 2a79595f3de..9a38b945a91 100644
--- a/framework/streaming/chat.go
+++ b/framework/streaming/chat.go
@@ -456,6 +456,9 @@ func (a *Accumulator) processAccumulatedChatStreamingChunks(requestID string, re
if lastChunk.SemanticCacheDebug != nil {
data.CacheDebug = lastChunk.SemanticCacheDebug
}
+ if lastChunk.GuardrailDebug != nil {
+ data.GuardrailDebug = lastChunk.GuardrailDebug
+ }
if lastChunk.Cost != nil {
data.Cost = lastChunk.Cost
}
@@ -569,6 +572,7 @@ func (a *Accumulator) processChatStreamingResponse(ctx *schemas.BifrostContext,
chunk.Cost = bifrost.Ptr(cost)
}
chunk.SemanticCacheDebug = result.GetExtraFields().CacheDebug
+ chunk.GuardrailDebug = result.GetExtraFields().GuardrailDebug
}
} else if result != nil && result.ChatResponse != nil {
// Extract delta and other information
@@ -598,6 +602,7 @@ func (a *Accumulator) processChatStreamingResponse(ctx *schemas.BifrostContext,
chunk.Cost = bifrost.Ptr(cost)
}
chunk.SemanticCacheDebug = result.GetExtraFields().CacheDebug
+ chunk.GuardrailDebug = result.GetExtraFields().GuardrailDebug
}
}
if addErr := a.addChatStreamChunk(requestID, streamType, chunk, isFinalChunk); addErr != nil {
diff --git a/framework/streaming/responses.go b/framework/streaming/responses.go
index 0651cb1be17..00ea62e82f3 100644
--- a/framework/streaming/responses.go
+++ b/framework/streaming/responses.go
@@ -984,6 +984,9 @@ func (a *Accumulator) processAccumulatedResponsesStreamingChunks(requestID strin
if lastChunk.SemanticCacheDebug != nil {
data.CacheDebug = lastChunk.SemanticCacheDebug
}
+ if lastChunk.GuardrailDebug != nil {
+ data.GuardrailDebug = lastChunk.GuardrailDebug
+ }
if lastChunk.Cost != nil {
data.Cost = lastChunk.Cost
}
@@ -1074,6 +1077,7 @@ func (a *Accumulator) processResponsesStreamingResponse(ctx *schemas.BifrostCont
chunk.Cost = bifrost.Ptr(cost)
}
chunk.SemanticCacheDebug = result.GetExtraFields().CacheDebug
+ chunk.GuardrailDebug = result.GetExtraFields().GuardrailDebug
}
}
diff --git a/framework/streaming/types.go b/framework/streaming/types.go
index 605855875c9..7ce0b06b60b 100644
--- a/framework/streaming/types.go
+++ b/framework/streaming/types.go
@@ -37,6 +37,7 @@ type AccumulatedData struct {
TokenUsage *schemas.BifrostLLMUsage
ServiceTier *schemas.BifrostServiceTier
CacheDebug *schemas.BifrostCacheDebug
+ GuardrailDebug *schemas.BifrostGuardrailDebug
Cost *float64
AudioOutput *schemas.BifrostSpeechResponse
TranscriptionOutput *schemas.BifrostTranscriptionResponse
@@ -82,6 +83,7 @@ type ChatStreamChunk struct {
TokenUsage *schemas.BifrostLLMUsage // Token usage if available
ServiceTier *schemas.BifrostServiceTier // Served OpenAI tier if available
SemanticCacheDebug *schemas.BifrostCacheDebug // Semantic cache debug if available
+ GuardrailDebug *schemas.BifrostGuardrailDebug // Guardrail debug if available
Cost *float64 // Cost in dollars from pricing plugin
ErrorDetails *schemas.BifrostError // Error if any
ChunkIndex int // Index of the chunk in the stream
@@ -96,6 +98,7 @@ type ResponsesStreamChunk struct {
TokenUsage *schemas.BifrostLLMUsage // Token usage if available
ServiceTier *schemas.BifrostServiceTier // Served OpenAI tier if available
SemanticCacheDebug *schemas.BifrostCacheDebug // Semantic cache debug if available
+ GuardrailDebug *schemas.BifrostGuardrailDebug // Guardrail debug if available
Cost *float64 // Cost in dollars from pricing plugin
ErrorDetails *schemas.BifrostError // Error if any
ChunkIndex int // Index of the chunk in the stream
@@ -361,6 +364,9 @@ func (p *ProcessedStreamResponse) ToBifrostResponse() *schemas.BifrostResponse {
if p.Data.CacheDebug != nil {
resp.TextCompletionResponse.ExtraFields.CacheDebug = p.Data.CacheDebug
}
+ if p.Data.GuardrailDebug != nil {
+ resp.TextCompletionResponse.ExtraFields.GuardrailDebug = p.Data.GuardrailDebug
+ }
case StreamTypeChat:
var message *schemas.ChatMessage
if p.Data.OutputMessage != nil {
@@ -413,6 +419,9 @@ func (p *ProcessedStreamResponse) ToBifrostResponse() *schemas.BifrostResponse {
if p.Data.CacheDebug != nil {
resp.ChatResponse.ExtraFields.CacheDebug = p.Data.CacheDebug
}
+ if p.Data.GuardrailDebug != nil {
+ resp.ChatResponse.ExtraFields.GuardrailDebug = p.Data.GuardrailDebug
+ }
case StreamTypeResponses:
responsesResp := &schemas.BifrostResponsesResponse{}
@@ -438,6 +447,9 @@ func (p *ProcessedStreamResponse) ToBifrostResponse() *schemas.BifrostResponse {
if p.Data.CacheDebug != nil {
responsesResp.ExtraFields.CacheDebug = p.Data.CacheDebug
}
+ if p.Data.GuardrailDebug != nil {
+ responsesResp.ExtraFields.GuardrailDebug = p.Data.GuardrailDebug
+ }
resp.ResponsesResponse = responsesResp
case StreamTypeAudio:
speechResp := p.Data.AudioOutput
@@ -461,6 +473,9 @@ func (p *ProcessedStreamResponse) ToBifrostResponse() *schemas.BifrostResponse {
if p.Data.CacheDebug != nil {
resp.SpeechResponse.ExtraFields.CacheDebug = p.Data.CacheDebug
}
+ if p.Data.GuardrailDebug != nil {
+ resp.SpeechResponse.ExtraFields.GuardrailDebug = p.Data.GuardrailDebug
+ }
case StreamTypeTranscription:
transcriptionResp := p.Data.TranscriptionOutput
if transcriptionResp == nil {
@@ -483,6 +498,9 @@ func (p *ProcessedStreamResponse) ToBifrostResponse() *schemas.BifrostResponse {
if p.Data.CacheDebug != nil {
resp.TranscriptionResponse.ExtraFields.CacheDebug = p.Data.CacheDebug
}
+ if p.Data.GuardrailDebug != nil {
+ resp.TranscriptionResponse.ExtraFields.GuardrailDebug = p.Data.GuardrailDebug
+ }
case StreamTypeImage:
imageResp := p.Data.ImageGenerationOutput
if imageResp == nil {
@@ -517,6 +535,9 @@ func (p *ProcessedStreamResponse) ToBifrostResponse() *schemas.BifrostResponse {
if p.Data.CacheDebug != nil {
resp.ImageGenerationResponse.ExtraFields.CacheDebug = p.Data.CacheDebug
}
+ if p.Data.GuardrailDebug != nil {
+ resp.ImageGenerationResponse.ExtraFields.GuardrailDebug = p.Data.GuardrailDebug
+ }
}
return resp
diff --git a/framework/tracing/tracer.go b/framework/tracing/tracer.go
index 01179166b88..1ce08438024 100644
--- a/framework/tracing/tracer.go
+++ b/framework/tracing/tracer.go
@@ -699,6 +699,7 @@ func (t *Tracer) ProcessStreamingChunk(ctx *schemas.BifrostContext, traceID stri
accResult.TokenUsage = processedResp.Data.TokenUsage
accResult.Cost = processedResp.Data.Cost
accResult.CacheDebug = processedResp.Data.CacheDebug
+ accResult.GuardrailDebug = processedResp.Data.GuardrailDebug
accResult.ErrorDetails = processedResp.Data.ErrorDetails
accResult.AudioOutput = processedResp.Data.AudioOutput
accResult.TranscriptionOutput = processedResp.Data.TranscriptionOutput
diff --git a/plugins/logging/main.go b/plugins/logging/main.go
index 982c64be6b0..206e7088213 100644
--- a/plugins/logging/main.go
+++ b/plugins/logging/main.go
@@ -264,6 +264,40 @@ func (p *LoggerPlugin) applyErrorBillingFromBilledUsage(ctx *schemas.BifrostCont
}
}
+// guardrailDebugForLog returns the request's guardrail debug snapshot.
+func guardrailDebugForLog(ctx *schemas.BifrostContext, result *schemas.BifrostResponse) *schemas.BifrostGuardrailDebug {
+ if debug, ok := schemas.GuardrailDebugFromContext(ctx); ok {
+ return debug
+ }
+ if result == nil {
+ return nil
+ }
+ return result.GetExtraFields().GuardrailDebug.Clone()
+}
+
+// applyInternalCallCosts adds sidecar costs when no response exists to carry them.
+func (p *LoggerPlugin) applyInternalCallCosts(ctx *schemas.BifrostContext, entry *logstore.Log, guardrailDebug *schemas.BifrostGuardrailDebug) {
+ if entry == nil || p.pricingManager == nil {
+ return
+ }
+ pricingScopes := modelcatalog.PricingLookupScopesFromContext(ctx, string(entry.Provider))
+ var cost float64
+ if cacheDebug, ok := schemas.CacheDebugFromContext(ctx); ok {
+ cost += p.pricingManager.CalculateCacheEmbeddingCost(cacheDebug, pricingScopes)
+ }
+ if guardrailDebug != nil {
+ cost += p.pricingManager.CalculateGuardrailCost(guardrailDebug, pricingScopes)
+ }
+ if cost <= 0 {
+ return
+ }
+ if entry.Cost == nil {
+ entry.Cost = &cost
+ return
+ }
+ *entry.Cost += cost
+}
+
const (
// maxDeferredUsageWatchers caps goroutines parked waiting for trailing usage on
// large-payload requests. Generous, because each one is idle on a channel receive;
@@ -1135,6 +1169,10 @@ func (p *LoggerPlugin) PostLLMHook(ctx *schemas.BifrostContext, result *schemas.
resolvedKeyAlias := bifrost.GetResponseRoutingInfo(result, bifrostErr).ResolvedKeyAlias
shouldStoreRaw, _ := ctx.Value(schemas.BifrostContextKeyShouldStoreRawInLogs).(bool)
contentLoggingEnabled := p.contentLoggingEnabled(ctx)
+ guardrailDebug := guardrailDebugForLog(ctx, result)
+ if result != nil && guardrailDebug != nil {
+ result.GetExtraFields().GuardrailDebug = guardrailDebug.Clone()
+ }
isFinalChunk := bifrost.IsFinalChunk(ctx)
@@ -1182,6 +1220,8 @@ func (p *LoggerPlugin) PostLLMHook(ctx *schemas.BifrostContext, result *schemas.
applyModelAlias(entry, originalModelRequested, resolvedModelUsed)
applyResolvedAliasInfo(entry, resolvedKeyAlias)
entry.ErrorDetailsParsed = sanitizeErrorForLogging(bifrostErr, contentLoggingEnabled, shouldStoreRaw)
+ entry.GuardrailDebugParsed = guardrailDebug
+ p.applyInternalCallCosts(ctx, entry, guardrailDebug)
if nodeID, _ := p.clusterNodeID.Load().(string); nodeID != "" {
entry.ClusterNodeID = &nodeID
}
@@ -1245,6 +1285,7 @@ func (p *LoggerPlugin) PostLLMHook(ctx *schemas.BifrostContext, result *schemas.
// Build the complete log entry with input (from PreLLMHook) + output (from PostLLMHook)
entry := buildCompleteLogEntryFromPending(pending)
+ entry.GuardrailDebugParsed = guardrailDebug
// Apply common output fields. For cache hits, prefer the cache-serve
// latency stamped by the semantic cache plugin over the original provider
// latency preserved in the cached response.
@@ -1349,6 +1390,7 @@ func (p *LoggerPlugin) PostLLMHook(ctx *schemas.BifrostContext, result *schemas.
// logs DB reflects what we were actually billed, mirroring the governance
// budget.
p.applyErrorBillingFromBilledUsage(ctx, entry, bifrostErr.ExtraFields.BilledUsage, requestType)
+ p.applyInternalCallCosts(ctx, entry, guardrailDebug)
applyLargePayloadPreviewsToEntry(ctx, entry, contentLoggingEnabled)
p.storeOrEnqueueEntry(ctx, entry, p.makePostWriteCallback(nil))
p.scheduleDeferredUsageUpdate(ctx, requestID, entry.TokenUsageParsed != nil)
@@ -1402,11 +1444,18 @@ func (p *LoggerPlugin) PostLLMHook(ctx *schemas.BifrostContext, result *schemas.
}
}
}
+ // A stream error can arrive with a response chunk, bypassing Path A.
+ // Preserve provider-billed usage and the sidecar calls in that case.
+ p.applyErrorBillingFromBilledUsage(ctx, entry, bifrostErr.ExtraFields.BilledUsage, requestType)
+ p.applyInternalCallCosts(ctx, entry, guardrailDebug)
} else if streamResponse == nil {
// tracer or traceID not available, or accumulator returned nil - still write what we have
entry.Status = logStatusSuccess
entry.Stream = true
applyModelAlias(entry, originalModelRequested, resolvedModelUsed)
+ // Without an accumulated response, CalculateCost cannot see cache or
+ // guardrail debug. Normal accumulated streams already include both.
+ p.applyInternalCallCosts(ctx, entry, guardrailDebug)
} else if isFinalChunk {
// Apply streaming output fields to the entry
entry.Stream = true
diff --git a/plugins/logging/operations.go b/plugins/logging/operations.go
index ad665a0a5b4..3ebe3cd87c1 100644
--- a/plugins/logging/operations.go
+++ b/plugins/logging/operations.go
@@ -435,6 +435,9 @@ func (p *LoggerPlugin) applyStreamingOutputToEntry(entry *logstore.Log, streamRe
if streamResponse.Data.CacheDebug != nil {
entry.CacheDebugParsed = streamResponse.Data.CacheDebug
}
+ if streamResponse.Data.GuardrailDebug != nil {
+ entry.GuardrailDebugParsed = streamResponse.Data.GuardrailDebug
+ }
// Finish/stop reason - always persist regardless of content logging settings
if streamResponse.Data.FinishReason != nil {
@@ -1726,7 +1729,8 @@ func (p *LoggerPlugin) calculateCostForLog(logEntry *logstore.Log) (float64, err
}
if (logEntry.TokenUsageParsed == nil && logEntry.TokenUsage != "") ||
- (logEntry.CacheDebugParsed == nil && logEntry.CacheDebug != "") {
+ (logEntry.CacheDebugParsed == nil && logEntry.CacheDebug != "") ||
+ (logEntry.GuardrailDebugParsed == nil && logEntry.GuardrailDebug != "") {
if err := logEntry.DeserializeFields(); err != nil {
return 0, fmt.Errorf("failed to deserialize fields for log %s: %w", logEntry.ID, err)
}
@@ -1734,9 +1738,10 @@ func (p *LoggerPlugin) calculateCostForLog(logEntry *logstore.Log) (float64, err
usage := logEntry.TokenUsageParsed
cacheDebug := logEntry.CacheDebugParsed
+ guardrailDebug := logEntry.GuardrailDebugParsed
- // If no cache hit and no usage, we can't calculate cost
- if usage == nil && (cacheDebug == nil || !cacheDebug.CacheHit) {
+ // If no cache hit, guardrail call, or usage, we can't calculate cost.
+ if usage == nil && (cacheDebug == nil || !cacheDebug.CacheHit) && guardrailDebug == nil {
return 0, fmt.Errorf("token usage not available for log %s", logEntry.ID)
}
@@ -1761,7 +1766,7 @@ func (p *LoggerPlugin) calculateCostForLog(logEntry *logstore.Log) (float64, err
}
requestType := normalizeLogRequestType(logEntry.Object)
- if requestType == "" && (cacheDebug == nil || !cacheDebug.CacheHit) {
+ if requestType == "" && (cacheDebug == nil || !cacheDebug.CacheHit) && guardrailDebug == nil {
p.logger.Warn("skipping cost calculation for log %s: object type is empty (timestamp: %s)", logEntry.ID, logEntry.Timestamp)
return 0, fmt.Errorf("object type is empty for log %s", logEntry.ID)
}
@@ -1779,6 +1784,7 @@ func (p *LoggerPlugin) calculateCostForLog(logEntry *logstore.Log) (float64, err
OriginalModelRequested: originalModelRequested,
ResolvedModelUsed: logEntry.Model,
CacheDebug: cacheDebug,
+ GuardrailDebug: guardrailDebug,
RoutingInfo: schemas.RoutingInfo{
Provider: schemas.ModelProvider(logEntry.Provider),
Model: originalModelRequested,
diff --git a/plugins/logging/operations_test.go b/plugins/logging/operations_test.go
index 30c97900ef4..25e4773e33c 100644
--- a/plugins/logging/operations_test.go
+++ b/plugins/logging/operations_test.go
@@ -347,7 +347,6 @@ func TestPostLLMHookStreamingErrorPreservesHeaderMetadata(t *testing.T) {
if _, _, err = plugin.PreLLMHook(ctx, req); err != nil {
t.Fatalf("PreLLMHook() error = %v", err)
}
-
statusCode := 500
bifrostErr := &schemas.BifrostError{
IsBifrostError: true,
@@ -395,7 +394,8 @@ func TestPostLLMHookStreamingErrorPreservesHeaderMetadata(t *testing.T) {
}
// TestPostLLMHookCancelledStreamLogsCost verifies #3357 at the logging layer: a
-// streaming request cancelled mid-flight (result==nil) whose error carries the
+// streaming request cancelled mid-flight (including when a chunk is returned)
+// whose error carries the
// partial usage the provider already processed (BifrostError.ExtraFields.BilledUsage)
// must produce a log row with status="cancelled", the consumed tokens, AND an
// accurate cost computed from the datasheet rates.
@@ -433,6 +433,26 @@ func TestPostLLMHookCancelledStreamLogsCost(t *testing.T) {
if _, _, err = plugin.PreLLMHook(ctx, req); err != nil {
t.Fatalf("PreLLMHook() error = %v", err)
}
+ embeddingProvider := "openai"
+ embeddingModel := "text-embedding-3-small"
+ embeddingTokens := 12
+ if !schemas.SetCacheDebugOnContext(ctx, &schemas.BifrostCacheDebug{
+ ProviderUsed: &embeddingProvider,
+ ModelUsed: &embeddingModel,
+ InputTokens: &embeddingTokens,
+ }) {
+ t.Fatal("expected semantic cache debug to be stored on context")
+ }
+ if !schemas.AppendGuardrailJudgeCallOnContext(ctx, schemas.BifrostGuardrailJudgeCall{
+ JudgeProvider: schemas.OpenAI,
+ JudgeModel: "gpt-4o",
+ JudgeRequestType: schemas.ChatCompletionRequest,
+ PromptTokens: 10,
+ CompletionTokens: 5,
+ TotalTokens: 15,
+ }) {
+ t.Fatal("expected guardrail judge call to be stored on context")
+ }
const promptTokens, completionTokens = 100, 50
statusCode := 499 // client closed request (mid-stream cancel)
@@ -453,7 +473,17 @@ func TestPostLLMHookCancelledStreamLogsCost(t *testing.T) {
},
},
}
- if _, _, err = plugin.PostLLMHook(ctx, nil, bifrostErr); err != nil {
+ streamChunk := &schemas.BifrostResponse{
+ ChatResponse: &schemas.BifrostChatResponse{
+ ExtraFields: schemas.BifrostResponseExtraFields{
+ RequestType: schemas.ChatCompletionStreamRequest,
+ Provider: schemas.OpenAI,
+ OriginalModelRequested: "gpt-4o",
+ ResolvedModelUsed: "gpt-4o",
+ },
+ },
+ }
+ if _, _, err = plugin.PostLLMHook(ctx, streamChunk, bifrostErr); err != nil {
t.Fatalf("PostLLMHook() error = %v", err)
}
if err := plugin.Cleanup(); err != nil {
@@ -477,7 +507,10 @@ func TestPostLLMHookCancelledStreamLogsCost(t *testing.T) {
t.Fatalf("expected a cost to be logged for a cancelled request that consumed tokens (#3357)")
}
// gpt-4o testdata rates: input 2.5e-6/token, output 1e-5/token.
- want := float64(promptTokens)*2.5e-6 + float64(completionTokens)*1e-5
+ // text-embedding-3-small is 2e-8/token. The cache lookup and the judge call
+ // must both be added even though the stream ended with an error chunk.
+ want := float64(promptTokens)*2.5e-6 + float64(completionTokens)*1e-5 +
+ float64(embeddingTokens)*2e-8 + float64(10)*2.5e-6 + float64(5)*1e-5
if diff := *entry.Cost - want; diff < -1e-9 || diff > 1e-9 {
t.Fatalf("logged cost %v does not match datasheet-computed cost %v", *entry.Cost, want)
}
@@ -2168,3 +2201,24 @@ func TestApplyNonStreamingOutputToEntryContentLoggingEnabled(t *testing.T) {
t.Error("expected OutputMessageParsed to be set when contentLoggingEnabled=true")
}
}
+
+// TestGuardrailDebugForLogReadsContextWithoutResponse verifies input blocks remain observable.
+func TestGuardrailDebugForLogReadsContextWithoutResponse(t *testing.T) {
+ ctx := schemas.NewBifrostContext(nil, schemas.NoDeadline)
+ requireCall := schemas.BifrostGuardrailJudgeCall{
+ JudgeProvider: schemas.OpenAI,
+ JudgeModel: "gpt-test",
+ TotalTokens: 18,
+ }
+ if !schemas.AppendGuardrailJudgeCallOnContext(ctx, requireCall) {
+ t.Fatal("failed to append guardrail judge call")
+ }
+
+ debug := guardrailDebugForLog(ctx, nil)
+ if debug == nil || len(debug.JudgeCalls) != 1 {
+ t.Fatalf("guardrail debug = %#v; want one context judge call", debug)
+ }
+ if debug.JudgeCalls[0] != requireCall {
+ t.Fatalf("guardrail call = %#v; want %#v", debug.JudgeCalls[0], requireCall)
+ }
+}
diff --git a/plugins/logging/utils.go b/plugins/logging/utils.go
index 1ed134ac56d..cb6b16859a9 100644
--- a/plugins/logging/utils.go
+++ b/plugins/logging/utils.go
@@ -829,6 +829,7 @@ func convertToProcessedStreamResponse(result *schemas.StreamAccumulatorResult, r
ErrorDetails: result.ErrorDetails,
TokenUsage: result.TokenUsage,
CacheDebug: result.CacheDebug,
+ GuardrailDebug: result.GuardrailDebug,
Cost: result.Cost,
AudioOutput: result.AudioOutput,
TranscriptionOutput: result.TranscriptionOutput,
diff --git a/plugins/logging/writer.go b/plugins/logging/writer.go
index 6571445651a..d8c2cd1b444 100644
--- a/plugins/logging/writer.go
+++ b/plugins/logging/writer.go
@@ -387,6 +387,7 @@ func estimateLogEntrySize(log *logstore.Log) int {
len(log.PassthroughResponseBody) +
len(log.ContentSummary) +
len(log.CacheDebug) +
+ len(log.GuardrailDebug) +
len(log.RoutingEngineLogs)
// Baseline for fixed-width columns and struct overhead
return n + 512
diff --git a/plugins/semanticcache/plugin_paths_test.go b/plugins/semanticcache/plugin_paths_test.go
index 404274aa2ca..d66c462668d 100644
--- a/plugins/semanticcache/plugin_paths_test.go
+++ b/plugins/semanticcache/plugin_paths_test.go
@@ -385,7 +385,6 @@ func TestPreLLMHook_EmitsPluginLogOnEmbeddingFailure(t *testing.T) {
if _, _, err := plugin.PreLLMHook(ctx, req); err != nil {
t.Fatalf("PreLLMHook failed: %v", err)
}
-
logs := ctx.GetPluginLogs()
if len(logs) == 0 {
t.Fatal("expected at least one plugin log entry on embedding failure, got none")
@@ -440,7 +439,6 @@ func TestPreLLMHook_NoDebugLogsOnFlow(t *testing.T) {
if _, _, err := plugin.PreLLMHook(ctx, req); err != nil {
t.Fatalf("PreLLMHook failed: %v", err)
}
-
logs := ctx.GetPluginLogs()
for _, l := range logs {
if l.PluginName != PluginName {
@@ -452,6 +450,41 @@ func TestPreLLMHook_NoDebugLogsOnFlow(t *testing.T) {
}
}
+// TestPreLLMHookStoresEmbeddingDebug verifies a successful semantic lookup remains billable if the main request later fails.
+func TestPreLLMHookStoresEmbeddingDebug(t *testing.T) {
+ plugin := newTestPlugin(t, newObservableStore())
+ plugin.SetEmbeddingRequestExecutor(func(_ *schemas.BifrostContext, _ *schemas.BifrostEmbeddingRequest) (*schemas.BifrostEmbeddingResponse, *schemas.BifrostError) {
+ return &schemas.BifrostEmbeddingResponse{
+ Data: []schemas.EmbeddingData{{
+ Embedding: schemas.EmbeddingStruct{EmbeddingArray: []float64{0.1, 0.2, 0.3}},
+ }},
+ Usage: &schemas.BifrostLLMUsage{TotalTokens: 12},
+ }, nil
+ })
+ req := &schemas.BifrostRequest{
+ RequestType: schemas.ChatCompletionRequest,
+ ChatRequest: CreateBasicChatRequest("first request", 0.7, 50),
+ }
+ ctx := scopedTestContext(t, "")
+
+ if _, _, err := plugin.PreLLMHook(ctx, req); err != nil {
+ t.Fatalf("PreLLMHook failed: %v", err)
+ }
+ cacheDebug, ok := schemas.CacheDebugFromContext(ctx)
+ if !ok {
+ t.Fatal("expected semantic embedding debug on request context")
+ }
+ if cacheDebug.ProviderUsed == nil || *cacheDebug.ProviderUsed != string(plugin.config.Provider) {
+ t.Fatalf("cache debug provider = %v, want %q", cacheDebug.ProviderUsed, plugin.config.Provider)
+ }
+ if cacheDebug.ModelUsed == nil || *cacheDebug.ModelUsed != plugin.config.EmbeddingModel {
+ t.Fatalf("cache debug model = %v, want %q", cacheDebug.ModelUsed, plugin.config.EmbeddingModel)
+ }
+ if cacheDebug.InputTokens == nil || *cacheDebug.InputTokens != 12 {
+ t.Fatalf("cache debug input tokens = %v, want 12", cacheDebug.InputTokens)
+ }
+}
+
func TestResolveCacheTypes_EmitsPluginLogOnInvalidValue(t *testing.T) {
plugin := newTestPlugin(t, newObservableStore())
ctx := scopedTestContext(t, "")
diff --git a/plugins/semanticcache/search.go b/plugins/semanticcache/search.go
index 4e10e73b9b9..416ff4c3d15 100644
--- a/plugins/semanticcache/search.go
+++ b/plugins/semanticcache/search.go
@@ -66,6 +66,13 @@ func (plugin *Plugin) performSemanticSearch(ctx *schemas.BifrostContext, state *
state.Embeddings = embedding
state.EmbeddingsInputTokens = inputTokens
+ if !schemas.SetCacheDebugOnContext(ctx, &schemas.BifrostCacheDebug{
+ ProviderUsed: bifrost.Ptr(string(plugin.config.Provider)),
+ ModelUsed: bifrost.Ptr(plugin.config.EmbeddingModel),
+ InputTokens: bifrost.Ptr(inputTokens),
+ }) {
+ plugin.logger.Warn("Failed to store semantic cache debug data on request context")
+ }
cacheThreshold := plugin.config.Threshold
if v := ctx.Value(CacheThresholdKey); v != nil {
diff --git a/ui/app/workspace/logs/sheets/logDetailView.tsx b/ui/app/workspace/logs/sheets/logDetailView.tsx
index 7f56237b92a..2ab806c2ada 100644
--- a/ui/app/workspace/logs/sheets/logDetailView.tsx
+++ b/ui/app/workspace/logs/sheets/logDetailView.tsx
@@ -1628,6 +1628,66 @@ export function LogDetailView({
)}
>
)}
+ {!isContainer && !isPassthrough && log.guardrail_debug?.judge_calls && log.guardrail_debug.judge_calls.length > 0 && (
+ <>
+