Documentation
¶
Overview ¶
Package flow provides chat orchestration and retry logic.
Index ¶
- Constants
- Variables
- func BackoffWithJitter(attempt int, cfg *RetryConfig) time.Duration
- func BuildToolPrompt(tools []Tool, toolChoice any, parallelCalls bool) string
- func FlowAPIKeyIDFromContext(ctx context.Context) uint
- func IsCFChallenge(err error) bool
- func IsNonRecoverable(err error) bool
- func IsRetryable(err error) bool
- func MapReasoningEffort(effort string) (grokThinking string, enabled bool)
- func ShouldCoolToken(err error, cfg *RetryConfig) bool
- func ShouldResetSession(err error, cfg *RetryConfig) bool
- func ShouldSwapToken(err error, cfg *RetryConfig) bool
- func SplitByTagPrefix(text, tag string) (string, string)
- func SuffixPrefixLength(text, tag string) int
- type ChatFlow
- type ChatFlowConfig
- type ChatRequest
- type ContentBlock
- type DownloadFunc
- type Function
- type FunctionCall
- type ImageData
- type ImageEditClient
- type ImageEditClientFactory
- type ImageEditRequest
- type ImageFlow
- func (f *ImageFlow) Edit(ctx context.Context, req *ImageEditRequest) (*ImageResponse, error)
- func (f *ImageFlow) Generate(ctx context.Context, req *ImageRequest) (*ImageResponse, error)
- func (f *ImageFlow) SetAppConfig(cfg *config.AppConfig)
- func (f *ImageFlow) SetEditClientFactory(factory ImageEditClientFactory)
- func (f *ImageFlow) SetImageConfig(cfg *config.ImageConfig)
- func (f *ImageFlow) SetTokenConfig(cfg *config.TokenConfig)
- func (f *ImageFlow) SetUsageRecorder(ur UsageRecorder)
- type ImageRequest
- type ImageResponse
- type ImageURLBlock
- type ImagineClientFactory
- type ImagineGenerator
- type Message
- type ProcessedContent
- type RetryConfig
- type StreamEvent
- type TokenServicer
- type Tool
- type ToolCall
- type Usage
- type UsageBuffer
- type UsageLogBatchInserter
- type UsageRecorder
- type VideoClient
- type VideoFlow
- type VideoFlowConfig
- type VideoRequest
- type XAIClientFactory
Constants ¶
const FlowAPIKeyIDKey flowCtxKey = "apiKeyID"
FlowAPIKeyIDKey is the context key for API key ID in the flow layer. HTTP handlers must bridge from their own context key to this one.
Variables ¶
var ErrRetryBudgetExceeded = errors.New("retry budget exhausted")
ErrRetryBudgetExceeded indicates retry time budget has been exhausted.
Functions ¶
func BackoffWithJitter ¶
func BackoffWithJitter(attempt int, cfg *RetryConfig) time.Duration
BackoffWithJitter calculates backoff delay with exponential growth and jitter. Formula: min(base * 2^attempt, max) * (1 +/- jitter)
func BuildToolPrompt ¶
BuildToolPrompt generates a system prompt with tool definitions. Returns empty string if tools is empty or toolChoice is "none".
func FlowAPIKeyIDFromContext ¶
FlowAPIKeyIDFromContext extracts the API key ID from context.
func IsCFChallenge ¶
IsCFChallenge returns true if the error is a Cloudflare challenge.
func IsNonRecoverable ¶
IsNonRecoverable returns true if the error should NOT be retried. Non-recoverable: context errors, ErrInvalidToken (401), 400 Bad Request.
func IsRetryable ¶
IsRetryable returns true if the error is retryable (all errors except non-recoverable).
func MapReasoningEffort ¶
MapReasoningEffort maps OpenAI reasoning_effort to Grok thinking parameter.
func ShouldCoolToken ¶
func ShouldCoolToken(err error, cfg *RetryConfig) bool
ShouldCoolToken returns true if the error indicates the token should be cooled. Only token-related errors (rate limit, forbidden) trigger cooling, not gateway errors.
func ShouldResetSession ¶
func ShouldResetSession(err error, cfg *RetryConfig) bool
ShouldResetSession returns true if a session reset should be attempted. CF challenge always resets session. Token-level 403 does NOT (token is bad, not session).
func ShouldSwapToken ¶
func ShouldSwapToken(err error, cfg *RetryConfig) bool
ShouldSwapToken returns true if the error should trigger an immediate token swap. CF challenge does NOT swap (same token can retry after session reset). Token-level 403 (ErrForbidden) swaps because the token is bad.
func SplitByTagPrefix ¶
SplitByTagPrefix splits text at the point where a suffix of text matches a prefix of tag, returning (clean, carry). This prevents partial tag matches from being emitted during streaming.
func SuffixPrefixLength ¶
SuffixPrefixLength returns the length of the longest suffix of text that matches a prefix of tag.
Types ¶
type ChatFlow ¶
type ChatFlow struct {
// contains filtered or unexported fields
}
ChatFlow orchestrates chat completion with retry logic.
func NewChatFlow ¶
func NewChatFlow(tokenSvc TokenServicer, clientFactory XAIClientFactory, cfg *ChatFlowConfig) *ChatFlow
NewChatFlow creates a new chat flow orchestrator.
func (*ChatFlow) Complete ¶
func (f *ChatFlow) Complete(ctx context.Context, req *ChatRequest) (<-chan StreamEvent, error)
Complete executes a chat completion with retry logic. Returns a channel of StreamEvents. The channel is closed when done.
func (*ChatFlow) SetAPIKeyUsageInc ¶
SetAPIKeyUsageInc sets the callback to increment API key daily usage on success.
func (*ChatFlow) SetCFRefreshTrigger ¶
func (f *ChatFlow) SetCFRefreshTrigger(fn func())
SetCFRefreshTrigger sets a callback invoked on 403 to trigger immediate CF cookie refresh.
func (*ChatFlow) SetUsageRecorder ¶
func (f *ChatFlow) SetUsageRecorder(ur UsageRecorder)
SetUsageRecorder sets the usage recorder for logging API usage.
type ChatFlowConfig ¶
type ChatFlowConfig struct {
*RetryConfig
// RetryConfigProvider returns the current RetryConfig, enabling hot-reload.
// When set, executeWithRetry calls this on every invocation instead of
// using the embedded RetryConfig.
RetryConfigProvider func() *RetryConfig
// TokenConfig provides model-to-pool mapping configuration.
TokenConfig *config.TokenConfig
// AppConfig provides Grok-specific parameters (temporary, custom_instruction, etc.).
AppConfig *config.AppConfig
// FilterTags lists HTML-like tags to strip from streamed tokens (e.g. "xaiartifact").
FilterTags []string
}
ChatFlowConfig holds chat flow configuration.
func DefaultChatFlowConfig ¶
func DefaultChatFlowConfig() *ChatFlowConfig
DefaultChatFlowConfig returns default chat flow configuration.
type ChatRequest ¶
type ChatRequest struct {
Messages []Message `json:"messages"`
Model string `json:"model"`
Stream bool `json:"stream"`
Temperature *float64 `json:"temperature,omitempty"`
TopP *float64 `json:"top_p,omitempty"`
MaxTokens *int `json:"max_tokens,omitempty"`
ReasoningEffort string `json:"reasoning_effort,omitempty"`
Tools []Tool `json:"tools,omitempty"`
ToolChoice any `json:"tool_choice,omitempty"`
ParallelToolCalls bool `json:"parallel_tool_calls,omitempty"`
}
ChatRequest represents a chat completion request.
type ContentBlock ¶
type ContentBlock struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
ImageURL *ImageURLBlock `json:"image_url,omitempty"`
}
ContentBlock represents a single content block in a multimodal message.
func ParseMultimodalContent ¶
func ParseMultimodalContent(content any) ([]ContentBlock, error)
ParseMultimodalContent parses OpenAI-style content into ContentBlocks. Content can be a string or an array of content parts.
type DownloadFunc ¶
DownloadFunc downloads content from a URL using an authenticated session.
type Function ¶
type Function struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Parameters any `json:"parameters,omitempty"`
}
Function represents a function definition within a tool.
type FunctionCall ¶
FunctionCall represents the function invocation details.
type ImageData ¶
type ImageData struct {
URL string `json:"url,omitempty"`
B64JSON string `json:"b64_json,omitempty"`
RevisedPrompt string `json:"revised_prompt,omitempty"`
}
ImageData represents a single generated image.
type ImageEditClient ¶
type ImageEditClient interface {
Chat(ctx context.Context, req *xai.ChatRequest) (<-chan xai.StreamEvent, error)
UploadFile(ctx context.Context, fileName, fileMimeType, contentBase64 string) (string, string, error)
CreateImagePost(ctx context.Context, imageURL string) (string, error)
DownloadURL(ctx context.Context, url string) ([]byte, error)
}
ImageEditClient defines the upstream calls required by the image edit chain.
type ImageEditClientFactory ¶
type ImageEditClientFactory func(token string) ImageEditClient
ImageEditClientFactory creates image edit clients for a token.
type ImageEditRequest ¶
type ImageEditRequest struct {
Model string
Prompt string
OriginalImages [][]byte
N int
Size string
ResponseFormat string
EnableNSFW *bool
}
ImageEditRequest represents an image edit request.
func (*ImageEditRequest) Validate ¶
func (r *ImageEditRequest) Validate() error
Validate validates the image edit request.
type ImageFlow ¶
type ImageFlow struct {
// contains filtered or unexported fields
}
ImageFlow handles image generation orchestration.
func NewImageFlow ¶
func NewImageFlow(tokenSvc TokenServicer, clientFactory ImagineClientFactory) *ImageFlow
NewImageFlow creates a new image flow with per-request token selection.
func (*ImageFlow) Edit ¶
func (f *ImageFlow) Edit(ctx context.Context, req *ImageEditRequest) (*ImageResponse, error)
Edit edits images through the same upload + app-chat path used by grok2api.
func (*ImageFlow) Generate ¶
func (f *ImageFlow) Generate(ctx context.Context, req *ImageRequest) (*ImageResponse, error)
Generate generates images based on the request.
func (*ImageFlow) SetAppConfig ¶
SetAppConfig sets app-level defaults for app-chat based image edits.
func (*ImageFlow) SetEditClientFactory ¶
func (f *ImageFlow) SetEditClientFactory(factory ImageEditClientFactory)
SetEditClientFactory sets the app-chat client factory used by image edits.
func (*ImageFlow) SetImageConfig ¶
func (f *ImageFlow) SetImageConfig(cfg *config.ImageConfig)
SetImageConfig sets image-generation defaults and retry behavior.
func (*ImageFlow) SetTokenConfig ¶
func (f *ImageFlow) SetTokenConfig(cfg *config.TokenConfig)
SetTokenConfig sets model-to-pool mapping config for token selection.
func (*ImageFlow) SetUsageRecorder ¶
func (f *ImageFlow) SetUsageRecorder(ur UsageRecorder)
SetUsageRecorder sets the usage recorder for logging API usage.
type ImageRequest ¶
type ImageRequest struct {
Model string `json:"model,omitempty"`
Prompt string `json:"prompt"`
N int `json:"n,omitempty"`
Size string `json:"size,omitempty"`
Quality string `json:"quality,omitempty"`
ResponseFormat string `json:"response_format,omitempty"`
Style string `json:"style,omitempty"`
User string `json:"user,omitempty"`
EnableNSFW *bool `json:"enable_nsfw,omitempty"`
}
ImageRequest represents an OpenAI-compatible image generation request.
func (*ImageRequest) Validate ¶
func (r *ImageRequest) Validate() error
Validate validates the image request.
type ImageResponse ¶
ImageResponse represents an OpenAI-compatible image generation response.
type ImageURLBlock ¶
type ImageURLBlock struct {
URL string `json:"url"`
Detail string `json:"detail,omitempty"` // "auto", "low", "high"
}
ImageURLBlock represents an image URL with optional detail level.
type ImagineClientFactory ¶
type ImagineClientFactory func(token string) ImagineGenerator
ImagineClientFactory creates ImagineGenerator instances for a given token.
type ImagineGenerator ¶
type ImagineGenerator interface {
Generate(ctx context.Context, prompt, aspectRatio string, enableNSFW bool) (<-chan xai.ImageEvent, error)
}
ImagineGenerator defines the interface for image generation.
type Message ¶
type Message struct {
Role string `json:"role"`
Content any `json:"content"` // string or []ContentBlock for multimodal
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
Name string `json:"name,omitempty"`
ToolCallID string `json:"tool_call_id,omitempty"`
}
Message represents a chat message.
func FormatToolHistory ¶
FormatToolHistory converts assistant messages with tool_calls and tool-role messages into text format suitable for Grok's web API which only accepts a single message string.
- assistant + tool_calls → content appended with <tool_call>JSON</tool_call> blocks - tool role → user role, content formatted as "tool (name, call_id): content"
type ProcessedContent ¶
type ProcessedContent struct {
Text string // Combined text from all text blocks
Images []string // Data URIs for all images
}
ProcessedContent holds the result of processing multimodal content.
func ProcessContent ¶
func ProcessContent(ctx context.Context, blocks []ContentBlock) (*ProcessedContent, error)
ProcessContent processes content blocks, downloading images as needed.
type RetryConfig ¶
type RetryConfig struct {
// MaxTokens is the maximum number of different tokens to try.
MaxTokens int
// PerTokenRetries is the number of retries per token before switching.
PerTokenRetries int
// BaseDelay is the initial backoff delay.
BaseDelay time.Duration
// MaxDelay is the maximum backoff delay.
MaxDelay time.Duration
// JitterFactor is the jitter range as a fraction of delay (e.g., 0.25 = +/-25%).
JitterFactor float64
// BackoffFactor controls exponential backoff growth (e.g., 2.0 = doubling).
BackoffFactor float64
// ResetSessionStatusCodes are HTTP status codes that require session reset before retry.
ResetSessionStatusCodes []int
// CoolingStatusCodes are HTTP status codes that should trigger token cooling.
// Only token-related errors should cool the token; gateway errors (502/503/504) should not.
CoolingStatusCodes []int
// RetryBudget caps total retry time. Zero means no budget.
RetryBudget time.Duration
}
RetryConfig holds retry behavior configuration.
func DefaultRetryConfig ¶
func DefaultRetryConfig() *RetryConfig
DefaultRetryConfig returns sensible default retry configuration.
type StreamEvent ¶
type StreamEvent struct {
Content string `json:"content,omitempty"`
ReasoningContent string `json:"reasoning_content,omitempty"`
FinishReason *string `json:"finish_reason,omitempty"`
Usage *Usage `json:"usage,omitempty"`
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
Error error `json:"-"`
IsThinking bool `json:"-"`
RolloutID string `json:"-"`
Downloader DownloadFunc `json:"-"`
}
StreamEvent represents a flow-level stream event.
type TokenServicer ¶
type TokenServicer interface {
Pick(pool string, cat tkn.QuotaCategory) (*store.Token, error)
PickExcluding(pool string, cat tkn.QuotaCategory, exclude map[uint]struct{}) (*store.Token, error)
Consume(tokenID uint, cat tkn.QuotaCategory, cost int) (remaining int, err error)
ReportSuccess(id uint)
ReportRateLimit(id uint, reason string)
ReportError(id uint, reason string)
MarkExpired(id uint, reason string)
}
TokenServicer defines the interface for token management.
type ToolCall ¶
type ToolCall struct {
ID string `json:"id"`
Type string `json:"type"`
Function FunctionCall `json:"function"`
Index *int `json:"index,omitempty"`
}
ToolCall represents a tool call in the response.
func ParseToolCallBlock ¶
ParseToolCallBlock parses a single <tool_call> block payload into a ToolCall. Returns nil if the payload is invalid or the tool name is not allowed.
type Usage ¶
type Usage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
}
Usage represents token usage statistics.
type UsageBuffer ¶
type UsageBuffer struct {
// contains filtered or unexported fields
}
UsageBuffer implements UsageRecorder with an in-memory buffer and periodic DB flush.
func NewUsageBuffer ¶
func NewUsageBuffer(s UsageLogBatchInserter, interval time.Duration) *UsageBuffer
NewUsageBuffer creates a new UsageBuffer.
func (*UsageBuffer) Start ¶
func (b *UsageBuffer) Start()
Start launches the periodic flush loop in a background goroutine.
func (*UsageBuffer) Stop ¶
func (b *UsageBuffer) Stop()
Stop signals the flush loop to stop and waits for remaining records to be flushed.
type UsageLogBatchInserter ¶
type UsageLogBatchInserter interface {
BatchInsert(ctx context.Context, logs []*store.UsageLog) error
}
UsageLogBatchInserter defines the interface for batch-inserting usage logs.
type UsageRecorder ¶
UsageRecorder defines the interface for recording API usage.
type VideoClient ¶
type VideoClient interface {
Chat(ctx context.Context, req *xai.ChatRequest) (<-chan xai.StreamEvent, error)
CreateImagePost(ctx context.Context, imageURL string) (string, error)
CreateVideoPost(ctx context.Context, prompt string) (string, error)
PollUpscale(ctx context.Context, videoID string, interval time.Duration) (string, error)
DownloadURL(ctx context.Context, url string) ([]byte, error)
UploadFile(ctx context.Context, fileName, fileMimeType, contentBase64 string) (string, string, error)
}
VideoClient defines the interface for video generation API calls.
type VideoFlow ¶
type VideoFlow struct {
// contains filtered or unexported fields
}
VideoFlow handles async video generation.
func NewVideoFlow ¶
func NewVideoFlow( tokenSvc TokenServicer, clientFactory func(token string) VideoClient, cfg *VideoFlowConfig, ) *VideoFlow
NewVideoFlow creates a new VideoFlow.
func (*VideoFlow) GenerateSync ¶
GenerateSync runs video generation synchronously and returns the final URL.
func (*VideoFlow) SetAppConfig ¶
SetAppConfig sets app-level defaults for app-chat based video generation.
func (*VideoFlow) SetCacheService ¶
SetCacheService sets the cache service for video download proxy.
func (*VideoFlow) SetUsageRecorder ¶
func (f *VideoFlow) SetUsageRecorder(ur UsageRecorder)
SetUsageRecorder sets the usage recorder for logging API usage.
type VideoFlowConfig ¶
type VideoFlowConfig struct {
TimeoutSeconds int
PollIntervalSeconds int
TokenConfig *config.TokenConfig
}
VideoFlowConfig holds configuration for video processing.
type VideoRequest ¶
type VideoRequest struct {
Prompt string
Model string
Size string
AspectRatio string // e.g. "16:9", "3:2" — passed directly to xAI
Seconds int
Quality string
Preset string
ReferenceImage []byte
}
VideoRequest represents a video generation request.
type XAIClientFactory ¶
XAIClientFactory creates xai.Client instances for a given token.