Skip to content

Instantly share code, notes, and snippets.

@safa-dayo
Created March 7, 2023 12:22
Show Gist options
  • Save safa-dayo/ed9b16839d425487a1c2f9c7b2176d36 to your computer and use it in GitHub Desktop.
Save safa-dayo/ed9b16839d425487a1c2f9c7b2176d36 to your computer and use it in GitHub Desktop.
YouTube動画『ChatGPT APIを使ってWeb上でチャットできるようにしよう! (Next.js利用)』で作成したソースコードとなります。
import { ChangeEvent, useRef, useState } from 'react';
import Head from 'next/head'
import styles from '@/styles/Home.module.css'
// ChatGPT APIとのやり取りに利用
const messages: Array<any> = [];
export default function Home() {
// 入力用
const [inputValue, setInputValue] = useState('');
// 初回実行時かどうかを判定するために利用
const isFirstTime = useRef(true);
const handleInputChange = (value: string) => {
setInputValue(value);
}
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
// 初回実行時はチャットボットの定義のみを実施する
if (isFirstTime.current) {
messages.push({ role: 'system', content: inputValue });
isFirstTime.current = false;
setInputValue('');
return;
}
// 会話処理
messages.push({ role: 'user', content: inputValue });
// 環境変数からAPIキーを読み取る
const apiKey = process.env.NEXT_PUBLIC_API_KEY;
const url = 'https://api.openai.com/v1/chat/completions';
// デバッグ用
// console.log('DEBUG:', messages);
// ChatGPT APIに送信
const res = await fetch(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: 'gpt-3.5-turbo',
messages,
})
});
const resJson = await res.json();
const message = resJson.choices[0].message;
// 回答内容をmessagesに追加して、前の会話内容を含めた上で会話できるようにしている
messages.push(message);
setInputValue('');
return;
}
return (
<>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<h1>ChatGPT APIサンプル</h1>
{isFirstTime.current && (
<div style={{ fontSize: 30 }}>どんなチャットボットとお話したいですか?人格を打ち込んでください。</div>
)}
{messages.length > 0 && messages.map((message, i) => {
const style: any = { fontSize: 30, width: '100%', textAlign: 'left' };
let name = "あなた:";
if (message.role === "assistant") {
name = "ChatGPT:";
} else if (message.role === "system") {
name = "ChatGPTの人格:"
}
return (
<div style={style} key={i}>{name}{message.content}</div>
)
})}
<form onSubmit={handleSubmit} style={{ width: '100%' }}>
<input type="text" value={inputValue} onChange={(e: ChangeEvent<HTMLInputElement>) => handleInputChange(e.target.value)} style={{ width: '100%', fontSize: 40 }} />
<button type="submit" style={{ "width": '100%', fontSize: 30 }}>送信</button>
</form>
</main>
</>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment