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 调用
要在 Node.js、Deno 或 Bun 等服务端 JavaScript 环境中使用 OpenAI API,您可以使用官方的 OpenAI SDK for TypeScript and JavaScript。首先,使用 npm 或您偏好的包管理器安装 SDK:
npm install openai安装 OpenAI SDK 后,创建一个名为 example.mjs 的文件,并将示例代码复制到其中:
import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.create({
model: "gpt-6-astra",
input: "Write a one-sentence bedtime story about a unicorn.",
});
console.log(response.output_text);使用 node example.mjs(或 Deno、Bun 中的等效命令)执行代码。稍等片刻,您应该就能看到 API 请求的输出。
查看该库在 GitHub 上的 README,了解更多 SDK 能力和选项。
要在 Python 中使用 OpenAI API,您可以使用官方的 Python 版 OpenAI SDK。首先使用 pip 安装 SDK:
pip install openai安装 OpenAI SDK 后,创建一个名为 example.py 的文件,并将示例代码复制到该文件中:
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-6-astra",
input="Write a one-sentence bedtime story about a unicorn.",
)
print(response.output_text)使用 python example.py 运行代码。稍等片刻,您应该就能看到 API 请求的输出。
查阅该库在 GitHub 上的 README,了解 SDK 的更多能力和选项。
OpenAI 与 Microsoft 合作,提供官方支持的 C# API 客户端。您可以使用 .NET CLI 从 NuGet 安装。
dotnet add package OpenAI
向 Responses API 发送简单 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-astra",
"Say 'this is a test.'"
);
Console.WriteLine($"[ASSISTANT]: {response.GetOutputText()}");OpenAI 提供了适用于 Java 编程语言的 API 辅助库,目前处于测试阶段。您可以使用以下配置添加 Maven 依赖项:
<dependency>
<groupId>com.openai</groupId>
<artifactId>openai-java</artifactId>
<version>4.58.0</version>
</dependency>向 Responses API 发送的简单 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-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 能力和选项。
OpenAI 提供了适用于 Go 编程语言的 API 辅助库,目前处于测试阶段。您可以使用以下代码导入该库:
import (
"github.com/openai/openai-go/v3" // imported as openai
)向 Responses API 发送的第一个 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-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 能力和选项。
要在 Ruby 中使用 OpenAI API,您可以使用官方的 OpenAI SDK for Ruby。首先,将该 gem 添加到您的应用中:
gem "openai"安装 OpenAI SDK 后,创建一个名为 example.rb 的文件,并将示例代码复制到其中:
require "openai"
openai = OpenAI::Client.new
response = openai.responses.create(
model: "gpt-6-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-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-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-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-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-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-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 = [
{
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-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-astra",
"tools": [
{
"type": "mcp",
"server_label": "dmcp",
"server_description": "A Dungeons and Dragons MCP server to assist with dice rolling.",
"server_url": "https://dmcp-server.deno.dev/mcp",
"require_approval": "never"
}
],
"input": "Roll 2d4+1"
}'了解网页搜索和文件搜索等功能强大的内置工具。
了解如何让模型调用您自己的自定义代码。
流式传输响应并构建实时应用
使用服务器发送的流式事件,在结果生成的同时将其显示出来;或使用 Realtime API 构建交互式语音应用,以及支持文本、音频和图像输入的应用。
import { OpenAI } from "openai";
const client = new OpenAI();
const stream = await client.responses.create({
model: "gpt-6-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 智能体。