Documentation
¶
Index ¶
- Constants
- Variables
- func AppendRequestConversionFromRequest(info *RelayInfo, req any)
- func ApplyParamOverride(jsonData []byte, paramOverride map[string]any, conditionContext map[string]any) ([]byte, error)
- func ApplyParamOverrideWithRelayInfo(jsonData []byte, info *RelayInfo) ([]byte, error)
- func BuildParamOverrideContext(info *RelayInfo) map[string]any
- func GetAPIVersion(c *gin.Context) string
- func GetEffectiveHeaderOverride(info *RelayInfo) map[string]any
- func GetFullRequestURL(baseURL string, requestURL string, channelType int) string
- func GuessRelayFormatFromRequest(req any) (types.RelayFormat, bool)
- func IsNonBillableResponsesStatus(status []byte) bool
- func NewAPIErrorFromParamOverride(err *ParamOverrideReturnError) *types.NewAPIError
- func NewOutboundJSONBody(data []byte) (body common.ReplayableBody, closer io.Closer, err error)
- func RemoveDisabledFields(jsonData []byte, channelOtherSettings dto.ChannelOtherSettings, ...) ([]byte, error)
- func RemoveGeminiDisabledFields(jsonData []byte) ([]byte, error)
- func SanitizeURLForLog(rawURL string) string
- type BillingSettler
- type BuildInToolInfo
- type ChannelMeta
- type ClaudeConvertInfo
- type ConditionOperation
- type HasImage
- type HasPrompt
- type ImageGenerationCallCounter
- type ParamOperation
- type ParamOverrideReturnError
- type RelayInfo
- func GenRelayInfo(c *gin.Context, relayFormat types.RelayFormat, request dto.Request, ...) (*RelayInfo, error)
- func GenRelayInfoAlphaSearch(c *gin.Context, request *dto.AlphaSearchRequest) *RelayInfo
- func GenRelayInfoClaude(c *gin.Context, request dto.Request) *RelayInfo
- func GenRelayInfoEmbedding(c *gin.Context, request dto.Request) *RelayInfo
- func GenRelayInfoGemini(c *gin.Context, request dto.Request) *RelayInfo
- func GenRelayInfoImage(c *gin.Context, request dto.Request) *RelayInfo
- func GenRelayInfoOpenAI(c *gin.Context, request dto.Request) *RelayInfo
- func GenRelayInfoOpenAIAudio(c *gin.Context, request dto.Request) *RelayInfo
- func GenRelayInfoRerank(c *gin.Context, request *dto.RerankRequest) *RelayInfo
- func GenRelayInfoResponses(c *gin.Context, request *dto.OpenAIResponsesRequest) *RelayInfo
- func GenRelayInfoResponsesCompaction(c *gin.Context, request *dto.OpenAIResponsesCompactionRequest) *RelayInfo
- func GenRelayInfoWs(c *gin.Context, ws *websocket.Conn) *RelayInfo
- func (info *RelayInfo) AppendRequestConversion(format types.RelayFormat)
- func (info *RelayInfo) ChatWebSearchWithoutCallCount() bool
- func (info *RelayInfo) ConvOptions() *convmeta.Options
- func (info *RelayInfo) ConversionDiagnostics() []types.ConversionDiagnostic
- func (info *RelayInfo) ConversionDiagnosticsTruncated() bool
- func (info *RelayInfo) CountBillableToolCall(itemType string, functionName string)
- func (info *RelayInfo) EnsureClaudeConvertInfo() *convmeta.ClaudeConvertInfo
- func (info *RelayInfo) GetBillingModelName() string
- func (info *RelayInfo) GetChannelID() int
- func (info *RelayInfo) GetChannelType() int
- func (info *RelayInfo) GetEstimatePromptTokens() int
- func (info *RelayInfo) GetFinalRequestRelayFormat() types.RelayFormat
- func (info *RelayInfo) GetIsStream() bool
- func (info *RelayInfo) GetOriginModelName() string
- func (info *RelayInfo) GetReasoningEffort() string
- func (info *RelayInfo) GetSendResponseCount() int
- func (info *RelayInfo) GetUpstreamModelName() string
- func (info *RelayInfo) HasChannelMeta() bool
- func (info *RelayInfo) HasSendResponse() bool
- func (info *RelayInfo) IncrSendResponseCount()
- func (info *RelayInfo) InitChannelMeta(c *gin.Context)
- func (info *RelayInfo) InitRequestConversionChain()
- func (info *RelayInfo) IsSearchPreviewModel() bool
- func (info *RelayInfo) ObserveResponseModel(model string)
- func (info *RelayInfo) ReasoningState() *dto.ReasoningConversionState
- func (info *RelayInfo) RecordConversionDiagnostics(ctx context.Context, diagnostics []types.ConversionDiagnostic)
- func (info *RelayInfo) RequestedImageCount() int
- func (info *RelayInfo) SetEstimatePromptTokens(promptTokens int)
- func (info *RelayInfo) SetFirstResponseTime()
- func (info *RelayInfo) SetReasoningEffort(effort string)
- func (info *RelayInfo) SetUpstreamHostedToolTypes(hostedToolTypes []string)
- func (info *RelayInfo) ToString() string
- func (info *RelayInfo) UndeclaredBillableToolCalls(observed []string) []string
- func (info *RelayInfo) UpdateImageCount(count int64)
- func (info *RelayInfo) UpstreamBillableToolNames() []string
- type RerankerInfo
- type ResponseModel
- type ResponseOutcome
- type ResponsesUsageInfo
- type StreamEndReason
- type StreamErrorEntry
- type StreamOutcome
- type StreamStatus
- func (s *StreamStatus) HasErrors() bool
- func (s *StreamStatus) IsNormalEnd() bool
- func (s *StreamStatus) MarkCancelled()
- func (s *StreamStatus) MarkCompleted()
- func (s *StreamStatus) MarkFailed(code, errorType string, status int)
- func (s *StreamStatus) MarkIncomplete(reason string)
- func (s *StreamStatus) OutcomeSnapshot() StreamOutcome
- func (s *StreamStatus) RecordError(msg string)
- func (s *StreamStatus) RequireTerminal()
- func (s *StreamStatus) ResponseFailed() bool
- func (s *StreamStatus) ResponseOutcome() string
- func (s *StreamStatus) SetEndReason(reason StreamEndReason, err error)
- func (s *StreamStatus) Summary() string
- func (s *StreamStatus) TotalErrorCount() int
- type ThinkingContentInfo
- type TokenCountMeta
Constants ¶
const ( LastMessageTypeNone = convmeta.LastMessageTypeNone LastMessageTypeText = convmeta.LastMessageTypeText LastMessageTypeTools = convmeta.LastMessageTypeTools LastMessageTypeThinking = convmeta.LastMessageTypeThinking )
Variables ¶
var ReservedBillableToolNames = map[string]struct{}{ dto.BuildInToolWebSearchPreview: {}, dto.BuildInToolWebSearch: {}, dto.BuildInToolFileSearch: {}, dto.BuildInToolGoogleSearch: {}, dto.BuildInToolImageGeneration: {}, }
ReservedBillableToolNames are the built-in tool identities this gateway can charge for, keyed by the name an operator prices. Custom function names are deliberately absent: they are billed only when that exact name is priced.
Functions ¶
func ApplyParamOverride ¶
func BuildParamOverrideContext ¶
BuildParamOverrideContext 提供 ApplyParamOverride 可用的上下文信息。 目前内置以下字段:
- upstream_model/model:始终为通道映射后的上游模型名。
- original_model:请求最初指定的模型名。
- user_id:已认证用户 ID。
- user_group:用户所属分组。
- token_group:令牌指定的分组;未指定时回退为用户分组。
- using_group:当前实际使用的分组,自动跨分组重试时可能变化。
- request_path:请求路径
- is_channel_test:是否为渠道测试请求(同 is_test)。
func GetAPIVersion ¶
func GetFullRequestURL ¶
func GuessRelayFormatFromRequest ¶
func GuessRelayFormatFromRequest(req any) (types.RelayFormat, bool)
GuessRelayFormatFromRequest moved to convmeta with the converters; the delegation keeps host callers unchanged.
func IsNonBillableResponsesStatus ¶
IsNonBillableResponsesStatus reports terminal response statuses that must not bill pending image_generation observations.
func NewAPIErrorFromParamOverride ¶
func NewAPIErrorFromParamOverride(err *ParamOverrideReturnError) *types.NewAPIError
func NewOutboundJSONBody ¶
NewOutboundJSONBody wraps the already-marshaled upstream request body into a BodyStorage. When disk cache is enabled and the payload exceeds the configured threshold, the data is written to a temp file and the original []byte can be GC'd, significantly reducing the heap residency while waiting for the upstream provider to respond (the dominant cost for large base64 payloads).
In memory mode the underlying memoryStorage reuses the same backing array, so this is equivalent to bytes.NewReader(data) in terms of memory usage.
The caller MUST invoke closer.Close() once the upstream call has finished (typically via defer) to release the disk file / memory accounting.
The returned body exposes its size and replay capability without exposing io.Closer. Request construction uses that metadata to populate ContentLength and GetBody, while the caller retains ownership of the underlying storage through the separately returned closer.
func RemoveDisabledFields ¶
func RemoveDisabledFields(jsonData []byte, channelOtherSettings dto.ChannelOtherSettings, channelPassThroughEnabled bool) ([]byte, error)
RemoveDisabledFields 从请求 JSON 数据中移除渠道设置中禁用的字段 service_tier: 服务层级字段,可能导致额外计费(OpenAI、Claude、Responses API 支持) inference_geo: Claude 数据驻留推理区域字段(仅 Claude 支持,默认过滤) speed: Claude 推理速度模式字段(仅 Claude 支持,默认过滤) store: 数据存储授权字段,涉及用户隐私(仅 OpenAI、Responses API 支持,默认允许透传,禁用后可能导致 Codex 无法使用) safety_identifier: 安全标识符,用于向 OpenAI 报告违规用户(仅 OpenAI 支持,涉及用户隐私) stream_options.include_obfuscation: 响应流混淆控制字段(仅 OpenAI Responses API 支持)
func RemoveGeminiDisabledFields ¶
RemoveGeminiDisabledFields removes disabled fields from Gemini request JSON data Currently supports removing functionResponse.id field which Vertex AI does not support
func SanitizeURLForLog ¶
Types ¶
type BillingSettler ¶
type BillingSettler interface {
// Settle 根据实际消耗额度进行结算,计算 delta = actualQuota - preConsumedQuota,
// 同时调整资金来源(钱包/订阅)和令牌额度。
Settle(actualQuota int) error
// Refund 退还所有预扣费额度(资金来源 + 令牌),幂等安全。
// 通过 gopool 异步执行。如果已经结算或退款则不做任何操作。
Refund(c *gin.Context)
// NeedsRefund 返回会话是否存在需要退还的预扣状态(未结算且未退款)。
NeedsRefund() bool
// GetPreConsumedQuota 返回实际预扣的额度值(信任用户可能为 0)。
GetPreConsumedQuota() int
// Reserve 将预扣额度补到目标值;若目标值不高于当前预扣额度则不做任何事。
Reserve(targetQuota int) error
}
BillingSettler 抽象计费会话的生命周期操作。 由 service.BillingSession 实现,存储在 RelayInfo 上以避免循环引用。
type BuildInToolInfo ¶
type ChannelMeta ¶
type ChannelMeta struct {
ChannelType int
ChannelId int
ChannelIsMultiKey bool
ChannelMultiKeyIndex int
ChannelBaseUrl string
ApiType int
ApiVersion string
ApiKey string
Organization string
ChannelCreateTime int64
ParamOverride map[string]any
HeadersOverride map[string]any
ChannelSetting dto.ChannelSettings
ChannelOtherSettings dto.ChannelOtherSettings
UpstreamModelName string
IsModelMapped bool
SupportStreamOptions bool // 是否支持流式选项
}
type ClaudeConvertInfo ¶
type ClaudeConvertInfo = convmeta.ClaudeConvertInfo
ClaudeConvertInfo now lives with the converters (convmeta); the alias keeps host code and adaptors compiling unchanged.
type ConditionOperation ¶
type ImageGenerationCallCounter ¶
type ImageGenerationCallCounter struct {
// contains filtered or unexported fields
}
ImageGenerationCallCounter counts completed Responses image_generation_call outputs with stream-safe identity deduplication.
func (*ImageGenerationCallCounter) Commit ¶
func (c *ImageGenerationCallCounter) Commit(info *RelayInfo)
Commit writes the capped completed-output count into RelayInfo once. Request tool declarations alone must not become billable calls.
func (*ImageGenerationCallCounter) Count ¶
func (c *ImageGenerationCallCounter) Count() int
Count returns the deduplicated completed image output count before commit capping.
func (*ImageGenerationCallCounter) Observe ¶
func (c *ImageGenerationCallCounter) Observe(item *dto.ResponsesOutput, outputIndex *int)
Observe records one completed final image output when billable. outputIndex may be nil; when set and nonnegative it participates in dedup.
func (*ImageGenerationCallCounter) Reset ¶
func (c *ImageGenerationCallCounter) Reset()
Reset clears pending observations (used when a terminal response fails).
type ParamOperation ¶
type ParamOperation struct {
Path string `json:"path"`
Mode string `json:"mode"` // delete, set, move, copy, prepend, append, trim_prefix, trim_suffix, ensure_prefix, ensure_suffix, trim_space, to_lower, to_upper, replace, regex_replace, return_error, prune_objects, set_header, delete_header, copy_header, move_header, pass_headers, sync_fields
Value any `json:"value"`
KeepOrigin bool `json:"keep_origin"`
From string `json:"from,omitempty"`
To string `json:"to,omitempty"`
Conditions []ConditionOperation `json:"conditions,omitempty"` // 条件列表
Logic string `json:"logic,omitempty"` // AND, OR (默认OR)
}
type ParamOverrideReturnError ¶
type ParamOverrideReturnError struct {
Message string
StatusCode int
Code string
Type string
SkipRetry bool
}
func AsParamOverrideReturnError ¶
func AsParamOverrideReturnError(err error) (*ParamOverrideReturnError, bool)
func (*ParamOverrideReturnError) Error ¶
func (e *ParamOverrideReturnError) Error() string
type RelayInfo ¶
type RelayInfo struct {
TokenId int
TokenKey string
TokenGroup string
UserId int
UsingGroup string // 使用的分组,当auto跨分组重试时,会变动
UserGroup string // 用户所在分组
TokenUnlimited bool
StartTime time.Time
FirstResponseTime time.Time
// AttemptStartTime is when the current upstream attempt began, so a budget
// that bounds one attempt (the wait for its first content) restarts on a
// retry instead of inheriting the time the previous attempt already spent.
AttemptStartTime time.Time
// ResponseEndTime is the instant the relay stopped serving this request,
// recorded once with the settlement reading that the consume log's
// use_time_ms comes from. The perf sample measures its latency and
// generation windows from this instant instead of from the wall clock at
// sampling time, because settlement (quota updates and the consume-log
// write) runs between the two and would otherwise be charged to the model.
ResponseEndTime time.Time
//SendLastReasoningResponse bool
IsStream bool
IsGeminiBatchEmbedding bool
IsPlayground bool
UsePrice bool
RelayMode int
OriginModelName string
ResponseModel *ResponseModel
// BillingModelName is the pricing identity for this request. It is kept
// separate from OriginModelName and UpstreamModelName so virtual pricing
// aliases never participate in channel selection or upstream routing.
BillingModelName string
RequestURLPath string
RequestHeaders map[string]string
// ConversationID identifies the downstream conversation this request belongs
// to. It is derived on first use (header_override {conversation_id}) and
// cached here so every upstream header of one attempt agrees on it.
ConversationID string
ShouldIncludeUsage bool
// TokenBudgetSettled records that the per-key TPM reservation was replaced
// by the settled usage, so a later failure refund must not drop it.
TokenBudgetSettled bool
// TokenBudgetMember identifies this request's TPM reservation. A WebSocket
// connection handles several response.create events under one request id,
// so each event needs its own member.
TokenBudgetMember string
DisablePing bool // 是否禁止向下游发送自定义 Ping
ClientWs *websocket.Conn
TargetWs *websocket.Conn
InputAudioFormat string
OutputAudioFormat string
RealtimeTools []dto.RealTimeTool
IsFirstRequest bool
AudioUsage bool
ReasoningEffort string
// ReasoningConversion is the suffix-derived reasoning intent attached
// after model mapping. Converters read it via ReasoningState().
ReasoningConversion *dto.ReasoningConversionState
UserSetting dto.UserSetting
UserEmail string
UserQuota int
RelayFormat types.RelayFormat
SendResponseCount int
// ClaudeToChatStreamState / ChatToGeminiStreamState hold per-attempt
// stream converters. InitChannelMeta nils them so a retry cannot resume a
// dirty converter (advanced tool index / finalized).
ClaudeToChatStreamState any
ChatToGeminiStreamState any
ReceivedResponseCount int
FinalPreConsumedQuota int // 最终预消耗的配额
// ForcePreConsume 为 true 时禁用 BillingSession 的信任额度旁路,
// 强制预扣全额。用于异步任务(视频/音乐生成等),因为请求返回后任务仍在运行,
// 必须在提交前锁定全额。
ForcePreConsume bool
// Billing 是计费会话,封装了预扣费/结算/退款的统一生命周期。
// 初始免费组可为 nil;若 auto 重试切换到付费组,会在发送前创建。
Billing BillingSettler
// RequestId is used for idempotent pre-consume/refund
RequestId string
IsClaudeBetaQuery bool // /v1/messages?beta=true
IsChannelTest bool // channel test request
RetryIndex int
LastError *types.NewAPIError
RuntimeHeadersOverride map[string]any
UseRuntimeHeadersOverride bool
ParamOverrideAudit []string
PriceData hosttypes.PriceData
// QuotaClamp is set (non-nil) when a quota conversion saturated at the
// supported single-request bound (or NaN fallback) while computing this request's charge.
// It is surfaced onto the consume/task log's admin_info for auditing.
QuotaClamp *common.QuotaClamp
// TieredBillingSnapshot captures tiered billing rules at pre-consume time.
// Auto-group retries refresh its group-dependent fields before each attempt
// and again before settlement. Non-nil only when billing mode is "tiered_expr".
TieredBillingSnapshot *billingexpr.BillingSnapshot
BillingRequestInput *billingexpr.RequestInput
BillingImageCount *int
// ImageRequestCount is the effective quantity sent on the current attempt;
// ImageQuotaBeforeGroup is the frozen legacy estimate before request ratios.
ImageRequestCount int
ImageQuotaBeforeGroup float64
Request dto.Request
// RequestConversionChain records request format conversions in order, e.g.
// ["openai", "openai_responses"] or ["openai", "claude"].
RequestConversionChain []types.RelayFormat
// 最终请求到上游的格式。可由 adaptor 显式设置;
// 若为空,调用 GetFinalRequestRelayFormat 会回退到 RequestConversionChain 的最后一项或 RelayFormat。
FinalRequestRelayFormat types.RelayFormat
StreamStatus *StreamStatus
// PerformanceOutputTokens is captured by settlement and sampled once at
// the request boundary, independently of billing success or failure.
PerformanceOutputTokens int64
PerformanceBusinessRejection bool
ThinkingContentInfo
TokenCountMeta
*ClaudeConvertInfo
*RerankerInfo
*ResponsesUsageInfo
*ChannelMeta
// contains filtered or unexported fields
}
func GenRelayInfo ¶
func GenRelayInfoAlphaSearch ¶
func GenRelayInfoAlphaSearch(c *gin.Context, request *dto.AlphaSearchRequest) *RelayInfo
func GenRelayInfoEmbedding ¶
func GenRelayInfoOpenAIAudio ¶
func GenRelayInfoRerank ¶
func GenRelayInfoRerank(c *gin.Context, request *dto.RerankRequest) *RelayInfo
func GenRelayInfoResponses ¶
func GenRelayInfoResponses(c *gin.Context, request *dto.OpenAIResponsesRequest) *RelayInfo
func GenRelayInfoResponsesCompaction ¶
func GenRelayInfoResponsesCompaction(c *gin.Context, request *dto.OpenAIResponsesCompactionRequest) *RelayInfo
func (*RelayInfo) AppendRequestConversion ¶
func (info *RelayInfo) AppendRequestConversion(format types.RelayFormat)
func (*RelayInfo) ChatWebSearchWithoutCallCount ¶
ChatWebSearchWithoutCallCount reports whether this attempt declares a hosted web search in the Chat Completions dialect, which reports no call detail: the upstream performs the search, the gateway never learns how many, so settlement charges the declaration as one fixed call. A declaration the conversion turned into web_search or google_search is counted from the response instead and is not this case. The upstream format decides: a chat request bridged to a Responses upstream is settled from counted items, and its conversion reports the Responses tool type rather than this dialect's field.
func (*RelayInfo) ConvOptions ¶
ConvOptions snapshots host settings for the converters. Rebuilt on each call site's first use; cached so one relay session sees one snapshot.
func (*RelayInfo) ConversionDiagnostics ¶
func (info *RelayInfo) ConversionDiagnostics() []types.ConversionDiagnostic
func (*RelayInfo) ConversionDiagnosticsTruncated ¶
func (*RelayInfo) CountBillableToolCall ¶
CountBillableToolCall is the single entry point for per-call tool billing counts. Built-in call types always count; custom function/tool_use names only count when priced.
func (*RelayInfo) EnsureClaudeConvertInfo ¶
func (info *RelayInfo) EnsureClaudeConvertInfo() *convmeta.ClaudeConvertInfo
func (*RelayInfo) GetBillingModelName ¶
GetBillingModelName returns the effective pricing identity without changing either the client-visible model or the model sent to the selected channel.
func (*RelayInfo) GetChannelID ¶
func (*RelayInfo) GetChannelType ¶
func (*RelayInfo) GetEstimatePromptTokens ¶
func (*RelayInfo) GetFinalRequestRelayFormat ¶
func (info *RelayInfo) GetFinalRequestRelayFormat() types.RelayFormat
func (*RelayInfo) GetIsStream ¶
func (*RelayInfo) GetOriginModelName ¶
func (*RelayInfo) GetReasoningEffort ¶
func (*RelayInfo) GetSendResponseCount ¶
func (*RelayInfo) GetUpstreamModelName ¶
func (*RelayInfo) HasChannelMeta ¶
func (*RelayInfo) HasSendResponse ¶
func (*RelayInfo) IncrSendResponseCount ¶
func (info *RelayInfo) IncrSendResponseCount()
func (*RelayInfo) InitChannelMeta ¶
func (*RelayInfo) InitRequestConversionChain ¶
func (info *RelayInfo) InitRequestConversionChain()
func (*RelayInfo) IsSearchPreviewModel ¶
IsSearchPreviewModel reports whether the model name alone charges one built-in web search call per request. Responses requests are excluded: they are charged from declared tools and counted tool-call items instead.
func (*RelayInfo) ObserveResponseModel ¶
ObserveResponseModel retains the first differing model for inspection, with mismatches taking priority over provider-path, prefix, or case-only differences. A later matching or empty event cannot erase it. Only observe upstream declarations, never models synthesized by a response converter.
func (*RelayInfo) ReasoningState ¶
func (info *RelayInfo) ReasoningState() *dto.ReasoningConversionState
func (*RelayInfo) RecordConversionDiagnostics ¶
func (info *RelayInfo) RecordConversionDiagnostics(ctx context.Context, diagnostics []types.ConversionDiagnostic)
RecordConversionDiagnostics retains conversion losses for the consume log and emits one request-correlated warning per distinct diagnostic. The cap prevents malformed streams from growing request state without bound.
func (*RelayInfo) RequestedImageCount ¶
func (*RelayInfo) SetEstimatePromptTokens ¶
func (*RelayInfo) SetFirstResponseTime ¶
func (info *RelayInfo) SetFirstResponseTime()
func (*RelayInfo) SetReasoningEffort ¶
func (*RelayInfo) SetUpstreamHostedToolTypes ¶
SetUpstreamHostedToolTypes records the hosted tool types the request converter wrote into the upstream request for this attempt. Converters report every hosted tool they wrote, including tools this gateway cannot charge, so the billing side decides which of them carry a price.
func (*RelayInfo) UndeclaredBillableToolCalls ¶
UndeclaredBillableToolCalls returns the observed built-in tool identities this attempt never declared to the upstream, sorted. Settlement may only charge a tool the upstream was asked for, so a non-empty result means the request-time price gate and settlement have drifted apart - a new counter, a new target format, or a conversion that stopped reporting. Callers log it rather than charging an undeclared tool in silence. Custom function names are excluded: they are billed only when priced and only when actually called.
func (*RelayInfo) UpdateImageCount ¶
UpdateImageCount replaces the billable quantity without changing the frozen request parameters or multiplying the legacy and expression prices together.
func (*RelayInfo) UpstreamBillableToolNames ¶
UpstreamBillableToolNames lists the built-in billable tool price identities this attempt can actually be charged for. When a converter rewrote the request body for the selected channel, the identities come from the hosted tool types that converter wrote upstream: a tool the target format cannot represent is dropped before the upstream ever sees it and therefore cannot be charged, so demanding a price for it would refuse a request that was never billable. Without a conversion the client's own format is the upstream namespace, and the client's declarations are the answer. A Chat Completions web search is charged per request whatever the client declared, so it is added on top.
Callers run this after the request has been converted, because the upstream format is decided per attempt by the selected channel.
type RerankerInfo ¶
type ResponseModel ¶
type ResponseModel struct {
RequestedModel string `json:"requested_model"`
UpstreamModel string `json:"upstream_model"`
ReturnedModel string `json:"returned_model"`
}
ResponseModel records upstream declarations before response conversion. It is diagnostic only: it must never change routing, pricing, or downstream output. Only the three names are stored; whether they disagree is computed on demand so every consumer applies the current comparison rule to old rows as well.
func (*ResponseModel) Mismatch ¶
func (r *ResponseModel) Mismatch() bool
Mismatch reports whether the retained upstream declaration disagrees with both the requested and upstream models.
type ResponseOutcome ¶
type ResponseOutcome string
ResponseOutcome is the protocol-level result of one response, independent of how the transport ended. Adaptors mark it from the events they already parse.
const ( ResponseOutcomeUnknown ResponseOutcome = "" ResponseOutcomeCompleted ResponseOutcome = "completed" ResponseOutcomeFailed ResponseOutcome = "failed" ResponseOutcomeIncomplete ResponseOutcome = "incomplete" ResponseOutcomeCancelled ResponseOutcome = "cancelled" )
type ResponsesUsageInfo ¶
type ResponsesUsageInfo struct {
BuiltInTools map[string]*BuildInToolInfo
// DeclaredTools is the request's own tool declarations, snapshotted when the
// relay info is built. BuiltInTools starts as a copy of them but is written
// to while the response is counted (a counted call item adds or increments an
// entry), so reading declarations back out of it after the response would
// also read whatever the upstream reported. The tool price gate and the
// settlement tripwire compare against this snapshot so their identity set is
// the same before and after the response. nil means the relay info was not
// built from a Responses-shaped request, and callers fall back to the
// BuiltInTools keys; a non-nil empty slice means the request declared no tool.
DeclaredTools []string
}
type StreamEndReason ¶
type StreamEndReason string
const ( StreamEndReasonNone StreamEndReason = "" StreamEndReasonDone StreamEndReason = "done" StreamEndReasonTimeout StreamEndReason = "timeout" StreamEndReasonClientGone StreamEndReason = "client_gone" StreamEndReasonScannerErr StreamEndReason = "scanner_error" StreamEndReasonHandlerStop StreamEndReason = "handler_stop" StreamEndReasonEOF StreamEndReason = "eof" StreamEndReasonPanic StreamEndReason = "panic" StreamEndReasonPingFail StreamEndReason = "ping_fail" )
type StreamErrorEntry ¶
type StreamOutcome ¶
type StreamOutcome struct {
EndReason StreamEndReason
HasErrors bool
ExpectsTerminal bool
Response ResponseOutcome
ErrorCode string
ErrorType string
ErrorStatus int
IncompleteReason string
}
StreamOutcome holds classification facts only; upstream messages never enter it because they may contain credentials or request content.
type StreamStatus ¶
type StreamStatus struct {
EndReason StreamEndReason
EndError error
Errors []StreamErrorEntry
ErrorCount int
// contains filtered or unexported fields
}
func NewStreamStatus ¶
func NewStreamStatus() *StreamStatus
func (*StreamStatus) HasErrors ¶
func (s *StreamStatus) HasErrors() bool
func (*StreamStatus) IsNormalEnd ¶
func (s *StreamStatus) IsNormalEnd() bool
func (*StreamStatus) MarkCancelled ¶
func (s *StreamStatus) MarkCancelled()
func (*StreamStatus) MarkCompleted ¶
func (s *StreamStatus) MarkCompleted()
MarkCompleted, MarkIncomplete and MarkCancelled keep the first terminal seen; MarkFailed always wins because an error after completion is still a failure.
func (*StreamStatus) MarkFailed ¶
func (s *StreamStatus) MarkFailed(code, errorType string, status int)
MarkFailed records a protocol failure. Empty details never erase details recorded earlier, so a bare error envelope keeps the structured error.
func (*StreamStatus) MarkIncomplete ¶
func (s *StreamStatus) MarkIncomplete(reason string)
func (*StreamStatus) OutcomeSnapshot ¶
func (s *StreamStatus) OutcomeSnapshot() StreamOutcome
func (*StreamStatus) RecordError ¶
func (s *StreamStatus) RecordError(msg string)
func (*StreamStatus) RequireTerminal ¶
func (s *StreamStatus) RequireTerminal()
RequireTerminal declares that the protocol always ends with an explicit terminal event, so a stream that ends without one was cut short.
func (*StreamStatus) ResponseFailed ¶
func (s *StreamStatus) ResponseFailed() bool
func (*StreamStatus) ResponseOutcome ¶
func (s *StreamStatus) ResponseOutcome() string
func (*StreamStatus) SetEndReason ¶
func (s *StreamStatus) SetEndReason(reason StreamEndReason, err error)
func (*StreamStatus) Summary ¶
func (s *StreamStatus) Summary() string
func (*StreamStatus) TotalErrorCount ¶
func (s *StreamStatus) TotalErrorCount() int
type ThinkingContentInfo ¶
type TokenCountMeta ¶
type TokenCountMeta struct {
// contains filtered or unexported fields
}