通过 OpenAI API,您可以使用统一的接口调用先进的 AI 模型,完成文本生成、自然语言处理、计算机视觉等任务。先创建 API 密钥并发起首次 API 调用,再探索如何生成文本、分析图像和构建智能体。
创建并导出 API 密钥
创建 API 密钥
开始之前,请在控制台中创建 API 密钥,以便安全地访问 API。请将密钥保存在安全的位置,例如您计算机上的 .zshrc 文件或其他文本文件。生成 API 密钥后,请在终端中将其导出为环境变量。
export OPENAI_API_KEY="your_api_key_here"setx OPENAI_API_KEY "your_api_key_here"各语言的 OpenAI SDK 都会自动从系统环境变量中读取您的 API 密钥。
安装 OpenAI SDK 并发起 API 调用
如果您的 TypeScript 应用运行在 Node.js、Deno 或 Bun 上,可以使用官方 OpenAI TypeScript SDK 调用 OpenAI API。同一个 openai 包也支持纯 JavaScript。首先,使用 npm 或您常用的包管理器安装 SDK。
npm install openai安装 OpenAI SDK 后,创建一个名为 example.mts 的文件,并将以下示例代码复制到该文件中。使用 .mts 扩展名后,即使在 CommonJS 项目中,这个 TypeScript 文件也会被视为 ES 模块。
import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.create({
model: "gpt-6.2-astra",
input: "Write a one-sentence bedtime story about a unicorn.",
});
console.log(response.output_text);如果使用 Node.js 22.6 或更高版本,请运行 node --experimental-strip-types example.mts 来执行代码。如果使用 Deno 或 Bun,请运行相应的命令。稍等片刻,您应该就能看到这次 API 请求的输出。
如果想以纯 JavaScript 运行此示例,请将同一段代码保存为 example.mjs,然后运行 node example.mjs。
查看该库在 GitHub 上的 README,了解 SDK 的更多功能和选项。
要在 Python 中调用 OpenAI API,您可以使用官方的 OpenAI Python SDK。首先,使用 pip 安装 SDK:
pip install openai安装 OpenAI SDK 后,创建一个名为 example.py 的文件,并将以下示例代码复制到文件中:
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-6.2-astra",
input="Write a one-sentence bedtime story about a unicorn.",
)
print(response.output_text)运行 python example.py 来执行示例代码。稍等片刻,您应该就能看到 API 请求的返回结果。
请参阅该库在 GitHub 上的 README,了解 SDK 的更多功能和选项。
OpenAI 与微软合作,为 C# 开发者提供官方支持的 API 客户端。您可以使用 .NET CLI 从 NuGet 安装该客户端。
dotnet add package OpenAI
以下示例展示了如何向 Responses API 发送一个简单的请求。
using OpenAI.Responses;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);
ResponseResult response = await client.CreateResponseAsync(
"gpt-6.2-astra",
"Say 'this is a test.'"
);
Console.WriteLine($"[ASSISTANT]: {response.GetOutputText()}");OpenAI 提供了用于调用 API 的 Java SDK。您可以使用以下配置添加 Maven 依赖:
<dependency>
<groupId>com.openai</groupId>
<artifactId>openai-java</artifactId>
<version>4.111.0</version>
</dependency>以下示例展示了如何向 Responses API 发送请求:
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
public class Main {
public static void main(String[] args) {
OpenAIClient client = OpenAIOkHttpClient.fromEnv();
ResponseCreateParams params =
ResponseCreateParams.builder().input("Say this is a test").model("gpt-6.2-astra").build();
Response response = client.responses().create(params);
response.output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(outputText -> System.out.println(outputText.text()));
}
}要进一步了解如何在 Java 中使用 OpenAI API,请查看下方链接的 GitHub 代码仓库。
查看该库在 GitHub 上的 README,了解 SDK 的更多功能和选项。
使用 Go SDK 向 Responses API 发送第一个请求:
package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
resp, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{
Model: "gpt-6.2-astra",
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Say this is a test")},
})
if err != nil {
panic(err.Error())
}
fmt.Println(resp.OutputText())
}要进一步了解如何在 Go 中使用 OpenAI API,请查看下方链接指向的 GitHub 代码仓库。
查看该库在 GitHub 上的 README,了解 SDK 的更多功能和选项。
您可以使用官方的 OpenAI Ruby SDK 在 Ruby 中调用 OpenAI API。首先,将这个 gem 添加到您的应用中:
gem "openai"安装 OpenAI SDK 后,创建一个名为 example.rb 的文件,并将以下示例代码复制到文件中:
require "openai"
openai = OpenAI::Client.new
response = openai.responses.create(
model: "gpt-6.2-astra",
input: "Write a one-sentence bedtime story about a unicorn."
)
puts(response.output_text)运行 ruby example.rb 来执行示例代码。稍等片刻,您应该就能看到 API 请求返回的结果。
查看该库在 GitHub 上的 README,了解 SDK 的更多功能和选项。
开始使用 Responses API 构建应用。
深入了解如何编写提示、使用消息角色和构建对话式应用。
添加额度,继续开发
前往账单页面
以下工具和文档可以帮助您更快地推出应用:
编写和测试对话提示,并将其嵌入您的应用。
使用 Agents SDK 构建、运行和观测智能体工作流。
分析图像和文件
将图像 URL、已上传的文件或 PDF 文档直接发送给模型,让模型提取文本、对内容进行分类或检测视觉元素。
import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.create({
model: "gpt-6.2-astra",
input: [
{
role: "user",
content: [
{
type: "input_text",
text: "What is in this image?",
},
{
type: "input_image",
image_url:
"https://openai-documentation.vercel.app/images/cat_and_otter.png",
detail: "auto",
},
],
},
],
});
console.log(response.output_text);import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.create({
model: "gpt-6.2-astra",
input: [
{
role: "user",
content: [
{
type: "input_text",
text: "Analyze the letter and provide a summary of the key points.",
},
{
type: "input_file",
file_url: "https://www.berkshirehathaway.com/letters/2024ltr.pdf",
},
],
},
],
});
console.log(response.output_text);import fs from "fs";
import OpenAI from "openai";
const client = new OpenAI();
const file = await client.files.create({
file: fs.createReadStream("fixtures/draconomicon.pdf"),
purpose: "user_data",
});
const response = await client.responses.create({
model: "gpt-6.2-astra",
input: [
{
role: "user",
content: [
{
type: "input_file",
file_id: file.id,
},
{
type: "input_text",
text: "What is the first dragon in the book?",
},
],
},
],
});
console.log(response.output_text);了解如何将图像作为模型输入,让模型解读图像内容。
了解如何将文件作为模型输入,让模型解读文档内容。
使用工具扩展模型能力
为模型添加工具,让模型能够访问外部数据和函数。您可以使用网页搜索或文件搜索等内置工具,也可以定义自己的工具来调用 API、运行代码或与第三方系统集成。
import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.create({
model: "gpt-6.2-astra",
tools: [{ type: "web_search" }],
input: "What was a positive news story from today?",
});
console.log(response.output_text);import OpenAI from "openai";
const openai = new OpenAI();
const response = await openai.responses.create({
model: "gpt-6.2-astra",
input: "What is deep research by OpenAI?",
tools: [
{
type: "file_search",
vector_store_ids: ["<vector_store_id>"],
},
],
});
console.log(response);import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.create({
model: "gpt-6.2-astra",
instructions:
"You are a personal math tutor. When asked a math question, write and run code to answer the question.",
tools: [
{
type: "code_interpreter",
container: { type: "auto" },
},
],
input: "I need to solve the equation 3x + 11 = 14. Can you help me?",
});
console.log(response.output_text);import OpenAI from "openai";
const client = new OpenAI();
const tools: OpenAI.Responses.Tool[] = [
{
type: "function",
name: "get_weather",
description: "Get current temperature for a given location.",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description: "City and country e.g. Bogotá, Colombia",
},
},
required: ["location"],
additionalProperties: false,
},
strict: true,
},
];
const response = await client.responses.create({
model: "gpt-6.2-astra",
input: [
{ role: "user", content: "What is the weather like in Paris today?" },
],
tools,
});
console.log(response.output[0]);curl https://api.openai.com/v1/responses \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-6.2-astra",
"tools": [
{
"type": "mcp",
"server_label": "openai_docs",
"server_description": "Search and read the public OpenAI documentation.",
"server_url": "https://developers.openai.com/mcp",
"require_approval": "never"
}
],
"input": "Search the OpenAI docs for Responses API streaming and return the relevant links."
}'了解网页搜索和文件搜索等强大的内置工具。
了解如何让模型调用您编写的代码。
流式传输响应并构建实时应用
通过服务器发送的流式事件,您可以在模型生成结果的同时将其展示给用户。您也可以使用 Realtime API 构建交互式语音应用,以及支持文本、音频和图像输入的应用。
import { OpenAI } from "openai";
const client = new OpenAI();
const stream = await client.responses.create({
model: "gpt-6.2-astra",
input: [
{
role: "user",
content: "Say 'double bubble bath' ten times fast.",
},
],
stream: true,
});
for await (const event of stream) {
console.log(event);
}使用服务器发送事件,将模型响应以流式方式快速传输给用户。
使用 WebRTC 或 WebSockets 构建响应极快的语音到语音 AI 应用。
构建智能体
在 OpenAI 平台上构建智能体,让它们代用户执行操作,例如操控计算机。使用 Agents SDK 在您的服务器上编写编排逻辑。
import { Agent, run } from "@openai/agents";
const spanishAgent = new Agent({
name: "Spanish agent",
instructions: "You only speak Spanish.",
});
const englishAgent = new Agent({
name: "English agent",
instructions: "You only speak English",
});
const triageAgent = new Agent({
name: "Triage agent",
instructions:
"Handoff to the appropriate agent based on the language of the request.",
handoffs: [spanishAgent, englishAgent],
});
const result = await run(triageAgent, "Hola, ¿cómo estás?");
console.log(result.finalOutput);了解如何使用 OpenAI 平台构建功能强大的 AI 智能体。