開始在 Databricks 上查詢 LLM

Important

這項功能位於 測試版 (Beta) 中。 帳號管理員可從帳號主控台 預覽頁面控制 此功能的存取權限。 請參閱 管理 Azure Databricks 預覽。

在 Unity Gateway 中使用 模型服務查詢 Azure Databricks 上的 LLM。

最簡單的起點是查詢系統提供的模型服務。system.ai 系統提供的模型服務預設對所有帳號使用者開放,因此你可以無需額外設定即可開始發送請求。 請參閱 客製化模型服務。

你也可以透過 AI Playground 測試和與這些模型聊天。 請參閱 與 LLM 對話並使用 AI Playground 製作 AI 應用程式原型。

Requirements

Important

作為生產環境的安全性最佳實踐,Databricks 建議您在生產期間使用 機器對機器 OAuth 令牌 進行驗證。

為了測試和開發,Databricks 建議使用屬於 服務主體 的個人存取令牌,而不是工作區使用者。 若要建立服務主體的令牌,請參閱 管理服務主體的令牌。

開始使用模型服務

以下範例是設計在 Azure Databricks 筆記本中執行的。 程式碼範例查詢系統提供的模型服務system.ai.claude-sonnet-4-5,原生服務由 Azure Databricks 提供。 關於其他可用模型,請參見 模型服務。

在這個例子中,你使用 OpenAI 客戶端來查詢模型,方法是將你想查詢的模型服務的完全限定名稱填入欄位。model 使用您的個人存取令牌填入 DATABRICKS_TOKEN 和 Databricks 工作區實例 ,將 OpenAI 用戶端連線到 Databricks。

from openai import OpenAI
import os

DATABRICKS_TOKEN = os.environ.get("DATABRICKS_TOKEN")

client = OpenAI(
  api_key=DATABRICKS_TOKEN, # your personal access token
  base_url="https://<workspace-url>/ai-gateway/mlflow/v1", # your Databricks workspace instance
)

chat_completion = client.chat.completions.create(
  messages=[
    {
      "role": "system",
      "content": "You are an AI assistant",
    },
    {
      "role": "user",
      "content": "What is a mixture of experts model?",
    }
  ],
  model="system.ai.claude-sonnet-4-5",
  max_tokens=256
)

print(chat_completion.choices[0].message.content)

Note

如果您遇到下列訊息 ImportError: cannot import name 'OpenAI' from 'openai',請使用 openai 升級您的 !pip install -U openai 版本。 安裝套件之後,請執行 dbutils.library.restartPython()。

預期輸出:


{
  "id": "xxxxxxxxxxxxx",
  "object": "chat.completion",
  "created": "xxxxxxxxx",
  "model": "system.ai.claude-sonnet-4-5",
  "choices": [
    {
      "index": 0,
      "message":
        {
          "role": "assistant",
          "content": "A Mixture of Experts (MoE) model is a machine learning technique that combines the predictions of multiple expert models to improve overall performance. Each expert model specializes in a specific subset of the data, and the MoE model uses a gating network to determine which expert to use for a given input."
        },
      "finish_reason": "stop"
    }
  ],
  "usage":
    {
      "prompt_tokens": 123,
      "completion_tokens": 23,
      "total_tokens": 146
    }
}

後續步驟