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で自作ミニCLIを作ってClaude / OpenAI APIを叩く

0
Posted at

はじめに

最近、AIを活用したアプリケーションの開発が注目されています。特に、Claude / OpenAI APIを使用したテキスト分析や生成タスクは、多くの開発者が挑戦しています。本記事では、TypeScriptで自作ミニCLIを作成し、Claude / OpenAI APIを叩く方法を紹介します。

CLIの基礎

CLI(コマンドラインインターフェース)とは、ユーザーがコマンドを入力してコンピュータと対話するインターフェースの一種です。Node.jsでは、process.argvを使用してコマンドライン引数を取得できます。

import { argv } from 'process';

console.log(argv);

Claude / OpenAI APIの概要

Claude / OpenAI APIは、テキスト分析や生成タスクを実行するためのAPIです。APIを使用するには、APIキーを取得してAPIエンドポイントにリクエストを送信する必要があります。

ミニCLIの作成

ここでは、TypeScriptで自作ミニCLIを作成します。まず、cli.tsファイルを作成し、以下のコードを記述します。

import axios from 'axios';

interface Options {
  apikey: string;
  prompt: string;
}

const options: Options = {
  apikey: 'YOUR_API_KEY',
  prompt: 'Hello, World!',
};

const apiEndpoint = 'https://api.openai.com/v1/completions';

axios.post(apiEndpoint, {
  model: 'text-davinci-002',
  prompt: options.prompt,
  max_tokens: 1024,
  temperature: 0.7,
}, {
  headers: {
    'Authorization': `Bearer ${options.apikey}`,
    'Content-Type': 'application/json',
  },
})
.then((response) => {
  console.log(response.data);
})
.catch((error) => {
  console.error(error);
});

CLIの実行

以上のコードを実行するには、ts-nodeコマンドを使用します。

npx ts-node cli.ts

まとめ

本記事では、TypeScriptで自作ミニCLIを作成し、Claude / OpenAI APIを叩く方法を紹介しました。ミニCLIを使用することで、コマンドラインからClaude / OpenAI APIを簡単に呼び出すことができます。詳しい手順はこちら → 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?