EN

OpenAI GPT-4o API 教程 2026:视觉、音频与实时能力

掌握 GPT-4o 的多模态特性,包括图像分析、音频转录以及用于交互式应用的全新实时流式 API

返回教程列表🌐 Read in English
进阶30 分钟

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 OpenAI

client = 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 Path

def 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 Path

response = 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 json

tools = [ { "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 OpenAI

client = 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-mini比 gpt-4o 便宜 95% 对异步处理使用批处理 API便宜 50% 提示缓存(>1024 令牌)缓存令牌节省 50% 减少 max_tokens直接降低成本 使用结构化输出减少重试次数

结论

GPT-4o 的多模态 API 使得构建几年前还属于科幻小说的应用成为可能。从实时发票处理到语音助手,所有基本组件都已就绪。从基本的聊天 API 开始,根据需要加入视觉功能,然后升级到函数调用以实现代理工作流。

相关工具

openaigpt-4opython