Hey guys!
I'm having trouble setting up the API with the 3.5 turbo model and I can't seem figure it out in the docs.
I'm trying to set it up to where you type into the input and then there's a div with a response.
I'm using Next.js / React and I'm still new to next and API's here is what I have.
index.tsx
import styles from './chatgpt.module.css';
import React from 'react';
const ENDPOINT = `https://api.openai.com/v1/chat/completions`;
export default function ChatGPT() {
const [input, setInput] = React.useState('');
const [status, setStatus] = React.useState('idle');
async function handleSubmit(event: React.ChangeEvent) {
event.preventDefault();
setStatus('loading');
const response = await fetch(ENDPOINT, {
method: 'POST',
body: JSON.stringify({}),
});
const json = await response.json();
}
return (
<main className={styles.main}>
<form onSubmit={handleSubmit}>
<div className={styles.heading}>Enter an input</div>
<input
type="text"
className={styles.input}
value={input}
onChange={(e) => {
setInput(e.target.value);
console.log(e.target.value);
}}
/>
<button className={styles.button}>Submit</button>
{status === 'success' && <div>{response}</div>}
</form>
</main>
);
}
openai.ts
import { Configuration, OpenAIApi } from 'openai';
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const completion = await openai.createChatCompletion({
model: 'gpt-3.5-turbo',
messages: [{ role: 'user', content: 'Hello world' }],
});
console.log(completion?.data?.choices[0]?.message);