How to Integrate OpenAI APIs into JavaScript Applications


Introduction to OpenAI and its capabilities

OpenAI is an AI research and deployment company. Our mission is to ensure that artificial general intelligence benefits all of humanity. We’ve trained a model called ChatGPT which interacts in a conversational way. The dialogue format makes it possible for ChatGPT to answer followup questions, admit its mistakes, challenge incorrect premises, and reject inappropriate requests. ChatGPT is trained to follow an instruction in a prompt and provide a detailed response. Try it now at chatgpt.com

  • Client Side ( React.js )
  • Server Side ( Node.js )
Prerequisites
  • Basic knowledge of JavaScript and React, and Node.js
  • Node.js installed on your machine
  • OpenAI API key

Implement OpenAI API on the Client Side (React.js)

You have integrated OpenAI’s API into your React application. This allows you to send queries to OpenAI’s models and display the responses dynamically. You can further enhance this setup by adding more features and error handling as needed.

import React, { useState } from 'react';
import axios from 'axios';

function OpenAiIntegration() {
const [search, setSearch] = useState("");
const [openAiResponse, setOpenAiResponse] = useState("");
const [loading, setLoading] = useState(false);

const handleSearchClick = () => {
setLoading(true);

const data = JSON.stringify({
  model: "gpt-3.5-turbo",
  messages: [
    {
      role: "user",
      content: search,
    },
  ],
  temperature: 0.7,
});

const config = {
  method: "post",
  url: `${process.env.REACT_APP_OPEN_AI_BASE_URL}/v1/chat/completions`,
  headers: {
    "Content-Type": "application/json",
    Authorization: `Bearer YOUR_OPENAI_API_KEY`,
  },
  data: data,
};

axios.request(config)
  .then((response) => {
    const content = response.data.choices[0].message.content;
    setOpenAiResponse(content);
    setLoading(false);
  })
  .catch((error) => {
    console.error("Error making API call:", error);
    setLoading(false);
  });
};

return (
 <div className="openai-integration">
      <input
        type="text"
        value={search}
        onChange={(e) => setSearch(e.target.value)}
        placeholder="Enter your query"
      />
      <button onClick={handleSearchClick}>Search</button>  
{loading && <p>Loading...</p>}
  {openAiResponse && <div><h3>Response:</h3><p>{openAiResponse}</p></div>}
</div>
);
}

export default OpenAiIntegration;
Additional Resources

Implement OpenAI API on the Server Side (Node.js)

How to integrate OpenAI’s API into a Node.js server application using Express. By following this approach, you can build powerful applications that leverage the capabilities of advanced language models.

import { Request, Response, RequestHandler } from 'express';
import openai from 'openai';

export const askLLM: RequestHandler = async (req: Request, res: Response) => {
  try {
    const { userPrompt, llmModel = "gpt-4o" } = req.body;
    const streamResponse =
      (req.query?.stream || "false") === "true" ? true : false;

    if (!req.session?.messages) {
      req.session.messages = [{ role: "user", content: userPrompt }];
    } else {
      // Add user message to session
      req.session.messages.push({ role: "user", content: userPrompt });
    }

    // Get response from OpenAI
    const chatConfig: any = {
      model: llmModel,
      messages: req.session.messages,
      stream: streamResponse,
      temperature: 0.7,
    };

    const response: any = await openai.chat.completions.create(chatConfig);

    if (streamResponse) {
      res.setHeader("Content-Type", "text/html");
      for await (const chunk of response) {
        res.write(chunk.choices[0]?.delta?.content || "");
      }
      res.end();
    } else {
      // JSON response
      const result = response.choices[0].message.content;
      res.status(200).send({
        success: true,
        data: result,
      });
    }
  } catch (err: any) {
    res.status(500).json({ success: false, message: `${err?.message}` });
  }
};
Additional Resources

You may also like

Leave a Reply