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_pbut 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リファレンスをよく読んで理解しましょう。
Checked out j888com recently. Nice layout, easy to find what you’re looking for. Customer service was responsive when I had a question. Thumbs up for that!
9dgame7, sounds pretty futuristic! Let’s see what kind of games they’ve got. Maybe I’ll find a new favorite. 9dgame7
Pk98game, yaar! A simple and entertaining option for some chill gaming time. Try it for something new and simple. pk98game.
Hey, dropping by to say I tested pak77game. Its fine! Give it a try, maybe you’ll like it! Visit pak77game!
Tried out mgpk777game last night. Not gonna lie, it’s pretty addictive. Decent graphics and easy enough to pick up. Might see you there! Hop on over to mgpk777game.
Curious about superph11 com? Check it out at superph11 com. Do your research!
Yo, anyone playing on trwin499? Is it legit? Check it out for yourselves trwin499.
Thinking about becoming an affiliate with Win777? The win777affiliate program looks promising. Worth checking out if you’re into that!
Alright, alright, pgasia777! Some people have been chatting about it. Looks like it’s got its fans, so it must have something going for it. Not my usual go-to, but I might give it a try based on the buzz. Check out pgasia777 and decide for yourself.
Loto288. I am feeling lucky, so give it a shot. Maybe, just maybe, your numbers come up! loto288. Could change your life!
I had a spin on Spark777game and it was OK. The games are bright and colourful and there are a few decent bonuses knocking about. Nothing outrageous, but decent enough. Give it a bash here spark777game.
vtxbGOkkKCFSQbdxq
Yo, is SlotVIPCasino worth the hype? I’m huntin’ for a new spot to spin some slots. Spill the tea, fam! slotvipcasino
Alright guys, giving idd88 a shoutout. Had a good time trying my luck. Bonuses were alright, and the customer service was surprisingly quick. Give it a shot and see what you think! Link right here: idd88
Downloaded the jq777apkdownload app. Install was smooth and the app works great on my phone. Easy to use and gets you right into the action. Get the download here: jq777apkdownload
ibTMcqWZVQLcgqrTMIHHQBm
Yo, anyone tried acesupercom yet? Kinda new to this but seems like a fun platform. Gonna give it a shot! Try your luck at acesupercom
Hey all! New here. Heard about betbbapp, gonna check it out. Fingers crossed for some wins! Check it out: betbbapp
Alright, jumping into cbet789. Hope its not another dud. Wish me well! See if you can strike gold here: cbet789
FaQsPhJPjYpIACfeyDghKGO
Yo, 119bets app is kinda neat! Easy to use, and makes placing bets on the go a breeze. Worth checking out for sure. Check it out here: 119bet app
Khelobet, huh? New to me, but always down to try new platforms. Hope the odds are sweet! Place your bets here: khelobet
Lucky Calico App? Okay, the name’s catchy! Let’s see if it lives up to the lucky part. Fingers crossed! Download it here: lucky calico app
KuMgnItxyAbPaJqUTcN
eHulpPYjjYvQPOMwTnZSojm
IkxUPfsRYpOizaTByMU
Looking to download Selcuksports? Heard it’s the way to go for streaming. Get that ‘selçuksports indir’ sorted and enjoy the game! selçuksports indir
Heard some buzz about dola789link and thought I’d check it out. Seems pretty legit, got a good vibe. Definitely worth a look! dola789link
Alright, alright, alright…luckywinplus! Gave it a spin and I gotta say, I’m impressed. Feels like I’ve found my new lucky spot. Check out luckywinplus!
Alright dudes, Jili77login’s the place to be, yeah? Super easy to get in and start playing. Good times all around! Check it: jili77login.
Jili88phcomapp rocks! Got the app on my phone and it’s smooth sailing. Plus, the games are actually pretty fun and pay out decent. Give it a shot! Here’s the link: jili88phcomapp.
OK9cassino, not gonna lie, it’s pretty sweet. Good selection of games and the website is clean. Thumbs up from me! You can find it here: ok9cassino.
Win88blueslot is calling my name! Those slots look tempting. Maybe today is my lucky day win88blueslot. Feeling lucky, are you?
32PHFun is legit! Always a good time, some laughs and maybe even a win or two. Give it a whirl you might just like it 32phfun.
Hey, I’ve been checking out bl5555 lately. Pretty straightforward. Easy to navigate, you know? I think it’s worth giving a shot. Check it out for yourself bl5555!
Easy access is important. I’m digging ssbetlogin. The login process is super smooth, and I never have any issues getting in. Time is of the essence! Check it out here ssbetlogin
ST666Press, huh? I heard some good things about it, finally decided to give it a try. I’m curious what it can offer. Goodluck to me st666press
I saw an advertisement about ST666Windsru on a social media post! I’m intrigued. Is it as good as it looks? Will someone vouch for it? Thinking of trying it soon st666windsru
Play99exch.win is where it’s at. Solid interface and keeps the action flowing, what more can I say. play99exch.win
Nustargame.com, right? I’ve seen it around, seems like a solid option. Might be worth checking out if you’re bored of the same old stuff: nustargame.com
Heard goldbet888casino.com is giving away goldbet free 50! Gonna try and snag it. Wish me luck guys! goldbet free 50
PAAEgVAawNZXFcPKAvGvy
Been playing on PHDream 88 and so far, so good! The games load fast and the payouts are on time. Plus, their customer service is actually helpful. My go-to for online gaming! Learn more here phdream 88.
Yo, just browsed through full 88. Seems like they’ve got a good thing going on. Worth a look if you’re bored. Here’s the link: full 88
Guys, bingoplus download straight from the source is the way to go. Safe and simple. Check it out on bingoplus download
1777sxgame is where the action is! It has a different vibe compared to the usual options. Highly recommended! 1777sxgame
1eegame definitely stands out. The login is straightforward, and I’ve had some enjoyable sessions. Give it a whirl! 1eegame
666casino is a solid choice if you’re looking for a casino experience. I’ve found it to be pretty reliable. Good for chilling and having some fun. 666casino
I like winbet777slot, the 777 makes it seem like there will be big winnings! Will it pay out? I need to check that. Hopefully the bonus rewards will be great. Let me know if it’s worth it! winbet777slot
Trying to find a hassle-free login? 888betslogin seems to do the trick! Quick and easy access, which is exactly what I need after a long day. Worth a visit if you’re tired of complicated logins. Give it a whirl at 888betslogin!
Bj99login. Not bad, not amazing, just… convenient. Gets the job done. Login is straightforward, which is always a plus in my book. Give it a shot if you need a quick fix at bj99login!
Want to find ‘playpix oficial’ without getting scammed? This is the real deal. Don’t risk clicking on dodgy ads, use this: playpix oficial
Keep seeing ‘iwn456’ mentioned alongside some gaming promotions. Is that just another name for Win456club or a different site entirely? Confused. iwn456
Yo, ketqua.net 9 is legit! If you’re looking for quick and accurate results, this is your spot. No messing around! Check it out here: ketqua.net 9
Alright, hopping into taya777pub. Let’s see if the rumors about big payouts are true! See if its right for you at taya777pub.
Downloading the Jio Lottery Game. Let’s try and get rich guys! Download at jio lottery game.
Alright alright, giving winbuzzregistration a shot. Registration was smooth, fingers crossed the rest is too! Get started: winbuzzregistration
Orionplaycasino is pretty cool. Smooth interface and some fun slots. Give ‘em a try, maybe you’ll get lucky. Check ‘em out at orionplaycasino
Playhay29 is what it is. Games are alright, nothing game-changing. But hey, a gamble’s a gamble. Give a spin on playhay29
Win3799… well, you can try to win, can’t you? Games are there, hope luck’s on your side. Go and try to win at win3799
Alright folks, let’s talk LuckyDayCasino. Tried it out last night and had a decent run. Nothing spectacular, but the slots were fun and the site was easy to navigate. Could use a few more table games though. Check it out yourself at luckydaycasino!
Anyadwinov? Never heard of it before. Looked like a solid spot. Games are fun, variety seems good, and the signup bonus got me going. See for yourself at anyadwinov. Good luck!
RummyGolds. I tried their rummy out and it’s a pretty smooth experience. If you’re into rummy, especially, then you gotta give them a peek. Click here to see your play rummygolds!