如何配置Azure OpenAI Service在API调用中自动使用默认系统消息?
Azure OpenAI Service 默认系统消息API调用配置方案
明确限制:Azure OpenAI Studio中设置的默认系统消息、示例对话仅适用于Studio内部的测试场景,API调用时不会自动加载这些配置,必须在请求体中显式传入相关内容。
实现自动复用Studio配置的两种可行方案:
通过Azure OpenAI管理API读取部署配置
- 调用Azure管理API获取目标部署的系统提示和示例对话,在React组件的API请求逻辑中自动注入这些内容,无需手动编写。
- React中简化实现代码:
// 获取默认系统提示 async function getDefaultSystemPrompt(deploymentId) { const response = await fetch(`https://management.azure.com/subscriptions/{你的订阅ID}/resourceGroups/{资源组}/providers/Microsoft.CognitiveServices/accounts/{AOAI账户名}/deployments/${deploymentId}?api-version=2024-04-01-preview`, { method: 'GET', headers: { 'Authorization': `Bearer ${你的Azure AD令牌}` } }); const deployment = await response.json(); return deployment.properties.systemPrompt; // 需根据实际返回结构调整字段 } // 调用聊天API时注入系统提示 async function sendChatMessage(userMessage) { const systemPrompt = await getDefaultSystemPrompt('你的部署ID'); const chatResponse = await fetch(`https://{AOAI账户名}.openai.azure.com/openai/deployments/{部署ID}/chat/completions?api-version=2024-02-15-preview`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'api-key': `{你的API密钥}` }, body: JSON.stringify({ messages: [ { role: 'system', content: systemPrompt }, { role: 'user', content: userMessage } ] }) }); return chatResponse.json(); } - 注意:管理API调用需要Azure AD权限(如Cognitive Services Contributor),需通过后端服务处理权限验证,避免前端暴露敏感令牌。
使用Azure App Configuration存储配置
- 在Azure App Configuration中创建键值对保存系统消息和示例对话,团队成员可直接通过Azure门户修改这些配置。
- React组件在初始化或每次API调用前,从App Configuration读取最新配置,再传入聊天API的请求体中。
- 优势:无需依赖管理API权限,配置修改更直观,适合非技术团队成员操作。
额外提示:无论采用哪种方案,都需确保配置修改后,React应用能及时获取最新值(可通过配置缓存策略或监听配置变更实现)。
内容的提问来源于stack exchange,提问作者kalbsschnitzel
相关产品推荐
相关产品推荐

