开始在 Databricks 上查询 LLM

Important

此功能在 Beta 版中。 帐户管理员可以从帐户控制台 预览 页控制对此功能的访问。 请参阅 Manage Azure Databricks 预览版。

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

最简单的入门方法是查询系统提供的system.ai。 默认情况下,系统提供的模型服务适用于所有帐户用户,因此你可以开始发送请求,而无需任何其他设置。 参见 定制模型服务。

还可以使用 AI Playground 测试这些模型并与之聊天。 参见使用 AI Playground 与 LLM 聊天并构建 AI 应用原型。

Requirements

Important

作为适用于生产场景的安全最佳做法,Databricks 建议在生产期间使用计算机到计算机 OAuth 令牌来进行身份验证。

对于测试和开发,Databricks 建议使用属于服务主体(而不是工作区用户)的个人访问令牌。 若要为服务主体创建令牌,请参阅管理服务主体的令牌。

开始使用模型服务

以下示例旨在运行在 Azure Databricks 笔记本中。 该代码示例查询系统提供的模型服务system.ai.claude-sonnet-4-5,原生由 Azure Databricks 提供。 有关其他可用模型,请参见 模型服务。

在此示例中,您通过将要查询的模型服务的完全限定名称填入 model 字段,使用 OpenAI 客户端查询模型。 使用个人访问令牌填充 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
    }
}

后续步骤