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,可以使用官方的 TypeScript 與 JavaScript 版 OpenAI SDK。首先,使用 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 輔助工具,目前仍為 Beta 版。你可以使用下列組態加入 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 輔助程式,目前處於 Beta 測試階段。你可以使用以下程式碼匯入此函式庫:
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 智慧體。