OpenAI GPT-4o API 教程 2026:视觉、音频与实时能力
掌握 GPT-4o 的多模态特性,包括图像分析、音频转录以及用于交互式应用的全新实时流式 API
OpenAI GPT-4o API 教程 2026:视觉、音频与实时能力
掌握 GPT-4o 的多模态特性,包括图像分析、音频转录以及用于交互式应用的全新实时流式 API
OpenAI GPT-4o API 完整指南,涵盖多模态输入、实时音频流、函数调用以及构建生产级应用。包含视觉分析、语音转文本集成和成本优化策略的代码示例。
OpenAI GPT-4o API 教程 2026:视觉、音频与实时能力
2026 年 GPT-4o 有何不同
GPT-4o("omni")代表了与 AI 模型交互方式的根本性转变。与之前通过独立管道处理文本、图像和音频的版本不同,GPT-4o 原生处理所有模态——从而带来更快的响应、更低的延迟以及更自然的多模态理解。
到 2026 年,GPT-4o 已成为数千个生产应用的支柱。本教程涵盖完整的 API 接口。
快速开始
python
from openai import OpenAIclient = OpenAI() # 使用 OPENAI_API_KEY 环境变量
基本文本补全
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "你是一个乐于助人的助手。"},
{"role": "user", "content": "GPT-4o 有什么新功能?"}
]
)print(response.choices[0].message.content)
print(f"使用的令牌数:{response.usage.total_tokens}")
视觉:分析图像
GPT-4o 可以分析来自 URL 或 base64 编码数据的图像:
python
分析基于 URL 的图像
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": "https://example.com/chart.png",
"detail": "high" # "low"、"high" 或 "auto"
}
},
{
"type": "text",
"text": "分析这张销售图表,找出关键趋势"
}
]
}
],
max_tokens=1000
)
实际视觉用例:发票处理
python
import base64
from pathlib import Pathdef extract_invoice_data(image_path: str) -> dict:
with open(image_path, "rb") as f:
image_data = base64.b64encode(f.read()).decode()
ext = Path(image_path).suffix.lower()
media_type = {'.jpg': 'image/jpeg', '.png': 'image/png', '.pdf': 'application/pdf'}.get(ext, 'image/jpeg')
response = client.chat.completions.create(
model="gpt-4o",
messages=[{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {"url": f"data:{media_type};base64,{image_data}"}
},
{
"type": "text",
"text": """将发票数据提取为 JSON:
- invoice_number
- date
- vendor_name
- total_amount
- line_items (数组)
只返回有效的 JSON。"""
}
]
}],
response_format={"type": "json_object"}
)
import json
return json.loads(response.choices[0].message.content)
使用 Whisper 进行音频转录
python
import openai转录音频文件
with open("meeting_recording.mp3", "rb") as audio_file:
transcript = client.audio.transcriptions.create(
model="whisper-1",
file=audio_file,
response_format="verbose_json", # 包含时间戳
timestamp_granularities=["segment"]
)print(transcript.text)
处理带时间戳的片段
for segment in transcript.segments:
print(f"[{segment.start:.1f}s - {segment.end:.1f}s]: {segment.text}")
文本转语音
python
from pathlib import Pathresponse = client.audio.speech.create(
model="tts-1-hd", # 或 "tts-1" 以获得更快/更便宜的效果
voice="alloy", # alloy, echo, fable, onyx, nova, shimmer
input="欢迎使用我们的 AI 驱动服务。今天我能为您做些什么?",
speed=1.0
)
Path("welcome.mp3").write_bytes(response.content)
函数调用(工具使用)
python
import jsontools = [
{
"type": "function",
"function": {
"name": "search_products",
"description": "搜索产品目录",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string"},
"category": {"type": "string", "enum": ["electronics", "clothing", "food"]},
"max_price": {"type": "number"}
},
"required": ["query"]
}
}
}
]
def run_conversation(user_message: str):
messages = [{"role": "user", "content": user_message}]
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools,
tool_choice="auto"
)
if response.choices[0].message.tool_calls:
# 执行工具调用
tool_call = response.choices[0].message.tool_calls[0]
args = json.loads(tool_call.function.arguments)
# 模拟工具执行
tool_result = {"products": [{"name": "产品 A", "price": 29.99}]}
# 继续对话并加入工具结果
messages.extend([
response.choices[0].message,
{
"role": "tool",
"tool_call_id": tool_call.id,
"content": json.dumps(tool_result)
}
])
final_response = client.chat.completions.create(
model="gpt-4o",
messages=messages
)
return final_response.choices[0].message.content
return response.choices[0].message.content
使用 Pydantic 的结构化输出
python
from pydantic import BaseModel
from typing import List
from openai import OpenAIclient = OpenAI()
class ProductReview(BaseModel):
sentiment: str
score: int
pros: List[str]
cons: List[str]
summary: str
completion = client.beta.chat.completions.parse(
model="gpt-4o-2024-08-06",
messages=[
{"role": "system", "content": "分析产品评论。"},
{"role": "user", "content": "电池续航惊人,能用 3 天!相机还行但软件有 bug。"}
],
response_format=ProductReview
)
review = completion.choices[0].message.parsed
print(f"情感:{review.sentiment}")
print(f"评分:{review.score}/10")
print(f"优点:{', '.join(review.pros)}")
用于节省成本的批处理 API
对于非实时工作负载,批处理 API 可降低 50% 的成本:
python
import json创建批处理文件
batch_requests = [
{
"custom_id": f"request-{i}",
"method": "POST",
"url": "/v1/chat/completions",
"body": {
"model": "gpt-4o",
"messages": [{"role": "user", "content": f"总结:{text}"}],
"max_tokens": 500
}
}
for i, text in enumerate(texts_to_summarize)
]写入 JSONL 文件
with open("batch_input.jsonl", "w") as f:
for req in batch_requests:
f.write(json.dumps(req) + "\n")上传并创建批处理
batch_file = client.files.create(file=open("batch_input.jsonl", "rb"), purpose="batch")
batch = client.batches.create(
input_file_id=batch_file.id,
endpoint="/v1/chat/completions",
completion_window="24h"
)
print(f"批处理 ID:{batch.id}")
成本优化技巧
结论
GPT-4o 的多模态 API 使得构建几年前还属于科幻小说的应用成为可能。从实时发票处理到语音助手,所有基本组件都已就绪。从基本的聊天 API 开始,根据需要加入视觉功能,然后升级到函数调用以实现代理工作流。
相关工具
相关教程
何时以及如何针对特定领域任务微调大语言模型
使用 Gemini 2.0 Flash 和 Pro 构建 multimodal AI 应用:视觉、音频、文档
大规模运行 Assistants API 的工程指南——线程管理、工具使用、文件处理和成本优化
使用Whisper转录音频文件、会议和实时语音
对比 DALL-E 3、Flux 和 Stable Diffusion API,用于生产环境图像生成
使用自然语音 TTS 和自定义语音克隆构建语音 AI 应用