次の方法で共有


基盤モデルと外部モデルのクエリを実行する

この記事では、基盤モデルと外部モデルのクエリ要求を書式設定し、それらをモデル提供エンドポイントに送信する方法について説明します。

従来の ML または Python モデルのクエリ要求については、「カスタム モデルのエンドポイントを提供するクエリ」をご覧ください。

Mosaic AI Model Serving では、生成 AI のモデルにアクセスするための Foundation Models API外部モデルがサポートされています。 Model Serving では、OpenAI と互換性のある統合された API と SDK を使って、それらのクエリが実行されます。 これにより、サポートされているすべてのクラウドとプロバイダーで運用環境の生成 AI モデルの実験とカスタマイズを行うことができます。

Mosaic AI Model Serving には、基盤モデルまたは外部モデルを提供するエンドポイントにスコアリング要求を送信するための以下のオプションがあります。

メソッド 詳細
OpenAI クライアント OpenAI クライアントを使用して、Mosaic AI Model Serving エンドポイントによってホストされているモデルに対してクエリを実行します。 モデル提供エンドポイント名を model 入力として指定します。 Foundation Model API または外部モデルで使用できるチャット、埋め込み、入力候補モデルでサポートされます。
提供 UI [提供エンドポイント] ページから [エンドポイントに対するクエリを実行] を選択します。 JSON 形式のモデル入力データを入力し、[要求の送信] をクリックします。 モデルに入力例がログされている場合は、[例の表示] を使用してそれを読み込みます。
REST API REST API を使用してモデルを呼び出してクエリを実行します。 詳細については、「POST /serving-endpoints/{name}/invocations」を参照してください。 複数のモデルを提供するエンドポイントへのスコアリング要求については、「エンドポイントの背後にある個々のモデルに対するクエリの実行」を参照してください。
MLflow デプロイ SDK モデルに対してクエリを実行するには、MLflow Deployments SDK の predict() 関数を使用します。
Databricks Python SDK Databricks Python SDK は、REST API 上のレイヤーです。 認証などの低レベルの詳細を処理するため、モデルとの対話が容易になります。
SQL 関数 SQL 関数の ai_query を使用して、SQL から直接モデル推論を呼び出します。 「ai_query() を使用した提供モデルに対するクエリの実行」を参照してください。

要件

重要

運用シナリオのセキュリティのベスト プラクティスとして、Databricks では、運用時の認証にコンピューター間 OAuth トークンを使用することをお勧めします。

テストおよび開発の場合は、Databricks では、ワークスペース ユーザーではなく、サービス プリンシパルに属する個人用アクセス トークンを使用することをお勧めします。 サービス プリンシパルのトークンを作成するには、「サービス プリンシパルのトークンを管理する」をご覧ください。

パッケージをインストールする

クエリ方法を選択したら、まずお使いのクラスターに適切なパッケージをインストールする必要があります。

OpenAI クライアント

OpenAI クライアントを使用するには、クラスターに openai パッケージをインストールする必要があります。 ノートブックまたはローカル ターミナルで次を実行してください。

!pip install openai

以下は、Databricks Notebook にパッケージをインストールする場合にのみ必要です

dbutils.library.restartPython()

REST API

Serving REST API へのアクセスは、Databricks Runtime for Machine Learning で利用できます。

MLflow デプロイ SDK

!pip install mlflow

以下は、Databricks Notebook にパッケージをインストールする場合にのみ必要です

dbutils.library.restartPython()

Databricks Python SDK

Databricks SDK for Python は、Databricks Runtime 13.3 LTS 以上を使用するすべての Azure Databricks クラスターに既にインストールされています。 Databricks Runtime 12.2 LTS 以下を使用する Azure Databricks クラスターの場合、まず Databricks SDK for Python をインストールする必要があります。 「手順 1: Databricks SDK for Python をインストールまたはアップグレードする」を参照してください。


## <a id="chat"> </a><a id="query-a-chat-completion-model"> </a>Query a chat completion model

The following are examples for querying a chat model. The example applies to querying a chat model made available using either of the Model Serving capabilities: Foundation Model APIs or external models.

For a batch inference example, see [Batch inference using Foundation Model APIs](../foundation-models/fmapi-batch-inference.md).

### OpenAI&nbsp;client

The following is a chat request for the DBRX Instruct model made available by the Foundation Model APIs pay-per-token endpoint, ``databricks-dbrx-instruct`` in your workspace.

To use the OpenAI client, specify the model serving endpoint name as the ``model`` input. The following example assumes you have a [Databricks API token](#required) and ``openai`` installed on your compute. You also need your [Databricks workspace instance](../../workspace/workspace-details.md#workspace-url) to connect the OpenAI client to Databricks.

```python

import os
import openai
from openai import OpenAI

client = OpenAI(
    api_key="dapi-your-databricks-token",
    base_url="https://example.staging.cloud.databricks.com/serving-endpoints"
)

response = client.chat.completions.create(
    model="databricks-dbrx-instruct",
    messages=[
      {
        "role": "system",
        "content": "You are a helpful assistant."
      },
      {
        "role": "user",
        "content": "What is a mixture of experts model?",
      }
    ],
    max_tokens=256
)

REST API

重要

次の例では、基盤モデルを提供する提供エンドポイントに対するクエリを実行するために REST API パラメーターを使用します。 これらのパラメーターはパブリック プレビューであり、定義が変更される可能性があります。 POST /serving-endpoints/{name}/invocations を参照してください。

以下は、ワークスペースで提供される Foundation Model API 従量課金トークン エンドポイント databricks-dbrx-instruct によって利用可能な DBRX Instruct モデルのチャット要求です。

curl \
-u token:$DATABRICKS_TOKEN \
-X POST \
-H "Content-Type: application/json" \
-d '{
  "messages": [
    {
      "role": "system",
      "content": "You are a helpful assistant."
    },
    {
      "role": "user",
      "content": " What is a mixture of experts model?"
    }
  ]
}' \
https://<workspace_host>.databricks.com/serving-endpoints/databricks-dbrx-instruct/invocations \

MLflow デプロイ SDK

重要

次の例では、MLflow デプロイ SDKpredict() API を使用します。

以下は、ワークスペースで提供される Foundation Model API 従量課金トークン エンドポイント databricks-dbrx-instruct によって利用可能な DBRX Instruct モデルのチャット要求です。


import mlflow.deployments

# Only required when running this example outside of a Databricks Notebook
export DATABRICKS_HOST="https://<workspace_host>.databricks.com"
export DATABRICKS_TOKEN="dapi-your-databricks-token"

client = mlflow.deployments.get_deploy_client("databricks")

chat_response = client.predict(
    endpoint="databricks-dbrx-instruct",
    inputs={
        "messages": [
            {
              "role": "user",
              "content": "Hello!"
            },
            {
              "role": "assistant",
              "content": "Hello! How can I assist you today?"
            },
            {
              "role": "user",
              "content": "What is a mixture of experts model??"
            }
        ],
        "temperature": 0.1,
        "max_tokens": 20
    }
)

Databricks Python SDK

以下は、ワークスペースで提供される Foundation Model API 従量課金トークン エンドポイント databricks-dbrx-instruct によって利用可能な DBRX Instruct モデルのチャット要求です。

このコードは、ワークスペース内のノートブックで実行する必要があります。 「Azure Databricks ノートブックから Databricks SDK for Python を使用する」を参照してください。

from databricks.sdk import WorkspaceClient
from databricks.sdk.service.serving import ChatMessage, ChatMessageRole

w = WorkspaceClient()
response = w.serving_endpoints.query(
    name="databricks-dbrx-instruct",
    messages=[
        ChatMessage(
            role=ChatMessageRole.SYSTEM, content="You are a helpful assistant."
        ),
        ChatMessage(
            role=ChatMessageRole.USER, content="What is a mixture of experts model?"
        ),
    ],
    max_tokens=128,
)
print(f"RESPONSE:\n{response.choices[0].message.content}")

LangChain

LangChain を使用して基盤モデル エンドポイントにクエリを実行するには、次のいずれかを行うことができます。

  • Databricks LLM クラスをインポートし、endpoint_nametransform_input_fn を指定してください。
  • ChatDatabricks ChatModel クラスをインポートし、endpoint を指定してください。

次の例では、LangChain の Databricks LLM クラスを使用して、Foundation Model API のトークン単位の支払いエンドポイントである databricks-dbrx-instruct にクエリを実行します。 Foundation Model API は要求ディクショナリの messages を想定していますが、LangChain Databricks LLM は既定で要求ディクショナリの prompt を提供します。 transform_input 関数を使用して、要求ディクショナリを想定される形式に準備してください。

from langchain.llms import Databricks
from langchain_core.messages import HumanMessage, SystemMessage

def transform_input(**request):
  request["messages"] = [
    {
      "role": "user",
      "content": request["prompt"]
    }
  ]
  del request["prompt"]
  return request

llm = Databricks(endpoint_name="databricks-dbrx-instruct", transform_input_fn=transform_input)
llm("What is a mixture of experts model?")

次の例では、ChatDatabricks ChatModel クラスを使用し、endpoint を指定します。

from langchain.chat_models import ChatDatabricks
from langchain_core.messages import HumanMessage, SystemMessage

messages = [
    SystemMessage(content="You're a helpful assistant"),
    HumanMessage(content="What is a mixture of experts model?"),
]
chat_model = ChatDatabricks(endpoint="databricks-dbrx-instruct", max_tokens=500)
chat_model.invoke(messages)

SQL

重要

次の例では、組み込みの SQL 関数である ai_query を使用します。 この関数はパブリック プレビューであり、定義が変更される可能性があります。 「ai_query() を使用した提供モデルに対するクエリの実行」を参照してください。

以下は、ワークスペースで提供される Foundation Model API 従量課金トークン エンドポイント databricks-llama-2-70b-chat によって利用可能な llama-2-70b-chat のチャット要求です。

Note

ai_query() 関数は、DBRX または DBRX Instruct モデルを提供するクエリ エンドポイントをサポートしていません。

SELECT ai_query(
    "databricks-llama-2-70b-chat",
    "Can you explain AI in ten words?"
  )

たとえば、次に示すのは REST API 使用時のチャット モデルで想定されている要求形式です。 外部モデルに対しては、特定のプロバイダーとエンドポイント構成で有効な追加のパラメータを含めることができます。 「その他のクエリ パラメーター」を参照してください。

{
  "messages": [
    {
      "role": "user",
      "content": "What is a mixture of experts model?"
    }
  ],
  "max_tokens": 100,
  "temperature": 0.1
}

REST API を使用して行う要求に対して想定されている応答形式は、次のとおりです。

{
  "model": "databricks-dbrx-instruct",
  "choices": [
    {
      "message": {},
      "index": 0,
      "finish_reason": null
    }
  ],
  "usage": {
    "prompt_tokens": 7,
    "completion_tokens": 74,
    "total_tokens": 81
  },
  "object": "chat.completion",
  "id": null,
  "created": 1698824353
}

埋め込みモデルに対してクエリを実行する

Foundation Model API によって利用可能となる bge-large-en モデルに対する埋め込み要求を次に示します。 この例は、Model Serving の機能 (Foundation Model API または外部モデル) のいずれかを使って利用できる埋め込みモデルのクエリに適用されます。

OpenAI クライアント

OpenAI クライアントを使用するには、モデル提供エンドポイント名を model 入力として指定します。 次の例では、Databricks API トークンがあり、クラスターに openai がインストールされていることを前提としています。


import os
import openai
from openai import OpenAI

client = OpenAI(
    api_key="dapi-your-databricks-token",
    base_url="https://example.staging.cloud.databricks.com/serving-endpoints"
)

response = client.embeddings.create(
  model="databricks-bge-large-en",
  input="what is databricks"
)

REST API

重要

次の例では、基盤モデルまたは外部モデルを提供する提供エンドポイントのクエリを実行するために REST API パラメーターを使っています。 これらのパラメーターはパブリック プレビューであり、定義が変更される可能性があります。 POST /serving-endpoints/{name}/invocations を参照してください。


curl \
-u token:$DATABRICKS_TOKEN \
-X POST \
-H "Content-Type: application/json" \
-d  '{ "input": "Embed this sentence!"}' \
https://<workspace_host>.databricks.com/serving-endpoints/databricks-bge-large-en/invocations

MLflow デプロイ SDK

重要

次の例では、MLflow デプロイ SDKpredict() API を使用します。


import mlflow.deployments

export DATABRICKS_HOST="https://<workspace_host>.databricks.com"
export DATABRICKS_TOKEN="dapi-your-databricks-token"

client = mlflow.deployments.get_deploy_client("databricks")

embeddings_response = client.predict(
    endpoint="databricks-bge-large-en",
    inputs={
        "input": "Here is some text to embed"
    }
)

Databricks Python SDK


from databricks.sdk import WorkspaceClient
from databricks.sdk.service.serving import ChatMessage, ChatMessageRole

w = WorkspaceClient()
response = w.serving_endpoints.query(
    name="databricks-bge-large-en",
    input="Embed this sentence!"
)
print(response.data[0].embedding)

LangChain

LangChain で Databricks Foundation Model API モデルを埋め込みモデルとして使用するには、DatabricksEmbeddings クラスをインポートし、次のように endpoint パラメーターを指定します。

from langchain.embeddings import DatabricksEmbeddings

embeddings = DatabricksEmbeddings(endpoint="databricks-bge-large-en")
embeddings.embed_query("Can you explain AI in ten words?")

SQL

重要

次の例では、組み込みの SQL 関数である ai_query を使用します。 この関数はパブリック プレビューであり、定義が変更される可能性があります。 「ai_query() を使用した提供モデルに対するクエリの実行」を参照してください。


SELECT ai_query(
    "databricks-bge-large-en",
    "Can you explain AI in ten words?"
  )

次に示すのは埋め込みモデルで想定されている要求形式です。 外部モデルに対しては、特定のプロバイダーとエンドポイント構成で有効な追加のパラメータを含めることができます。 「その他のクエリ パラメーター」を参照してください。


{
  "input": [
    "embedding text"
  ]
}

想定されている応答形式は次のとおりです。

{
  "object": "list",
  "data": [
    {
      "object": "embedding",
      "index": 0,
      "embedding": []
    }
  ],
  "model": "text-embedding-ada-002-v2",
  "usage": {
    "prompt_tokens": 2,
    "total_tokens": 2
  }
}

テキスト入力候補モデルに対してクエリを実行する

次に、Foundation Model API によって使用可能になった databricks-mpt-30b-instruct モデルの補完要求を示します。 この例は、Model Serving の機能 (Foundation Model API または外部モデル) のいずれかを使って利用できるチャット モデルのクエリに適用されます。 パラメーターと構文については、「完了タスク」を参照してください。

OpenAI クライアント

OpenAI クライアントを使用するには、モデル提供エンドポイント名を model 入力として指定します。 次の例では、Databricks API トークンがあり、クラスターに openai がインストールされていることを前提としています。


import os
import openai
from openai import OpenAI

client = OpenAI(
    api_key="dapi-your-databricks-token",
    base_url="https://example.staging.cloud.databricks.com/serving-endpoints"
)

completion = client.completions.create(
  model="databricks-mpt-30b-instruct",
  prompt="what is databricks",
  temperature=1.0
)

REST API

重要

次の例では、基盤モデルまたは外部モデルを提供する提供エンドポイントのクエリを実行するために REST API パラメーターを使っています。 これらのパラメーターはパブリック プレビューであり、定義が変更される可能性があります。 POST /serving-endpoints/{name}/invocations を参照してください。


curl \
 -u token:$DATABRICKS_TOKEN \
 -X POST \
 -H "Content-Type: application/json" \
 -d '{"prompt": "What is a quoll?", "max_tokens": 64}' \
https://<workspace_host>.databricks.com/serving-endpoints/databricks-mpt-30b-instruct/invocations

MLflow デプロイ SDK

重要

次の例では、MLflow デプロイ SDKpredict() API を使用します。


import os
import mlflow.deployments

# Only required when running this example outside of a Databricks Notebook

os.environ['DATABRICKS_HOST'] = "https://<workspace_host>.databricks.com"
os.environ['DATABRICKS_TOKEN'] = "dapi-your-databricks-token"

client = mlflow.deployments.get_deploy_client("databricks")

completions_response = client.predict(
    endpoint="databricks-mpt-30b-instruct",
    inputs={
        "prompt": "What is the capital of France?",
        "temperature": 0.1,
        "max_tokens": 10,
        "n": 2
    }
)

# Print the response
print(completions_response)

Databricks Python SDK

from databricks.sdk import WorkspaceClient
from databricks.sdk.service.serving import ChatMessage, ChatMessageRole

w = WorkspaceClient()
response = w.serving_endpoints.query(
    name="databricks-mpt-7b-instruct",
    prompt="Write 3 reasons why you should train an AI model on domain specific data sets."
)
print(response.choices[0].text)

SQL

重要

次の例では、組み込みの SQL 関数である ai_query を使用します。 この関数はパブリック プレビューであり、定義が変更される可能性があります。 「ai_query() を使用した提供モデルに対するクエリの実行」を参照してください。

SELECT ai_query(
    "databricks-mpt-30b-instruct",
    "Can you explain AI in ten words?"
  )

次に示すのは補完モデルで想定されている要求形式です。 外部モデルに対しては、特定のプロバイダーとエンドポイント構成で有効な追加のパラメータを含めることができます。 「その他のクエリ パラメーター」を参照してください。

{
  "prompt": "What is mlflow?",
  "max_tokens": 100,
  "temperature": 0.1,
  "stop": [
    "Human:"
  ],
  "n": 1,
  "stream": false,
  "extra_params":{
    "top_p": 0.9
  }
}

想定されている応答形式は次のとおりです。

{
  "id": "cmpl-8FwDGc22M13XMnRuessZ15dG622BH",
  "object": "text_completion",
  "created": 1698809382,
  "model": "gpt-3.5-turbo-instruct",
  "choices": [
    {
    "text": "MLflow is an open-source platform for managing the end-to-end machine learning lifecycle. It provides tools for tracking experiments, managing and deploying models, and collaborating on projects. MLflow also supports various machine learning frameworks and languages, making it easier to work with different tools and environments. It is designed to help data scientists and machine learning engineers streamline their workflows and improve the reproducibility and scalability of their models.",
    "index": 0,
    "logprobs": null,
    "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 5,
    "completion_tokens": 83,
    "total_tokens": 88
  }
}

AI プレイグラウンドを使ってサポートされているモデル LLM とチャットする

AI プレイグラウンドを使って、サポートされている大規模言語モデルを操作できます。 AI プレイグラウンドは、Azure Databricks ワークスペースから LLM をテスト、ダイアログを表示、比較できるチャットのような環境です。

AI プレイグラウンド

その他のリソース