用量与计费

OpenAI API 示例:7 段可直接复制的代码(2026)

ROIBest AI

运行示例之前

下面所有示例都使用 Responses API(POST /v1/responses)——这是 OpenAI 快速入门里新代码统一采用的接口——以及官方 SDK(pip install openai、npm install openai)。先设置一次密钥,SDK 会自动读取:

export OPENAI_API_KEY="sk-..."

还没有密钥的话,参考 如何获取 OpenAI API Key。示例里的模型是 gpt-6.2-sol,它是 2026 年 11 月 OpenAI 定价页上价格较低的旗舰模型;难任务可换成 gpt-6.2-astra,简单又要省钱的任务可换成 gpt-6-luna。所有代码已于 2026 年 11 月 25 日对照 OpenAI 快速入门与函数调用指南核对。

任务

端点

关键字段

生成文本

/v1/responses

input,读取 output_text

流式输出

/v1/responses

stream: true

识别图片或 PDF

/v1/responses

input_image、input_file 内容块

调用你自己的函数

/v1/responses

tools,type: "function"

返回严格 JSON

/v1/responses

text.format 配 JSON Schema

联网搜索

/v1/responses

tools: [{"type": "web_search"}]

生成向量

/v1/embeddings

model、input

示例 1:生成文本

from openai import OpenAI

client = OpenAI()
response = client.responses.create(
    model="gpt-6.2-sol",
    instructions="你是一名简洁的技术写作者。",
    input="用两句话解释什么是幂等键。",
)
print(response.output_text)
import OpenAI from "openai";

const client = new OpenAI();
const response = await client.responses.create({
  model: "gpt-6.2-sol",
  input: "用两句话解释什么是幂等键。",
});
console.log(response.output_text);
curl https://api.openai.com/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{"model": "gpt-6.2-sol", "input": "用两句话解释什么是幂等键。"}'

output_text 是 SDK 提供的便捷属性,会把所有文本片段拼起来。直接用 HTTP 调用时要读 output 数组:助手回复在 type 为 message 的条目里,位于 content[].text。

示例 2:流式输出

stream = client.responses.create(
    model="gpt-6.2-sol",
    input="写一首关于限流的俳句。",
    stream=True,
)
for event in stream:
    if event.type == "response.output_text.delta":
        print(event.delta, end="", flush=True)

流式返回的是带类型的 SSE 事件。实时打印 response.output_text.delta 事件即可,等到 response.completed 事件再读取用量合计。

示例 3:发送图片或 PDF

response = client.responses.create(
    model="gpt-6.2-sol",
    input=[{
        "role": "user",
        "content": [
            {"type": "input_text", "text": "这张图片里有什么?"},
            {"type": "input_image", "image_url": "https://example.com/receipt.png"},
        ],
    }],
)
print(response.output_text)

PDF 用 input_file 内容块,可传 file_url、Files API 返回的 file_id,或 base64 的 file_data。各内容块支持哪些格式,见 OpenAI API 支持的文件类型。

示例 4:函数调用

模型不会替你执行代码。它返回一个 function_call 条目,由你执行函数,再把结果以 function_call_output 发回去:

import json

tools = [{
    "type": "function",
    "name": "get_order_status",
    "description": "查询订单的物流状态。",
    "strict": True,
    "parameters": {
        "type": "object",
        "properties": {"order_id": {"type": "string"}},
        "required": ["order_id"],
        "additionalProperties": False,
    },
}]

history = [{"role": "user", "content": "订单 A-1042 到哪了?"}]
response = client.responses.create(model="gpt-6.2-sol", tools=tools, input=history)
history += response.output

for item in response.output:
    if item.type == "function_call" and item.name == "get_order_status":
        args = json.loads(item.arguments)
        result = {"order_id": args["order_id"], "status": "shipped"}  # 换成真实查询
        history.append({"type": "function_call_output", "call_id": item.call_id,
                        "output": json.dumps(result)})

final = client.responses.create(model="gpt-6.2-sol", tools=tools, input=history)
print(final.output_text)

OpenAI 函数调用指南里有两点要特别注意:保留 strict: True 和 additionalProperties: False,参数才会始终符合 Schema;要把整个 response.output 回传,因为推理模型需要把推理条目和工具结果一起送回。

示例 5:结构化 JSON 输出

import json

response = client.responses.create(
    model="gpt-6.2-sol",
    input="提取公司名和金额:'Acme Ltd 开来一张 1,250 美元的发票。'",
    text={"format": {
        "type": "json_schema",
        "name": "invoice",
        "strict": True,
        "schema": {
            "type": "object",
            "properties": {"company": {"type": "string"}, "amount": {"type": "number"}},
            "required": ["company", "amount"],
            "additionalProperties": False,
        },
    }},
)
print(json.loads(response.output_text))

开启 strict 后,输出会被约束在 Schema 之内,比在提示词里要求"返回 JSON"可靠得多。Python SDK 还提供 client.responses.parse(),可以直接传 Pydantic 模型拿到类型化对象。

示例 6:内置联网搜索

response = client.responses.create(
    model="gpt-6.2-sol",
    tools=[{"type": "web_search"}],
    input="最新的 Node.js LTS 版本有哪些变化?",
)
print(response.output_text)

联网搜索按调用次数计费(2026 年 11 月定价页为每 1,000 次 10 美元),检索到的内容 token 另按模型单价计费,所以不要默认给每个请求都打开。

示例 7:生成向量(Embeddings)

emb = client.embeddings.create(
    model="text-embedding-3-small",
    input=["年付套餐的退款政策", "如何取消订阅"],
)
vectors = [d.embedding for d in emb.data]
print(len(vectors), len(vectors[0]))

text-embedding-3-small 每百万 token 0.02 美元,绝大多数检索、聚类任务都够用;text-embedding-3-large 为 0.13 美元。

把同样的示例跑在其他服务商上

这些示例都用官方 SDK,所以改两个参数就能跑在 OpenAI 兼容网关或自建服务上:

client = OpenAI(base_url="https://your-gateway.example.com/v1", api_key="YOUR_GATEWAY_KEY")

要注意的是,很多兼容服务只实现了 /v1/chat/completions,没有 /v1/responses。遇到这种情况,改用 client.chat.completions.create(model=..., messages=[...])。哪些能力能平移,见 什么是 OpenAI 兼容 API;同样的调用换成 Claude 的写法,见 Claude API curl 示例。

常见问题

官方的 OpenAI API 示例在哪里?

developers.openai.com 上的快速入门和各功能指南都带 Python、JavaScript、curl 等 SDK 代码片段,GitHub 上的 OpenAI Cookbook 则有更完整的 Notebook 示例。本文的代码都依照这些指南编写。

新代码该用 Responses API 还是 Chat Completions?

用 Responses API。OpenAI 的快速入门和工具指南都以它为准,联网搜索、文件检索等内置工具也通过它调用。Chat Completions 如今主要用于不支持 /v1/responses 的 OpenAI 兼容服务。

最简单的 OpenAI API 示例是什么?

把密钥放进 OPENAI_API_KEY 环境变量,调用一次 client.responses.create(model="gpt-6.2-sol", input="..."),再 print(response.output_text) 就够了。

为什么示例返回 401 或 429?

401 表示密钥缺失、错误或已被吊销。429 表示触发了速率限制,或项目余额不足;先在控制台检查账单和用量限制,再用指数退避重试。

这些示例能在 Node.js / TypeScript 里用吗?

能。openai npm 包提供同样的 client.responses.create 方法和 output_text 属性;文件存为 .mts 或启用 ES 模块,就能使用顶层 await。

一句话总结

装好 SDK,设置 OPENAI_API_KEY,从 client.responses.create 起步。需要实时输出就加 stream=True,图片和 PDF 用内容块,函数调用和联网搜索用 tools,要 JSON 就用带严格 Schema 的 text.format。准备放量之前,先看看这些调用要花多少钱:OpenAI API 价格详解。