Learn how to integrate Bolt.new AI with OpenAI GPT with our step-by-step guide. Discover tips, best practices, and expert insights to boost your AI projects.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
index.ts
) to set up the variable. Replace YOUROPENAIAPI_KEY
with your actual key:
process.env.OPENAIAPIKEY = "YOUROPENAIAPI_KEY";
gpt.ts
in your project. This file will contain the TypeScript function that calls the OpenAI GPT API.gpt.ts
:
const openaiApiKey = process.env.OPENAIAPIKEY;
export async function getGPTResponse(prompt: string): Promise {
const endpoint = "https://api.openai.com/v1/chat/completions";
const headers = {
"Content-Type": "application/json",
"Authorization": Bearer ${openaiApiKey}
};
const body = {
model: "gpt-3.5-turbo",
messages: [{ role: "user", content: prompt }],
temperature: 0.7
};
try {
const response = await fetch(endpoint, {
method: "POST",
headers,
body: JSON.stringify(body)
});
if (!response.ok) {
throw new Error(Error ${response.status}: ${response.statusText});
}
const data = await response.json();
return data.choices[0].message.content;
} catch (error) {
console.error("Error fetching GPT response:", error);
return "";
}
}
gpt.ts
to import the fetch polyfill:
import fetch from "node-fetch";
index.ts
), import the function from gpt.ts
by adding the following line near the top:
import { getGPTResponse } from "./gpt";
async function handleUserPrompt(userPrompt: string) {
const gptResponse = await getGPTResponse(userPrompt);
console.log("GPT response:", gptResponse);
// Further process the response or display it in your UI
}
handleUserPrompt("Your prompt text here")
from the appropriate part of your application to trigger the integration.
handleUserPrompt
function within your application to test if the GPT API responds correctly. Check the console log output for the response from GPT.
node-fetch
for older Node versions), follow Bolt.new AI’s instructions for adding dependencies via code comments or project settings since the platform does not support a command-line interface.When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.