llm

package
v0.20260527.2 Latest Latest
Warning

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

Go to latest
Published: May 27, 2026 License: MIT Imports: 31 Imported by: 0

Documentation

Index

Constants

View Source
const AnthropicAPIVersion = "2023-06-01"
View Source
const AnthropicOAuthBeta = "oauth-2025-04-20"

Variables

View Source
var ErrCircuitOpen = errors.New("provider temporarily unavailable")
View Source
var ErrStreamAccumulatorRejected = errors.New("chat completion stream accumulator rejected chunk")

Functions

func AnthropicMessagesURL added in v0.20260521.2

func AnthropicMessagesURL(base string) string

func ApplyChatReasoning

func ApplyChatReasoning(cfg *config.Root, p *openai.ChatCompletionNewParams, forceDisable bool)

func ApplyMaxResponseTokens

func ApplyMaxResponseTokens(cfg *config.Root, p *openai.ChatCompletionNewParams)

func ApplyProviderSimpleParams added in v0.20260521.2

func ApplyProviderSimpleParams(proto Protocol, cfg *config.Root, openaiParams *openai.ChatCompletionNewParams, forceDisable bool)

func ApplyProviderTurnParams added in v0.20260521.2

func ApplyProviderTurnParams(proto Protocol, cfg *config.Root, openaiParams *openai.ChatCompletionNewParams, forceDisable bool)

func ApplyReasoningDisable

func ApplyReasoningDisable(p *openai.ChatCompletionNewParams)

func ApplySimpleReasoning added in v0.20260526.3

func ApplySimpleReasoning(cfg *config.Root, p *openai.ChatCompletionNewParams, forceDisable bool)

func BackoffDelay added in v0.20260523.0

func BackoffDelay(policy config.APIResiliencePolicy, attempt int, retryAfter time.Duration, rng *rand.Rand) time.Duration

func BuildUserContentParts

func BuildUserContentParts(content string, imageFiles map[int]string) []openai.ChatCompletionContentPartUnionParam

func HostKeyFromBaseURL added in v0.20260523.0

func HostKeyFromBaseURL(baseURL string) string

func ImagePlaceholder

func ImagePlaceholder(seq int) string

ImagePlaceholder returns the placeholder string for a given image sequence number.

func JumpLeftOverImgTag

func JumpLeftOverImgTag(line []rune, pos int) int

JumpLeftOverImgTag treats an [img-<n>] tag as a single atomic unit: if the cursor lies anywhere inside the tag (start < pos <= end), it jumps to start (before the tag). Spaces around the tag are never considered part of the placeholder.

func JumpRightOverImgTag

func JumpRightOverImgTag(line []rune, pos int) int

JumpRightOverImgTag treats an [img-<n>] tag as a single atomic unit: if the cursor lies anywhere inside the tag (start <= pos < end), it jumps to end (after the tag). Spaces around the tag are never considered part of the placeholder.

func LastAssistantIndex added in v0.20260521.2

func LastAssistantIndex(msgs []chatstore.Message) int

func MessageForAPI added in v0.20260521.2

func MessageForAPI(m chatstore.Message, includeReasoning bool) chatstore.Message

func MessageParams

func MessageParams(system string, msgs []chatstore.Message, imageFiles map[int]string) []openai.ChatCompletionMessageParamUnion

MessageParams builds OpenAI API message params from chatstore messages. If imageFiles is non-nil and contains entries for [img-<n>] placeholders found in user messages, those placeholders are replaced with image content parts.

func MessagesForAPI added in v0.20260521.2

func MessagesForAPI(msgs []chatstore.Message) []chatstore.Message

func ModelID

func ModelID(s string) shared.ChatModel

func NewResilientHTTPClient added in v0.20260523.0

func NewResilientHTTPClient(policy config.APIResiliencePolicy) *http.Client

func OpenAIClientFromBackend added in v0.20260521.2

func OpenAIClientFromBackend(b CompletionBackend) (openai.Client, bool)

func PopulateAssistantTurnUsage

func PopulateAssistantTurnUsage(dst *chatstore.Message, system string, msgsPrior []chatstore.Message, u UsageStats)

func PromptDisplaySplit

func PromptDisplaySplit(system string, msgs []chatstore.Message, apiPromptTokens int64) (contextTok int64, lastUserTok int64)

func RetryMessage added in v0.20260523.0

func RetryMessage(attempt, max int, err error, wait time.Duration) string

func UsagePromptParts

func UsagePromptParts(system string, msgs []chatstore.Message, promptTokens int64, cachedPromptTokens int64) (contextTok int64, lastUserTok int64, contextEstimated bool)

func UsageTokensDisplayParts

func UsageTokensDisplayParts(system string, msgs []chatstore.Message, u UsageStats, turnCount int) (contextTok, lastUserTok int64, contextEstimated bool, reasoningTok, responseTok, totalTok int64)

func UserFacingAPIError added in v0.20260527.0

func UserFacingAPIError(err error) string

Types

type AnthropicAuth added in v0.20260521.2

type AnthropicAuth struct {
	Kind  AnthropicAuthKind
	Token string
}

func AnthropicAuthFromAPIKey added in v0.20260521.2

func AnthropicAuthFromAPIKey(token string) AnthropicAuth

func AnthropicAuthFromOAuthBearer added in v0.20260521.2

func AnthropicAuthFromOAuthBearer(token string) AnthropicAuth

func (AnthropicAuth) ApplyTo added in v0.20260521.2

func (a AnthropicAuth) ApplyTo(req *http.Request)

type AnthropicAuthKind added in v0.20260521.2

type AnthropicAuthKind int
const (
	AnthropicAuthAPIKey AnthropicAuthKind = iota
	AnthropicAuthOAuthBearer
)

type AnthropicBackend added in v0.20260521.2

type AnthropicBackend struct {
	// contains filtered or unexported fields
}

func NewAnthropicBackend added in v0.20260521.2

func NewAnthropicBackend(baseURL string, auth AnthropicAuth) *AnthropicBackend

func NewAnthropicBackendWithClient added in v0.20260523.0

func NewAnthropicBackendWithClient(baseURL string, auth AnthropicAuth, client *http.Client) *AnthropicBackend

func (*AnthropicBackend) CompleteText added in v0.20260521.2

func (b *AnthropicBackend) CompleteText(ctx context.Context, req SimpleCompletionRequest) (string, error)

func (*AnthropicBackend) ListModels added in v0.20260521.2

func (b *AnthropicBackend) ListModels(ctx context.Context) ([]string, error)

func (*AnthropicBackend) Protocol added in v0.20260521.2

func (b *AnthropicBackend) Protocol() Protocol

func (*AnthropicBackend) StreamText added in v0.20260521.2

func (b *AnthropicBackend) StreamText(ctx context.Context, req SimpleCompletionRequest, contentOut io.Writer, opts StreamOpts) (string, UsageStats, error)

func (*AnthropicBackend) StreamTurn added in v0.20260521.2

func (b *AnthropicBackend) StreamTurn(ctx context.Context, req TurnRequest, contentOut io.Writer, opts StreamOpts) (AssistantTurnResult, error)

type AnthropicUsagePayload added in v0.20260521.2

type AnthropicUsagePayload struct {
	InputTokens              int64 `json:"input_tokens"`
	OutputTokens             int64 `json:"output_tokens"`
	CacheReadInputTokens     int64 `json:"cache_read_input_tokens"`
	CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"`
}

type AssistantToolCall

type AssistantToolCall struct {
	ID        string
	Name      string
	Arguments string
}

type AssistantTurnResult

type AssistantTurnResult struct {
	Content       string
	ReasoningText string
	ToolCalls     []AssistantToolCall
	Usage         UsageStats
}

func StreamAssistantTurn

func StreamAssistantTurn(ctx context.Context, client openai.Client, params openai.ChatCompletionNewParams, contentOut io.Writer, opts StreamOpts) (AssistantTurnResult, error)

type CircuitRegistry added in v0.20260523.0

type CircuitRegistry struct {
	// contains filtered or unexported fields
}

func NewCircuitRegistry added in v0.20260523.0

func NewCircuitRegistry() *CircuitRegistry

func (*CircuitRegistry) IsOpen added in v0.20260523.0

func (c *CircuitRegistry) IsOpen(hostKey string) bool

func (*CircuitRegistry) Reset added in v0.20260523.0

func (c *CircuitRegistry) Reset(hostKey string)

func (*CircuitRegistry) Trip added in v0.20260523.0

func (c *CircuitRegistry) Trip(hostKey string, openFor time.Duration)

type CompletionBackend added in v0.20260521.2

type CompletionBackend interface {
	Protocol() Protocol
	StreamTurn(ctx context.Context, req TurnRequest, contentOut io.Writer, opts StreamOpts) (AssistantTurnResult, error)
	StreamText(ctx context.Context, req SimpleCompletionRequest, contentOut io.Writer, opts StreamOpts) (string, UsageStats, error)
	CompleteText(ctx context.Context, req SimpleCompletionRequest) (string, error)
	ListModels(ctx context.Context) ([]string, error)
}

func NewCompletionBackend added in v0.20260521.2

func NewCompletionBackend(ctx context.Context, cfg *config.Root, p *config.Provider) (CompletionBackend, error)

type ErrorClass added in v0.20260523.0

type ErrorClass int
const (
	ErrorPermanent ErrorClass = iota
	ErrorRetryable
	ErrorCircuitOpen
)

func ClassifyAPIError added in v0.20260523.0

func ClassifyAPIError(err error, circuitOpen bool) (ErrorClass, int, time.Duration)

type OpenAIBackend added in v0.20260521.2

type OpenAIBackend struct {
	Client openai.Client
}

func (*OpenAIBackend) CompleteText added in v0.20260521.2

func (b *OpenAIBackend) CompleteText(ctx context.Context, req SimpleCompletionRequest) (string, error)

func (*OpenAIBackend) ListModels added in v0.20260521.2

func (b *OpenAIBackend) ListModels(ctx context.Context) ([]string, error)

func (*OpenAIBackend) Protocol added in v0.20260521.2

func (b *OpenAIBackend) Protocol() Protocol

func (*OpenAIBackend) StreamText added in v0.20260521.2

func (b *OpenAIBackend) StreamText(ctx context.Context, req SimpleCompletionRequest, contentOut io.Writer, opts StreamOpts) (string, UsageStats, error)

func (*OpenAIBackend) StreamTurn added in v0.20260521.2

func (b *OpenAIBackend) StreamTurn(ctx context.Context, req TurnRequest, contentOut io.Writer, opts StreamOpts) (AssistantTurnResult, error)

type Protocol added in v0.20260521.2

type Protocol string
const (
	ProtocolOpenAI    Protocol = "openai"
	ProtocolAnthropic Protocol = "anthropic"
)

type ProviderHTTPError added in v0.20260523.0

type ProviderHTTPError struct {
	StatusCode int
	Message    string
	RetryAfter time.Duration
}

func NewProviderHTTPError added in v0.20260523.0

func NewProviderHTTPError(status int, message string, retryAfter time.Duration) *ProviderHTTPError

func (*ProviderHTTPError) Error added in v0.20260523.0

func (e *ProviderHTTPError) Error() string

type ResilientBackend added in v0.20260523.0

type ResilientBackend struct {
	Inner         CompletionBackend
	HostKey       string
	Policy        config.APIResiliencePolicy
	Circuits      *CircuitRegistry
	SidecarRevive func(context.Context, error)
	// contains filtered or unexported fields
}

func NewResilientBackend added in v0.20260523.0

func NewResilientBackend(inner CompletionBackend, hostKey string, policy config.APIResiliencePolicy, circuits *CircuitRegistry) *ResilientBackend

func (*ResilientBackend) CompleteText added in v0.20260523.0

func (b *ResilientBackend) CompleteText(ctx context.Context, req SimpleCompletionRequest) (string, error)

func (*ResilientBackend) ListModels added in v0.20260523.0

func (b *ResilientBackend) ListModels(ctx context.Context) ([]string, error)

func (*ResilientBackend) Protocol added in v0.20260523.0

func (b *ResilientBackend) Protocol() Protocol

func (*ResilientBackend) StreamText added in v0.20260523.0

func (b *ResilientBackend) StreamText(ctx context.Context, req SimpleCompletionRequest, contentOut io.Writer, opts StreamOpts) (string, UsageStats, error)

func (*ResilientBackend) StreamTurn added in v0.20260523.0

func (b *ResilientBackend) StreamTurn(ctx context.Context, req TurnRequest, contentOut io.Writer, opts StreamOpts) (AssistantTurnResult, error)

type SimpleCompletionRequest added in v0.20260521.2

type SimpleCompletionRequest struct {
	Cfg                   *config.Root
	Model                 string
	System                string
	User                  string
	ForceDisableReasoning bool
}

type StreamOpts

type StreamOpts struct {
	ShowThinking  bool
	ReasoningSink io.Writer
	OnDelta       func(channel, text string)
	OnRetry       func(attempt int, max int, err error, wait time.Duration)
}

type ToolDef added in v0.20260521.2

type ToolDef struct {
	Name        string
	Description string
	Parameters  map[string]any
	Required    []string
}

func ToolDefsFromOpenAI added in v0.20260521.2

func ToolDefsFromOpenAI(tools []openai.ChatCompletionToolUnionParam) []ToolDef

type TurnRequest added in v0.20260521.2

type TurnRequest struct {
	Cfg                   *config.Root
	Model                 string
	System                string
	Messages              []chatstore.Message
	ImageFiles            map[int]string
	Tools                 []ToolDef
	ParallelToolCalls     bool
	ForceDisableReasoning bool
}

type UsageStats

type UsageStats struct {
	PromptTokens              int64
	CachedPromptTokens        int64
	CacheCreationPromptTokens int64
	ReasoningTokens           int64
	ResponseTokens            int64
	TotalTokens               int64
	OutputTPS                 float64
	TTFTSecs                  float64
	PromptTPS                 float64
	TurnWallSecs              float64
	ThoughtSecs               float64
}

func AggregateConsecutiveTurnUsage

func AggregateConsecutiveTurnUsage(usages []UsageStats) UsageStats

func NormalizeAnthropicUsage added in v0.20260521.2

func NormalizeAnthropicUsage(u AnthropicUsagePayload) UsageStats

func StreamText

func StreamText(ctx context.Context, client openai.Client, params openai.ChatCompletionNewParams, contentOut io.Writer, opts StreamOpts) (string, UsageStats, error)

Jump to

Keyboard shortcuts

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