siliconflow

package
v0.0.0-...-71b755f Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2026 License: MIT, Apache-2.0 Imports: 7 Imported by: 0

README ΒΆ

SiliconFlow Go Provider

License Go

A Go implementation of the SiliconFlow AI provider for the HelixAgent Toolkit. Provides comprehensive integration with SiliconFlow's API endpoints including chat completions, embeddings, image generation, and model discovery.

✨ Features

  • πŸ”„ Dynamic Model Discovery: Automatically fetches and categorizes all available SiliconFlow models
  • 🎯 Full API Coverage: Supports all SiliconFlow endpoints (chat, embeddings, rerank, images, audio, video)
  • βœ… Comprehensive Testing: Real API integration tests with extensive model validation
  • πŸ“‹ Schema Compatibility: Fully compatible with HelixAgent Toolkit interfaces
  • πŸ’Ύ Intelligent Caching: Reduces API calls with smart response caching
  • πŸ›‘οΈ Enterprise Security: Secure API key handling with proper error management
  • πŸ“Š Rich Logging: Structured logging with context for monitoring

πŸš€ Quick Start

Installation

Add to your Go project:

go get github.com/helixagent/toolkit/SiliconFlow/providers/siliconflow
Basic Usage
package main

import (
    "context"
    "log"

    "github.com/helixagent/toolkit/SiliconFlow/providers/siliconflow"
    "github.com/helixagent/toolkit/pkg/toolkit"
)

func main() {
    // Create provider configuration
    config := map[string]interface{}{
        "api_key": "your-siliconflow-api-key",
        "base_url": "https://api.siliconflow.com/v1",
        "timeout": 30000,
    }

    // Create provider instance
    provider, err := siliconflow.NewProvider(config)
    if err != nil {
        log.Fatal(err)
    }

    // Discover available models
    ctx := context.Background()
    models, err := provider.DiscoverModels(ctx)
    if err != nil {
        log.Fatal(err)
    }

    log.Printf("Discovered %d models", len(models))

    // Perform chat completion
    req := toolkit.ChatRequest{
        Model: "Qwen/Qwen2.5-7B-Instruct",
        Messages: []toolkit.ChatMessage{
            {Role: "user", Content: "Hello, how are you?"},
        },
        MaxTokens:   1000,
        Temperature: 0.7,
    }

    resp, err := provider.Chat(ctx, req)
    if err != nil {
        log.Fatal(err)
    }

    log.Printf("Response: %s", resp.Content)
}

πŸ“š Architecture

Core Components
SiliconFlow/
β”œβ”€β”€ providers/
β”‚   └── siliconflow/
β”‚       β”œβ”€β”€ builder.go    # Provider factory and registration
β”‚       β”œβ”€β”€ client.go     # HTTP client and API interactions
β”‚       └── discovery.go  # Model discovery and categorization
└── siliconflow.go        # Main provider implementation
API Client Features

The SiliconFlowProvider implements the full HelixAgent Toolkit Provider interface:

Chat Completions
req := toolkit.ChatRequest{
    Model: "Qwen/Qwen2.5-7B-Instruct",
    Messages: []toolkit.ChatMessage{
        {Role: "user", Content: "Explain quantum computing"},
    },
    MaxTokens:   2000,
    Temperature: 0.7,
}

resp, err := provider.Chat(ctx, req)
Embeddings
req := toolkit.EmbeddingRequest{
    Model: "text-embedding-ada-002",
    Input: []string{"Hello world", "How are you?"},
}

resp, err := provider.Embed(ctx, req)
Image Generation
// Note: Image generation support depends on available models
req := toolkit.ImageGenerationRequest{
    Model: "black-forest-labs/FLUX.1-dev",
    Prompt: "A beautiful sunset over mountains",
    Size: "1024x1024",
}

resp, err := provider.CreateImage(ctx, req)
Dynamic Model Discovery

The provider automatically discovers and categorizes models:

models, err := provider.DiscoverModels(ctx)
if err != nil {
    log.Fatal(err)
}

for _, model := range models {
    log.Printf("Model: %s (%s) - %s", model.Name, model.ID, model.Category)
    log.Printf("  Context Window: %d", model.Capabilities.ContextWindow)
    log.Printf("  Supports Vision: %v", model.Capabilities.SupportsVision)
}

πŸ”§ Configuration

Provider Configuration
config := map[string]interface{}{
    "api_key":    "your-siliconflow-api-key",     // Required
    "base_url":   "https://api.siliconflow.com/v1", // Optional, defaults to SiliconFlow API
    "timeout":    30000,                          // Optional, milliseconds
    "retries":    3,                              // Optional
    "rate_limit": 60,                             // Optional, requests per minute
}
Integration with HelixAgent Toolkit

Register the provider with the toolkit:

tk := toolkit.NewToolkit()

// Register SiliconFlow provider factory
if err := siliconflow.Register(tk.GetProviderFactoryRegistry()); err != nil {
    log.Fatal(err)
}

// Create provider instance
provider, err := tk.CreateProvider("siliconflow", config)
if err != nil {
    log.Fatal(err)
}

πŸ§ͺ Testing

Running Tests
# Run unit tests
go test ./providers/siliconflow/...

# Run with verbose output
go test -v ./providers/siliconflow/...

# Run integration tests (requires API key)
SILICONFLOW_API_KEY=your-key go test -tags=integration ./providers/siliconflow/...
Test Coverage
  • βœ… API Client Tests: All endpoints tested with mocked responses
  • βœ… Model Discovery Tests: Categorization and capability inference
  • βœ… Configuration Tests: Provider configuration validation
  • βœ… Integration Tests: Real API calls (when API key provided)
  • βœ… Error Handling Tests: Comprehensive error scenarios

πŸ“Š Model Categories

Category Count Default Model Capabilities
Chat 77+ Qwen/Qwen2.5-14B-Instruct Text generation, reasoning, function calling
Vision 12+ Qwen/Qwen2.5-VL-7B-Instruct Image understanding, visual chat
Audio 3+ FunAudioLLM/CosyVoice2-0.5B Speech synthesis, voice cloning
Video 2+ Wan-AI/Wan2.2-T2V-A14B Video generation from text
Embedding 0 - Text embeddings (coming soon)
Rerank 0 - Document reranking (coming soon)

πŸ”’ Security

  • API Key Protection: Keys handled securely, never logged
  • HTTPS Only: All API calls use HTTPS
  • Input Validation: Comprehensive validation of all inputs
  • Error Sanitization: Sensitive information removed from errors

πŸ“ˆ Performance

  • Smart Caching: Model discovery results cached to reduce API calls
  • Connection Pooling: HTTP client reuses connections
  • Concurrent Safety: Thread-safe implementation
  • Memory Optimized: Efficient JSON processing and streaming support

πŸ› Troubleshooting

Common Issues
  1. API Key Not Found

    export SILICONFLOW_API_KEY=your-key
    
  2. Timeout Errors

    • Increase timeout in configuration
    • Check network connectivity
  3. Rate Limiting

    • Implement retry logic with backoff
    • Check rate limit configuration
  4. Model Not Found

    • Verify model ID is correct
    • Run model discovery to see available models
Debug Mode

Enable detailed logging:

import "log"

log.SetFlags(log.LstdFlags | log.Lshortfile)
// Provider will log detailed information

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new functionality
  4. Ensure all tests pass: go test ./...
  5. Run linting: golangci-lint run
  6. Submit a pull request
Development Setup
# Clone the repository
git clone <repository-url>
cd SiliconFlow

# Initialize Go module (if not already done)
go mod init github.com/helixagent/toolkit/SiliconFlow

# Install dependencies
go mod tidy

# Run tests
go test ./...

# Format code
gofmt -w .

# Run linter
golangci-lint run
File Structure
SiliconFlow/
β”œβ”€β”€ go.mod                 # Go module definition
β”œβ”€β”€ go.sum                 # Go module checksums
β”œβ”€β”€ providers/
β”‚   └── siliconflow/
β”‚       β”œβ”€β”€ builder.go     # Provider factory and registration
β”‚       β”œβ”€β”€ client.go      # HTTP client implementation
β”‚       β”œβ”€β”€ discovery.go   # Model discovery logic
β”‚       └── siliconflow.go # Main provider implementation
β”œβ”€β”€ .gitignore             # Go-specific ignore patterns
β”œβ”€β”€ README.md              # This documentation
β”œβ”€β”€ AGENTS.md              # Agent development guidelines
β”œβ”€β”€ LICENSE                # MIT license
└── API_REFERENCE.md       # Technical API documentation

πŸ“„ License

MIT License - see LICENSE for details.

πŸ™ Acknowledgments

  • SiliconFlow: For providing comprehensive AI infrastructure
  • HelixAgent Team: For the toolkit framework
  • Go Community: For excellent HTTP and JSON libraries

Documentation ΒΆ

Overview ΒΆ

Package siliconflow provides configuration builders for SiliconFlow.

Package siliconflow provides a Go client for the SiliconFlow API.

Package siliconflow provides model discovery for SiliconFlow API.

Package siliconflow provides a SiliconFlow provider implementation.

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

This section is empty.

Functions ΒΆ

func Factory ΒΆ

func Factory(config map[string]interface{}) (toolkit.Provider, error)

Factory function for creating SiliconFlow providers.

func NewProvider ΒΆ

func NewProvider(config map[string]interface{}) (toolkit.Provider, error)

NewProvider creates a new SiliconFlow provider.

func Register ΒΆ

func Register(registry *toolkit.ProviderFactoryRegistry) error

Register registers the SiliconFlow provider with the registry.

func SetGlobalProviderRegistry ΒΆ

func SetGlobalProviderRegistry(registry *toolkit.ProviderFactoryRegistry)

SetGlobalProviderRegistry sets the global provider registry for auto-registration.

Types ΒΆ

type Client ΒΆ

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

Client represents a SiliconFlow API client.

func NewClient ΒΆ

func NewClient(apiKey string) *Client

NewClient creates a new SiliconFlow API client.

func (*Client) ChatCompletion ΒΆ

func (c *Client) ChatCompletion(ctx context.Context, req toolkit.ChatRequest) (toolkit.ChatResponse, error)

ChatCompletion performs a chat completion request.

func (*Client) CreateEmbeddings ΒΆ

func (c *Client) CreateEmbeddings(ctx context.Context, req toolkit.EmbeddingRequest) (toolkit.EmbeddingResponse, error)

CreateEmbeddings performs an embedding request.

func (*Client) CreateRerank ΒΆ

func (c *Client) CreateRerank(ctx context.Context, req toolkit.RerankRequest) (toolkit.RerankResponse, error)

CreateRerank performs a rerank request.

func (*Client) GetModels ΒΆ

func (c *Client) GetModels(ctx context.Context) ([]ModelInfo, error)

GetModels retrieves available models from the API.

type Config ΒΆ

type Config struct {
	APIKey    string `json:"api_key"`
	BaseURL   string `json:"base_url"`
	Timeout   int    `json:"timeout"`
	Retries   int    `json:"retries"`
	RateLimit int    `json:"rate_limit"`
}

Config represents SiliconFlow-specific configuration.

type ConfigBuilder ΒΆ

type ConfigBuilder struct{}

ConfigBuilder implements the ConfigBuilder interface for SiliconFlow.

func NewConfigBuilder ΒΆ

func NewConfigBuilder() *ConfigBuilder

NewConfigBuilder creates a new SiliconFlow config builder.

func (*ConfigBuilder) Build ΒΆ

func (b *ConfigBuilder) Build(config map[string]interface{}) (interface{}, error)

Build builds a SiliconFlow configuration from a map.

func (*ConfigBuilder) Merge ΒΆ

func (b *ConfigBuilder) Merge(base, override interface{}) (interface{}, error)

Merge merges two SiliconFlow configurations.

func (*ConfigBuilder) Validate ΒΆ

func (b *ConfigBuilder) Validate(config interface{}) error

Validate validates a SiliconFlow configuration.

type Discovery ΒΆ

type Discovery struct {
	*discovery.BaseDiscovery
	// contains filtered or unexported fields
}

Discovery implements the ModelDiscovery interface for SiliconFlow.

func NewDiscovery ΒΆ

func NewDiscovery(apiKey string) *Discovery

NewDiscovery creates a new SiliconFlow model discovery instance.

func (*Discovery) Discover ΒΆ

func (d *Discovery) Discover(ctx context.Context) ([]toolkit.ModelInfo, error)

Discover discovers available models from SiliconFlow.

type ModelInfo ΒΆ

type ModelInfo struct {
	ID   string `json:"id"`
	Type string `json:"type"`
}

ModelInfo represents basic model information from the API.

type Provider ΒΆ

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

Provider implements the Provider interface for SiliconFlow.

func (*Provider) Chat ΒΆ

Chat performs a chat completion request.

func (*Provider) DiscoverModels ΒΆ

func (p *Provider) DiscoverModels(ctx context.Context) ([]toolkit.ModelInfo, error)

DiscoverModels discovers available models from the provider.

func (*Provider) Embed ΒΆ

Embed performs an embedding request.

func (*Provider) Name ΒΆ

func (p *Provider) Name() string

Name returns the name of the provider.

func (*Provider) Rerank ΒΆ

Rerank performs a rerank request.

func (*Provider) ValidateConfig ΒΆ

func (p *Provider) ValidateConfig(config map[string]interface{}) error

ValidateConfig validates the provider configuration.

type SiliconFlowCapabilityInferrer ΒΆ

type SiliconFlowCapabilityInferrer struct{}

SiliconFlowCapabilityInferrer implements capability inference for SiliconFlow models.

func (*SiliconFlowCapabilityInferrer) InferCapabilities ΒΆ

func (s *SiliconFlowCapabilityInferrer) InferCapabilities(modelID, modelType string) toolkit.ModelCapabilities

InferCapabilities infers model capabilities from ID and type.

type SiliconFlowModelFormatter ΒΆ

type SiliconFlowModelFormatter struct{}

SiliconFlowModelFormatter implements model formatting for SiliconFlow models.

func (*SiliconFlowModelFormatter) FormatModelName ΒΆ

func (s *SiliconFlowModelFormatter) FormatModelName(modelID string) string

FormatModelName formats model ID into human-readable name.

func (*SiliconFlowModelFormatter) GetModelDescription ΒΆ

func (s *SiliconFlowModelFormatter) GetModelDescription(modelID string) string

GetModelDescription returns a description for the model.

Jump to

Keyboard shortcuts

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