0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

BunでOpenAI APIを叩いてみた。Node.jsとの違いも解説

0
Last updated at Posted at 2026-02-14

こんにちは、六月書房neo の高橋です。
前回の「Node.jsでOpenAI APIを叩いてみた」は、
AIのAPIをCurlで叩いてみる」の続編として書いたものでした。

今回はそのNode.js版の実装を、話題のJavaScriptランタイム「Bun」で書き直してみようと思います。
Node.jsとの違いや、Bunの魅力も交えて紹介していきます。


🧠 やりたいこと

OpenAIのAPI(ChatGPT)を使って、簡単なプロンプトを送信し、レスポンスを受け取るCLIツールを作る。


🛠️ 環境

  • Ubuntu 20.04.6 LTS (GNU/Linux 5.15.0-1089-azure x86_64)
  • Node.js: v20.19.6
  • Bun: 1.3.5

📁 ファイル構成

今回作成するプロジェクトの構成は以下のようになります:

bun-openai-cli/
├── .env            //環境変数APIキーなど
├── bun.lockb       //自動生成
├── index.ts
├── node_modules/   //自動生成
├── package.json    //自動生成
├── tsconfig.json   //自動生成(自動生成される場合あり)

bun initpackage.jsonbun.lockb が生成されます。
tsconfig.json は明示的に作らなくても動作しますが、必要に応じて追加してください。

📦 Node.js版のコード(前回記事

import { config } from "dotenv";
import OpenAI from "openai";

config();

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

const main = async () => {
  const chatCompletion = await openai.chat.completions.create({
    messages: [{ role: "user", content: "こんにちは!自己紹介して" }],
    model: "gpt-3.5-turbo",
  });

  console.log(chatCompletion.choices[0].message.content);
};

main();

実行方法(Node.js)

node index.js

⚡ Bun版のコード

プロジェクトの作成とパッケージのインストール

mkdir bun-openai-cli
cd bun-openai-cli
bun init
bun add openai dotenv

.env ファイルの作成

API_KEYの取得方法は、 前回の記事を参照してね。

OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

index.ts の作成

import { config } from "dotenv";
import OpenAI from "openai";

config(); // .envを読み込む(Bunは自動読み込みも対応)

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

const main = async () => {
  const chatCompletion = await openai.chat.completions.create({
    messages: [{ role: "user", content: "こんにちは!自己紹介して" }],
    model: "gpt-3.5-turbo",
  });

  console.log(chatCompletion.choices[0].message.content);
};

main();

実行方法(Bun)

bun index.ts

🔍 Node.jsとBunの違いまとめ

項目 Node.js Bun(v1.3.5)
ランタイム V8 + libuv Zig + JavaScriptCore
パッケージ管理 npm / yarn / pnpm(外部ツール) bun(内蔵パッケージマネージャー)
実行速度 標準的 非常に高速 ⚡
ESModule対応 一部制限あり デフォルトで完全対応
require のサポート フルサポート 一部サポート(基本は非推奨)
.env の読み込み dotenv を使って明示的に読み込む 自動読み込み(明示も可能)

✅ Bunの良いところ

  • bun installがとにかく速い!
  • bunコマンド一つで、実行・ビルド・テストができる
  • Node.jsのコードをほぼそのまま使える
  • TypeScriptもそのまま動く(tsconfig不要)

📝 まとめ

  • BunでもOpenAI APIは簡単に叩ける。
  • Node.jsのコードをそのまま移植できるケースが多い
  • 開発体験が軽快で、特にCLIツールとの相性が良い。

Bun、これからの開発に取り入れてみる価値アリです。🌊
質問やフィードバックがあれば、ぜひコメントで教えてください。


🔗 参考リンク

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?