ChatGPTのAPIを楽しむ為に課金をされた方は多いんじゃないかと思います。または危機感がきっかけとなり学びのために課金される方もいるかもしれません。どのみち課金をしたら使わないともったいないので例文くらいは試して楽しんでおきたいものです。
まずはExamplesの最初にあるQ&Aについて見ていきましょう
https://platform.openai.com/examples/default-qa でnode.jsを選択するとサンプルのコードが表示されます。
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.createCompletion({
model: "text-davinci-003",
prompt: "I am a highly intelligent question answering bot. If you ask me a question that is rooted in truth, I will give you the answer. If you ask me a question that is nonsense, trickery, or has no clear answer, I will respond with \"Unknown\".\n\nQ: What is human life expectancy in the United States?\nA: Human life expectancy in the United States is 78 years.\n\nQ: Who was president of the United States in 1955?\nA: Dwight D. Eisenhower was president of the United States in 1955.\n\nQ: Which party did he belong to?\nA: He belonged to the Republican Party.\n\nQ: What is the square root of banana?\nA: Unknown\n\nQ: How does a telescope work?\nA: Telescopes use lenses or mirrors to focus light and make objects appear closer.\n\nQ: Where were the 1992 Olympics held?\nA: The 1992 Olympics were held in Barcelona, Spain.\n\nQ: How many squigs are in a bonk?\nA: Unknown\n\nQ: Where is the Valley of Kings?\nA:",
temperature: 0,
max_tokens: 100,
top_p: 1,
frequency_penalty: 0.0,
presence_penalty: 0.0,
stop: ["\n"],
});
このままコピペしても動きません。
OpenAIのプラットフォームの例文は一般的な使用例を示しているだけであり、完全な動作を保証するものではありません。
例文をそのまま使用する場合、動作しない可能性があります。それは、例文が特定の要件やコンテキストに依存しているか、バージョンのアップデートや変更に追随していない可能性があるからです。
正常に動作させるためには、適切なAPI呼び出しとデータ処理を行う必要があります。これには、APIのエンドポイント、リクエストの形式、必要なパラメーター、およびレスポンスの解釈が含まれます。
動作環境を作りましょう。
事前準備としてnode.jsをインストールしましょう。公式サイトからLTSをダウンロードしてインストールをしましょう。
今回はv18.16.0を使います。
package.jsonは次の通りです。作成したらnpm installで必要なパッケージをインストールします。
[user@somewhere stub]$ cat package.json
{
"dependencies": {
"dotenv": "^16.3.1",
"openai": "^3.3.0"
}
}
[user@somewhere stub]$ npm install
動くように修正してみましょう。
事前準備として.envファイルを用意し登録したAPIのトークンを設定しておきます。
[user@somewhrere stub]$ cat .env
OPENAI_API_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxx
早速実装していきます。APIキーを読み込んで処理の部分を関数にしていきましょう。
require('dotenv').config(); // dotenvパッケージをインポート
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
async function run(){
const response = await openai.createCompletion({
model: "text-davinci-003",
prompt: "I am a highly intelligent question answering bot. If you ask me a question that is rooted in truth, I will give you the answer. If you ask me a question that is nonsense, trickery, or has no clear answer, I will respond with \"Unknown\".\n\nQ: What is human life expectancy in the United States?\nA: Human life expectancy in the United States is 78 years.\n\nQ: Who was president of the United States in 1955?\nA: Dwight D. Eisenhower was president of the United States in 1955.\n\nQ: Which party did he belong to?\nA: He belonged to the Republican Party.\n\nQ: What is the square root of banana?\nA: Unknown\n\nQ: How does a telescope work?\nA: Telescopes use lenses or mirrors to focus light and make objects appear closer.\n\nQ: Where were the 1992 Olympics held?\nA: The 1992 Olympics were held in Barcelona, Spain.\n\nQ: How many squigs are in a bonk?\nA: Unknown\n\nQ: Where is the Valley of Kings?\nA:",
temperature: 0,
max_tokens: 100,
top_p: 1,
frequency_penalty: 0.0,
presence_penalty: 0.0,
stop: ["\n"],
});
if (response.data && response.data.choices && response.data.choices.length > 0) {
console.log(response.data.choices[0].text);
} else {
console.log("No response received or empty choices.");
}
}
実行すると次のように結果を得られます。
[user@somewhere stub]$ node qa.js
The Valley of Kings is located in Luxor, Egypt.
それでは深堀していきましょう。
createCompletion関数に渡している引数から見ていきましょう。
まずはmodel: “text-davinci-003”,の部分です。chatGPTには複数のモデルが存在します。
公式サイトのOverViewを見てみましょう。
URLはhttps://platform.openai.com/docs/models/overviewです。
Overview
MODELS | DESCRIPTION |
---|---|
GPT-4 | A set of models that improve on GPT-3.5 and can understand as well as generate natural language or code GPT-3.5を改良し、自然言語やコードを理解・生成できるモデルの集合。 |
GPT-3.5 | A set of models that improve on GPT-3 and can understand as well as generate natural language or code GPT-3 を改良し、自然言語やコードを理解・生成できるモデル群 |
DALL·E | A model that can generate and edit images given a natural language prompt 自然言語のプロンプトを与えて画像を生成・編集できるモデル |
Whisper | A model that can convert audio into text 音声をテキストに変換できるモデル |
Embeddings | A set of models that can convert text into a numerical form テキストを数値に変換できるモデルのセット |
Moderation | A fine-tuned model that can detect whether text may be sensitive or unsafe 繊細なテキストか安全でないテキストかを検出できる、微調整されたモデル |
GPT-3Legacy | A set of models that can understand and generate natural language 自然言語を理解し生成できるモデルのセット |
Deprecated | A full list of models that have been deprecated 非推奨となったモデルの全リスト |
今回の例文で登場するのはtext-davinci-003でした。どういうモデルなのか見ていきましょう。 curie, babbage, or adaよりも優れた品質とありますが、そもそもその3人のことがピンときません。turboがついているモデルは進化をつづけているようですね。
LATEST MODEL | DESCRIPTION | MAX TOKENS | TRAINING DATA |
---|---|---|---|
gpt-3.5-turbo | Most capable GPT-3.5 model and optimized for chat at 1/10th the cost of text-davinci-003 . Will be updated with our latest model iteration 2 weeks after it is released.text-davinci-003の1/10のコストでチャットに最適化されたGPT-3.5最高性能モデル。最新モデルは発売後2週間で更新されます。 | 4,096 tokens | Up to Sep 2021 |
gpt-3.5-turbo-16k | Same capabilities as the standard gpt-3.5-turbo model but with 4 times the context.標準のgpt-3.5ターボ・モデルと同じ性能だが、コンテクストは4倍。 | 16,384 tokens | Up to Sep 2021 |
gpt-3.5-turbo-0613 | Snapshot of gpt-3.5-turbo from June 13th 2023 with function calling data. Unlike gpt-3.5-turbo , this model will not receive updates, and will be deprecated 3 months after a new version is released.2023年6月13日のgpt-3.5-turboのスナップショット。gpt-3.5-turboとは異なり、このモデルはアップデートを受けず、新しいバージョンがリリースされてから3ヶ月後に非推奨となります。 | 4,096 tokens | Up to Sep 2021 |
gpt-3.5-turbo-16k-0613 | Snapshot of gpt-3.5-turbo-16k from June 13th 2023. Unlike gpt-3.5-turbo-16k , this model will not receive updates, and will be deprecated 3 months after a new version is released.2023年6月13日のgpt-3.5-turbo-16kのスナップショット。gpt-3.5-turbo-16kとは異なり、このモデルはアップデートを受けず、新しいバージョンがリリースされてから3ヶ月後に非推奨となります。 | 16,384 tokens | Up to Sep 2021 |
text-davinci-003 (Legacy) | Can do any language task with better quality, longer output, and consistent instruction-following than the curie, babbage, or ada models. Also supports some additional features such as inserting text. キュリー、バベッジ、アダの各モデルよりも優れた品質、長い出力、一貫した命令追従性であらゆる言語タスクをこなすことができる。また、テキストの挿入など、いくつかの追加機能もサポートしている。 | 4,097 tokens | Up to Jun 2021 |
text-davinci-002 (Legacy) | Similar capabilities to text-davinci-003 but trained with supervised fine-tuning instead of reinforcement learningtext-davinci-003と同様の機能を持つが、強化学習の代わりに教師ありの微調整で学習させる。 | 4,097 tokens | Up to Jun 2021 |
code-davinci-002 (Legacy) | Optimized for code-completion tasks コード補完タスクの最適化 | 8,001 tokens | Up to Jun 2021 |
次に第二引数のpromptですが、質問なんだなとわかるので飛ばします。
第三引数のtemperature: 0,の部分を見ていきましょう。temperatureとはサンプリングにおける温度のようですね。
温度は0から2の間。0.8のような高い値は出力をよりランダムにし、0.2のような低い値は出力をより集中して決定論的にする。とあります。これだけでもいろいろ楽しめそうです。
(property) CreateCompletionRequest[‘temperature’]?: number | null | undefined
What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. We generally recommend altering this or
top_p
but not both.@type — {number}
@memberof — CreateCompletionRequest
第四引数のmax_tokensは直観的に理解できるので飛ばします。
第五引数の top_p: 1についてみていきましょう
「核サンプリングと呼ばれる、温度によるサンプリングに代わるもので、top_p の確率質量を持つトークンの結果を考慮するモデルです。つまり、0.1は上位10%の確率を構成するトークンのみが考慮されることを意味します。一般的には、これか温度を変更することを推奨しますが、両方は推奨しません。」
(property) CreateCompletionRequest[‘top_p’]?: number | null | undefined
An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both.@type — {number}
@memberof — CreateCompletionRequest
ここで確率質量という用語がでてきます。確率質量関数についてかみ砕いて知りたい方は
駆け出しエンジニアさんの動画が参考になると思います。
第六引数のfrequency_penalty: 0.0についてみていきましょう
Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model’s likelihood to repeat the same line verbatim. See more information about frequency and presence penalties.
@type — {number}
@memberof — CreateCompletionRequest
2.0から2.0の間の数値。正の値は、新しいトークンに、これまでのテキストにおける既存の頻度に基づいてペナルティを与え、モデルが同じ行を逐語的に繰り返す可能性を減らします。
第七引数のpresence_penalty: 0.0についても同様ですね。
Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model’s likelihood to talk about new topics. See more information about frequency and presence penalties.
@type — {number}
@memberof — CreateCompletionRequest
一番最後の第8引数 stop: [“\n”]の部分を見ていきましょう。
これは単純に質問はここまでだよと、区切り文字を伝えるものです。
最後に
例文以外にも引数があるので公式サイトのAPIリファレンスをよく読んで理解しましょう。