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-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 的其他功能與選項。
你可以透過官方的 OpenAI Python SDK 在 Python 中呼叫 OpenAI API。先使用 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 傳送簡單的請求。
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 SDK 可用來呼叫 API。你可以使用下列設定,將 SDK 加入 Maven 專案的相依套件清單:
<dependency>
<groupId>com.openai</groupId>
<artifactId>openai-java</artifactId>
<version>4.105.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-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-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-astra",
input: "Write a one-sentence bedtime story about a unicorn."
)
puts(response.output_text)使用 ruby example.rb 執行程式碼。稍等片刻,應該就能看到 API 請求的結果。
如需瞭解 SDK 的更多功能與選項,請參閱此函式庫在 GitHub 上的 README。
開始使用 Responses API 開發應用程式。
進一步瞭解如何撰寫提示詞、使用訊息角色及建構對話式應用程式。
儲值點數以繼續開發
前往帳務頁面
探索以下工具和文件,讓你的應用程式更快上線:
撰寫並測試對話用的提示詞,再將提示詞嵌入應用程式。
使用 Agents SDK 建立、執行及觀察智慧體工作流程。
分析影像與檔案
將影像網址、已上傳的檔案或 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: 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-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": "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-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 智慧體。