llmapi

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Jan 17, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package llmapi provides an OpenAI-compatible API client with retry logic, system message support, and concurrent request handling.

Index

Constants

View Source
const DefaultBaseURL = "https://api.openai.com/v1"

DefaultBaseURL is the default OpenAI API endpoint.

View Source
const DefaultModel = "gpt-4o-mini"

DefaultModel is the default model to use.

Variables

This section is empty.

Functions

func CleanResponse

func CleanResponse(response string) string

CleanResponse removes markdown code fences and extracts the content.

func ExtractJSON

func ExtractJSON(response string) (string, error)

ExtractJSON cleans the response and validates it's valid JSON.

Types

type APIConfig

type APIConfig struct {
	APIKey  string
	BaseURL string
	Model   string
}

APIConfig holds API configuration settings.

func GetAPIConfig

func GetAPIConfig() *APIConfig

GetAPIConfig loads API configuration from environment variables with defaults. Supported environment variables:

  • OPENAI_API_KEY or ANTHROPIC_API_KEY for API key (required)
  • OPENAI_BASE_URL for custom endpoint (default: https://api.openai.com/v1)
  • OPENAI_MODEL for model selection (default: gpt-4o-mini)

func (*APIConfig) Validate

func (c *APIConfig) Validate() error

Validate checks that required configuration values are present.

type APIError

type APIError struct {
	ErrorInfo struct {
		Message string `json:"message"`
		Type    string `json:"type"`
		Code    string `json:"code"`
	} `json:"error"`
	StatusCode int `json:"-"` // HTTP status code
}

APIError represents an API error response.

func (*APIError) Error

func (e *APIError) Error() string

Error implements the error interface for APIError.

type BatchProcessor

type BatchProcessor struct {
	Client      *LLMClient
	Concurrency int
}

BatchProcessor handles concurrent processing of items with an LLM client.

func NewBatchProcessor

func NewBatchProcessor(client *LLMClient, concurrency int) *BatchProcessor

NewBatchProcessor creates a new batch processor with the given concurrency limit.

func (*BatchProcessor) ProcessItems

func (bp *BatchProcessor) ProcessItems(ctx context.Context, items []interface{}, fn ProcessFunc) []BatchResult

ProcessItems processes multiple items concurrently using errgroup. Results are returned in the same order as inputs.

func (*BatchProcessor) ProcessItemsWithProgress

func (bp *BatchProcessor) ProcessItemsWithProgress(ctx context.Context, items []interface{}, fn ProcessFunc, progress ProgressCallback) []BatchResult

ProcessItemsWithProgress processes items with a progress callback.

func (*BatchProcessor) ProcessStrings

func (bp *BatchProcessor) ProcessStrings(ctx context.Context, systemPrompt string, prompts []string) []BatchResult

ProcessStrings is a convenience method for processing string prompts concurrently.

type BatchResult

type BatchResult struct {
	Index  int
	Input  interface{}
	Output interface{}
	Error  error
}

BatchResult contains the result of processing a single item.

type ChatRequest

type ChatRequest struct {
	Model       string    `json:"model"`
	Messages    []Message `json:"messages"`
	Temperature float64   `json:"temperature,omitempty"`
	MaxTokens   int       `json:"max_tokens,omitempty"`
}

ChatRequest represents a chat completion request.

type ChatResponse

type ChatResponse struct {
	ID      string   `json:"id"`
	Object  string   `json:"object"`
	Created int64    `json:"created"`
	Model   string   `json:"model"`
	Choices []Choice `json:"choices"`
}

ChatResponse represents a chat completion response.

type Choice

type Choice struct {
	Index        int     `json:"index"`
	Message      Message `json:"message"`
	FinishReason string  `json:"finish_reason"`
}

Choice represents a response choice.

type LLMClient

type LLMClient struct {
	APIKey     string
	BaseURL    string
	Model      string
	HTTPClient *http.Client

	// Generation parameters
	Temperature float64 // Temperature for generation (default: 0.7)

	// Retry configuration
	MaxRetries   int
	RetryDelay   time.Duration
	RetryBackoff float64 // Multiplier for exponential backoff
}

LLMClient is an OpenAI-compatible API client with retry support.

func NewLLMClient

func NewLLMClient(apiKey, baseURL, model string) *LLMClient

NewLLMClient creates a new LLM client with the given configuration.

func NewLLMClientFromConfig

func NewLLMClientFromConfig(config *APIConfig) *LLMClient

NewLLMClientFromConfig creates a new LLM client from APIConfig.

func (*LLMClient) Complete

func (c *LLMClient) Complete(prompt string, timeout time.Duration) (string, error)

Complete sends a chat completion request and returns the response content. This is a convenience method that uses only a user message.

func (*LLMClient) CompleteMessages

func (c *LLMClient) CompleteMessages(ctx context.Context, messages []Message) (string, error)

CompleteMessages sends a chat completion request with custom messages.

func (*LLMClient) CompleteWithContext

func (c *LLMClient) CompleteWithContext(ctx context.Context, systemPrompt, userPrompt string) (string, error)

CompleteWithContext sends a chat completion request using the provided context.

func (*LLMClient) CompleteWithSystem

func (c *LLMClient) CompleteWithSystem(systemPrompt, userPrompt string, timeout time.Duration) (string, error)

CompleteWithSystem sends a chat completion request with both system and user messages.

type Message

type Message struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

Message represents a chat message.

type ProcessFunc

type ProcessFunc func(ctx context.Context, client *LLMClient, item interface{}) (interface{}, error)

ProcessFunc is a function that processes a single item with the LLM client.

type ProgressCallback

type ProgressCallback func(completed, total int, result BatchResult)

ProcessWithProgress processes items and calls a progress callback after each completion.

Jump to

Keyboard shortcuts

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