OpenAI API 提供了对 GPT 系列模型的程序化访问能力,支持文本生成、对话、函数调用、图像生成、语音合成等多种功能。开发者可以通过 REST API 或官方 SDK 快速集成到应用中。
export OPENAI_API_KEY=sk-xxxpip install openai
from openai import OpenAI
client = OpenAI() # 自动读取 OPENAI_API_KEY
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "你是一个专业的技术顾问。"},
{"role": "user", "content": "解释什么是大语言模型?"}
],
temperature=0.7,
max_tokens=1000
)
print(response.choices[0].message.content)
stream = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "写一首关于AI的诗"}],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")
让模型决定何时调用预定义的函数:
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取指定城市的天气",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名称"}
},
"required": ["city"]
}
}
}]
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "北京今天天气怎么样?"}],
tools=tools
)
| 模型 | 适用场景 | 上下文 |
|---|---|---|
| GPT-4o | 通用,性价比最优 | 128K |
| GPT-4o-mini | 轻量任务,成本低 | 128K |
| GPT-5.2 | 最强推理能力 | 256K |
| o3 | 复杂推理,数学/编程 | 200K |
| DALL·E 3 | 图像生成 | - |
| Whisper | 语音转文字 | - |
| TTS | 文字转语音 | - |
| 模型 | 输入价格 | 输出价格 |
|---|---|---|
| GPT-4o | $2.50/1M tokens | $10.00/1M tokens |
| GPT-4o-mini | $0.15/1M tokens | $0.60/1M tokens |
| GPT-5.2 | $10.00/1M tokens | $30.00/1M tokens |
评论区