Search code examples
google-chrome-extensionchatbotopenai-api

How can I call the chatgpt api in Google Chrome Extension?


I want to make a chrome extension that can call chatgpt api. But I haven't seen openai open the api.

I see that the corresponding chrome extension implements such technology, such as this blog https://www.extspy.com/blog/List-of-10-Best-Chatgpt-Chrome-Extensions-for-2023

Can anyone tell me how to do it?


Solution

  • Use the fetch API to send a request to the OpenAI API.

    You will need to signup for an API key with OpenAI first: https://openai.com/api/

    To send a question to GPT you would make the following Fetch API call.

    const response = await fetch('https://api.openai.com/v1/completions', {
      method: 'POST',
      headers: {
        'Content-Type: application/json',
        'Authorization: Bearer YOUR_API_KEY'
      },
      body: {
        model: 'text-davinci-003',
        prompt: 'How do I make an API call to OpenAI inside a Chrome Extension?',
        max_tokens: 2000
      }
    })
    
    console.log(response.data.choices[0].text)
    

    Ref: https://platform.openai.com/docs/api-reference/completions