我有 Azure 开放 AI 资源。我想根据用户输入创建一个简单的标题。例如,当用户输入
[
{
"type": "Group",
"source": "<group-id>"
}
]
它应该生成一个标题“All Users in ”。此外,它应该进行图形调用
https://graph.microsoft.com/v1.0/groups/<group-id>
并在标题中包含组名称,以便最终输出将是“All Users in ”。
我创建了以下代码:
.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';
}
};
标题生成器.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;
运行此程序时,我看到错误:
{
"statusCode": 401,
"message": "Unauthorized. Access token is missing, invalid, audience is incorrect (https://cognitiveservices.azure.com), or have expired."
}
我已提供 REACT_APP_OPENAI_API_KEY 和 REACT_APP_OPENAI_API_ENDPOINT。
我错过了什么?
azure openai 使用 apikey,所以这个标头不正确
Authorization: Bearer ${openaiApiKey}
,应该只是 api-key: xxxx
尝试下面的curl示例进行测试,然后你可以调整你的代码
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
}'