Skip to main content

统一的AI服务网关SDK,支持硅基流动、OpenAI等多种AI厂商

Project description

AI Service Gateway SDK

统一的 AI 服务网关 SDK,支持硅基流动、OpenAI 等多种 AI 厂商,一次接入,随处使用。

特性

  • 🚀 简单易用 - 统一的客户端接口,几行代码即可接入
  • 🔌 插件化架构 - 支持多种 AI 厂商,可轻松扩展
  • 🛡️ 完善错误处理 - 清晰的异常体系,易于调试
  • 📦 类型提示完整 - 完整的 Type Hints 支持 IDE 自动补全
  • 🔄 自动重试 - 内置请求重试机制,提高稳定性
  • 🌊 流式输出 - 支持实时流式文本生成,增强交互体验
  • 📊 监控指标 - 内置 Prometheus 监控指标,便于运维监控
  • 📈 缓存机制 - 支持内存缓存和 Redis 缓存,提高性能

支持的 AI 厂商

厂商 文本生成 图像生成 语音识别 语音合成
硅基流动
OpenAI
百度文心
阿里通义
Anthropic

安装

pip install aiservice-gateway-sdk

快速开始

硅基流动使用示例

from aiservice_gateway_sdk import AIServiceGatewayClient

# 初始化客户端
client = AIServiceGatewayClient(
    provider="silicon",           # AI服务厂商
    api_key="your-api-key"        # 你的API Key
)

# 文本生成
result = client.text.generate(
    prompt="你好,请介绍一下你自己",
    model="Qwen/Qwen2.5-7B-Instruct",
    max_tokens=1000,
    temperature=0.7
)

print(result.text)
print(f"使用模型: {result.model}")
print(f"消耗Token: {result.usage.total_tokens}")

OpenAI 使用示例

# 初始化OpenAI客户端
client = AIServiceGatewayClient(
    provider="openai",
    api_key="your-openai-api-key"
)

# 文本生成
result = client.text.generate(
    prompt="Hello, introduce yourself",
    model="gpt-4o",
    max_tokens=1000
)

百度文心使用示例

# 初始化百度文心客户端(需要API Key和Secret Key)
client = AIServiceGatewayClient(
    provider="baidu",
    api_key="your-baidu-api-key",
    secret_key="your-baidu-secret-key"  # 百度特有的Secret Key
)

# 文本生成
result = client.text.generate(
    prompt="你好,请介绍一下你自己",
    model="ERNIE-4.0"
)

阿里通义使用示例

# 初始化阿里通义客户端
client = AIServiceGatewayClient(
    provider="aliyun",
    api_key="your-aliyun-api-key"
)

# 文本生成
result = client.text.generate(
    prompt="你好,请介绍一下你自己",
    model="qwen-turbo"
)

Anthropic Claude 使用示例

# 初始化Anthropic客户端
client = AIServiceGatewayClient(
    provider="anthropic",
    api_key="your-anthropic-api-key"
)

# 文本生成
result = client.text.generate(
    prompt="你好,请介绍一下你自己",
    model="claude-sonnet-4-20250514",
    max_tokens=1024
)

流式文本生成

import asyncio
from aiservice_gateway_sdk import AIServiceGatewayClient

# 初始化客户端
client = AIServiceGatewayClient(
    provider="silicon",
    api_key="your-api-key"
)

# 流式文本生成
async def stream_example():
    async for chunk in client.text.generate_stream(
        prompt="请给我讲一个关于人工智能的故事",
        model="Qwen/Qwen2.5-7B-Instruct",
        max_tokens=500,
        temperature=0.8
    ):
        print(chunk.text, end="", flush=True)
        if chunk.is_final:
            print("\n生成完成!")

asyncio.run(stream_example())

监控指标

from aiservice_gateway_sdk import start_http_server, metrics

# 启动指标服务器
start_http_server(port=8000)

# 查看指标: http://localhost:8000/metrics

缓存功能

from aiservice_gateway_sdk import AIServiceGatewayClient, RedisCache
import redis

# 初始化 Redis 客户端
redis_client = redis.Redis(host="localhost", port=6379, db=0)
redis_cache = RedisCache(redis_client)

# 初始化客户端并使用 Redis 缓存
client = AIServiceGatewayClient(
    provider="silicon",
    api_key="your-api-key",
    cache=redis_cache
)

# 第一次请求会调用 API
result1 = client.text.generate(
    prompt="你好,请介绍一下你自己",
    model="Qwen/Qwen2.5-7B-Instruct"
)

# 第二次请求会从缓存获取
result2 = client.text.generate(
    prompt="你好,请介绍一下你自己",
    model="Qwen/Qwen2.5-7B-Instruct"
)

# 禁用缓存
result3 = client.text.generate(
    prompt="你好,请介绍一下你自己",
    model="Qwen/Qwen2.5-7B-Instruct",
    cache=False
)

图像生成

# 图像生成
result = client.image.generate(
    prompt="一只可爱的橘猫在阳光下打盹",
    model="dall-e-3",
    size="1024x1024",
    n=1
)

for img in result.image_urls:
    print(f"图像URL: {img.url}")

语音识别

# 读取音频文件
with open("audio.wav", "rb") as f:
    audio_data = f.read()

# 语音识别
result = client.audio.recognize(
    audio=audio_data,
    model="whisper-1",
    language="zh"
)

print(f"识别结果: {result.text}")

语音合成

# 语音合成
result = client.audio.synthesize(
    text="你好,欢迎使用AI服务网关SDK",
    model="tts-1",
    voice="alloy"
)

# 保存音频文件
with open("output.mp3", "wb") as f:
    f.write(result.audio)

配置选项

参数 类型 默认值 说明
provider str "silicon" AI 服务厂商
api_key str None API 密钥
secret_key str None 百度文心特有的 Secret Key
base_url str None 自定义 API 地址
timeout int 30 请求超时时间(秒)
max_retries int 3 最大重试次数
retry_delay float 1.0 重试延迟时间(秒)

错误处理

from aiservice_gateway_sdk import (
    AIServiceGatewayClient,
    AuthenticationError,
    RateLimitError,
    APIError,
)

client = AIServiceGatewayClient(
    provider="silicon",
    api_key="your-api-key"
)

try:
    result = client.text.generate("你好")
except AuthenticationError:
    print("认证失败,请检查API Key")
except RateLimitError:
    print("请求频率超限,请稍后重试")
except APIError as e:
    print(f"API错误: {e.message}")

支持的模型

硅基流动

文本生成模型:

  • Qwen/Qwen2.5-7B-Instruct
  • Qwen/Qwen2.5-14B-Instruct
  • Qwen/Qwen2.5-72B-Instruct
  • deepseek-ai/DeepSeek-V2.5
  • THUDM/GLM-4-9B-Chat

图像生成模型:

  • dall-e-3

语音识别模型:

  • whisper-1

语音合成模型:

  • tts-1

OpenAI

文本生成模型:

  • gpt-4o
  • gpt-4-turbo
  • gpt-4
  • gpt-3.5-turbo
  • gpt-3.5-turbo-16k

图像生成模型:

  • dall-e-3
  • dall-e-2

语音识别模型:

  • whisper-1

语音合成模型:

  • tts-1
  • tts-1-hd

百度文心

文本生成模型:

  • ERNIE-4.0
  • ERNIE-3.5
  • ERNIE-Bot
  • ERNIE-Bot-turbo

图像生成模型:

  • ERNIE-ViLG-3.0

语音识别模型:

  • 百度ASR API

语音合成模型:

  • 百度TTS API

阿里通义

文本生成模型:

  • qwen-turbo
  • qwen-plus
  • qwen-max
  • qwen2.5-7b
  • qwen2.5-14b
  • qwen2.5-72b

图像生成模型:

  • qwen-vl-plus

语音识别模型:

  • 阿里ASR API

语音合成模型:

  • 阿里TTS API

Anthropic Claude

文本生成模型:

  • claude-sonnet-4-20250514
  • claude-3-5-sonnet-latest
  • claude-3-opus-latest
  • claude-3-haiku-latest

从源码安装

git clone https://github.com/your-repo/aiservice-gateway-sdk.git
cd aiservice-gateway-sdk
pip install -e .

开发

# 克隆项目
git clone https://github.com/your-repo/aiservice-gateway-sdk.git

# 创建虚拟环境
python -m venv venv
source venv/bin/activate  # Linux/Mac
# 或
.\venv\Scripts\activate  # Windows

# 安装开发依赖
pip install -e ".[dev]"

# 运行测试
pytest tests/

# 代码格式化
black src/
isort src/

发布到 PyPI

# 构建包
python -m build

# 上传到 PyPI
twine upload dist/*

License

MIT License - 详见 LICENSE 文件

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

aiservice_gateway_sdk-1.4.0-py3-none-any.whl (35.0 kB view details)

Uploaded Python 3

File details

Details for the file aiservice_gateway_sdk-1.4.0-py3-none-any.whl.

File metadata

File hashes

Hashes for aiservice_gateway_sdk-1.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 862a95bd5b5bd9c9e27067eb547c5cf2517ae5937c5b620261491276b3f9cd5e
MD5 37c41cbe7044bbcea1b0a45f2dbd0f82
BLAKE2b-256 4dc7c27d67d508059adf15ddf491e5a688572fb891f2b9a5e9d71cf5757837a9

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page