config

package module
v0.0.0-...-2b7c671 Latest Latest
Warning

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

Go to latest
Published: Dec 31, 2025 License: MIT Imports: 5 Imported by: 0

README

Config Package

Shared configuration package for AI Provider Kit example programs.

Overview

This package provides common configuration structures and utilities for parsing the standard config.yaml format used across all AI Provider Kit examples. It handles:

  • YAML configuration file parsing
  • Multiple authentication methods (API key, multiple keys, OAuth)
  • Conversion to types.ProviderConfig structures
  • Provider type determination
  • OAuth credential handling

Usage

Import the Package
import "github.com/cecil-the-coder/ai-provider-kit/examples/config"
Load a Configuration File
cfg, err := config.LoadConfig("config.yaml")
if err != nil {
    log.Fatalf("Failed to load config: %v", err)
}
Get Provider Configuration
// Get a provider entry by name
providerEntry := config.GetProviderEntry(cfg, "anthropic")
if providerEntry == nil {
    log.Fatal("Provider not found")
}

// Build types.ProviderConfig
providerConfig := config.BuildProviderConfig("anthropic", providerEntry)
Complete Example
package main

import (
    "fmt"
    "log"

    "github.com/cecil-the-coder/ai-provider-kit/examples/config"
    "github.com/cecil-the-coder/ai-provider-kit/pkg/factory"
)

func main() {
    // Load configuration
    cfg, err := config.LoadConfig("config.yaml")
    if err != nil {
        log.Fatalf("Failed to load config: %v", err)
    }

    // Create factory
    providerFactory := factory.NewProviderFactory()
    factory.RegisterDefaultProviders(providerFactory)

    // Process each enabled provider
    for _, providerName := range cfg.Providers.Enabled {
        // Get provider entry
        entry := config.GetProviderEntry(cfg, providerName)
        if entry == nil {
            fmt.Printf("Provider %s not found\\n", providerName)
            continue
        }

        // Build provider config
        providerConfig := config.BuildProviderConfig(providerName, entry)

        // Create provider instance
        provider, err := providerFactory.CreateProvider(providerConfig.Type, providerConfig)
        if err != nil {
            fmt.Printf("Failed to create provider: %v\\n", err)
            continue
        }

        fmt.Printf("Created provider: %s\\n", providerName)
    }
}

Configuration Format

The standard config.yaml format supports multiple authentication methods:

Single API Key
providers:
  enabled:
    - openai
  openai:
    api_key: "sk-..."
Multiple API Keys
providers:
  enabled:
    - cerebras
  cerebras:
    api_keys:
      - "csk-key1..."
      - "csk-key2..."

The package uses the first API key from the array.

OAuth Credentials
providers:
  enabled:
    - gemini
  gemini:
    oauth_credentials:
      - id: default
        client_id: "your-client-id"
        client_secret: "your-client-secret"
        access_token: "ya29..."
        refresh_token: "1//06..."
        expires_at: "2025-11-16T18:38:22-07:00"
        scopes:
          - https://www.googleapis.com/auth/cloud-platform
Custom Providers
providers:
  enabled:
    - groq
  custom:
    groq:
      type: openai  # Uses OpenAI-compatible API
      base_url: https://api.groq.com/openai/v1
      api_key: "gsk-..."
      default_model: "llama-3.3-70b-versatile"

API Reference

Functions
LoadConfig(filename string) (*DemoConfig, error)

Loads and parses a YAML configuration file.

GetProviderEntry(config *DemoConfig, name string) *ProviderConfigEntry

Retrieves the provider config entry for a given provider name.

BuildProviderConfig(name string, entry *ProviderConfigEntry) types.ProviderConfig

Constructs a types.ProviderConfig from a ProviderConfigEntry.

DetermineProviderType(name string, entry *ProviderConfigEntry) types.ProviderType

Determines the provider type based on name and config.

ConvertOAuthCredentials(entries []OAuthCredentialEntry) []*types.OAuthCredentialSet

Converts OAuth credential entries to the format expected by the kit.

MaskAPIKey(key string) string

Masks an API key for safe display (shows first 4 and last 4 characters).

Types
DemoConfig

Complete configuration structure.

ProvidersConfig

Provider configurations with built-in and custom providers.

ProviderConfigEntry

Single provider configuration with all supported fields.

OAuthCredentialEntry

OAuth credentials structure.

MetricsConfig

Metrics configuration (optional).

AsyncConfig

Async configuration (optional).

Examples Using This Package

  • demo-client - Interactive chat client
  • demo-client-streaming - Streaming chat client
  • model-discovery-demo - Model discovery demonstration
  • config-demo - Configuration parsing example

Development

To update the package after changes:

cd examples/config
go mod tidy

License

Same as the AI Provider Kit project.

Documentation

Overview

Package config provides shared configuration structures and utilities for AI Provider Kit example programs. It handles parsing the standard config.yaml format and converting it to types.ProviderConfig structures.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildProviderConfig

func BuildProviderConfig(name string, entry *ProviderConfigEntry) types.ProviderConfig

BuildProviderConfig constructs a types.ProviderConfig from a ProviderConfigEntry This converts the config file format into the structure required by the ai-provider-kit module.

func ConvertOAuthCredentials

func ConvertOAuthCredentials(entries []OAuthCredentialEntry) []*types.OAuthCredentialSet

ConvertOAuthCredentials converts []OAuthCredentialEntry to []*types.OAuthCredentialSet

func DetermineProviderType

func DetermineProviderType(name string, entry *ProviderConfigEntry) types.ProviderType

DetermineProviderType determines the types.ProviderType based on name and config

func MaskAPIKey

func MaskAPIKey(key string) string

MaskAPIKey masks an API key for display purposes

Types

type AsyncConfig

type AsyncConfig struct {
	Enabled bool `yaml:"enabled"`
}

AsyncConfig represents async configuration

type DemoConfig

type DemoConfig struct {
	Providers ProvidersConfig `yaml:"providers"`
	Metrics   MetricsConfig   `yaml:"metrics,omitempty"`
	Async     AsyncConfig     `yaml:"async,omitempty"`
}

DemoConfig represents the complete configuration structure

func LoadConfig

func LoadConfig(filename string) (*DemoConfig, error)

LoadConfig loads and parses a YAML configuration file

type MetricsConfig

type MetricsConfig struct {
	Enabled bool `yaml:"enabled"`
	Port    int  `yaml:"port"`
}

MetricsConfig represents metrics configuration

type OAuthCredentialEntry

type OAuthCredentialEntry struct {
	// Unique identifier for this credential set
	ID string `yaml:"id"`

	// OAuth client credentials
	ClientID     string `yaml:"client_id"`
	ClientSecret string `yaml:"client_secret"`

	// OAuth tokens
	AccessToken  string `yaml:"access_token"`
	RefreshToken string `yaml:"refresh_token"`

	// Token expiration
	ExpiresAt string `yaml:"expires_at"`

	// OAuth scopes
	Scopes []string `yaml:"scopes"`
}

OAuthCredentialEntry represents a single set of OAuth credentials

type ProviderConfigEntry

type ProviderConfigEntry struct {
	// Provider type (e.g., "openai", "anthropic", "gemini")
	// For custom providers, this specifies which provider API to use
	Type string `yaml:"type"`

	// Default model to use for this provider
	DefaultModel string `yaml:"default_model"`

	// Base URL for the provider API (optional, uses provider default if not set)
	BaseURL string `yaml:"base_url"`

	// Single API key (used if only one key is needed)
	APIKey string `yaml:"api_key"`

	// Multiple API keys for load balancing or failover
	APIKeys []string `yaml:"api_keys"`

	// Project ID (used by some providers like Gemini)
	ProjectID string `yaml:"project_id"`

	// Maximum tokens for completions
	MaxTokens int `yaml:"max_tokens"`

	// Temperature for response generation
	Temperature float64 `yaml:"temperature"`

	// OAuth credentials (can have multiple sets for failover)
	OAuthCredentials []OAuthCredentialEntry `yaml:"oauth_credentials"`

	// Custom provider-specific models list
	Models interface{} `yaml:"models,omitempty"`
}

ProviderConfigEntry represents a single provider's configuration

func GetProviderEntry

func GetProviderEntry(config *DemoConfig, name string) *ProviderConfigEntry

GetProviderEntry retrieves the provider config entry for a given provider name

type ProvidersConfig

type ProvidersConfig struct {
	// List of enabled providers
	Enabled []string `yaml:"enabled"`

	// Preferred order for provider selection
	PreferredOrder []string `yaml:"preferred_order"`

	// Built-in provider configurations
	Anthropic  *ProviderConfigEntry `yaml:"anthropic,omitempty"`
	OpenAI     *ProviderConfigEntry `yaml:"openai,omitempty"`
	Cerebras   *ProviderConfigEntry `yaml:"cerebras,omitempty"`
	Gemini     *ProviderConfigEntry `yaml:"gemini,omitempty"`
	Qwen       *ProviderConfigEntry `yaml:"qwen,omitempty"`
	OpenRouter *ProviderConfigEntry `yaml:"openrouter,omitempty"`

	// Custom providers (map of provider name to config)
	Custom map[string]ProviderConfigEntry `yaml:"custom,omitempty"`
}

ProvidersConfig contains all provider configurations

Jump to

Keyboard shortcuts

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