reactjstypescriptazure-openai

Unable to create title based on user input using Azure OpenAI


I have Azure Open AI resource. I want to create a simple title based on a user input. For example, when the user inputs

[
    {
        "type": "Group",
        "source": "<group-id>"
    }
]

it should generate a title 'All Users in ''. Additionally, it should make a graph call https://graph.microsoft.com/v1.0/groups/<group-id> and include the group name in the title so the final output will be 'All Users in ''.

I have created the following code:

.env

REACT_APP_OPENAI_API_KEY=
REACT_APP_OPENAI_API_ENDPOINT=

openai.ts

import axios from 'axios';

const openaiApiKey = process.env.REACT_APP_OPENAI_API_KEY;
const openaiApiEndpoint = process.env.REACT_APP_OPENAI_API_ENDPOINT;

const openaiApiUrl = `${openaiApiEndpoint}/openai/deployments/gpt-4o/chat/completions?api-version=2024-08-01-preview`;

interface OpenAIResponse {
  choices: { text: string }[];
}

export const generateTitle = async (groupName: string): Promise<string> => {
  const prompt = `Generate a title for a group with the name: '${groupName}'. The title should be in the format: 'All users in <group-name>'.`;

  try {
    const response = await axios.post<OpenAIResponse>(
      openaiApiUrl,
      {
        prompt: prompt,
        max_tokens: 60,
        temperature: 0.7
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${openaiApiKey}`
        }
      }
    );

    return response.data.choices[0].text.trim();
  } catch (error) {
    console.error('Error calling OpenAI API:', error);
    return 'Error generating title';
  }
};

TitleGenerator.tsx

import React, { useState } from 'react';
import { generateTitle } from '../apis/openai';

const TitleGenerator: React.FC = () => {
  const [groupName, setGroupName] = useState<string>('');
  const [title, setTitle] = useState<string>('');
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<string>('');

  const handleGenerateTitle = async () => {
    if (!groupName) {
      setError('Please enter a group name.');
      return;
    }

    setLoading(true);
    setError('');
    
    try {
      const generatedTitle = await generateTitle(groupName);
      setTitle(generatedTitle);
    } catch (err) {
      setError('An error occurred while generating the title.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <h1>Title Generator</h1>
      <input
        type="text"
        value={groupName}
        onChange={(e) => setGroupName(e.target.value)}
        placeholder="Enter group name"
      />
      <button onClick={handleGenerateTitle} disabled={loading}>
        {loading ? 'Generating...' : 'Generate Title'}
      </button>
      {error && <p style={{ color: 'red' }}>{error}</p>}
      {title && <h2>{title}</h2>}
    </div>
  );
};

export default TitleGenerator;

On running this, I see the error:

{
    "statusCode": 401,
    "message": "Unauthorized. Access token is missing, invalid, audience is incorrect (https://cognitiveservices.azure.com), or have expired."
}

I have provided the REACT_APP_OPENAI_API_KEY & REACT_APP_OPENAI_API_ENDPOINT.

enter image description here

What am I missing?


Solution

  • azure openai uses apikey, so this header is incorrect Authorization: Bearer ${openaiApiKey}, should be just api-key: xxxx

    try out below curl example for a test, then you can adjust your code

    curl -i --location 'https://xxxxx.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2024-08-01-preview' \
    --header 'Content-Type: application/json' \
    --header 'api-key: xxxxxxx' \
    --data '{
        "messages": [
            {
                "role": "system",
                "content": [
                    {
                        "type": "text",
                        "text": "You are a helpful assistant who talks like a pirate."
                    }
                ]
            },
            {
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        "text": "Good day, who am I talking to?"
                    }
                ]
            },
            {
                "role": "assistant",
                "content": [
                    {
                        "type": "text",
                        "text": "Ahoy there, matey! What be bringin ye to these waters today? "
                    }
                ]
            }
        ],
        "temperature": 0.7,
        "top_p": 0.95,
        "max_tokens": 800
    }'