LoginSignup
3
1

More than 1 year has passed since last update.

ChatGPT API で文脈を含めたやりとりをサクッと出来るようにする

Last updated at Posted at 2023-03-06

やりたいこと

ChatGPT API でウェブ版のように文脈を含めたやりとりをしたい。

仕組み

messages に今までのやりとりを含めれば OK です。
まず、2020年のワールドシリーズを制したのは?という質問を尋ねる場合は以下になります。

const response = await openaiClient.createChatCompletion({
    model: 'gpt-3.5-turbo',
    messages: [
        {"role": "system", "content": "あなたは役にたつアシスタントです"},
        {"role": "user", "content": "2020年のワールドシリーズを制したのは?"},
    ]
});

これのレスポンスが、ロサンゼルス・ドジャースがワールドシリーズを制覇しました。だとします。
そしてこの回答のあとにどこでプレイされたでしょうかという質問をする場合は以下になります。

const response = await openaiClient.createChatCompletion({
    model: 'gpt-3.5-turbo',
    messages: [
        {"role": "system", "content": "あなたは役にたつアシスタントです"},
        {"role": "user", "content": "2020年のワールドシリーズを制したのは?"},
        {"role": "assistant", "content": "ロサンゼルス・ドジャースがワールドシリーズを制覇しました。"},
        {"role": "user", "content": "どこでプレイされたでしょうか?"}
    ]
});

このように、質問者はroleuserとし、ChatGPT のレスはroleassistantとしてmessagesに突っ込んでいくだけです。
簡単ですね。

実装

import { createInterface } from "readline";
import { Configuration, OpenAIApi } from "openai";

// ユーザーの入力を受け付ける
async function getUserInput() {
  const rl = createInterface({
    input: process.stdin,
    output: process.stdout
  });

  return new Promise((resolve, reject) => {
    rl.question('you: ', (answer) => {
      resolve(answer);
      rl.close();
    });
  });
}

// openAIクライアントの設定
const openaiConfig = new Configuration({
  apiKey: "API_KEY",
});
const openaiClient = new OpenAIApi(openaiConfig);

// AIのsystem設定
const system = `あなたは役にたつAIアシスタントです。`;
const messages = [
  { role: 'system', content: system },
];

// 入力を受け付けて ChatGPT からのレスポンスを返し会話を続ける
while (true) {
  const text = await getUserInput();
  messages.push({ role: 'user', content: text });

  const response = await openaiClient.createChatCompletion({
    model: 'gpt-3.5-turbo',
    messages: messages,
  });
  const message = response.data.choices[0].message?.content;
  console.log('ChatGPT: ' + message);

  messages.push({ role: 'assistant', content: message });
}

結果

you: こんにちは
ChatGPT: こんにちは!どのようにお力添えできますか?
you: りんごの剥き方
ChatGPT: りんごの剥き方ですね。以下の手順で剥くことができます。

1. りんごを水洗いし、十分に水気を取ります。
2. りんごを切る前に、上下を切り落とし、平らな面を作ります。
3. そこから剥き器を使って、表面を剥きます。剥き器を使わずにおろす場合は、例えばピーラーを使って削いでいくのも良いでしょう。
4. うまく剥けない場合は、りんごの部分部分で剥きやすいところを見つけるか、りんごをさらに小さく切り、切り口から剥き取っていきます。

以上のようにすると、簡単にりんごを剥くことができます。
you: さっき私なんの質問したっけ?
ChatGPT: 少し前に「りんごの剥き方」についての質問をされました。
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