ai_tool

package module
v0.0.0-...-e302a94 Latest Latest
Warning

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

Go to latest
Published: Sep 13, 2025 License: MIT Imports: 6 Imported by: 0

README

AI Tool Repository

一个基于 katool-go net 模块的多AI服务集成工具库,采用OpenAI兼容接口标准,支持多种AI提供者的统一使用。

支持的AI提供者

🌐 云端服务
  • OpenAI (标准接口)
  • DeepSeek (OpenAI兼容)
  • Claude (Anthropic) (特殊接口)
🏠 本地服务
  • Ollama (OpenAI兼容)
  • LocalAI (OpenAI兼容)
  • 通义千问 (Qwen) (计划支持)
  • 文心一言 (ERNIE) (计划支持)

核心特性

  • 🚀 统一接口: 所有兼容OpenAI的服务使用相同API
  • 🔄 流式响应: 支持Server-Sent Events流式输出
  • 🛡️ 类型安全: 完整的Go类型定义
  • ⚙️ 智能配置: 环境变量和配置文件支持
  • 📝 完整日志: 集成日志记录系统
  • 🔌 易于扩展: 简单的提供者添加机制
  • 🎯 智能降级: 多提供者自动故障转移

快速开始

基本使用
package main

import (
    "fmt"
    "github.com/karosown/katool-go/ai_tool"
    "github.com/karosown/katool-go/ai_tool/aiconfig"
)

func main() {
    // 创建OpenAI客户端
    client, err := ai_tool.NewAIClientFromEnv(aiconfig.ProviderOpenAI)
    if err != nil {
        panic(err)
    }
    
    // 发送消息
    response, err := client.Chat(&aiconfig.ChatRequest{
        Model: "gpt-3.5-turbo",
        Messages: []aiconfig.Message{
            {Role: "user", Content: "Hello, AI!"},
        },
    })
    
    if err != nil {
        panic(err)
    }
    
    fmt.Println(response.Choices[0].Message.Content)
}
多提供者统一使用
// 所有兼容OpenAI的服务使用相同接口
providers := []aiconfig.ProviderType{
    aiconfig.ProviderOpenAI,
    aiconfig.ProviderDeepSeek,
    aiconfig.ProviderOllama,
    aiconfig.ProviderLocalAI,
}

manager := ai_tool.NewAIClientManager()

// 添加所有提供者
for _, provider := range providers {
    manager.AddClientFromEnv(provider)
}

// 使用相同请求格式
request := &aiconfig.ChatRequest{
    Model: "gpt-3.5-turbo", // 大多数服务都支持
    Messages: []aiconfig.Message{
        {Role: "user", Content: "Hello!"},
    },
}

// 智能降级
response, err := manager.ChatWithFallback(providers, request)

流式响应

// 流式聊天 - 所有提供者都支持
stream, err := client.ChatStream(&aiconfig.ChatRequest{
    Model: "gpt-3.5-turbo",
    Messages: []aiconfig.Message{
        {Role: "user", Content: "Tell me a story"},
    },
})

if err != nil {
    panic(err)
}

for chunk := range stream {
    if len(chunk.Choices) > 0 && chunk.Choices[0].Delta.Content != "" {
        fmt.Print(chunk.Choices[0].Delta.Content)
    }
}

配置

环境变量
# 云端服务
export OPENAI_API_KEY="your-openai-key"
export DEEPSEEK_API_KEY="your-deepseek-key"
export CLAUDE_API_KEY="your-claude-key"

# 本地服务
export OLLAMA_BASE_URL="http://localhost:11434/v1"
export LOCALAI_BASE_URL="http://localhost:8080/v1"
export LOCALAI_API_KEY="your-localai-key"  # 可选
配置文件
{
  "openai": {
    "api_key": "your-openai-key",
    "base_url": "https://api.openai.com/v1",
    "timeout": "30s",
    "max_retries": 3
  },
  "ollama": {
    "base_url": "http://localhost:11434/v1",
    "timeout": "60s",
    "max_retries": 5
  }
}

架构优势

🎯 OpenAI兼容标准
  • 大多数AI服务都兼容OpenAI接口
  • 统一的请求/响应格式
  • 相同的模型命名规范
🔧 简化实现
  • 一个提供者实现支持多个服务
  • 减少代码重复
  • 易于维护和扩展
🚀 智能降级
  • 自动故障转移
  • 多提供者负载均衡
  • 高可用性保证

扩展新的AI提供者

兼容OpenAI接口的服务
// 直接使用OpenAI兼容提供者
provider := aiconfig.NewOpenAICompatibleProvider(
    aiconfig.ProviderType("your-service"),
    config,
)
自定义接口的服务
type MyAIProvider struct {
    config *aiconfig.Config
}

func (p *MyAIProvider) Chat(req *aiconfig.ChatRequest) (*aiconfig.ChatResponse, error) {
    // 实现自定义聊天逻辑
}

func (p *MyAIProvider) ChatStream(req *aiconfig.ChatRequest) (<-chan *aiconfig.ChatResponse, error) {
    // 实现自定义流式聊天逻辑
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AIClient

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

AIClient AI客户端

func NewAIClient

func NewAIClient(providerType aiconfig.ProviderType, config *aiconfig.Config) (*AIClient, error)

NewAIClient 创建AI客户端

func NewAIClientFromEnv

func NewAIClientFromEnv(providerType aiconfig.ProviderType) (*AIClient, error)

NewAIClientFromEnv 从环境变量创建AI客户端

func (*AIClient) Chat

Chat 发送聊天请求

func (*AIClient) ChatStream

func (c *AIClient) ChatStream(req *aiconfig.ChatRequest) (<-chan *aiconfig.ChatResponse, error)

ChatStream 发送流式聊天请求

func (*AIClient) GetLogger

func (c *AIClient) GetLogger() xlog.Logger

GetLogger 获取日志记录器

func (*AIClient) GetModels

func (c *AIClient) GetModels() []string

GetModels 获取支持的模型列表

func (*AIClient) GetProvider

func (c *AIClient) GetProvider() aiconfig.AIProvider

GetProvider 获取提供者

func (*AIClient) GetProviderName

func (c *AIClient) GetProviderName() string

GetProviderName 获取提供者名称

func (*AIClient) SetLogger

func (c *AIClient) SetLogger(logger xlog.Logger)

SetLogger 设置日志记录器

type AIClientManager

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

AIClientManager AI客户端管理器

func NewAIClientManager

func NewAIClientManager() *AIClientManager

NewAIClientManager 创建AI客户端管理器

func (*AIClientManager) AddClient

func (m *AIClientManager) AddClient(providerType aiconfig.ProviderType, config *aiconfig.Config) error

AddClient 添加客户端

func (*AIClientManager) AddClientFromEnv

func (m *AIClientManager) AddClientFromEnv(providerType aiconfig.ProviderType) error

AddClientFromEnv 从环境变量添加客户端

func (*AIClientManager) ChatStreamWithFallback

func (m *AIClientManager) ChatStreamWithFallback(providerTypes []aiconfig.ProviderType, req *aiconfig.ChatRequest) (<-chan *aiconfig.ChatResponse, error)

ChatStreamWithFallback 使用多个提供者发送流式聊天请求(带降级)

func (*AIClientManager) ChatStreamWithProvider

func (m *AIClientManager) ChatStreamWithProvider(providerType aiconfig.ProviderType, req *aiconfig.ChatRequest) (<-chan *aiconfig.ChatResponse, error)

ChatStreamWithProvider 使用指定提供者发送流式聊天请求

func (*AIClientManager) ChatWithFallback

func (m *AIClientManager) ChatWithFallback(providerTypes []aiconfig.ProviderType, req *aiconfig.ChatRequest) (*aiconfig.ChatResponse, error)

ChatWithFallback 使用多个提供者发送聊天请求(带降级)

func (*AIClientManager) ChatWithProvider

func (m *AIClientManager) ChatWithProvider(providerType aiconfig.ProviderType, req *aiconfig.ChatRequest) (*aiconfig.ChatResponse, error)

ChatWithProvider 使用指定提供者发送聊天请求

func (*AIClientManager) GetClient

func (m *AIClientManager) GetClient(providerType aiconfig.ProviderType) (*AIClient, error)

GetClient 获取客户端

func (*AIClientManager) GetDefaultClient

func (m *AIClientManager) GetDefaultClient() (*AIClient, error)

GetDefaultClient 获取默认客户端(OpenAI)

func (*AIClientManager) ListClients

func (m *AIClientManager) ListClients() []aiconfig.ProviderType

ListClients 列出所有客户端

func (*AIClientManager) RemoveClient

func (m *AIClientManager) RemoveClient(providerType aiconfig.ProviderType)

RemoveClient 移除客户端

func (*AIClientManager) SetLogger

func (m *AIClientManager) SetLogger(logger xlog.Logger)

SetLogger 设置日志记录器

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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