Documentation
¶
Overview ¶
Package republic provides one interface to AI providers. Agent loops, gateways, and tool execution belong to the caller.
Index ¶
- func AllProviders() []string
- func DeepMerge(base, override map[string]any) map[string]any
- func LoginCLI(ctx context.Context, executable string, args ...string) error
- func ReadSSE(r io.Reader, endMarker string, yield func(ServerSentEvent) error) error
- func RegisterProvider(name string, spec ProviderSpec)
- func StrictSchema(schema map[string]any, requireAll bool) (map[string]any, error)
- type Answer
- type Auth
- type AuthFunc
- type BuiltinTool
- type BuiltinToolCall
- type ChatFormat
- type ChatModel
- type ChatRequest
- type Citation
- type CopilotAuth
- type DecisionAPIFormat
- type DecisionModel
- type DecisionResponse
- type Delta
- type DeviceAuthorize
- type EmbeddingAPIFormat
- type EmbeddingModel
- type EmbeddingResponse
- type Error
- type ErrorKind
- type Event
- type Extension
- type ExtensionFuncs
- type FilePart
- type GitHubCLIAuth
- type HTTPRequest
- type HeaderAuth
- type History
- type ImageAPIFormat
- type ImageModel
- type ImageResponse
- type InMemoryHistory
- type Message
- type ModelInfo
- type OAuth2Auth
- type OpenRouterAuth
- type Options
- type OutputSchema
- type Part
- func Audio(source any, mediaType string) (Part, error)
- func Image(source any, mediaType string) (Part, error)
- func LoadMedia(kind string, source any, mediaType string) (Part, error)
- func ProviderData(format string, payload map[string]any) Part
- func Reasoning(s string) Part
- func Text(s string) Part
- func Video(source any, mediaType string) (Part, error)
- type Provider
- func (p *Provider) Close() error
- func (p *Provider) GetDecisionModel(name string) (*DecisionModel, error)
- func (p *Provider) GetEmbeddingModel(name string) (*EmbeddingModel, error)
- func (p *Provider) GetImageModel(name string) (*ImageModel, error)
- func (p *Provider) GetModel(name string) (*ChatModel, error)
- func (p *Provider) IsClosed() bool
- func (p *Provider) ListModels(ctx context.Context) (models []ModelInfo, err error)
- type ProviderConfig
- type ProviderSpec
- type Question
- type Response
- type ResponseBuilder
- type ServerSentEvent
- type Stream
- type StreamParser
- type TokenAuth
- func CodexAuthFromFile(path string) (*TokenAuth, error)
- func GrokAuthFromFile(path string) (*TokenAuth, error)
- func LoginCodex(ctx context.Context, executable string, device bool) (*TokenAuth, error)
- func LoginGrok(ctx context.Context, executable string, device bool) (*TokenAuth, error)
- func NewCodexAuth(token map[string]any, accountID string) (*TokenAuth, error)
- func NewGrokAuth(token map[string]any) (*TokenAuth, error)
- type TokenUsage
- type Tool
- type ToolCall
- type ToolCallFragment
- type UserLocation
- type WireFormat
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AllProviders ¶
func AllProviders() []string
func ReadSSE ¶
ReadSSE reads arbitrarily long events without Scanner's default 64 KiB limit. Returning an error from yield stops reading immediately.
func RegisterProvider ¶
func RegisterProvider(name string, spec ProviderSpec)
Types ¶
type Answer ¶
type Answer struct {
Type string `json:"type"`
Noul float64 `json:"noul,omitempty"`
Choice string `json:"choice,omitempty"`
Score float64 `json:"score,omitempty"`
Probabilities map[string]float64 `json:"probabilities,omitempty"`
Confidence float64 `json:"confidence,omitempty"`
Legend map[string]string `json:"legend,omitempty"`
}
type BuiltinTool ¶
type BuiltinTool struct {
Kind string `json:"kind"`
MaxUses *int `json:"max_uses"`
AllowedDomains []string `json:"allowed_domains"`
BlockedDomains []string `json:"blocked_domains"`
UserLocation *UserLocation `json:"user_location"`
APIFormat string `json:"api_format"`
Definition map[string]any `json:"definition"`
}
func CodeExecution ¶
func CodeExecution() BuiltinTool
func ImageGeneration ¶
func ImageGeneration() BuiltinTool
func NativeTool ¶
func NativeTool(format string, definition map[string]any) BuiltinTool
func WebFetch ¶
func WebFetch() BuiltinTool
func WebSearch ¶
func WebSearch() BuiltinTool
type BuiltinToolCall ¶
type ChatFormat ¶
type ChatFormat interface {
Name() string
Headers() http.Header
Build(ChatRequest, bool) (HTTPRequest, error)
Parse([]byte) ([]Delta, error)
NewParser() StreamParser
}
ChatFormat is implemented by custom wire protocols. Methods must be safe for concurrent calls; NewParser returns fresh state for each stream.
type ChatModel ¶
type ChatModel struct {
Provider *Provider
Name string
Format ChatFormat
History History
}
type ChatRequest ¶
type ChatRequest struct {
Model string
Messages []Message
Options Options
OutputSchema *OutputSchema
}
type CopilotAuth ¶
type CopilotAuth struct {
// contains filtered or unexported fields
}
func LoginCopilot ¶
func LoginCopilot(ctx context.Context, onAuthorize DeviceAuthorize) (*CopilotAuth, error)
func NewCopilotAuth ¶
func NewCopilotAuth(githubToken string) (*CopilotAuth, error)
func (*CopilotAuth) GitHubToken ¶
func (a *CopilotAuth) GitHubToken() string
type DecisionAPIFormat ¶
type DecisionAPIFormat interface {
Name() string
Headers() http.Header
Build(model string, state any, questions map[string]Question) (HTTPRequest, error)
Parse(map[string]any) (DecisionResponse, error)
}
DecisionAPIFormat implements a typed decision protocol.
type DecisionModel ¶
type DecisionModel struct {
Provider *Provider
Name, Format string
APIFormat DecisionAPIFormat
}
func GetDecisionModel ¶
func GetDecisionModel(spec string, c ProviderConfig) (*DecisionModel, error)
func (*DecisionModel) Close ¶
func (m *DecisionModel) Close() error
func (*DecisionModel) Decide ¶
func (m *DecisionModel) Decide(ctx context.Context, state any, questions map[string]Question) (r DecisionResponse, err error)
type DecisionResponse ¶
type Delta ¶
type Delta struct {
Event *Event
ProviderData *Part
Fragment *ToolCallFragment
Usage map[string]int
ID string
Model string
FinishReason string
}
Delta contains either a public event or an internal cumulative update.
type EmbeddingAPIFormat ¶
type EmbeddingAPIFormat interface {
Name() string
Headers() http.Header
Build(model string, texts []string, dimensions *int) (HTTPRequest, error)
Parse(map[string]any) (EmbeddingResponse, error)
}
EmbeddingAPIFormat implements a custom embedding protocol.
type EmbeddingModel ¶
type EmbeddingModel struct {
Provider *Provider
Name, Format string
APIFormat EmbeddingAPIFormat
}
func GetEmbeddingModel ¶
func GetEmbeddingModel(spec string, c ProviderConfig) (*EmbeddingModel, error)
func (*EmbeddingModel) Close ¶
func (m *EmbeddingModel) Close() error
func (*EmbeddingModel) Embed ¶
func (m *EmbeddingModel) Embed(ctx context.Context, text string, dimensions *int) (EmbeddingResponse, error)
func (*EmbeddingModel) EmbedMany ¶
func (m *EmbeddingModel) EmbedMany(ctx context.Context, texts []string, dimensions *int) (r EmbeddingResponse, err error)
type EmbeddingResponse ¶
type EmbeddingResponse struct {
Vectors [][]float64
TokenUsage TokenUsage
Model, RequestID string
Headers http.Header
}
func (EmbeddingResponse) Vector ¶
func (r EmbeddingResponse) Vector() ([]float64, error)
type Error ¶
type ErrorKind ¶
type ErrorKind string
const ( ErrAuthentication ErrorKind = "authentication" ErrProviderNotFound ErrorKind = "provider_not_found" ErrUnsupportedFormat ErrorKind = "unsupported_api_format" ErrUnsupportedFeature ErrorKind = "unsupported_feature" ErrAPIStatus ErrorKind = "api_status" ErrConnection ErrorKind = "api_connection" ErrTimeout ErrorKind = "api_timeout" ErrAPIResponse ErrorKind = "api_response" ErrStreamIncomplete ErrorKind = "stream_incomplete" ErrStreamNotFinished ErrorKind = "stream_not_finished" ErrClosed ErrorKind = "closed" )
type Event ¶
type Event struct {
Type string `json:"type"`
Chunk string `json:"chunk,omitempty"`
CallID string `json:"call_id,omitempty"`
Name string `json:"name,omitempty"`
Usage TokenUsage `json:"usage,omitempty"`
Image *Part `json:"image,omitempty"`
Call *ToolCall `json:"call,omitempty"`
BuiltinCall *BuiltinToolCall `json:"builtin_call,omitempty"`
Citation *Citation `json:"citation,omitempty"`
Response *Response `json:"response,omitempty"`
}
Event is emitted in protocol order. Completed always contains the final result.
type Extension ¶
type Extension interface {
OnStart(provider, operation, model string) any
OnRetry(state any, err error, attempt int, delay time.Duration)
OnFinish(state, response any, err error)
}
Extension hooks run synchronously in registration order. A panic is isolated and logged; hooks must not mutate responses borrowed from the library.
type ExtensionFuncs ¶
type ExtensionFuncs struct {
Start func(provider, operation, model string) any
Retry func(state any, err error, attempt int, delay time.Duration)
Finish func(state, response any, err error)
}
ExtensionFuncs allows callers to implement only the hooks they need.
func (ExtensionFuncs) OnFinish ¶
func (e ExtensionFuncs) OnFinish(s, r any, err error)
func (ExtensionFuncs) OnStart ¶
func (e ExtensionFuncs) OnStart(p, o, m string) any
type GitHubCLIAuth ¶
type GitHubCLIAuth struct{ Hostname, Executable string }
func LoginGitHubCLI ¶
func LoginGitHubCLI(ctx context.Context, executable, hostname string) (GitHubCLIAuth, error)
type HTTPRequest ¶
type HeaderAuth ¶
type HeaderAuth struct{ Name, Value string }
type ImageAPIFormat ¶
type ImageAPIFormat interface {
Name() string
Headers() http.Header
Generate(model, prompt string, options Options) (HTTPRequest, error)
Edit(model, prompt string, images []Part, mask *Part, options Options) (HTTPRequest, error)
Parse(map[string]any) (ImageResponse, error)
}
ImageAPIFormat implements image generation and editing.
type ImageModel ¶
type ImageModel struct {
Provider *Provider
Name, Format string
APIFormat ImageAPIFormat
}
func GetImageModel ¶
func GetImageModel(spec string, c ProviderConfig) (*ImageModel, error)
func (*ImageModel) Close ¶
func (m *ImageModel) Close() error
func (*ImageModel) Edit ¶
func (m *ImageModel) Edit(ctx context.Context, prompt string, images []Part, mask *Part, options Options) (ImageResponse, error)
func (*ImageModel) Generate ¶
func (m *ImageModel) Generate(ctx context.Context, prompt string, options Options) (ImageResponse, error)
type ImageResponse ¶
type InMemoryHistory ¶
type InMemoryHistory struct {
// contains filtered or unexported fields
}
InMemoryHistory keeps whole user turns when bounded. Zero means unbounded.
func NewHistory ¶
func NewHistory(maxEntries int) (*InMemoryHistory, error)
type Message ¶
type Message struct {
Role string
Parts []Part
ToolCalls []ToolCall
ToolCall *ToolCall
IsError bool
}
func (Message) MarshalJSON ¶
func (*Message) UnmarshalJSON ¶
type OAuth2Auth ¶
type OAuth2Auth struct{ AccessToken string }
OAuth2Auth sends a caller-managed bearer token without persisting it.
type OpenRouterAuth ¶
type OpenRouterAuth struct{ APIKey string }
func LoginOpenRouter ¶
func LoginOpenRouter(ctx context.Context, authorize func(context.Context, string) (string, error)) (OpenRouterAuth, error)
LoginOpenRouter delegates displaying the authorization URL and collecting its code to the caller. The resulting API key is persisted only by the caller.
func NewOpenRouterAuth ¶
func NewOpenRouterAuth(key string) (OpenRouterAuth, error)
type Options ¶
Options uses Republic's portable option names. Presence matters: false and zero are sent when explicitly supplied.
type OutputSchema ¶
type Part ¶
type Part struct {
Type string `json:"type"`
Text string `json:"-"`
MediaType string `json:"media_type,omitempty"`
Data []byte `json:"data,omitempty"`
URL string `json:"url,omitempty"`
APIFormat string `json:"api_format,omitempty"`
Payload map[string]any `json:"payload,omitempty"`
}
Part is a typed message content item. Data is encoded as base64 in JSON. ProviderData is opaque and may only be replayed to its originating format.
func (Part) Base64Data ¶
func (Part) MarshalJSON ¶
func (*Part) UnmarshalJSON ¶
type Provider ¶
type Provider struct {
Name, APIBase string
// contains filtered or unexported fields
}
func GetProvider ¶
func GetProvider(name string, c ProviderConfig) (*Provider, error)
func NewProvider ¶
func NewProvider(spec ProviderSpec, c ProviderConfig) (*Provider, error)
func (*Provider) GetDecisionModel ¶
func (p *Provider) GetDecisionModel(name string) (*DecisionModel, error)
func (*Provider) GetEmbeddingModel ¶
func (p *Provider) GetEmbeddingModel(name string) (*EmbeddingModel, error)
func (*Provider) GetImageModel ¶
func (p *Provider) GetImageModel(name string) (*ImageModel, error)
type ProviderConfig ¶
type ProviderSpec ¶
type ProviderSpec struct {
Name, APIBase, ModelsPath, AuthHeader string
Formats []string
// SelectFormat overrides chat dialect selection for custom providers.
SelectFormat func(model, format string) ChatFormat
SelectEmbeddingFormat func(model, format string) EmbeddingAPIFormat
SelectImageFormat func(model, format string) ImageAPIFormat
SelectDecisionFormat func(model, format string) DecisionAPIFormat
ModelsParams func(previous any) map[string]string
ParseModels func(data any) ([]ModelInfo, error)
}
type Response ¶
type Response struct {
Message Message `json:"message"`
TokenUsage TokenUsage `json:"token_usage"`
Output any `json:"output"`
FinishReason string `json:"finish_reason,omitempty"`
Refusal string `json:"refusal,omitempty"`
Citations []Citation `json:"citations"`
BuiltinToolCalls []BuiltinToolCall `json:"builtin_tool_calls"`
ID string `json:"id,omitempty"`
Model string `json:"model,omitempty"`
RequestID string `json:"request_id,omitempty"`
Headers http.Header `json:"-"`
}
func (Response) ImageParts ¶
type ResponseBuilder ¶
type ResponseBuilder struct {
// contains filtered or unexported fields
}
func (*ResponseBuilder) Add ¶
func (b *ResponseBuilder) Add(d Delta) []Event
func (*ResponseBuilder) ReleaseToolCalls ¶
func (b *ResponseBuilder) ReleaseToolCalls() []Event
func (*ResponseBuilder) Response ¶
func (b *ResponseBuilder) Response() Response
type ServerSentEvent ¶
type Stream ¶
type StreamParser ¶
StreamParser converts one wire protocol into deltas, retaining per-stream state. A parser must never be shared by independent requests.
func NewStreamParser ¶
func NewStreamParser(format string) (StreamParser, error)
type TokenAuth ¶
TokenAuth maintains Codex or Grok OAuth credentials. Token returns a snapshot; refreshes are serialized. HTTPClient may be set before first use.
func CodexAuthFromFile ¶
func GrokAuthFromFile ¶
func LoginCodex ¶
type TokenUsage ¶
type TokenUsage struct {
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
ReasoningTokens int `json:"reasoning_tokens"`
CachedTokens int `json:"cached_tokens"`
CacheWriteTokens int `json:"cache_write_tokens"`
}
func (TokenUsage) TotalTokens ¶
func (u TokenUsage) TotalTokens() int
type Tool ¶
type ToolCall ¶
type ToolCallFragment ¶
type UserLocation ¶
type WireFormat ¶
func (WireFormat) Build ¶
func (f WireFormat) Build(r ChatRequest, stream bool) (HTTPRequest, error)
func (WireFormat) Headers ¶
func (f WireFormat) Headers() http.Header
func (WireFormat) Name ¶
func (f WireFormat) Name() string
func (WireFormat) NewParser ¶
func (f WireFormat) NewParser() StreamParser