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?

OpenAI API クイックスタート

Last updated at Posted at 2025-03-15

どこでも、いつでも簡単に使用できるようにするために、OpenAI API を使用する手順を記述します。

OpenAI API を使用するためには、課金しているユーザーでログインする必要があります。また、APIクレジットを購入する必要があります。送信と受信のトークン数で課金されます。

次のページを参考にしています。

 
■ Ubuntu に JavaScript(Node.js)をインストール

今回は、Windows の WLS2 の Ubuntu 22.04 を使用しました。デフォルトでインストールされる Node.js のバージョンが古いため、そのままでは OpenAI API のサンプルプログラムが動作しないので、nvm を使用して v20 をインストールします。

sudo apt update
sudo apt install npm

0315_01m.png

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
source ~/.bashrc
nvm --version
nvm install 20
nvm use 20
node -v  (v20.19.0 が表示される)

 
■ Node.js に OpenAI API ライブラリを追加

プログラムを作成する作業フォルダを作成してそこに移動します。npm install コマンドを実行します。その作業フォルダで openai ライブラリが使用できるようになります。

mkdir working_directory
cd working_directory
npm install openai

 
■ テキストエディタとデバッグ

VSCode を使用して、WSL2 上の Ubuntu の Node.js の実行とデバッグが可能です。

使用したサンプルプログラム:https://platform.openai.com/docs/quickstart?lang=javascript

[拡張機能]で、「Dev Containers」を追加します。

0315_01n.png

左下の[リモートウィンドウを開きます]ボタンを押します。

中央上で、「WSL への接続」を選択します。

左帯のエクスプローラーから「フォルダーを開く」を選択します。

サンプルプログラム(FirstAPIRequest.mjs)を配置したフォルダーを選択し、ファイルを開きます。まだファイルを作成していない場合は、新規作成してそこにプログラムコードをコピー貼り付けします。

0315_02n.png

0315_03n.png

0315_04n.png

左帯から[実行とデバッグ]を選択します。

「JavaScript Debug Termina」ボタンを押します(「実行とデバッグ」ボタンではなく)。すると、下部にターミナルウィンドウが開きます。

OpenAI API を実行するために、始めに、ここで環境変数をセットします。(グローバルで使えるように設定しても良い。)(先にテキストファイルに準備しておき、コピー貼り付けする。)
export OPENAI_API_KEY="..."

任意の行にブレークポイントを設定して、ターミナルウィンドウで、
node FirstAPIRequest.mjs
を実行すると(「実行とデバッグ」ボタンで実行するのではなく)、デバッグが開始され、ブレークポイントで停止します。

F5キー(実行)またはF10キー(ステップオーバー)で実行を継続すると、最後まで進み、結果がターミナルウィンドウに表示されます。

0315_05n.png

※ テキストの文字コードは UTF-8 で開く(右下)

送信したデータ1

0315_06.png

あなたは役に立つアシスタントです。

プログラミングにおける再帰についての俳句を書いてください。

受信したデータ1

0315_07.png

関数が自らを呼び、
流れの中でループし、
無限の層

参考サンプルプログラム: https://platform.openai.com/docs/guides/text-generation

送信したデータ2
[システムメッセージ]を追加すると、特性を指示できます。

0315_08.png

あなたは役に立つアシスタントです。日本語で話してください。

0315_12.png.png

(日本語で)
 繰り返し、
 コードの中に、
 無限の道

参考サンプルプログラム: https://platform.openai.com/docs/guides/text-generation

送信したデータ3
[アシスタントメッセージ]で会話履歴を追加できます。次のAIの回答に履歴を反映します。

0315_10.png

コンコン。
そこにいるのは誰?
オレンジだよ。

受信したデータ3

0315_11.png

オレンジ誰? (英語では Orange who? )

※ 前の会話が無いと、
「オレンジですね。果物のオレンジを指しているのでしょうか?それとも色のオレンジでしょうか?どちらについてもっと知りたいですか? 」が返される。

その他のサンプル

AnalyzeImageInputs.mjs

0315_04.png

この画像は何ですか。日本語で説明してください。

0315_05.png

この画像には、青い空と草原が広がっている風景が映っています。中央には木製の歩道が見え、その両側には緑の草や灌木があります。穏やかな自然の風景が感じられ、開放感があります。

 
ConvertImageText.mjs
URLまたはファイルの画像を言葉に変換するプログラムを作成しました。
プログラムは、テキストファイルを1行ずつ読み込み、画像の場合は OpenAI API を使用して文章に変換し、文章の場合はそのまま出力します。
(OCR 機能を追加することも可能かもしれませんが、今のところ他の画像と同じに処理します。)

「temperature: 0, 」を指定しても、全く同じ回答になるわけではないようです(なので削除)。

ConvertImageText.mjs
import OpenAI from "openai"
import fs from 'fs';

const openai = new OpenAI();

function isUrl(text) {
    const urlPattern = /https?:\/\/\S+/;
    return urlPattern.test(text);
}

function isImageFile(text) {
    const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp'];
    return imageExtensions.some(ext => text.trim().toLowerCase().endsWith(ext));
}

async function analyzeImageUrl(imageUrl) {
    try {
        const response = await openai.chat.completions.create({
            model: "gpt-4o-mini",
            messages: [
                {
                    role: "user",
                    content: [
                        { type: "text", text: "What's in this image? Please speak in Japanese." },
                        { type: "image_url", image_url: { url: imageUrl } },
                    ],
                },
            ],
        });
        return response.choices[0].message.content;
    } catch (error) {
        console.error("Error analyzing image URL:", error);
        return "(エラーが発生しました)";
    }
}

async function analyzeImageFile(imagePath) {
    try {
        const imageBuffer = fs.readFileSync(imagePath);
        const encodedImage = imageBuffer.toString('base64');
        
        const response = await openai.chat.completions.create({
            model: "gpt-4o-mini",
            messages: [
                {
                    role: "user",
                    content: [
                        { type: "text", text: "What's in this image? Please speak in Japanese." },
                        { type: "image_url", image_url: { url: `data:image/jpeg;base64,${encodedImage}` } },
                    ],
                },
            ],
        });
        return response.choices[0].message.content;
    } catch (error) {
        console.error("Error analyzing image file:", error);
        return "(エラーが発生しました)";
    }
}


// 使用例
const inputFilename = 'input.txt';
const outputFilename = 'output.txt';
let outputText = "";

const inputLines = fs.readFileSync(inputFilename, 'utf-8').split('\n');

(async () => { // await を使用するための即時実行関数
    for (let line of inputLines) {
        line = line.trim();
    
        if (isUrl(line) || isImageFile(line)) {
            let text = "";
    
            if (isUrl(line)) {
                console.log(`URL found: ${line}`);
                text = await analyzeImageUrl(line);

            } else if (isImageFile(line)) {
                console.log(`Image file found: ${line}`);
                text = await analyzeImageFile(line);
            }
    
            let prefix = "";
            prefix = "この画像";
            if (text.startsWith(prefix)) {
                 text = "画像" + text.slice(prefix.length);
            }
            prefix = "申し訳ありませんが";
            if (text.startsWith(prefix)) {
                text = "(説明できない画像)";
            }

            outputText += text + '\n';

        } else {
            outputText += line + '\n';
        }    
    }
    
    fs.writeFileSync(outputFilename, outputText, 'utf-8');
    console.log(`Character count: ${outputText.length}`);
})();

実行
node ConvertImageText.mjs
URL found: https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg
Image file found: top.jpg
Character count: 4382
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?