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-InstructQwen/Qwen2.5-14B-InstructQwen/Qwen2.5-72B-Instructdeepseek-ai/DeepSeek-V2.5THUDM/GLM-4-9B-Chat
图像生成模型:
dall-e-3
语音识别模型:
whisper-1
语音合成模型:
tts-1
OpenAI
文本生成模型:
gpt-4ogpt-4-turbogpt-4gpt-3.5-turbogpt-3.5-turbo-16k
图像生成模型:
dall-e-3dall-e-2
语音识别模型:
whisper-1
语音合成模型:
tts-1tts-1-hd
百度文心
文本生成模型:
ERNIE-4.0ERNIE-3.5ERNIE-BotERNIE-Bot-turbo
图像生成模型:
ERNIE-ViLG-3.0
语音识别模型:
- 百度ASR API
语音合成模型:
- 百度TTS API
阿里通义
文本生成模型:
qwen-turboqwen-plusqwen-maxqwen2.5-7bqwen2.5-14bqwen2.5-72b
图像生成模型:
qwen-vl-plus
语音识别模型:
- 阿里ASR API
语音合成模型:
- 阿里TTS API
Anthropic Claude
文本生成模型:
claude-sonnet-4-20250514claude-3-5-sonnet-latestclaude-3-opus-latestclaude-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 文件
Metadata
Release files for aiservice-gateway-sdk 1.4.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| aiservice_gateway_sdk-1.4.0-py3-none-any.whl | Python 3 | none | any | Details |
Release files / aiservice_gateway_sdk-1.4.0-py3-none-any.whl
| Download URL | aiservice_gateway_sdk-1.4.0-py3-none-any.whl |
|---|---|
| Size | 35.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
862a95bd5b5bd9c9e27067eb547c5cf2517ae5937c5b620261491276b3f9cd5e
|
|
BLAKE2b-256 checksum How to use checksums |
4dc7c27d67d508059adf15ddf491e5a688572fb891f2b9a5e9d71cf5757837a9
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.9.13
|
Security for aiservice-gateway-sdk 1.4.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.