前言
用 ChatGPT 的网页版聊天很简单,但如果想把 AI 能力集成到自己的应用里——比如做个客服机器人、自动写周报的工具、代码审查助手——就需要通过 API。
OpenAI 的 API 是目前最成熟的大模型接口,而且很多国产模型(DeepSeek、通义千问、豆包)都兼容它的格式,学一次到处能用。
一、申请 API Key
- 打开 platform.openai.com
- 注册账号(需要海外手机号验证,可以用虚拟号平台)
- 进入 Dashboard → API Keys → Create new secret key
- 复制 Key(只显示一次,保存好)
充值:OpenAI 是预付费制,在 Billing 页面绑定信用卡或使用充值额度。个人开发者先充 5-10 美元足够玩很久了。
如果 OpenAI 用不了怎么办?
国内的替代方案(都兼容 OpenAI API 格式,只改 base_url 和 key):
| 平台 |
base_url |
获取 Key |
| DeepSeek |
https://api.deepseek.com |
platform.deepseek.com |
| 通义千问 |
https://dashscope.aliyuncs.com/compatible-mode/v1 |
阿里云百炼平台 |
| 豆包(字节) |
https://ark.cn-beijing.volces.com/api/v3 |
火山引擎 |
| 硅基流动 |
https://api.siliconflow.cn/v1 |
siliconflow.cn(有免费额度) |
| 零一万物 |
https://api.lingyiwanwu.com/v1 |
platform.lingyiwanwu.com |
二、第一个 API 调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| from openai import OpenAI
client = OpenAI(api_key="sk-your-key-here")
response = client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": "你是一个 Linux 运维专家"}, {"role": "user", "content": "如何查看端口占用?"} ] )
print(response.choices[0].message.content)
|
三个 message 角色:
| role |
含义 |
什么时候用 |
system |
设定 AI 的身份和行为规则 |
在最前面,定义”人设” |
user |
用户说的话 |
每次用户输入 |
assistant |
AI 之前回复过的话 |
多轮对话时把历史回复带上 |
三、多轮对话
模型本身没有记忆,每次请求都是独立的。要实现”记得之前聊了什么”,需要把对话历史在每次请求时都带过去:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| messages = [ {"role": "system", "content": "你是一个 Python 编程助手"}, ]
while True: user_input = input("你: ") if user_input == "quit": break messages.append({"role": "user", "content": user_input}) response = client.chat.completions.create( model="gpt-4o", messages=messages ) reply = response.choices[0].message.content print(f"AI: {reply}") messages.append({"role": "assistant", "content": reply})
|
对话历史越长,消耗的 token 越多(因为每次都要把历史重新发给模型)。实际应用中需要考虑对话摘要或滑动窗口来控制上下文长度。
四、流式输出
ChatGPT 的那种一个字一个字往外蹦的效果,就是流式输出(streaming):
1 2 3 4 5 6 7 8 9 10
| stream = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": "讲个笑话"}], stream=True )
for chunk in stream: if chunk.choices[0].delta.content: print(chunk.choices[0].delta.content, end="", flush=True) print()
|
流式输出的好处:用户体验好,不用等半天才看到结果,特别适合交互式应用。
五、核心参数调优
1 2 3 4 5 6 7 8 9 10 11
| response = client.chat.completions.create( model="gpt-4o", messages=[...], temperature=0.7, top_p=0.9, max_tokens=1000, frequency_penalty=0.0, presence_penalty=0.0, stop=["\n\n\n"], n=1, )
|
| 参数 |
作用 |
代码/翻译用 |
创意写作用 |
temperature |
越高越随机 |
0.1~0.3 |
0.7~0.9 |
top_p |
核采样阈值 |
0.5~0.8 |
0.9~1.0 |
max_tokens |
控制回答长度 |
看需求 |
看需求 |
frequency_penalty |
抑制重复 |
0.1~0.3(避免废话) |
0 |
六、Token 管理
查看用了多少 token
1 2 3 4 5 6 7
| response = client.chat.completions.create(...) print(response.usage)
|
估算费用
GPT-4o 的价格(2024 年):
- 输入:$2.50 / 1M tokens
- 输出:$10.00 / 1M tokens
举例:一次问答输入 500 token + 输出 200 token,费用约为 (500/1M)*2.5 + (200/1M)*10 = $0.00325,约 2 分钱人民币。
计算 token 数量
1 2 3 4 5
| import tiktoken
enc = tiktoken.encoding_for_model("gpt-4o") tokens = enc.encode("Hello, 你好") print(len(tokens))
|
也可以直接用 OpenAI 的在线工具 tokenizer。
控制上下文不超限
1 2 3 4 5 6 7 8 9 10 11 12
| def trim_messages(messages, max_tokens=4000): """保留最近的对话,确保总 token 不超限""" enc = tiktoken.encoding_for_model("gpt-4o") total = 0 trimmed = [] for msg in reversed(messages): count = len(enc.encode(msg["content"])) if total + count > max_tokens: break trimmed.insert(0, msg) total += count return trimmed
|
七、错误处理
1 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
| from openai import ( APIError, APIConnectionError, RateLimitError, APITimeoutError, AuthenticationError )
def chat_with_retry(messages, max_retries=3): for attempt in range(max_retries): try: return client.chat.completions.create( model="gpt-4o", messages=messages, timeout=30 ) except RateLimitError: wait = 2 ** attempt print(f"请求太频繁,{wait}秒后重试...") time.sleep(wait) except APITimeoutError: print(f"请求超时,重试 {attempt+1}/{max_retries}") except APIConnectionError: print("网络连接失败,检查代理或 VPN") raise except AuthenticationError: print("API Key 无效") raise return None
|
八、一个小示例:代码审查机器人
1 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
| from openai import OpenAI import sys
client = OpenAI(api_key="sk-xxx")
SYSTEM_PROMPT = """你是一个资深代码审查专家。审查代码时请关注: 1. 潜在的 bug 和逻辑错误 2. 性能问题 3. 安全隐患 4. 代码风格和可读性 回复格式:先给总体评分(1-10),再逐条列出问题和改进建议。"""
def review_code(code): response = client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": f"请审查以下代码:\n```\n{code}\n```"} ], temperature=0.3, max_tokens=2000 ) return response.choices[0].message.content
if __name__ == "__main__": if len(sys.argv) < 2: print("用法: python code_review.py <文件路径>") sys.exit(1) with open(sys.argv[1], "r") as f: code = f.read() print(review_code(code))
|
1
| python code_review.py app.py
|
九、几个实用技巧
1. 在 system prompt 里指定输出格式能大幅提升稳定性:
1 2
| 回复时必须使用以下 JSON 格式(不要包含其他文字): {"score": 评分, "issues": [{"title": "问题", "suggestion": "建议"}]}
|
2. 让模型自己检查自己:
1 2 3 4 5 6 7 8 9 10 11
| response = client.chat.completions.create(...) answer = response.choices[0].message.content
check = client.chat.completions.create( model="gpt-4o", messages=[ {"role": "user", "content": f"检查以下回答是否有事实错误或逻辑问题:\n{answer}"} ] )
|
3. 不要在一轮对话里塞太多任务:一个 Prompt 问一件事的效果,远好于一个 Prompt 同时问五件事。
以上覆盖了 OpenAI API 日常开发 80% 的场景。掌握了这些,换成 DeepSeek、通义千问、豆包等兼容接口的模型基本不需要额外的学习成本。