无法查询 azure search ai 端点

问题描述 投票:0回答:1

我正在使用以下内容对 azure 搜索进行身份验证:

cred = DefaultAzureCredential()
token = cred.get_token(api)
params = {'api-version': os.environ['AZURE_SEARCH_API_VERSION']}
headers = {'Authorization': f'Bearer {token}','Content-Type': 'application/json'}

search_payload = {
        "search": QUESTION, # Text query
        "select": "id, title, name, location, chunk",
        "queryType": "semantic",
        "vectorQueries": [{"text": QUESTION, "fields": "chunkVector", "kind": "text", "k": k}], # Vector query
        "semanticConfiguration": "my-semantic-config",
        "captions": "extractive",
        "answers": "extractive",
        "count":"true",
        "top": k
    }

r = requests.post(os.environ['AZURE_SEARCH_ENDPOINT'] + "/indexes/" + index + "/docs/search",
                     data=json.dumps(search_payload), headers=headers, params=params)

但是,当我打印 r 的状态代码时,我收到 401 错误代码。

注意:我有“搜索索引数据读取器”的权限,并且该应用程序有一个身份。

还有什么可能导致此问题?

azure azure-active-directory bearer-token
1个回答
0
投票

发生错误是因为您在生成令牌来调用 Azure AI 搜索端点时使用了错误的范围

我有一个 Azure 搜索服务,我将 API 访问控制启用为两者,如下所示:

enter image description here

现在,我在搜索服务下向我的用户添加了 “搜索索引数据读取器” 角色,如下所示:

enter image description here

但是当我尝试使用

api
值作为 https://cognitiveservices.azure.com/.default 调用搜索端点查询时,我也得到了响应代码 401 :

enter image description here

要解决此错误,您需要使用 https://search.azure.com/.default 作为

api
值来为 Azure AI 搜索端点生成令牌。

当我通过进行上述更改来运行下面的代码时,我成功地得到了response,如下所示:

import os
import json
import requests
from azure.identity import DefaultAzureCredential

api_version = "2020-06-30" 
index = "hotels-sample-index"

search_endpoint = "https://demosearch0904.search.windows.net"

k = 10 
QUESTION = "luxury" 
api = "https://search.azure.com/.default"

cred = DefaultAzureCredential()
token = cred.get_token(api)

params = {'api-version': api_version}
headers = {'Authorization': f'Bearer {token.token}', 'Content-Type': 'application/json'}

search_payload = {
    "search": QUESTION,
    "select": "*",  
    "count": "true",
    "top": k
}

r = requests.post(f"{search_endpoint}/indexes/{index}/docs/search",
                  data=json.dumps(search_payload), headers=headers, params=params)

if r.status_code == 200:
    search_results = r.json()
    print(search_results)
else:
    print(f"Error: {r.status_code} - {r.text}")

回复:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.