02 - 环境搭建与配置
第 02 章 · 环境搭建与配置
从零开始配置 OpenAI API 开发环境:获取 Key、安装 SDK、搭建项目骨架。
2.1 获取 API Key
步骤一:注册 OpenAI 账号
- 访问 platform.openai.com
- 点击 Sign Up 注册
- 完成邮箱验证和手机验证
步骤二:创建 API Key
- 登录后进入 API Keys 页面
- 点击 “Create new secret key”
- 为 Key 添加名称(如
dev-key) - 复制并安全保存(只显示一次)
sk-proj-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
⚠️ 重要安全提示:
- API Key 只在创建时显示,务必立即保存
- 不要将 Key 硬编码在代码中
- 不要将 Key 提交到 Git 仓库
- 不要在前端代码中使用 Key
- 定期轮换 Key,设置用量上限
步骤三:设置用量限制
进入 Billing 页面:
- 设置 Monthly Budget(月度预算上限)
- 设置 Email Alerts(用量预警通知)
2.2 Python 环境配置
2.2.1 安装 Python SDK
# 创建虚拟环境(推荐)
python -m venv openai-env
source openai-env/bin/activate # Linux/Mac
# openai-env\Scripts\activate # Windows
# 安装 OpenAI SDK
pip install openai
# 查看版本
python -c "import openai; print(openai.__version__)"
2.2.2 安装常用依赖
# 基础开发
pip install openai python-dotenv httpx
# 完整开发(含所有功能)
pip install openai python-dotenv httpx tiktoken pydantic rich
# RAG 相关
pip install openai numpy faiss-cpu
# Whisper 音频处理
pip install openai pydub
2.2.3 配置环境变量
创建 .env 文件:
# .env(务必加入 .gitignore)
OPENAI_API_KEY=sk-proj-xxxxxxxxxxxxxxxxxxxxxxxx
OPENAI_ORG_ID=org-xxxxxxxxxxxxxxxx # 可选
OPENAI_PROJECT_ID=proj-xxxxxxxxxxxxxxxx # 可选
OPENAI_BASE_URL=https://api.openai.com/v1 # 可选,用于代理
创建 .gitignore:
.env
__pycache__/
*.pyc
openai-env/
2.2.4 验证配置
# verify_setup.py
import os
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()
client = OpenAI() # 自动读取 OPENAI_API_KEY 环境变量
# 测试 API 连通性
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": "Say 'API connection successful' in one sentence."}
],
max_tokens=50
)
print(response.choices[0].message.content)
print(f"Tokens used: {response.usage.total_tokens}")
python verify_setup.py
# 预期输出: API connection successful
# Tokens used: 25
2.3 Node.js 环境配置
2.3.1 安装 SDK
# 初始化项目
mkdir openai-demo && cd openai-demo
npm init -y
# 安装 OpenAI SDK
npm install openai
# 安装辅助包
npm install dotenv
2.3.2 配置环境变量
# .env
OPENAI_API_KEY=sk-proj-xxxxxxxxxxxxxxxxxxxxxxxx
2.3.3 验证配置
// verify_setup.mjs
import OpenAI from 'openai';
import dotenv from 'dotenv';
dotenv.config();
const client = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
async function main() {
const response = await client.chat.completions.create({
model: 'gpt-4o-mini',
messages: [
{ role: 'user', content: "Say 'API connection successful' in one sentence." }
],
max_tokens: 50,
});
console.log(response.choices[0].message.content);
console.log(`Tokens used: ${response.usage.total_tokens}`);
}
main();
node verify_setup.mjs
2.4 项目结构推荐
Python 项目结构
openai-project/
├── .env # 环境变量(不提交)
├── .gitignore
├── requirements.txt
├── config.py # 配置管理
├── src/
│ ├── __init__.py
│ ├── client.py # OpenAI 客户端封装
│ ├── chat.py # 对话功能
│ ├── embeddings.py # 向量功能
│ ├── vision.py # 视觉功能
│ └── utils.py # 工具函数
├── tests/
│ ├── test_chat.py
│ └── test_embeddings.py
├── examples/
│ ├── basic_chat.py
│ └── streaming.py
└── data/
└── documents/ # RAG 文档存储
配置管理模块
# config.py
import os
from dotenv import load_dotenv
load_dotenv()
class OpenAIConfig:
"""统一配置管理"""
API_KEY: str = os.getenv("OPENAI_API_KEY", "")
ORG_ID: str = os.getenv("OPENAI_ORG_ID", "")
BASE_URL: str = os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1")
# 默认模型
DEFAULT_MODEL: str = "gpt-4o-mini"
EMBEDDING_MODEL: str = "text-embedding-3-small"
# 默认参数
DEFAULT_MAX_TOKENS: int = 1000
DEFAULT_TEMPERATURE: float = 0.7
@classmethod
def validate(cls):
if not cls.API_KEY:
raise ValueError("OPENAI_API_KEY 环境变量未设置")
if not cls.API_KEY.startswith("sk-"):
raise ValueError("OPENAI_API_KEY 格式不正确")
# 启动时验证
OpenAIConfig.validate()
客户端封装
# src/client.py
from openai import OpenAI
from config import OpenAIConfig
# 单例客户端(全局复用,避免重复创建)
client = OpenAI(
api_key=OpenAIConfig.API_KEY,
organization=OpenAIConfig.ORG_ID or None,
base_url=OpenAIConfig.BASE_URL,
timeout=30.0, # 请求超时(秒)
max_retries=2, # 自动重试次数
)
def get_client() -> OpenAI:
"""获取 OpenAI 客户端实例"""
return client
2.5 代理与自定义端点
使用 HTTP 代理
import httpx
from openai import OpenAI
client = OpenAI(
http_client=httpx.Client(
proxies="http://127.0.0.1:7890", # 本地代理地址
timeout=30.0,
)
)
使用自定义 Base URL(兼容 API)
# 适用于 Azure OpenAI 或第三方兼容服务
client = OpenAI(
base_url="https://your-proxy.example.com/v1",
api_key="your-api-key",
)
2.6 Token 计算工具
Python (tiktoken)
import tiktoken
def count_tokens(text: str, model: str = "gpt-4o-mini") -> int:
"""计算文本的 token 数量"""
encoding = tiktoken.encoding_for_model(model)
tokens = encoding.encode(text)
return len(tokens)
def estimate_cost(input_tokens: int, output_tokens: int, model: str = "gpt-4o-mini") -> float:
"""估算 API 调用成本(美元)"""
prices = {
"gpt-4o-mini": {"input": 0.15 / 1_000_000, "output": 0.60 / 1_000_000},
"gpt-4o": {"input": 2.50 / 1_000_000, "output": 10.00 / 1_000_000},
"gpt-4.1": {"input": 2.00 / 1_000_000, "output": 8.00 / 1_000_000},
"gpt-4.1-mini": {"input": 0.40 / 1_000_000, "output": 1.60 / 1_000_000},
"gpt-4.1-nano": {"input": 0.10 / 1_000_000, "output": 0.40 / 1_000_000},
}
price = prices.get(model, prices["gpt-4o-mini"])
return input_tokens * price["input"] + output_tokens * price["output"]
# 使用示例
text = "你好,请帮我写一首关于春天的诗。"
tokens = count_tokens(text)
print(f"文本: {text}")
print(f"Token 数: {tokens}")
print(f"预估成本: ${estimate_cost(tokens, tokens * 3):.6f}")
2.7 常见问题排查
| 问题 | 原因 | 解决方案 |
|---|---|---|
AuthenticationError | API Key 无效或过期 | 重新生成 Key |
RateLimitError | 超出速率限制 | 升级 Tier 或加入重试逻辑 |
Timeout | 请求超时 | 增加 timeout 参数,检查网络 |
ConnectionError | 网络不通 | 检查代理配置、防火墙 |
InvalidRequestError | 请求参数错误 | 检查模型名、消息格式 |
重试策略示例
import time
from openai import OpenAI, RateLimitError, APITimeoutError, APIConnectionError
client = OpenAI()
def call_with_retry(func, max_retries=3, base_delay=1.0):
"""带指数退避的重试调用"""
for attempt in range(max_retries):
try:
return func()
except (RateLimitError, APITimeoutError, APIConnectionError) as e:
if attempt == max_retries - 1:
raise
delay = base_delay * (2 ** attempt)
print(f"请求失败,{delay}s 后重试 (第 {attempt+1} 次): {e}")
time.sleep(delay)
# 使用
response = call_with_retry(
lambda: client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "你好"}]
)
)
2.8 注意事项
- API Key 安全:永远不要在客户端暴露 Key,使用后端代理
- 环境隔离:开发/测试/生产使用不同的 Key
- 版本锁定:
requirements.txt中锁定 SDK 版本 - 超时设置:根据业务场景设置合理超时(流式请求建议 60s+)
- 日志记录:记录请求/响应的 token 用量,便于成本分析
2.9 扩展阅读
下一章:03 - Chat Completions API — 深入消息格式、参数调优、多轮对话实现。