0
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?

導入

OpenAIのChatGPT APIを使うと、さまざまなアプリケーションに自然言語処理の能力を簡単に追加できます。TypeScriptでOpenAI APIを利用してみたので、その内容を記事にしました。

手順

前提

  1. Node.jsとnpmのインストール: Node.jsとnpmがインストールされている必要があります。
  2. プロジェクトのセットアップ: 既にNext.jsやNuxt.jsなどのTypeScriptを利用するプロジェクトがセットアップ済みとします。
  3. OpenAI APIキー: OpenAIのAPIキーが必要です。OpenAIのウェブサイトでログインして取得できます。

1. OpenAI APIのインストール

openaiというライブラリを使用して、OpenAIのAPIにアクセスします。
以下のコマンドでこれをインストールします。

npm install openai

2. APIキーの取得

前提にも記載しましたが、APIキーを取得します。OpenAIのAPIキーから取得可能です。
このキーを使ってAPIにアクセスします。

3. 環境変数の設定

ルートディレクトリに.envファイルを作成し、APIキーを設定します。

.env
OPENAI_API_KEY=openai-api-key

openai-api-keyは、取得したAPIキーに置き換えてください。

4. TypeScriptでの実装

import { Configuration, OpenAIApi } from "openai";
import * as dotenv from "dotenv";
dotenv.config();

// 環境変数からAPIキーを取得します
const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

/** 
 * GPT-4とチャットをするための関数
 * prompt: GPTに送信するメッセージ(プロンプト)
 */
async function getChatGPTResponse(prompt: string) {
  try {
    const response = await openai.createChatCompletion({
      model: "gpt-4",
      messages: [{ role: "user", content: prompt }],
    });
    return response.data.choices[0].message?.content;
  } catch (error) {
    console.error("Error response from OpenAI: ", error);
  }
}

// 使用例
(async () => {
  const response = await getChatGPTResponse("こんにちは");
  console.log(response);
})();

終わりに

この記事では、TypeScriptでOpenAIのChatGPT APIを利用するための基本的な手順を解説しました。
これを基に、是非AIを様々なことに活用してみてください。

0
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
0
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?