2
1

Node.jsでAzure Open AIのライブラリ(@azure/openai)を使ってAzure Open AIを使うメモ

Last updated at Posted at 2023-12-06

前回の記事で、The completion operation does not work with the specified model, gpt-35-turbo. Please choose different model and try again. You can learn more about which models can be used with each operationというエラーがでるという話をしていましたが、どうやら使おうとしているモデルとメソッドの対応がよくなかった模様でした。

タイトル、冗長ですが、、前回は公式OpenAIライブラリでAzure Open AIを使ったので今回の表現で良い気がする...

準備

こちらの記事を元に、モデルを準備します。

次にライブラリは@azure/openaiを使います。

$ npm i @azure/openai

listChatCompletionsを使ってコピペで試す

systemとuserで指定して回答させます。

JavaとJavaScriptの違い を教えてもらいましょう。

const { OpenAIClient,AzureKeyCredential } = require("@azure/openai");

const endpoint = `https://XXXXXXXX.openai.azure.com/`; //エンドポイント
const azureApiKey = `xxxxxxxxxxxxxxxxxxxx`; //APIキー
const deploymentId = "nobisuke-gpt-35-turbo"; //デプロイ名

async function main(){
    const client = new OpenAIClient(endpoint, new AzureKeyCredential(azureApiKey));
    const messages = [
        { role: "system", content: "あなたはプログラミングの先生で、ユーザーはあなたの生徒です。質問に対してユーモアを混ぜて回答してください。" },
        { role: "user", content: "JavaとJavaScriptの違いを教えてください。" }
    ];
    
    console.log(`Messages: ${messages.map((m) => m.content).join("\n")}`);
    const events = client.listChatCompletions(deploymentId, messages, { maxTokens: 256 });
    
    let msg = '';
    for await (const event of events) {
        for (const choice of event.choices) {
            const delta = choice.delta?.content;
            if (delta !== undefined) {
                msg += delta;
                // console.log(`Chatbot: ${delta}`);
            }
        }
    }

    console.log(msg); //結果を出力
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

無事にレスポンスが返ってきました。

$ node app.js
Messages: あなたはプログラミングの先生で、ユーザーはあなたの生徒です。質問に対してユーモアを混ぜて回答してください。
JavaとJavaScriptの違いを教えてください。

JavaとJavaScriptの違いは、名前に「Java」と「Script」という言葉が入るくらいです。まったく別の言語ですよ!Javaはバックエンドで使用されることが多く、堅実でしっかり者です。一方、JavaScriptはフロントエンドで使用され、おしゃべりで活発な性格をしています。Javaはプログラムのコンパイルが必要ですが、JavaScriptはインタープリター方式なので、すぐに動作します。そう、JavaとJavaScriptは見た目が似ているかもしれませんが、中身はまったく別物なのです!思考停止しないでくださいね。

なるほど分かりやすい(?)ですね

Chat CompletionsとCompletionsの違い

ここの違いが分かってなくてなんかコード動かないなと思ってましたが、.listChatCompletions()はgpt-3.5-turboでも使えるけど、.getCompletions()はgpt-3.5-tourboでは使えない模様です。

名前紛らわしいですね。。

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