查詢路由最佳化的服務端點

本文說明如何擷取適當的驗證認證和 URL,以便查詢路由最佳化 模型服務功能服務 端點。

需求

  • 已啟用路由最佳化的模型服務端點或功能服務端點。 請參閱 服務端點的路由優化
  • 查詢路由最佳化端點僅支援使用 OAuth 令牌。 不支援個人存取權杖。

快速入門:端對端查詢操作範例

以下範例將從外部用戶端查詢路由最佳化端點所需的所有步驟整合為單一可執行的流程。 如果你想快速驗證可用的設定,請使用這部分。 請參閱以下章節以獲得每個步驟的更多細節。

# 1. Set the variables for your environment.
export DATABRICKS_HOST="https://<your-workspace>.cloud.databricks.com"
export ENDPOINT_NAME="<your-endpoint>"
export WORKSPACE_ID="<workspace-id>"

# 2. Create an account-level service principal and an OAuth secret for it.
SP_ID=$(databricks account service-principals create \
  --json '{"displayName":"my-app","active":true}' --output json | jq -r '.id')
SECRET_JSON=$(databricks account service-principal-secrets create "$SP_ID" --output json)
export CLIENT_ID=$(databricks account service-principals get "$SP_ID" --output json | jq -r '.applicationId')
export CLIENT_SECRET=$(echo "$SECRET_JSON" | jq -r '.secret')

# 3. Assign the service principal to the workspace and grant CAN_QUERY on the endpoint.
databricks account workspace-assignment update "$WORKSPACE_ID" "$SP_ID" \
  --json '{"permissions":["USER"]}'
ENDPOINT_ID=$(databricks serving-endpoints get "$ENDPOINT_NAME" --output json | jq -r '.id')
databricks permissions update serving-endpoints "$ENDPOINT_ID" \
  --json "{\"access_control_list\":[{\"service_principal_name\":\"$CLIENT_ID\",\"permission_level\":\"CAN_QUERY\"}]}"

# 4. Mint an endpoint-scoped OAuth token. `authorization_details` is required for
# route-optimized endpoints -- a plain `scope=all-apis` token is rejected with
# 401 "Missing authorization details" when used against the route-optimized URL.
TOKEN=$(curl -sS -X POST -u "$CLIENT_ID:$CLIENT_SECRET" \
  --data-urlencode "grant_type=client_credentials" \
  --data-urlencode "scope=all-apis" \
  --data-urlencode "authorization_details=[{\"type\":\"workspace_permission\",\"object_type\":\"serving-endpoints\",\"object_path\":\"/serving-endpoints/$ENDPOINT_ID\",\"actions\":[\"query_inference_endpoint\"]}]" \
  "$DATABRICKS_HOST/oidc/v1/token" | jq -r '.access_token')

# 5. Invoke the endpoint at its route-optimized URL.
RO_URL=$(databricks serving-endpoints get "$ENDPOINT_NAME" --output json | jq -r '.endpoint_url')
curl -sS -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{"inputs":[[0.12,0.34]]}' "https://$RO_URL"

取得路由優化的 URL

警告

2025 年 9 月 22 日開始,所有新建立的路由最佳化端點都必須專門透過路由最佳化 URL 進行查詢。 在此日期之後建立的端點不支援透過工作區 URL 進行查詢。

如果您的路由最佳化端點是在 2025 年 9 月 22 日之前建立的:

  • 標準工作區 URL 也可用於查詢端點。 標準工作區 URL 路徑不提供 路由最佳化的優點。

    https://<databricks-workspace>/serving-endpoints/<endpoint-name>/invocations

  • 在此日期之前建立的路由最佳化端點會繼續支援這兩個叫用 URL:路由最佳化 URL 路徑和標準工作區 URL 路徑。

當您建立路由最佳化端點時,會為端點建立下列路由最佳化 URL。

https://<unique-id>.<shard>.serving.azuredatabricks.net/<workspace-id>/serving-endpoints/<endpoint-name>/invocations

您可以從以下位置取得此 URL:

提供使用者介面

路由最佳化端點 URL

REST API

使用 GET /api/2.0/serving-endpoints/{name} API 呼叫。 URL 存在於端點的回應物件中,做為 endpoint_url。 只有在終端經過路由最佳化時,才會填入此欄位。

GET /api/2.0/serving-endpoints/my-endpoint
{
  "name": "my-endpoint"
}

Databricks SDK

使用 Serving Endpoints API get 呼叫功能。 URL 存在於端點的回應物件中,做為 endpoint_url。 只有在終端經過路由最佳化時,才會填入此欄位。

from databricks.sdk import WorkspaceClient

workspace = WorkspaceClient()

workspace.serving_endpoints.get("my-endpoint")

擷取 OAuth 令牌並查詢端點

若要查詢經最佳化路由的端點,您必須使用 OAuth 令牌。 Databricks 建議在生產應用程式中使用 服務主體,以程式方式獲取 OAuth 權杖。 下列各節說明如何取得測試與生產環境的 OAuth 令牌之建議指引。

使用 Serving UI 取得 OAuth 令牌

以下步驟說明如何在 Serving UI 中取得權杖。 建議這些步驟用於開發和測試您的端點。

針對生產用途,例如在應用程式中使用路由最佳化的端點,系統會透過服務主體來擷取您的 Token。 如需獲取在生產環境中使用的 OAuth 令牌的推薦指引,請參閱以程式方式取得 OAuth 令牌

從工作區的 [服務 UI]:

  1. 在 [服務端點] 頁面上,選取路由最佳化端點以查看端點詳細資料。
  2. 在 [端點詳細數據] 頁面上,選取 [ 使用 ] 按鈕。
  3. 選取 擷取令牌 索引標籤。
  4. 選取 [擷取 OAuth 令牌] 按鈕。 此權杖有效期為 1 小時。 如果您目前的權杖已過期,請取得新的權杖。

擷取 OAuth 令牌之後,請使用您的端點 URL 和 OAuth 令牌來查詢端點。

REST API

以下是 REST API 範例:


URL="<endpoint-url>"
OAUTH_TOKEN="<token>"

curl -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OAUTH_TOKEN" \
  --data "@data.json" \
  "$URL"

Python

以下是 Python 範例:


import requests
import json

url = "<url>"
oauth_token = "<token>"

data = {
    "dataframe_split": {
        "columns": ["feature_1", "feature_2"],
        "data": [
            [0.12, 0.34],
            [0.56, 0.78],
            [0.90, 0.11]
        ]
    }
}

headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {oauth_token}"
}

response = requests.post(url, headers=headers, json=data)

# Print the response
print("Status Code:", response.status_code)
print("Response Body:", response.text)

透過程式取得 OAuth 權杖

針對生產環境,Databricks 建議設定服務主體以嵌入您的應用程式中,並以程式化方式獲取 OAuth 令牌。 這些擷取的令牌可用來查詢最佳路由端點。

請遵循使用 OAuth 授權服務主體存取 Azure Databricks 中的步驟,至步驟 2 建立服務主體、指派許可權,以及建立服務主體的 OAuth 秘密。 建立服務主體之後,您必須至少為服務主體提供端點的 查詢許可權 。 請參閱 管理模型服務端點的許可

Databricks Python SDK 提供 API,可直接查詢路由最佳化端點。

備註

Databricks SDK 也可在 Go 中使用,請參閱 Databricks SDK for Go

下一個範例需要下列專案,才能使用 Databricks SDK 查詢路由最佳化端點:

  • 提供端點名稱 (SDK 會根據此名稱擷取正確的端點 URL)
  • 服務主體用戶端識別碼
  • 服務主體憑證密碼
  • 工作區主機名
from databricks.sdk import WorkspaceClient
import databricks.sdk.core as client

endpoint_name = "<Serving-Endpoint-Name>" ## Insert the endpoint name here

# Initialize Databricks SDK
c = client.Config(
    host="<Workspace-Host>", ## For example, my-workspace.cloud.databricks.com
    client_id="<Client-Id>", ## Service principal ID
    client_secret="<Secret>"   ## Service principal secret
)
w = WorkspaceClient(
    config = c
)

response = w.serving_endpoints_data_plane.query(endpoint_name, dataframe_records = ....)

手動獲取 OAuth 令牌

針對 Databricks SDK 或服務 UI 無法用來擷取 OAuth 令牌的案例,您可以手動擷取 OAuth 令牌。 本節中的指引主要適用於使用者想要用來查詢生產中端點的自定義用戶端案例。

當您手動擷取 OAuth 令牌時,必須在要求中指定 authorization_details

  • <token-endpoint-URL>中,將https://<databricks-instance>替換為您的 Databricks 部署的工作區 URL,以建構https://<databricks-instance>/oidc/v1/token。 例如, https://my-workspace.0.azuredatabricks.net/oidc/v1/token
  • <client-id> 替換為服務主體的客戶端 ID,也稱為應用程式識別碼。
  • <client-secret> 取代為您建立的服務主體的 OAuth 密碼。
  • <endpoint-id> 取代為路由最佳化端點的端點 ID。 這是您可以在端點 URL 中找到的端點字母數字識別碼 hostName。 例如,如果服務端點為 https://abcdefg.0.serving.azuredatabricks.net/9999999/serving-endpoints/test,則端點識別碼為 abcdefg
  • <action> 取代為提供給服務主體的動作權限。 動作可以是 query_inference_endpoint,也可以是 manage_inference_endpoint

REST API

以下是 REST API 範例:



export CLIENT_ID=<client-id>
export CLIENT_SECRET=<client-secret>
export ENDPOINT_ID=<endpoint-id>
export ACTION=<action>  # for example, 'query_inference_endpoint'

curl --request POST \
--url <token-endpoint-URL> \
--user "$CLIENT_ID:$CLIENT_SECRET" \
--data 'grant_type=client_credentials&scope=all-apis'
--data-urlencode 'authorization_details=[{"type":"workspace_permission","object_type":"serving-endpoints","object_path":"'"/serving-endpoints/$ENDPOINT_ID"'","actions": ["'"$ACTION"'"]}]'

Python

以下是 Python 範例:

import os
import requests

# Set your environment variables or replace them directly here
CLIENT_ID = os.getenv("CLIENT_ID")
CLIENT_SECRET = os.getenv("CLIENT_SECRET")
ENDPOINT_ID = os.getenv("ENDPOINT_ID")
ACTION = "query_inference_endpoint" # Can also be `manage_inference_endpoint`

# Token endpoint URL
TOKEN_URL = "<token-endpoint-URL>"

# Build the payload, note the creation of authorization_details
payload = { 'grant_type': 'client_credentials', 'scope': 'all-apis', 'authorization_details': f'''[{{"type":"workspace_permission","object_type":"serving-endpoints","object_path":"/serving-endpoints/{ENDPOINT_ID}","actions":["{ACTION}"]}}]''' }

# Make the POST request with basic auth
response = requests.post( TOKEN_URL, auth=(CLIENT_ID, CLIENT_SECRET), data=payload )

# Check the response
if response.ok:
  token_response = response.json()
  access_token = token_response.get("access_token")
  if access_token:
    print(f"Access Token: {access_token}")
  else:
    print("access_token not found in response.")
else: print(f"Failed to fetch token: {response.status_code} {response.text}")

擷取 OAuth 令牌之後,請使用您的端點 URL 和 OAuth 令牌來查詢端點。

REST API

以下是 REST API 範例:


URL="<endpoint-url>"
OAUTH_TOKEN="<token>"

curl -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OAUTH_TOKEN" \
  --data "@data.json" \
  "$URL"

Python

以下是 Python 範例:


import requests
import json

url = "<url>"
oauth_token = "<token>"

data = {
    "dataframe_split": {
        "columns": ["feature_1", "feature_2"],
        "data": [
            [0.12, 0.34],
            [0.56, 0.78],
            [0.90, 0.11]
        ]
    }
}

headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {oauth_token}"
}

response = requests.post(url, headers=headers, json=data)

# Print the response
print("Status Code:", response.status_code)
print("Response Body:", response.text)

來自代理或外部應用程式的呼叫

AI 編碼助理及查詢路由優化端點的外部應用程式無法使用開發者的個人存取權杖或工作區 OAuth 權杖。 他們必須使用服務主體來處理 OAuth M2M 流程,並將 token 請求包含 authorization_details 在其中。 流程如下:

  1. 在帳號層級建立一個服務主體,並為其建立一個 OAuth 秘密。 請參見 使用 OAuth 授權服務主體存取至 Azure Databricks
  2. 將服務主體指派給工作區,並在端點上授與其 CAN_QUERY
  3. 從應用程式中,透過呼叫 POST <workspace-host>/oidc/v1/token 服務主體憑證並 authorization_details 引用端點 ID 來鑄造端點範圍的令牌。 請參閱 手動擷取 OAuth 令牌
  4. 用所得標記呼叫經過路由優化的 URL。

上方快速 入門 區包含一個可複製貼上的腳本,涵蓋每個步驟。

故障排除

錯誤 原因 修復
401 Malformed token 從路由最佳化 URL 傳回 該憑證是個人存取憑證或叢集執行時憑證,而非 OAuth JWT。 路由優化端點僅接受 OAuth 代幣。 使用服務主體搭配 OAuth M2M 流程來取得 OAuth 標記。 請參閱 以程式方式取得 OAuth 權杖
401 Missing authorization details for accessing model serving endpoints 從路由最佳化 URL 傳回 權杖要求中遺漏了會將權杖範圍限縮至特定端點的 authorization_details 宣告。 普通 scope=all-apis 代幣是不夠的。 在呼叫 authorization_details時,傳遞query_inference_endpoint端點 ID 與/oidc/v1/token動作的參考。 請參閱 手動擷取 OAuth 令牌
400 This is a route-optimized endpoint. Please use the correct route-optimized URL provided: ... 你將請求傳送到工作區 URL https://<workspace>/serving-endpoints/<name>/invocations,而不是已針對路由最佳化的 URL。 請使用欄位endpoint_urlGET /api/2.0/serving-endpoints/<name>中回傳的網址。 請參見 「擷取路由優化網址」。
403 Permission denied 即使 OAuth 權杖已具有 authorization_details,仍從路由最佳化 URL 傳回 服務主體在端點上沒有 CAN_QUERY ,或是 的 authorization_details 動作與授權權限不符。 在端點上將 CAN_QUERY 授與服務主體,並使用 query_inference_endpoint 作為動作。 請參閱 管理模型服務端點的許可
invalid_scope/oidc/v1/token 返回 權杖要求傳遞了 `all-apis` 以外的範圍值。 唯一支援的路由優化端點令牌範圍為 all-apis。 端點縮小是透過 authorization_details,而不是 scope