pkg

package
v0.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 8, 2025 License: MIT Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultBaseURL is the default base URL for the OpenRouter API
	DefaultBaseURL = "https://openrouter.ai/api/v1"

	// DefaultTimeout is the default timeout for HTTP requests
	DefaultTimeout = 2 * time.Minute
)

Variables

This section is empty.

Functions

func CreateStructuredPrompt

func CreateStructuredPrompt(userPrompt string, schemaDescription string) string

CreateStructuredPrompt creates a prompt that encourages JSON output

func ExtractCitations

func ExtractCitations(resp *models.ChatCompletionResponse) []models.URLCitation

ExtractCitations extracts URL citations from a response

func FormatCitationsAsMarkdown

func FormatCitationsAsMarkdown(citations []models.URLCitation) string

FormatCitationsAsMarkdown formats citations as markdown links

func GenerateSchema

func GenerateSchema(v interface{}) (map[string]interface{}, error)

GenerateSchema generates a JSON schema from a Go struct

func ParseStructuredResponse

func ParseStructuredResponse(resp *models.ChatCompletionResponse, target interface{}) error

ParseStructuredResponse parses a structured response into a Go struct

func ValidateJSONResponse

func ValidateJSONResponse(content string) (map[string]interface{}, error)

ValidateJSONResponse validates that a response contains valid JSON

Types

type Agent

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

Agent represents an autonomous agent that can handle tool calls

func NewAgent

func NewAgent(client *Client, model string) *Agent

NewAgent creates a new agent

func (*Agent) RegisterTool

func (a *Agent) RegisterTool(tool models.Tool, executor ToolExecutor)

RegisterTool registers a tool with the agent

func (*Agent) RegisterToolFunc

func (a *Agent) RegisterToolFunc(tool models.Tool, fn func(models.ToolCall) (string, error))

RegisterToolFunc registers a tool function with the agent

func (*Agent) Run

func (a *Agent) Run(ctx context.Context, messages []models.Message, opts RunOptions) ([]models.Message, error)

Run runs the agent with the given messages

func (*Agent) RunStream

func (a *Agent) RunStream(ctx context.Context, messages []models.Message, opts StreamOptions) ([]models.Message, error)

RunStream runs the agent with streaming support

type BatchProcessor

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

BatchProcessor processes requests in batches

func NewBatchProcessor

func NewBatchProcessor(client *ConcurrentClient, batchSize int) *BatchProcessor

NewBatchProcessor creates a new batch processor

func (*BatchProcessor) ProcessBatch

func (p *BatchProcessor) ProcessBatch(ctx context.Context, requests []models.ChatCompletionRequest, callback func(ChatCompletionResult)) error

ProcessBatch processes requests in batches and calls the callback for each result

type ChatCompletionResult

type ChatCompletionResult struct {
	Response *models.ChatCompletionResponse
	Error    error
	Index    int
}

ChatCompletionResult represents the result of a concurrent chat completion

type CircuitBreaker

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

CircuitBreaker implements circuit breaker pattern

func NewCircuitBreaker

func NewCircuitBreaker(client *Client, failureThreshold int, resetTimeout time.Duration) *CircuitBreaker

NewCircuitBreaker creates a new circuit breaker

func (*CircuitBreaker) CreateChatCompletion

CreateChatCompletion creates a chat completion with circuit breaker

type CircuitState

type CircuitState int

CircuitState represents the state of a circuit breaker

const (
	CircuitClosed CircuitState = iota
	CircuitOpen
	CircuitHalfOpen
)

type Client

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

Client is the main client for interacting with the OpenRouter API

func NewClient

func NewClient(apiKey string, opts ...Option) *Client

NewClient creates a new OpenRouter client with the given API key

func (*Client) CreateAPIKey

func (c *Client) CreateAPIKey(ctx context.Context, req models.CreateAPIKeyRequest) (*models.APIKey, error)

CreateAPIKey creates a new API key Requires a Provisioning API key

func (*Client) CreateChatCompletion

func (c *Client) CreateChatCompletion(ctx context.Context, req models.ChatCompletionRequest) (*models.ChatCompletionResponse, error)

CreateChatCompletion creates a chat completion

func (*Client) CreateChatCompletionStream

func (c *Client) CreateChatCompletionStream(ctx context.Context, req models.ChatCompletionRequest) (*streaming.ChatCompletionStreamReader, error)

CreateChatCompletionStream creates a streaming chat completion

func (*Client) CreateCoinbaseCharge

CreateCoinbaseCharge creates and hydrates a Coinbase Commerce charge for cryptocurrency payments

func (*Client) CreateCompletion

CreateCompletion creates a text completion using the legacy completions endpoint

func (*Client) CreateCompletionStream

CreateCompletionStream creates a streaming text completion

func (*Client) DeleteAPIKey

func (c *Client) DeleteAPIKey(ctx context.Context, keyHash string) error

DeleteAPIKey deletes an API key Requires a Provisioning API key

func (*Client) ExchangeAuthCodeForAPIKey

func (c *Client) ExchangeAuthCodeForAPIKey(ctx context.Context, req models.ExchangeAuthCodeRequest) (*models.ExchangeAuthCodeResponse, error)

ExchangeAuthCodeForAPIKey exchanges an authorization code from the PKCE OAuth flow for a user-controlled API key

func (*Client) GetAPIKey

func (c *Client) GetAPIKey(ctx context.Context, keyHash string) (*models.APIKey, error)

GetAPIKey returns details about a specific API key Requires a Provisioning API key

func (*Client) GetCredits

func (c *Client) GetCredits(ctx context.Context) (*models.CreditsResponse, error)

GetCredits returns the total credits purchased and used for the authenticated user

func (*Client) GetCurrentAPIKey

func (c *Client) GetCurrentAPIKey(ctx context.Context) (*models.APIKey, error)

GetCurrentAPIKey gets information on the API key associated with the current authentication session

func (*Client) GetGeneration

func (c *Client) GetGeneration(ctx context.Context, generationID string) (*models.GenerationResponse, error)

GetGeneration retrieves metadata about a specific generation

func (*Client) ListAPIKeys

func (c *Client) ListAPIKeys(ctx context.Context, opts *ListAPIKeysOptions) (*models.APIKeysResponse, error)

ListAPIKeys returns a list of all API keys associated with the account Requires a Provisioning API key

func (*Client) ListModelEndpoints

func (c *Client) ListModelEndpoints(ctx context.Context, model string) (*models.ModelEndpointsResponse, error)

ListModelEndpoints returns the available endpoints/providers for a specific model The model parameter should be in the format "author/slug" (e.g., "openai/gpt-4")

func (*Client) ListModels

func (c *Client) ListModels(ctx context.Context, opts *ListModelsOptions) (*models.ModelsResponse, error)

ListModels lists available models

func (*Client) ListProviders

func (c *Client) ListProviders(ctx context.Context) (*models.ProvidersResponse, error)

ListProviders returns a list of providers available through the API

func (*Client) UpdateAPIKey

func (c *Client) UpdateAPIKey(ctx context.Context, keyHash string, req models.UpdateAPIKeyRequest) (*models.APIKey, error)

UpdateAPIKey updates an existing API key Requires a Provisioning API key

type ConcurrentClient

type ConcurrentClient struct {
	*Client
	// contains filtered or unexported fields
}

ConcurrentClient wraps Client with concurrent execution capabilities

func NewConcurrentClient

func NewConcurrentClient(apiKey string, maxConcurrency int, opts ...Option) *ConcurrentClient

NewConcurrentClient creates a new concurrent client

func (*ConcurrentClient) CreateChatCompletionsConcurrent

func (c *ConcurrentClient) CreateChatCompletionsConcurrent(ctx context.Context, requests []models.ChatCompletionRequest) []ChatCompletionResult

CreateChatCompletionsConcurrent executes multiple chat completions concurrently

func (*ConcurrentClient) CreateChatCompletionsStreamConcurrent

func (c *ConcurrentClient) CreateChatCompletionsStreamConcurrent(ctx context.Context, requests []models.ChatCompletionRequest) <-chan StreamingResult

CreateChatCompletionsStreamConcurrent executes multiple streaming chat completions concurrently

type Entity

type Entity struct {
	Name string `json:"name" description:"Entity name"`
	Type string `json:"type" description:"Entity type (person, place, organization, etc.)"`
}

Entity represents a named entity

type ExtractedData

type ExtractedData struct {
	Title    string   `json:"title" description:"Main title or subject"`
	Summary  string   `json:"summary" description:"Brief summary"`
	Keywords []string `json:"keywords" description:"Key terms or topics"`
	Entities []Entity `json:"entities" description:"Named entities found"`
}

ExtractedData represents extracted information

type ImageInput

type ImageInput struct {
	URL    string
	Path   string
	Data   []byte
	Detail string // "auto", "low", "high"
}

ImageInput represents an image input

func LoadImageFromFile

func LoadImageFromFile(path string) (ImageInput, error)

LoadImageFromFile loads an image from a file

func LoadImageFromReader

func LoadImageFromReader(reader io.Reader) (ImageInput, error)

LoadImageFromReader loads an image from a reader

func LoadImageFromURL

func LoadImageFromURL(url string) (ImageInput, error)

LoadImageFromURL loads an image from a URL

type ListAPIKeysOptions

type ListAPIKeysOptions struct {
	Offset          int
	IncludeDisabled bool
}

ListAPIKeysOptions contains options for listing API keys

type ListModelsOptions

type ListModelsOptions struct {
	Category string
}

ListModelsOptions represents options for listing models

type LogLevel

type LogLevel int

LogLevel represents logging level

const (
	LogLevelDebug LogLevel = iota
	LogLevelInfo
	LogLevelWarn
	LogLevelError
)

type Logger

type Logger interface {
	Debug(msg string, fields ...interface{})
	Info(msg string, fields ...interface{})
	Warn(msg string, fields ...interface{})
	Error(msg string, fields ...interface{})
}

Logger interface for custom logging

type MetricsCollector

type MetricsCollector interface {
	RecordLatency(operation string, duration time.Duration, labels map[string]string)
	RecordTokens(promptTokens, completionTokens int, labels map[string]string)
	RecordCost(cost float64, labels map[string]string)
	RecordError(operation string, err error, labels map[string]string)
}

MetricsCollector interface for metrics collection

type MultiModalHelper

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

MultiModalHelper provides utilities for working with multi-modal inputs

func NewMultiModalHelper

func NewMultiModalHelper(client *Client) *MultiModalHelper

NewMultiModalHelper creates a new multi-modal helper

func (*MultiModalHelper) CreateWithImage

func (m *MultiModalHelper) CreateWithImage(ctx context.Context, text string, image ImageInput, model string) (*models.ChatCompletionResponse, error)

CreateWithImage creates a chat completion with image input

func (*MultiModalHelper) CreateWithImages

func (m *MultiModalHelper) CreateWithImages(ctx context.Context, text string, images []ImageInput, model string) (*models.ChatCompletionResponse, error)

CreateWithImages creates a chat completion with multiple images

func (*MultiModalHelper) CreateWithMixed

func (m *MultiModalHelper) CreateWithMixed(ctx context.Context, text string, images []ImageInput, pdfs []PDFInput, model string) (*models.ChatCompletionResponse, error)

CreateWithMixed creates a chat completion with mixed media

func (*MultiModalHelper) CreateWithPDF

func (m *MultiModalHelper) CreateWithPDF(ctx context.Context, text string, pdf PDFInput, model string) (*models.ChatCompletionResponse, error)

CreateWithPDF creates a chat completion with PDF input

type ObservabilityOptions

type ObservabilityOptions struct {
	Logger       Logger
	Metrics      MetricsCollector
	LogRequests  bool
	LogResponses bool
	TrackCosts   bool
}

ObservabilityOptions contains options for observability

type ObservableClient

type ObservableClient struct {
	*Client
	// contains filtered or unexported fields
}

ObservableClient wraps a client with observability features

func NewObservableClient

func NewObservableClient(apiKey string, obsOpts ObservabilityOptions, clientOpts ...Option) *ObservableClient

NewObservableClient creates a new observable client

func (*ObservableClient) AddRequestHook

func (o *ObservableClient) AddRequestHook(hook RequestHook)

AddRequestHook adds a request hook

func (*ObservableClient) AddResponseHook

func (o *ObservableClient) AddResponseHook(hook ResponseHook)

AddResponseHook adds a response hook

func (*ObservableClient) CreateChatCompletion

CreateChatCompletion creates a chat completion with observability

type Option

type Option func(*Client)

Option is a function that configures the client

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL sets a custom base URL for the API

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) Option

WithHTTPClient sets a custom HTTP client

func WithHTTPReferer

func WithHTTPReferer(referer string) Option

WithHTTPReferer sets the HTTP-Referer header for rankings on openrouter.ai

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout sets a custom timeout for HTTP requests

func WithUserAgent

func WithUserAgent(userAgent string) Option

WithUserAgent sets a custom user agent for requests

func WithXTitle

func WithXTitle(title string) Option

WithXTitle sets the X-Title header for rankings on openrouter.ai

type PDFInput

type PDFInput struct {
	Path     string
	Data     []byte
	Filename string
	Engine   models.PDFEngine
}

PDFInput represents a PDF input

func LoadPDFFromFile

func LoadPDFFromFile(path string, engine models.PDFEngine) (PDFInput, error)

LoadPDFFromFile loads a PDF from a file

func LoadPDFFromReader

func LoadPDFFromReader(reader io.Reader, filename string, engine models.PDFEngine) (PDFInput, error)

LoadPDFFromReader loads a PDF from a reader

type RequestHook

type RequestHook func(ctx context.Context, operation string, request interface{}) context.Context

RequestHook is called before a request is made

type ResearchAgent

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

ResearchAgent is an agent specialized for research tasks

func (*ResearchAgent) Research

func (r *ResearchAgent) Research(ctx context.Context, topic string, depth int) (*ResearchResult, error)

Research performs a multi-step research process

type ResearchResult

type ResearchResult struct {
	Topic     string
	Summary   string
	Sections  []ResearchSection
	Citations []models.URLCitation
}

ResearchResult represents the result of a research process

type ResearchSection

type ResearchSection struct {
	Title     string
	Content   string
	Citations []models.URLCitation
}

ResearchSection represents a section of research

type ResponseHook

type ResponseHook func(ctx context.Context, operation string, request interface{}, response interface{}, err error)

ResponseHook is called after a response is received

type RetryClient

type RetryClient struct {
	*Client
	// contains filtered or unexported fields
}

RetryClient wraps a client with retry logic

func NewRetryClient

func NewRetryClient(apiKey string, retryConfig *RetryConfig, opts ...Option) *RetryClient

NewRetryClient creates a new retry client

func (*RetryClient) CreateChatCompletion

CreateChatCompletion creates a chat completion with retry logic

func (*RetryClient) CreateChatCompletionStream

CreateChatCompletionStream creates a streaming chat completion with retry logic

type RetryConfig

type RetryConfig struct {
	MaxRetries      int
	InitialDelay    time.Duration
	MaxDelay        time.Duration
	BackoffFactor   float64
	JitterFactor    float64
	RetryableErrors map[errors.ErrorCode]bool
}

RetryConfig represents retry configuration

func DefaultRetryConfig

func DefaultRetryConfig() *RetryConfig

DefaultRetryConfig returns default retry configuration

type RunOptions

type RunOptions struct {
	MaxIterations int
	Tools         []models.Tool
	ToolChoice    models.ToolChoice
}

RunOptions contains options for running the agent

type SearchOptions

type SearchOptions struct {
	MaxResults   int
	SearchPrompt string
}

SearchOptions represents options for web search

type SimpleLogger

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

SimpleLogger implements Logger interface with standard log package

func NewSimpleLogger

func NewSimpleLogger(level LogLevel) *SimpleLogger

NewSimpleLogger creates a new simple logger

func (*SimpleLogger) Debug

func (l *SimpleLogger) Debug(msg string, fields ...interface{})

func (*SimpleLogger) Error

func (l *SimpleLogger) Error(msg string, fields ...interface{})

func (*SimpleLogger) Info

func (l *SimpleLogger) Info(msg string, fields ...interface{})

func (*SimpleLogger) Warn

func (l *SimpleLogger) Warn(msg string, fields ...interface{})

type SimpleMetricsCollector

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

SimpleMetricsCollector implements MetricsCollector with in-memory storage

func NewSimpleMetricsCollector

func NewSimpleMetricsCollector() *SimpleMetricsCollector

NewSimpleMetricsCollector creates a new simple metrics collector

func (*SimpleMetricsCollector) GetSummary

func (m *SimpleMetricsCollector) GetSummary() map[string]interface{}

GetSummary returns a summary of collected metrics

func (*SimpleMetricsCollector) RecordCost

func (m *SimpleMetricsCollector) RecordCost(cost float64, labels map[string]string)

func (*SimpleMetricsCollector) RecordError

func (m *SimpleMetricsCollector) RecordError(operation string, err error, labels map[string]string)

func (*SimpleMetricsCollector) RecordLatency

func (m *SimpleMetricsCollector) RecordLatency(operation string, duration time.Duration, labels map[string]string)

func (*SimpleMetricsCollector) RecordTokens

func (m *SimpleMetricsCollector) RecordTokens(promptTokens, completionTokens int, labels map[string]string)

type StreamOptions

type StreamOptions struct {
	Tools      []models.Tool
	ToolChoice models.ToolChoice
	OnChunk    func(chunk *models.ChatCompletionResponse) error
	OnToolCall func(toolCall models.ToolCall, result string) error
}

StreamOptions contains options for streaming with tool support

type StreamingResult

type StreamingResult struct {
	Stream *models.ChatCompletionResponse
	Error  error
	Index  int
	Final  bool
}

StreamingResult represents a streaming result

type StructuredOutput

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

StructuredOutput provides helper methods for structured outputs

func NewStructuredOutput

func NewStructuredOutput(client *Client) *StructuredOutput

NewStructuredOutput creates a new structured output helper

func (*StructuredOutput) CreateWithSchema

func (s *StructuredOutput) CreateWithSchema(ctx context.Context, req models.ChatCompletionRequest, schemaName string, schema interface{}) (*models.ChatCompletionResponse, error)

CreateWithSchema creates a completion with a structured output schema

type ToolExecutor

type ToolExecutor interface {
	Execute(toolCall models.ToolCall) (string, error)
}

ToolExecutor is an interface for executing tool calls

type ToolExecutorFunc

type ToolExecutorFunc func(models.ToolCall) (string, error)

ToolExecutorFunc is a function adapter for ToolExecutor

func (ToolExecutorFunc) Execute

func (f ToolExecutorFunc) Execute(toolCall models.ToolCall) (string, error)

Execute implements ToolExecutor

type ToolRegistry

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

ToolRegistry manages tool executors

func NewToolRegistry

func NewToolRegistry() *ToolRegistry

NewToolRegistry creates a new tool registry

func (*ToolRegistry) Execute

func (r *ToolRegistry) Execute(toolCall models.ToolCall) (string, error)

Execute executes a tool call

func (*ToolRegistry) Register

func (r *ToolRegistry) Register(name string, executor ToolExecutor)

Register registers a tool executor

func (*ToolRegistry) RegisterFunc

func (r *ToolRegistry) RegisterFunc(name string, fn func(models.ToolCall) (string, error))

RegisterFunc registers a tool executor function

type WeatherInfo

type WeatherInfo struct {
	Location    string  `json:"location" description:"City or location name"`
	Temperature float64 `json:"temperature" description:"Temperature in Celsius"`
	Conditions  string  `json:"conditions" description:"Weather conditions description"`
	Humidity    int     `json:"humidity,omitempty" description:"Humidity percentage"`
	WindSpeed   float64 `json:"wind_speed,omitempty" description:"Wind speed in km/h"`
}

WeatherInfo represents weather information

type WebSearchHelper

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

WebSearchHelper provides utilities for web search functionality

func NewWebSearchHelper

func NewWebSearchHelper(client *Client) *WebSearchHelper

NewWebSearchHelper creates a new web search helper

func (*WebSearchHelper) CreateResearchAgent

func (w *WebSearchHelper) CreateResearchAgent(model string) *ResearchAgent

CreateResearchAgent creates an agent specialized for research tasks

func (*WebSearchHelper) CreateWithNativeWebSearch

func (w *WebSearchHelper) CreateWithNativeWebSearch(ctx context.Context, prompt string, model string, contextSize string) (*models.ChatCompletionResponse, error)

CreateWithNativeWebSearch creates a chat completion using native web search models

func (*WebSearchHelper) CreateWithWebSearch

func (w *WebSearchHelper) CreateWithWebSearch(ctx context.Context, prompt string, model string, opts *SearchOptions) (*models.ChatCompletionResponse, error)

CreateWithWebSearch creates a chat completion with web search enabled

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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