3
1

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 と Claude / OpenAI API でミニCLIを作る

3
Posted at

はじめに

TypeScriptとClaude / OpenAI APIを組み合わせて、ミニCLIツールを作成する方法を紹介します。このツールは、ユーザーがテキストを入力すると、AIが生成したテキストを出力することができます。

必要なもの

  • Node.jsの最新バージョン
  • TypeScriptの最新バージョン
  • Claude / OpenAI APIのアカウントとAPIキー

プロジェクトのセットアップ

まず、プロジェクトのディレクトリを作成し、次のコマンドを実行して必要なパッケージをインストールします。

npm init -y
npm install --save-dev typescript @types/node

次に、tsconfig.jsonファイルを作成し、次の設定を追加します。

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "outDir": "build",
    "rootDir": "src",
    "strict": true,
    "esModuleInterop": true
  }
}

Claude / OpenAI APIの設定

Claude / OpenAI APIのAPIキーを取得し、次のコードでAPIを呼び出します。

import axios from 'axios';

const apikey = 'YOUR_API_KEY';
const url = 'https://api.openai.com/v1/engines/text-davinci-002/completions';

const params = {
  prompt: 'Hello, World!',
  max_tokens: 100,
  temperature: 0.7,
};

axios.post(url, params, {
  headers: {
    'Authorization': `Bearer ${apikey}`,
    'Content-Type': 'application/json',
  },
})
.then(response => {
  console.log(response.data.choices[0].text);
})
.catch(error => {
  console.error(error);
});

ミニCLIツールの作成

次に、ミニCLIツールを作成します。次のコードで、ユーザーが入力したテキストをClaude / OpenAI APIに送信し、生成されたテキストを出力します。

import readline from 'readline';
import axios from 'axios';

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const apikey = 'YOUR_API_KEY';
const url = 'https://api.openai.com/v1/engines/text-davinci-002/completions';

rl.question('テキストを入力してください: ', (answer) => {
  const params = {
    prompt: answer,
    max_tokens: 100,
    temperature: 0.7,
  };

  axios.post(url, params, {
    headers: {
      'Authorization': `Bearer ${apikey}`,
      'Content-Type': 'application/json',
    },
  })
  .then(response => {
    console.log(response.data.choices[0].text);
    rl.close();
  })
  .catch(error => {
    console.error(error);
    rl.close();
  });
});

まとめ

この記事では、TypeScriptとClaude / OpenAI APIを組み合わせて、ミニCLIツールを作成する方法を紹介しました。このツールは、ユーザーがテキストを入力すると、AIが生成したテキストを出力することができます。詳しい手順はこちら → https://felixstudio0.gumroad.com/?utm_source=qiita&utm_medium=github_actions&utm_campaign=2026-q1&utm_content=qiita-footer

3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?