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 openaiOpenAI 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 リクエストの出力が表示されるはずです。
SDK のその他の機能やオプションについては、GitHub にあるライブラリの README をご覧ください。
Python で OpenAI API を使用するには、公式の OpenAI SDK for Python を利用できます。まず、pip を使って SDK をインストールします。
pip install openaiOpenAI 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 リクエストの出力が表示されるはずです。
SDK のその他の機能やオプションについては、GitHub にあるライブラリの README をご覧ください。
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 リポジトリをご覧ください。
SDK のその他の機能やオプションについては、GitHub にあるライブラリの README をご覧ください。
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 リポジトリをご覧ください。
SDK のその他の機能やオプションについては、ライブラリの GitHub リポジトリにある README をご覧ください。
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 リクエストの出力が表示されるはずです。
SDK のその他の機能やオプションについては、ライブラリの GitHub リポジトリにある README をご覧ください。
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 エージェントを構築する方法を学びます。