AsyncAzureOpenAI对接自定义FastAPI LLM端点遇404问题求解
问题解答
核心结论
可以通过base_url参数传入自定义端点,不要使用azure_endpoint——该参数是为Azure官方OpenAI服务设计的,会自动拼接Azure特有的路径前缀(如/openai/chat/completions)和api-version查询参数,导致与自定义端点不匹配。
问题根源分析
你当前把完整端点路径填到azure_endpoint中,客户端会在其基础上自动追加Azure规范的路径和api-version参数,最终请求路径变为:/v1/genai/models/deployments/gpt-4/chat/completions/openai/chat/completions?api-version=2024-06-01
这显然与你的FastAPI端点路径不符,因此返回404。
正确示例代码
基础版本(匹配自定义端点路径)
import asyncio from openai import AsyncAzureOpenAI LATEST_URL = "http://localhost:8080" model_id = "gpt-4" B2B_token = "xxxx" async def test_custom_endpoint(): client = AsyncAzureOpenAI( base_url=f"{LATEST_URL}/v1/genai/models/deployments/{model_id}", api_key=B2B_token, skip_api_version=True, # 禁用自动添加api-version参数 max_retries=0, ) response = await client.chat.completions.create( messages=[{"role": "user", "content": "Hi"}], model=model_id, max_tokens=50, temperature=0.7, timeout=30 ) print(response.choices[0].message.content) if __name__ == "__main__": asyncio.run(test_custom_endpoint())
该代码会生成正确的请求路径:http://localhost:8080/v1/genai/models/deployments/gpt-4/chat/completions,无额外拼接内容。
鉴权适配版本(如果端点要求Bearer令牌)
若你的FastAPI端点采用Bearer格式的B2B令牌鉴权(请求头为Authorization: Bearer <token>),需手动覆盖默认请求头:
import asyncio from openai import AsyncAzureOpenAI LATEST_URL = "http://localhost:8080" model_id = "gpt-4" B2B_token = "xxxx" async def test_custom_endpoint(): client = AsyncAzureOpenAI( base_url=f"{LATEST_URL}/v1/genai/models/deployments/{model_id}", api_key="placeholder", # 必填参数,填任意占位值即可 skip_api_version=True, max_retries=0, default_headers={"Authorization": f"Bearer {B2B_token}"} ) response = await client.chat.completions.create( messages=[{"role": "user", "content": "Hi"}], model=model_id, max_tokens=50, temperature=0.7, timeout=30 ) print(response.choices[0].message.content) if __name__ == "__main__": asyncio.run(test_custom_endpoint())
关键注意事项
skip_api_version=True:必须设置该参数,避免客户端自动添加Azure特有的api-version查询参数。base_url取值:仅需填写到自定义端点的基础路径部分,客户端会自动拼接chat/completions(对应chat.completions.create方法的路径),无需在base_url中包含完整端点路径。- 鉴权适配:根据自定义端点的鉴权规则调整请求头,确保令牌传递格式正确。
内容的提问来源于stack exchange,提问作者Ytiam Unata
相关产品推荐
相关产品推荐

