Azure OpenAI API not working in React app, but working in Python script

68 Views Asked by At

I have the following React code, which throws the error code: "Unauthorized. Access token is missing, invalid, audience is incorrect (https://cognitiveservices.azure.com), or have expired."

 import React, { useEffect } from 'react';

const AzureOpenAIComponent: React.FC = () => {
  useEffect(() => {
    const fetchCompletion = async () => {
      // const azureEndpoint = process.env.REACT_APP_AZURE_OPENAI_ENDPOINT; // Ensure to set this in your .env file
      const apiKey = process.env.REACT_APP_AZURE_OPENAI_KEY; // Ensure to set this in your .env file
      const azureEndpoint = "https://openai-testbench.openai.azure.com/";
      const apiVersion = "2023-05-15";
      const url = `${azureEndpoint}openai/deployments/gpt-35-turbo/completions?api-version=${apiVersion}`;

       //const url = "https://openai-testbench.openai.azure.com/openai/deployments/gpt-35-turbo/completions?api-version=2023-05-15";
      const requestBody = {
        model: "gpt-35-turbo",
        messages: [
          { role: "system", content: "Assistant is a large language model trained by OpenAI." },
          { role: "user", content: "Who were the founders of Microsoft?" }
        ],
      };

      try {
        const response = await fetch(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${apiKey}`,
          },
          body: JSON.stringify(requestBody),
        });

        if (!response.ok) {
          throw new Error('Network response was not ok');
        }

        const data = await response.json();
        console.log(data);
      } catch (error) {
        console.error('Error fetching data: ', error);
      }
    };

    fetchCompletion();
  }, []);

  return ( <>
    <div>Check the console for the response.</div>
  </>);
  
};

export default AzureOpenAIComponent;

But if I try to call the same EP in a Python script the request works as expected.

import os
from openai import AzureOpenAI

client = AzureOpenAI(api_version="2023-05-15",
azure_endpoint="https://openai-testbench.openai.azure.com/",
api_key="my_token_goes_here_but_i_removed_it")

# Set Azure OpenAI credentials
# openai.api_base = os.getenv("AZURE_OPENAI_ENDPOINT")  # Your Azure OpenAI resource's endpoint value
# openai.api_key = os.getenv("AZURE_OPENAI_KEY")

# Create a chat conversation
response = client.chat.completions.create(model="gpt-35-turbo",  # Choose the deployment name for GPT-3.5-Turbo or GPT-4
messages=[
    {"role": "system", "content": "Assistant is a large language model trained by OpenAI."},
    {"role": "user", "content": "Who were the founders of Microsoft?"}
])

# Print the response
print(response)

And yes, the environment variables are being set; I've checked using console.log, and I can see that the apiKey is the correct one, but still, it doesn't work.

1

There are 1 best solutions below

0
Dasari Kamali On

I provided the API key as 'api-key': apiKey in the headers and returned the message in the div in the React TypeScript code below, which ran successfully.

Go to your OpenAI deployment model > Open in Playground > View code, select curl, and copy your endpoint. Replace it in the provided code as shown below.

enter image description here

Code :

AzureOpenAIComponent.tsx :

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

const AzureOpenAIComponent: React.FC = () => {
  const [messageContent, setMessageContent] = useState<string>('');

  useEffect(() => {
    const fetchCompletion = async () => {
      const apiKey = "<API_key>";
      const url = `https://<openai_name>.openai.azure.com/openai/deployments/<deployment_name>/chat/completions?api-version=2024-02-15-preview`; // Replace your api-verion also

      const requestBody = {
        messages: [
          { role: "system", content: "Assistant is a large language model trained by OpenAI." },
          { role: "user", content: "Who were the founders of Microsoft?" }
        ],
      };

      try {
        const response = await fetch(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'api-key': apiKey,
          },
          body: JSON.stringify(requestBody),
        });

        if (!response.ok) {
          throw new Error('Network response was not ok');
        }

        const data = await response.json();
        if (data && data.choices && data.choices.length > 0 && data.choices[0].message && data.choices[0].message.content) {
          setMessageContent(data.choices[0].message.content);
        } else {
          setMessageContent('No message found');
        }
      } catch (error) {
        console.error('Error fetching data: ', error);
      }
    };

    fetchCompletion();
  }, []);

  return (
    <div>
      <p>Message Content:</p>
      <div>{messageContent}</div>
    </div>
  );
};
export default AzureOpenAIComponent;

Output :

The following code ran successfully:

enter image description here

Browser Output :

Below is the output OpenAI message response for the React application that appeared in the browser.

enter image description here