getting-started installation chatgpt
Overview
This guide will walk you through integrating the OpenAI API into a Next.js application. We will cover the setup process, installing the necessary packages, configuring the environment, and creating a simple API route to communicate with OpenAI.
Prerequisites
Before proceeding with the setup, ensure you have the following:
- Node.js installed
- A Next.js application set up
- Basic knowledge of using environment variables
- An OpenAI API key (You can get it from OpenAI)
Important:
Ensure your OpenAI API key is kept private and never exposed in the frontend code.
Step 1: Install OpenAI Node.js Package
First, install the openai
package from npm.
npm install openai
Step 2: Setup Environment Variables
Create a .env.local
file at the root of your project (if it doesn’t already exist) and add your OpenAI API key:
NEXT_PUBLIC_OPENAI_API_KEY=your-openai-api-key-here
Security Tip:
Do not commit your .env.local
file to version control (e.g., Git). Add it to your .gitignore
.
Step 3: Create API Route
Next, create an API route in your Next.js app to interact with the OpenAI API. Create a file at pages/api/openai.js
with the following code:
import { Configuration, OpenAIApi } from "openai";
const configuration = new Configuration({
apiKey: process.env.NEXT_PUBLIC_OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
export default async function handler(req, res) {
if (req.method !== "POST") {
return res.status(405).json({ message: "Only POST requests are allowed" });
}
const { prompt } = req.body;
if (!prompt) {
return res.status(400).json({ message: "Prompt is required" });
}
try {
const response = await openai.createCompletion({
model: "text-davinci-003",
prompt,
max_tokens: 100,
});
return res.status(200).json({ result: response.data.choices[0].text });
} catch (error) {
return res.status(500).json({ message: "Error with OpenAI API" });
}
}
Step 4: Create Frontend Form
Now, create a simple frontend form to interact with the API route you created. Inside your pages/index.js
, add the following code:
import { useState } from "react";
export default function Home() {
const [prompt, setPrompt] = useState("");
const [result, setResult] = useState("");
async function handleSubmit(e) {
e.preventDefault();
const res = await fetch("/api/openai", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ prompt }),
});
const data = await res.json();
setResult(data.result);
}
return (
<div>
<h1>OpenAI Text Generation</h1>
<form onSubmit={handleSubmit}>
<input
type="text"
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
placeholder="Enter a prompt"
/>
<button type="submit">Submit</button>
</form>
<p>Result: {result}</p>
</div>
);
}
Step 5: Run Your Application
After completing the steps above, run your Next.js application:
npm run dev
# or
yarn dev
Your app should now have a form that allows you to input a prompt and receive a response from OpenAI’s API.
Additional Resources
For more details, refer to the official OpenAI Documentation.
getting-started installation chatgpt
Overview
This guide will walk you through integrating the OpenAI API into a Next.js application. We will cover the setup process, installing the necessary packages, configuring the environment, and creating a simple API route to communicate with OpenAI.
Prerequisites
Before proceeding with the setup, ensure you have the following:
- Node.js installed
- A Next.js application set up
- Basic knowledge of using environment variables
- An OpenAI API key (You can get it from OpenAI)
Important:
Ensure your OpenAI API key is kept private and never exposed in the frontend code.
Step 1: Install OpenAI Node.js Package
First, install the openai
package from npm.
npm install openai
Step 2: Setup Environment Variables
Create a .env.local
file at the root of your project (if it doesn’t already exist) and add your OpenAI API key:
NEXT_PUBLIC_OPENAI_API_KEY=your-openai-api-key-here
Security Tip:
Do not commit your .env.local
file to version control (e.g., Git). Add it to your .gitignore
.
Step 3: Create API Route
Next, create an API route in your Next.js app to interact with the OpenAI API. Create a file at pages/api/openai.js
with the following code:
import { Configuration, OpenAIApi } from "openai";
const configuration = new Configuration({
apiKey: process.env.NEXT_PUBLIC_OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
export default async function handler(req, res) {
if (req.method !== "POST") {
return res.status(405).json({ message: "Only POST requests are allowed" });
}
const { prompt } = req.body;
if (!prompt) {
return res.status(400).json({ message: "Prompt is required" });
}
try {
const response = await openai.createCompletion({
model: "text-davinci-003",
prompt,
max_tokens: 100,
});
return res.status(200).json({ result: response.data.choices[0].text });
} catch (error) {
return res.status(500).json({ message: "Error with OpenAI API" });
}
}
Step 4: Create Frontend Form
Now, create a simple frontend form to interact with the API route you created. Inside your pages/index.js
, add the following code:
import { useState } from "react";
export default function Home() {
const [prompt, setPrompt] = useState("");
const [result, setResult] = useState("");
async function handleSubmit(e) {
e.preventDefault();
const res = await fetch("/api/openai", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ prompt }),
});
const data = await res.json();
setResult(data.result);
}
return (
<div>
<h1>OpenAI Text Generation</h1>
<form onSubmit={handleSubmit}>
<input
type="text"
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
placeholder="Enter a prompt"
/>
<button type="submit">Submit</button>
</form>
<p>Result: {result}</p>
</div>
);
}
Step 5: Run Your Application
After completing the steps above, run your Next.js application:
npm run dev
# or
yarn dev
Your app should now have a form that allows you to input a prompt and receive a response from OpenAI’s API.
Additional Resources
For more details, refer to the official OpenAI Documentation.