flow

package
v0.5.0-beta Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 5, 2026 License: MIT Imports: 29 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package flow provides chat orchestration and retry logic.

Index

Constants

View Source
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

View Source
var (
	// ErrVideoCache indicates that the generated video could not be cached locally.
	ErrVideoCache = errors.New("video cache failed")
	// ErrVideoPostProcess indicates that post-generation video processing failed.
	ErrVideoPostProcess = errors.New("video postprocess failed")
)
View Source
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

func BuildToolPrompt(tools []Tool, toolChoice any, parallelCalls bool) string

BuildToolPrompt generates a system prompt with tool definitions. Returns empty string if tools is empty or toolChoice is "none".

func FlowAPIKeyIDFromContext

func FlowAPIKeyIDFromContext(ctx context.Context) uint

FlowAPIKeyIDFromContext extracts the API key ID from context.

func IsCFChallenge

func IsCFChallenge(err error) bool

IsCFChallenge returns true if the error is a Cloudflare challenge.

func IsNonRecoverable

func IsNonRecoverable(err error) bool

IsNonRecoverable returns true if the error should NOT be retried. Non-recoverable: context errors, ErrInvalidToken (401), 400 Bad Request.

func IsRetryable

func IsRetryable(err error) bool

IsRetryable returns true if the error is retryable (all errors except non-recoverable).

func MapReasoningEffort

func MapReasoningEffort(effort string) (grokThinking string, enabled bool)

MapReasoningEffort maps OpenAI reasoning_effort to Grok thinking parameter.

func SafeGo

func SafeGo(name string, fn func())

SafeGo runs fn in a goroutine and recovers panics to keep the process alive.

func ShouldCoolToken

func ShouldCoolToken(err error, _ *RetryConfig) bool

ShouldCoolToken returns true only for 429 quota exhaustion semantics.

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

func SplitByTagPrefix(text, tag string) (string, string)

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

func SuffixPrefixLength(text, tag string) int

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

func (f *ChatFlow) SetAPIKeyUsageInc(fn func(ctx context.Context, apiKeyID uint))

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
	// ModelResolver resolves model names to pool floor and cost.
	ModelResolver tkn.ModelResolver
	// AppConfig provides static Grok-specific parameters.
	AppConfig *config.AppConfig
	// AppConfigProvider provides Grok-specific parameters.
	AppConfigProvider func() *config.AppConfig
	// FilterTags lists static HTML-like tags to strip from streamed tokens.
	FilterTags []string
	// FilterTagsProvider provides HTML-like tags to strip from streamed tokens.
	FilterTagsProvider func() []string
	// ResolveUpstream resolves a request model name to its Grok API upstream
	// model name and mode. Returns false if the model is not found.
	ResolveUpstream func(requestName string) (upstreamModel, upstreamMode string, ok bool)
}

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"`
	UpstreamModel     string    `json:"-"` // Grok API model name from registry
	UpstreamMode      string    `json:"-"` // Grok API model mode from registry
	ForceThinking     bool      `json:"-"` // Force reasoning_effort=high from registry
	DeepSearch        string    `json:"-"` // "default" | "deeper"
	Mode              string    `json:"-"` // mode from registry for quota tracking
}

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

type DownloadFunc func(ctx context.Context, url string) ([]byte, error)

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

type FunctionCall struct {
	Name      string `json:"name"`
	Arguments string `json:"arguments"`
}

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
	UpstreamModel  string
	UpstreamMode   string
	Mode           string // mode from registry for quota tracking
	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

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) GenerateLite

func (f *ImageFlow) GenerateLite(ctx context.Context, req *ImageLiteRequest) (*ImageResponse, error)

GenerateLite generates images via the chat endpoint (Aurora path). This is used for image-lite models that don't go through WebSocket.

func (*ImageFlow) SetAppConfig

func (f *ImageFlow) SetAppConfig(cfg *config.AppConfig)

SetAppConfig sets app-level defaults for app-chat based image edits.

func (*ImageFlow) SetAppConfigProvider

func (f *ImageFlow) SetAppConfigProvider(fn func() *config.AppConfig)

SetAppConfigProvider sets a dynamic app config provider.

func (*ImageFlow) SetCacheService

func (f *ImageFlow) SetCacheService(svc *cache.Service)

SetCacheService sets the cache service for local_url image output.

func (*ImageFlow) SetEditClientFactory

func (f *ImageFlow) SetEditClientFactory(factory ImageEditClientFactory)

SetEditClientFactory sets the app-chat client factory used by image edits.

func (*ImageFlow) SetEnableProResolver

func (f *ImageFlow) SetEnableProResolver(fn func(model string) bool)

SetEnableProResolver sets a function that resolves whether pro mode is enabled for a model.

func (*ImageFlow) SetImageConfig

func (f *ImageFlow) SetImageConfig(cfg *config.ImageConfig)

SetImageConfig sets image-generation defaults and retry behavior.

func (*ImageFlow) SetImageConfigProvider

func (f *ImageFlow) SetImageConfigProvider(fn func() *config.ImageConfig)

SetImageConfigProvider sets a dynamic image config provider.

func (*ImageFlow) SetModeResolver

func (f *ImageFlow) SetModeResolver(resolver ModeResolver)

SetModeResolver sets the mode resolver for quota tracking.

func (*ImageFlow) SetModelResolver

func (f *ImageFlow) SetModelResolver(resolver tkn.ModelResolver)

SetModelResolver sets the model resolver for pool routing.

func (*ImageFlow) SetUsageRecorder

func (f *ImageFlow) SetUsageRecorder(ur UsageRecorder)

SetUsageRecorder sets the usage recorder for logging API usage.

type ImageLiteRequest

type ImageLiteRequest struct {
	Model          string
	Prompt         string
	N              int
	UpstreamMode   string // "fast"
	ResponseFormat string
	Mode           string // mode from registry for quota tracking
}

ImageLiteRequest represents a lite image generation request (Aurora path).

func (*ImageLiteRequest) Validate

func (r *ImageLiteRequest) Validate() error

Validate validates the lite image request.

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"`
	Mode            string `json:"-"` // mode from registry for quota tracking
	CooldownSeconds int    `json:"-"`
}

ImageRequest represents an OpenAI-compatible image generation request.

func (*ImageRequest) Validate

func (r *ImageRequest) Validate() error

Validate validates the image request.

type ImageResponse

type ImageResponse struct {
	Created int64       `json:"created"`
	Data    []ImageData `json:"data"`
}

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, enablePro 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

func FormatToolHistory(messages []Message) []Message

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 ModeResolver

type ModeResolver interface {
	ResolveMode(requestName string) (mode string, ok bool)
}

ModeResolver resolves a model request name to its quota mode string.

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

	// 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 SearchSource

type SearchSource struct {
	URL   string `json:"url"`
	Title string `json:"title"`
	Type  string `json:"type"` // "web" or "x_post"
}

SearchSource represents a single search result citation.

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:"-"`
	SearchSources    []SearchSource `json:"-"`
	Downloader       DownloadFunc   `json:"-"`
}

StreamEvent represents a flow-level stream event.

type TokenServicer

type TokenServicer interface {
	Pick(pool string, mode string) (*store.Token, error)
	PickExcluding(pool string, mode string, exclude map[uint]struct{}) (*store.Token, error)
	PickAnyExcluding(pool string, exclude map[uint]struct{}) (*store.Token, error)
	RefundQuota(id uint, mode string)
	ReportSuccess(id uint)
	ReportRateLimit(id uint, mode string, reason string)
	ReportError(id uint, mode string, recoverable bool, reason string)
	ReportErrorKeepInflight(id uint, mode string, recoverable bool, reason string)
	MarkExpired(id uint, reason string)
	ReleaseToken(id uint)
}

TokenServicer defines the interface for token management.

type Tool

type Tool struct {
	Type     string   `json:"type"`
	Function Function `json:"function"`
}

Tool represents an OpenAI-compatible tool definition.

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

func ParseToolCallBlock(raw string, tools []Tool, index int) *ToolCall

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.

func ParseToolCalls

func ParseToolCalls(content string, tools ...[]Tool) (string, []ToolCall)

ParseToolCalls extracts tool calls from response content. Returns the remaining text and parsed tool calls. When tools is non-nil, only tool calls with names matching the provided tools are accepted.

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) Record

func (b *UsageBuffer) Record(_ context.Context, log *store.UsageLog) error

Record appends a usage log to the in-memory buffer (non-blocking).

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

type UsageRecorder interface {
	Record(ctx context.Context, log *store.UsageLog) error
}

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)
	DownloadTo(ctx context.Context, url string, w io.Writer) 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

func (f *VideoFlow) GenerateSync(ctx context.Context, req *VideoRequest) (string, error)

GenerateSync runs video generation synchronously and returns the final URL.

func (*VideoFlow) SetAppConfig

func (f *VideoFlow) SetAppConfig(cfg *config.AppConfig)

SetAppConfig sets app-level defaults for app-chat based video generation.

func (*VideoFlow) SetAppConfigProvider

func (f *VideoFlow) SetAppConfigProvider(fn func() *config.AppConfig)

SetAppConfigProvider sets a dynamic app config provider.

func (*VideoFlow) SetCacheService

func (f *VideoFlow) SetCacheService(svc *cache.Service)

SetCacheService sets the cache service for video download proxy.

func (*VideoFlow) SetModeResolver

func (f *VideoFlow) SetModeResolver(resolver ModeResolver)

SetModeResolver sets the mode resolver for quota tracking.

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
	ModelResolver       tkn.ModelResolver
}

VideoFlowConfig holds configuration for video processing.

type VideoRequest

type VideoRequest struct {
	Prompt          string
	Model           string
	UpstreamModel   string
	UpstreamMode    string
	Mode            string // mode from registry for quota tracking
	Size            string
	AspectRatio     string // e.g. "16:9", "3:2" — passed directly to xAI
	Seconds         int
	Quality         string
	Preset          string
	ReferenceImages [][]byte
}

VideoRequest represents a video generation request.

type XAIClientFactory

type XAIClientFactory func(token string) xai.Client

XAIClientFactory creates xai.Client instances for a given token.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL