OpenAI API 快速开始
本指南帮助你在 5 分钟内完成 OpenAI API 的第一次调用。
#准备工作
#1. 获取 API Key
- 访问 OpenAI Platform↗
- 注册或登录账号
- 进入 API Keys↗ 页面
- 点击 "Create new secret key"
- 复制并安全保存 Key
⚠️ 重要:API Key 只显示一次,请立即保存!
#2. 设置环境变量
bash# macOS / Linux export OPENAI_API_KEY="sk-..." # Windows PowerShell $env:OPENAI_API_KEY="sk-..." # 或在 .env 文件中 OPENAI_API_KEY=sk-...
#Python 快速开始
#安装
bashpip install openai
#第一次调用
pythonfrom openai import OpenAI client = OpenAI() # 自动读取环境变量中的 API Key response = client.chat.completions.create( model="gpt-4o", messages=[ {"role": "user", "content": "用一句话介绍人工智能"} ] ) print(response.choices[0].message.content)
#运行结果
人工智能是让计算机模拟人类智能行为的技术,包括学习、推理和解决问题的能力。
#Node.js 快速开始
#安装
bashnpm install openai
#第一次调用
typescriptimport OpenAI from 'openai'; const client = new OpenAI(); // 自动读取环境变量 async function main() { const response = await client.chat.completions.create({ model: 'gpt-4o', messages: [ { role: 'user', content: '用一句话介绍人工智能' } ] }); console.log(response.choices[0].message.content); } main();
#使用 curl
不想安装 SDK?可以直接用 curl:
bashcurl https://api.openai.com/v1/chat/completions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-4o", "messages": [ {"role": "user", "content": "用一句话介绍人工智能"} ] }'
#核心概念
#Messages 结构
pythonmessages = [ {"role": "system", "content": "你是一个专业的程序员"}, # 系统提示 {"role": "user", "content": "什么是 API?"}, # 用户消息 {"role": "assistant", "content": "API 是..."}, # 助手回复 {"role": "user", "content": "给个例子"} # 继续对话 ]
#角色说明
| 角色 | 作用 |
|---|---|
| system | 设置 AI 的行为和角色 |
| user | 用户的输入 |
| assistant | AI 的回复(多轮对话时需要包含) |
#常用参数
pythonresponse = client.chat.completions.create( model="gpt-4o", # 模型选择 messages=[...], # 对话内容 max_tokens=1000, # 最大输出长度 temperature=0.7, # 创造性 (0-2) top_p=1, # 采样参数 frequency_penalty=0, # 重复惩罚 presence_penalty=0 # 话题惩罚 )
#temperature 参数
0.0 - 最确定,适合代码/数学
0.7 - 平衡,适合一般对话
1.0+ - 更有创意,适合写作/创意
#模型选择
#推荐模型
| 模型 | 特点 | 价格 |
|---|---|---|
| gpt-4o | 最强,多模态 | 中等 |
| gpt-4o-mini | 快速,经济 | 最低 |
| gpt-4-turbo | 稳定可靠 | 较高 |
#代码示例
python# 日常使用 model = "gpt-4o" # 预算敏感 model = "gpt-4o-mini" # 需要稳定性 model = "gpt-4-turbo"
#完整示例
#简单问答
pythonfrom openai import OpenAI client = OpenAI() def ask(question: str) -> str: response = client.chat.completions.create( model="gpt-4o", messages=[ {"role": "user", "content": question} ] ) return response.choices[0].message.content # 使用 answer = ask("Python 和 JavaScript 的主要区别是什么?") print(answer)
#带系统提示
pythondef ask_expert(question: str, expertise: str) -> str: response = client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": f"你是一位{expertise}专家,用简洁专业的语言回答问题。"}, {"role": "user", "content": question} ] ) return response.choices[0].message.content # 使用 answer = ask_expert( "如何优化 React 应用性能?", "前端开发" )
#多轮对话
pythonclass ChatBot: def __init__(self, system_prompt: str = None): self.client = OpenAI() self.messages = [] if system_prompt: self.messages.append({"role": "system", "content": system_prompt}) def chat(self, user_input: str) -> str: self.messages.append({"role": "user", "content": user_input}) response = self.client.chat.completions.create( model="gpt-4o", messages=self.messages ) assistant_message = response.choices[0].message.content self.messages.append({"role": "assistant", "content": assistant_message}) return assistant_message # 使用 bot = ChatBot("你是一个友好的编程助手") print(bot.chat("你好")) print(bot.chat("Python 怎么读文件?")) print(bot.chat("那写文件呢?")) # 记住上下文
#错误处理
pythonfrom openai import OpenAI, APIError, RateLimitError, AuthenticationError client = OpenAI() try: response = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": "Hello"}] ) except AuthenticationError: print("API Key 无效") except RateLimitError: print("请求太频繁,请稍后重试") except APIError as e: print(f"API 错误: {e}")
#费用监控
pythonresponse = client.chat.completions.create(...) # 查看 token 使用 usage = response.usage print(f"输入 tokens: {usage.prompt_tokens}") print(f"输出 tokens: {usage.completion_tokens}") print(f"总计 tokens: {usage.total_tokens}") # 估算费用 (以 gpt-4o 为例) # 输入: $5/M tokens, 输出: $15/M tokens input_cost = usage.prompt_tokens * 5 / 1_000_000 output_cost = usage.completion_tokens * 15 / 1_000_000 print(f"估算费用: ${input_cost + output_cost:.4f}")
#下一步
- 流式响应 - 实时输出
- Function Calling - 函数调用
- Embeddings - 文本向量化
提示:建议先在 OpenAI Playground↗ 测试,再写代码。