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?

TypeScriptで作るAI対話CLI:ClaudeとOpenAIを手軽に呼び出す方法

0
Posted at

はじめに

最近は生成AIを活用したツールが増えており、CLI(コマンドラインインタフェース)から手軽に呼び出せると便利です。
本稿では TypeScript と Node.js を使って、Claude と OpenAI の Chat API を叩くシンプルなミニCLIを作ります。プログラミング初心者でも数ステップで完成できるように解説します。

前提条件

  • Node.js 18 以上がインストールされていること
  • npm または pnpm が使えること
  • Claude と OpenAI の API キーを取得していること(環境変数に設定します)

プロジェクトの作成

# ディレクトリ作成 & 初期化
mkdir ai-cli && cd ai-cli
npm init -y

# TypeScript と型定義をインストール
npm i -D typescript @types/node
npx tsc --init --rootDir src --outDir dist --esModuleInterop

# 必要なライブラリ
npm i commander axios dotenv

src/index.ts を作成し、以下のように記述します。

実装コード

import { Command } from "commander";
import axios from "axios";
import * as dotenv from "dotenv";

dotenv.config();

const program = new Command();

program
  .name("ai-cli")
  .description("Claude と OpenAI の Chat API を呼び出すミニCLI")
  .option("-m, --model <model>", "使用するモデル (claude-2, gpt-4o など)", "gpt-4o")
  .argument("<prompt>", "AI に投げる質問や指示")
  .action(async (prompt, options) => {
    try {
      const response = await callAi(prompt, options.model);
      console.log("\n=== AI の返答 ===\n");
      console.log(response);
    } catch (e) {
      console.error("エラー:", e);
    }
  });

async function callAi(prompt: string, model: string): Promise<string> {
  // Claude と OpenAI のエンドポイントを分岐
  if (model.startsWith("claude")) {
    const url = "https://api.anthropic.com/v1/messages";
    const res = await axios.post(
      url,
      {
        model,
        max_tokens: 1024,
        messages: [{ role: "user", content: prompt }],
      },
      {
        headers: {
          "x-api-key": process.env.CLAUDE_API_KEY,
          "anthropic-version": "2023-06-01",
          "Content-Type": "application/json",
        },
      }
    );
    return res.data.content[0].text;
  } else {
    const url = "https://api.openai.com/v1/chat/completions";
    const res = await axios.post(
      url,
      {
        model,
        messages: [{ role: "user", content: prompt }],
        max_tokens: 1024,
      },
      {
        headers: {
          Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
          "Content-Type": "application/json",
        },
      }
    );
    return res.data.choices[0].message.content;
  }
}

program.parse();

ポイント解説

  1. Commander
    CLI のオプション・引数定義に使います。-m でモデルを切り替えられるので、Claude と OpenAI を同一コマンドで呼び出せます。
  2. dotenv
    .env ファイルに CLAUDE_API_KEY と OPENAI_API_KEY を書くことで、コードにキーをハードコーディングしません。
  3. axios
    HTTP リクエストをシンプルに書けます。ヘッダーに API キーを付与し、JSON ボディでプロンプトを送ります。

ビルドと実行

# TypeScript をコンパイル
npm run build   # 事前に "build": "tsc" を package.json に追加

# 実行例
node dist/index.js "今日の天気は?" -m claude-2

-m を省略するとデフォルトで gpt-4o が選択されます。プロンプトを変えるだけで、すぐに AI の返答が得られます。

まとめ

  • TypeScript と Commander だけで、数行のコードで AI 対話CLIが完成
  • Claude と OpenAI の両方に対応できるので、プロジェクトの要件に合わせて柔軟に切り替え可能
  • 環境変数でキーを管理すれば、セキュリティ面も安心です

実務で CI に組み込んだり、ローカル開発の補助ツールとして活用すれば、作業効率が格段に上がります。ぜひ自分のプロジェクトでも試してみてください。

詳しい手順はこちら → https://felixstudio0.gumroad.com/?utm_source=qiita&utm_medium=github_actions&utm_campaign=2026-q1&utm_content=qiita-footer

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?