Discover how to integrate Lovable with OpenAI GPT easily. Follow our step-by-step guide with code examples and best practices for shaping next-level AI interactions.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
openaiService.ts
. This file will hold the TypeScript code for communicating with the OpenAI API.openaiService.ts
:
export interface ChatMessage {
role: "system" | "user" | "assistant";
content: string;
}
export async function callOpenAIGPT(messages: ChatMessage[], apiKey: string): Promise {
const response = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": Bearer ${apiKey}
},
body: JSON.stringify({
model: "gpt-3.5-turbo",
messages,
}),
});
if (!response.ok) {
throw new Error(OpenAI API returned an error: ${response.statusText});
}
return await response.json();
}
callOpenAIGPT
, that sends a POST request to the OpenAI API using the built-in fetch API.
openaiService.ts
by adding the following code at the top:
import { callOpenAIGPT, ChatMessage } from "./openaiService";
YOUROPENAIAPI_KEY
with your actual OpenAI API key.
const apiKey = "YOUROPENAIAPI_KEY"; // Insert your OpenAI API key here
async function sendMessageToGPT() {
const messages: ChatMessage[] = [
{ role: "system", content: "You are an assistant that helps with coding." },
{ role: "user", content: "How do I integrate GPT with my project?" }
];
try {
const result = await callOpenAIGPT(messages, apiKey);
console.log("GPT response:", result);
} catch (error) {
console.error("Error calling GPT:", error);
}
}
// Trigger the function when needed (e.g., on page load or via a button click)
sendMessageToGPT();
callOpenAIGPT
function.
"./openaiService"
in your main file should correctly point to the location of the openaiService.ts
file.YOUROPENAIAPI_KEY
within the code with your actual OpenAI API key.sendMessageToGPT
is called. Open your browser’s console to view the output or any error messages.When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.