最佳实践
本文档汇总了使用 51API 的最佳实践,帮助你更安全、高效、省钱地使用 AI API。
安全最佳实践
API Key 安全
核心原则
API Key 就像你的银行卡密码,泄露后可能导致额度被盗用!
1. 永远不要硬编码 API Key
python
# ❌ 错误:直接写在代码里
client = OpenAI(api_key="sk-xxxxxxxx")
# ✅ 正确:使用环境变量
import os
client = OpenAI(api_key=os.getenv("NEWAPI_API_KEY"))1
2
3
4
5
6
2
3
4
5
6
2. 不要提交到代码仓库
在 .gitignore 中添加:
gitignore
# 环境变量文件
.env
.env.local
.env.*.local
# API Key 配置
config.local.json
secrets.json1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
3. 使用 .env 文件管理
bash
# .env 文件(不要提交到 Git)
NEWAPI_API_KEY=sk-xxxxxxxx1
2
2
python
# 使用 python-dotenv 加载
from dotenv import load_dotenv
load_dotenv()
api_key = os.getenv("NEWAPI_API_KEY")1
2
3
4
5
2
3
4
5
4. 定期轮换 API Key
- 建议每 3-6 个月更换一次 API Key
- 如果怀疑泄露,立即在控制台删除并重新创建
- 不同项目使用不同的 API Key
5. 限制 API Key 权限
在创建令牌时:
- 只勾选需要的模型
- 设置合理的额度限制
- 使用最小权限原则
性能最佳实践
1. 选择合适的模型
| 场景 | 推荐模型 | 原因 |
|---|---|---|
| 简单问答 | gemini-2.5-flash | 快速、便宜 |
| 日常对话 | gpt-4o | 平衡性能和成本 |
| 代码开发 | claude-sonnet-4-5 | 代码能力强 |
| 复杂推理 | gpt-5-thinking | 推理能力强 |
2. 使用流式输出
流式输出可以显著提升用户体验:
python
# 流式输出 - 用户立即看到响应
stream = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "写一篇文章"}],
stream=True
)
for chunk in stream:
print(chunk.choices[0].delta.content, end="")1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
3. 合理设置超时
python
# 普通模型:30-60 秒
client = OpenAI(
api_key=os.getenv("NEWAPI_API_KEY"),
base_url="https://www.51api.org/v1",
timeout=60.0
)
# Thinking/DeepSearch 模型:5-10 分钟
import httpx
client = OpenAI(
api_key=os.getenv("NEWAPI_API_KEY"),
base_url="https://www.51api.org/v1",
timeout=httpx.Timeout(600.0, connect=30.0)
)1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
4. 实现重试机制
python
import time
from openai import OpenAI, APIError, RateLimitError
def chat_with_retry(client, messages, max_retries=3):
for attempt in range(max_retries):
try:
return client.chat.completions.create(
model="gpt-4o",
messages=messages
)
except RateLimitError:
# 速率限制,等待后重试
wait_time = 2 ** attempt
print(f"速率限制,{wait_time}秒后重试...")
time.sleep(wait_time)
except APIError as e:
if attempt == max_retries - 1:
raise
print(f"API 错误,重试中...")
time.sleep(1)
raise Exception("重试次数已用完")1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
5. 连接池复用
python
# 复用同一个 client 实例
client = OpenAI(
api_key=os.getenv("NEWAPI_API_KEY"),
base_url="https://www.51api.org/v1"
)
# ✅ 正确:复用 client
def chat(message):
return client.chat.completions.create(...)
# ❌ 错误:每次创建新 client
def chat_bad(message):
client = OpenAI(...) # 每次都创建新连接
return client.chat.completions.create(...)1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
成本优化
1. 选择性价比高的模型
| 模型 | 倍率 | 适用场景 |
|---|---|---|
gemini-2.5-flash-free | 0.25x | 免费体验、测试 |
gemini-2.5-flash | 0.4x | 日常使用首选 |
claude-haiku-4-5 | 0.5x | 快速响应场景 |
gpt-4o | 1x | 需要高质量输出 |
2. 精简 Prompt
python
# ❌ 冗长的 prompt
prompt = """
你好,我想请问一下,能不能帮我把下面这段话翻译成英文?
这段话是关于人工智能的,请你翻译得准确一些,谢谢!
原文是:今天天气很好。
"""
# ✅ 精简的 prompt
prompt = "翻译成英文:今天天气很好"1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
3. 控制输出长度
python
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "写一首诗"}],
max_tokens=200 # 限制输出长度
)1
2
3
4
5
2
3
4
5
4. 缓存常见请求
python
import hashlib
import json
# 简单的内存缓存
cache = {}
def cached_chat(messages):
# 生成缓存键
key = hashlib.md5(json.dumps(messages).encode()).hexdigest()
if key in cache:
return cache[key]
response = client.chat.completions.create(
model="gpt-4o",
messages=messages
)
cache[key] = response
return response1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
5. 批量处理
如果有多个独立请求,可以并行处理:
python
import asyncio
from openai import AsyncOpenAI
async_client = AsyncOpenAI(
api_key=os.getenv("NEWAPI_API_KEY"),
base_url="https://www.51api.org/v1"
)
async def batch_chat(prompts):
tasks = [
async_client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": p}]
)
for p in prompts
]
return await asyncio.gather(*tasks)
# 使用
prompts = ["问题1", "问题2", "问题3"]
results = asyncio.run(batch_chat(prompts))1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
错误处理
完整的错误处理示例
python
from openai import OpenAI, APIError, AuthenticationError, RateLimitError
client = OpenAI(
api_key=os.getenv("NEWAPI_API_KEY"),
base_url="https://www.51api.org/v1"
)
def safe_chat(message):
try:
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": message}]
)
return response.choices[0].message.content
except AuthenticationError:
# 401: API Key 无效
print("错误:API Key 无效,请检查配置")
return None
except RateLimitError:
# 429: 请求过于频繁
print("错误:请求过于频繁,请稍后重试")
return None
except APIError as e:
# 其他 API 错误
if e.status_code == 403:
print("错误:权限不足,请检查令牌分组")
elif e.status_code == 404:
print("错误:接口不存在,请检查 URL 是否包含 /v1")
else:
print(f"API 错误:{e.message}")
return None
except Exception as e:
print(f"未知错误:{e}")
return None1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
日志和监控
记录请求日志
python
import logging
from datetime import datetime
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def logged_chat(message, model="gpt-4o"):
start_time = datetime.now()
try:
response = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": message}]
)
elapsed = (datetime.now() - start_time).total_seconds()
usage = response.usage
logger.info(
f"模型: {model}, "
f"耗时: {elapsed:.2f}s, "
f"输入Token: {usage.prompt_tokens}, "
f"输出Token: {usage.completion_tokens}"
)
return response.choices[0].message.content
except Exception as e:
logger.error(f"请求失败: {e}")
raise1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
监控 Token 消耗
python
class TokenTracker:
def __init__(self):
self.total_prompt_tokens = 0
self.total_completion_tokens = 0
self.request_count = 0
def track(self, usage):
self.total_prompt_tokens += usage.prompt_tokens
self.total_completion_tokens += usage.completion_tokens
self.request_count += 1
def report(self):
print(f"总请求数: {self.request_count}")
print(f"总输入Token: {self.total_prompt_tokens}")
print(f"总输出Token: {self.total_completion_tokens}")
print(f"总Token: {self.total_prompt_tokens + self.total_completion_tokens}")
tracker = TokenTracker()
def tracked_chat(message):
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": message}]
)
tracker.track(response.usage)
return response.choices[0].message.content1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
生产环境检查清单
在部署到生产环境前,请确认:
安全
- [ ] API Key 存储在环境变量中
- [ ] API Key 没有提交到代码仓库
- [ ] 使用了最小权限的令牌分组
- [ ] 设置了合理的额度限制
性能
- [ ] 选择了合适的模型
- [ ] 设置了合理的超时时间
- [ ] 实现了重试机制
- [ ] 复用了 client 连接
成本
- [ ] 设置了 max_tokens 限制
- [ ] 精简了 prompt
- [ ] 考虑了缓存策略
监控
- [ ] 记录了请求日志
- [ ] 监控了 Token 消耗
- [ ] 设置了错误告警
