Documentation
¶
Index ¶
- Variables
- func ApplyOptions(cfg *Config, opts ...Option)
- func MustRegisterProvider(name string, factory ProviderFactory)
- func RegisterProvider(name string, factory ProviderFactory) error
- func RegisteredProviders() []string
- type Client
- type Config
- type ContentPart
- type Error
- type ImageContent
- type Message
- func NewAssistantMessage(parts ...ContentPart) *Message
- func NewMessage(role Role, parts ...ContentPart) *Message
- func NewSystemMessage(parts ...ContentPart) *Message
- func NewToolMessage(parts ...ContentPart) *Message
- func NewToolResultMessage(toolCallID, name string, parts ...ContentPart) *Message
- func NewUserMessage(parts ...ContentPart) *Message
- type Option
- func WithAPIKey(key string) Option
- func WithBaseURL(url string) Option
- func WithCost(inputCostPerMillionTokens, outputCostPerMillionTokens float64) Option
- func WithExtraBody(extra map[string]json.RawMessage) Option
- func WithHTTPClient(client *http.Client) Option
- func WithHeader(key, value string) Option
- func WithMaxTokens(max int) Option
- func WithModel(model string) Option
- func WithResponseModalities(modalities ...string) Option
- func WithRetryOnStatus(status int, retry bool) Option
- func WithTemperature(temp float64) Option
- func WithTokenSource(source auth.TokenSource) Option
- func WithToolChoice(choice ToolChoice) Option
- func WithTools(tools ...Tool) Option
- func WithWebSearch(enabled bool) Option
- type Provider
- type ProviderFactory
- type ReasoningContent
- type Response
- type Role
- type StreamChunk
- type TextContent
- type Tool
- type ToolCallContent
- type ToolChoice
- type ToolChoiceMode
- type UsageMetadata
Constants ¶
This section is empty.
Variables ¶
var ( // ErrProviderNotFound is returned when the requested provider has not been registered. ErrProviderNotFound = errors.New("llmhub: provider not found") // ErrProviderAlreadyRegistered signals that a provider name has already been registered. ErrProviderAlreadyRegistered = errors.New("llmhub: provider already registered") // ErrNotImplemented is used by provider stubs that have not yet been wired up. ErrNotImplemented = errors.New("llmhub: feature not implemented") // ErrInvalidInput wraps validation failures on user-supplied data. ErrInvalidInput = errors.New("llmhub: invalid input") )
Functions ¶
func ApplyOptions ¶
ApplyOptions mutates a Config in-place with the provided options.
func MustRegisterProvider ¶
func MustRegisterProvider(name string, factory ProviderFactory)
MustRegisterProvider registers a provider and panics on failure.
func RegisterProvider ¶
func RegisterProvider(name string, factory ProviderFactory) error
RegisterProvider adds a provider factory to the global registry.
func RegisteredProviders ¶
func RegisteredProviders() []string
RegisteredProviders returns a sorted slice of registered provider names.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the main entry point for interacting with LLM providers via the unified API.
func (*Client) Generate ¶
func (c *Client) Generate(ctx context.Context, prompt []*Message, opts ...Option) (*Response, error)
Generate performs a single request/response interaction with the provider.
func (*Client) ProviderName ¶
ProviderName returns the underlying provider identifier.
type Config ¶
type Config struct {
Model string
Temperature float64
// MaxTokens applies a hard cap to generated output tokens.
// Leave this unset unless you specifically need that cap, because values
// that are too low can cause the model to return truncated output.
MaxTokens int
APIKey string
TokenSource auth.TokenSource
BaseURL string
HTTPClient *http.Client
Headers map[string]string
ExtraBody map[string]json.RawMessage
EnableWebSearch bool // Enables web search/grounding (Gemini: google_search, Perplexity: always on)
Tools []Tool
ToolChoice *ToolChoice
// RetryOnStatus overrides whether HTTP-backed providers retry a given
// status code. true means retry with backoff; false means return the
// response immediately. Statuses not present keep the default (retry
// 429 only). Set via WithRetryOnStatus.
RetryOnStatus map[int]bool
// ResponseModalities controls the output modalities the model should
// produce. For example, setting this to []string{"IMAGE"} tells the
// Gemini image-generation models to return an image instead of text.
// Leave nil for the provider default (text).
ResponseModalities []string
// Cost accounting: prices expressed per 1 million tokens.
InputCostPerMillionTokens float64
OutputCostPerMillionTokens float64
}
Config captures all tunable request options shared across providers.
type ContentPart ¶
type ContentPart interface {
Type() string
}
ContentPart is implemented by any structure that can be included inside a message.
type Error ¶
Error captures provider-specific failures with additional context.
type ImageContent ¶
type ImageContent struct {
URL string
Detail string // optional granularity instruction used by some providers
}
ImageContent represents a reference to an image by URL or base64 payload.
func (*ImageContent) Type ¶
func (i *ImageContent) Type() string
Type identifies the piece as an image.
type Message ¶
type Message struct {
Role Role
Content []ContentPart
Meta map[string]string
}
Message represents one turn in a conversation with the provider and can mix modalities.
func NewAssistantMessage ¶
func NewAssistantMessage(parts ...ContentPart) *Message
NewAssistantMessage returns a message authored by the assistant.
func NewMessage ¶
func NewMessage(role Role, parts ...ContentPart) *Message
NewMessage constructs a message with the provided role and content parts.
func NewSystemMessage ¶
func NewSystemMessage(parts ...ContentPart) *Message
NewSystemMessage returns a message authored by the system.
func NewToolMessage ¶
func NewToolMessage(parts ...ContentPart) *Message
NewToolMessage returns a message authored by a tool.
func NewToolResultMessage ¶
func NewToolResultMessage(toolCallID, name string, parts ...ContentPart) *Message
NewToolResultMessage returns a message containing the result for a tool call.
func NewUserMessage ¶
func NewUserMessage(parts ...ContentPart) *Message
NewUserMessage returns a message authored by the end-user.
func (*Message) Append ¶
func (m *Message) Append(parts ...ContentPart)
Append adds one or more content parts to the message.
type Option ¶
type Option func(*Config)
Option mutates a Config in a functional-options friendly way.
func WithAPIKey ¶
WithAPIKey stores the credential used by the provider.
func WithBaseURL ¶
WithBaseURL overrides the provider base URL (useful for proxies and on-prem).
func WithCost ¶
WithCost sets the cost per 1 million tokens (input and output) in US dollars. This is used to compute the estimated cost of each request based on token usage.
func WithExtraBody ¶
func WithExtraBody(extra map[string]json.RawMessage) Option
WithExtraBody adds arbitrary additional fields to the outbound JSON request body. On key collision, these fields override the standard generated fields. Applies only to OpenAI-compatible providers (OpenAI, OpenRouter, xAI); other providers ignore it. Values must be valid JSON.
func WithHTTPClient ¶
WithHTTPClient swaps the HTTP client used by HTTP-backed providers.
func WithHeader ¶
WithHeader injects a custom header for every request.
func WithMaxTokens ¶
WithMaxTokens applies a hard cap to the number of generated tokens.
Prefer leaving this unset unless you specifically need a strict output limit, because setting it too low often causes truncated responses.
func WithResponseModalities ¶
WithResponseModalities specifies the output modalities the model should produce. For Gemini image-generation models (e.g. gemini-2.5-flash-image), pass "IMAGE" to receive image output. Pass "TEXT" and "IMAGE" together to allow mixed output. Leave unset for the provider default (text only).
func WithRetryOnStatus ¶
WithRetryOnStatus overrides whether HTTP-backed providers retry a given status code. By default, providers retry 429 with backoff. Pass WithRetryOnStatus(429, false) to surface rate limits immediately so the caller can apply its own backoff or failover. Pass true to opt into retry for a status that is not retried by default (for example 500).
func WithTemperature ¶
WithTemperature sets the sampling temperature.
func WithTokenSource ¶
func WithTokenSource(source auth.TokenSource) Option
WithTokenSource configures an abstract token source for providers that support OAuth or dynamic token acquisition.
For providers supporting both API keys and OAuth (e.g. xAI), a non-nil TokenSource takes precedence over APIKey.
func WithToolChoice ¶
func WithToolChoice(choice ToolChoice) Option
WithToolChoice controls whether supplied tools may, must, or must not be used.
func WithWebSearch ¶
WithWebSearch enables web search/grounding capabilities. For Gemini, this enables google_search tool. For Perplexity models, web search is always enabled.
type Provider ¶
type Provider interface {
Name() string
Generate(ctx context.Context, prompt []*Message, opts ...Option) (*Response, error)
Stream(ctx context.Context, prompt []*Message, opts ...Option) (<-chan StreamChunk, error)
}
Provider describes a backend capable of generating responses from LLMs.
type ProviderFactory ¶
ProviderFactory describes a function that can instantiate a provider backed by a specific vendor SDK.
type ReasoningContent ¶
type ReasoningContent struct {
Text string
}
ReasoningContent represents model-internal reasoning or thinking text when providers expose it.
func Reasoning ¶
func Reasoning(s string) *ReasoningContent
Reasoning is a helper constructor for a reasoning part.
func (*ReasoningContent) Type ¶
func (r *ReasoningContent) Type() string
Type identifies the piece as reasoning.
type Response ¶
type Response struct {
ID string
Content []ContentPart
Usage UsageMetadata
Raw interface{}
}
Response contains the normalized result returned from a provider.
func (*Response) ReasoningText ¶
ReasoningText concatenates reasoning segments exposed by providers.
func (*Response) Text ¶
Text concatenates the textual segments of the response for the common use case where only text matters.
func (*Response) ToolCalls ¶
func (r *Response) ToolCalls() []*ToolCallContent
ToolCalls returns all normalized tool calls requested in the response.
type StreamChunk ¶
type StreamChunk struct {
// ID is the upstream completion identifier when the provider reports one
// (OpenAI-compatible lanes and Anthropic). It is best-effort telemetry and
// may be empty for lanes that do not report a stable stream id.
ID string
// Delta is the incremental text produced since the previous chunk.
Delta string
// ReasoningDelta is the incremental reasoning text produced since the previous chunk.
ReasoningDelta string
// ToolCalls carries streamed tool call deltas.
ToolCalls []*ToolCallContent
// Usage carries token and cost accounting when the upstream reports it.
Usage *UsageMetadata
// FinishReason describes how the response ended, using the OpenAI
// vocabulary (stop, length, tool_calls). It is empty when the upstream
// reports no reason or the reason cannot be mapped. It is typically set on
// the final content frame (not on the terminal Done frame).
FinishReason string
Done bool
Err error
}
StreamChunk represents a partial streaming response.
type ToolCallContent ¶
ToolCallContent represents a model-requested call to a tool.
func ToolCall ¶
func ToolCall(id, name, arguments string) *ToolCallContent
ToolCall is a helper constructor for a tool-call content part.
func ToolCallWithIndex ¶
func ToolCallWithIndex(index int, id, name, arguments string) *ToolCallContent
ToolCallWithIndex is a helper constructor for a streaming tool-call delta.
func (*ToolCallContent) Type ¶
func (t *ToolCallContent) Type() string
Type identifies the piece as a tool call.
type ToolChoice ¶
type ToolChoice struct {
Mode ToolChoiceMode
Name string
}
ToolChoice controls whether the model may, must, or must not call tools.
func AutoToolChoice ¶
func AutoToolChoice() ToolChoice
AutoToolChoice lets the model choose whether to call tools.
func NamedToolChoice ¶
func NamedToolChoice(name string) ToolChoice
NamedToolChoice requires the model to call the named tool.
func NoToolChoice ¶
func NoToolChoice() ToolChoice
NoToolChoice prevents the model from calling tools.
func RequiredToolChoice ¶
func RequiredToolChoice() ToolChoice
RequiredToolChoice requires the model to call at least one tool.
type ToolChoiceMode ¶
type ToolChoiceMode string
ToolChoiceMode controls how providers should use supplied tools.
const ( ToolChoiceAuto ToolChoiceMode = "auto" ToolChoiceNone ToolChoiceMode = "none" ToolChoiceRequired ToolChoiceMode = "required" ToolChoiceNamed ToolChoiceMode = "named" )
type UsageMetadata ¶
type UsageMetadata struct {
PromptTokens int
CompletionTokens int
TotalTokens int
CacheReadTokens int
CacheCreationTokens int
ReasoningTokens int
Cost float64 // Estimated cost in US dollars based on configured per-million-token rates.
}
UsageMetadata captures token consumption and cost information reported by providers.
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
cli
command
CLI tool for end-to-end testing of llmhub providers.
|
CLI tool for end-to-end testing of llmhub providers. |
|
xai-oauth
command
|
|
|
zai
command
zai demonstrates using llmhub's Z.AI provider with the OpenAI-compatible Chat Completions API.
|
zai demonstrates using llmhub's Z.AI provider with the OpenAI-compatible Chat Completions API. |
|
internal
|
|
|
providers
|
|