Condividi tramite


Eseguire query sui modelli di base

Questo articolo illustra come formattare le richieste di query per i modelli di base e inviarle all'endpoint di gestione del modello.

Per le richieste di query dei modelli di Machine Learning o Python tradizionali, vedere Eseguire query sugli endpoint per i modelli personalizzati.

Databricks Model Serving supporta le API dei modelli di base e i modelli esterni per l'accesso ai modelli di base e usa un'API e un SDK openAI unificato per l'esecuzione di query. In questo modo è possibile sperimentare e personalizzare i modelli di base per la produzione in cloud e provider supportati.

Databricks Model Serving offre le opzioni seguenti per l'invio di richieste di assegnazione dei punteggi ai modelli di base:

metodo Dettagli
Client OpenAI Eseguire una query su un modello ospitato da un endpoint di Gestione modelli di Databricks usando il client OpenAI. Specificare il nome dell'endpoint di gestione del model modello come input. Supportato per i modelli di chat, incorporamenti e completamenti resi disponibili dalle API del modello foundation o da modelli esterni.
Interfaccia utente di gestione Selezionare Endpoint di query nella pagina Endpoint di servizio . Inserire i dati di input del modello in formato JSON e fare clic su Invia richiesta. Se nel modello è registrato un esempio di input, usare Mostra esempio per caricarlo.
REST API Chiamare ed eseguire query sul modello usando l'API REST. Per informazioni dettagliate, vedere POST /serving-endpoints/{name}/chiamate . Per le richieste di assegnazione dei punteggi agli endpoint che servono più modelli, vedere Eseguire query su singoli modelli dietro un endpoint.
MLflow Deployments SDK Usare la funzione predict() di MLflow Deployments SDK per eseguire query sul modello.
Databricks GenAI SDK Databricks GenAI SDK è un livello sopra l'API REST. Gestisce dettagli di basso livello, ad esempio l'autenticazione e il mapping degli ID modello agli URL degli endpoint, semplificando l'interazione con i modelli. L'SDK è progettato per essere usato dai notebook di Databricks.
Funzione SQL Richiamare l'inferenza del modello direttamente da SQL usando la ai_query funzione SQL. Vedere Eseguire query su un modello servito con ai_query().

Requisiti

Importante

Come procedura consigliata per la sicurezza per gli scenari di produzione, Databricks consiglia di usare token OAuth da computer a computer per l'autenticazione durante l'ambiente di produzione.

Per il test e lo sviluppo, Databricks consiglia di usare un token di accesso personale appartenente alle entità servizio anziché agli utenti dell'area di lavoro. Per creare token per le entità servizio, vedere Gestire i token per un'entità servizio.

Installare i pacchetti

Dopo aver selezionato un metodo di query, è prima necessario installare il pacchetto appropriato nel cluster.

Client Openai

Per usare il client OpenAI, è necessario installare il openai pacchetto nel cluster. Eseguire quanto segue nel notebook o nel terminale locale:

!pip install openai

Di seguito è necessario solo quando si installa il pacchetto in un notebook di Databricks

dbutils.library.restartPython()

API REST

L'accesso all'API REST di servizio è disponibile in Databricks Runtime per Machine Learning.

Sdk per le distribuzioni mlflow

!pip install mlflow

Di seguito è necessario solo quando si installa il pacchetto in un notebook di Databricks

dbutils.library.restartPython()

Databricks genai sdk

 !pip install databricks-genai

Di seguito è necessario solo quando si installa il pacchetto in un notebook di Databricks

 dbutils.library.restartPython()

Eseguire query su un modello di completamento della chat

Di seguito sono riportati alcuni esempi per l'esecuzione di query su un modello di chat.

Per un esempio di inferenza batch, vedere Inferenza batch con le API del modello di base.

Client Openai

Di seguito è riportata una richiesta di chat per il modello DBRX Instruct reso disponibile dall'endpoint con pagamento in base al token delle API del modello foundation nell'area databricks-dbrx-instruct di lavoro.

Per usare il client OpenAI, specificare il nome dell'endpoint model di gestione del modello come input. L'esempio seguente presuppone che nel calcolo sia installato un tokenopenai DELL'API Databricks. È anche necessaria l'istanza dell'area di lavoro di Databricks per connettere il client OpenAI a Databricks.


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
)

API REST

Importante

L'esempio seguente usa i parametri dell'API REST per l'esecuzione di query sugli endpoint che servono i modelli di base. Questi parametri sono Anteprima pubblica e la definizione potrebbe cambiare. Vedere POST /serving-endpoints/{name}/chiamate.

Di seguito è riportata una richiesta di chat per il modello DBRX Instruct reso disponibile dall'endpoint con pagamento in base al token delle API del modello foundation nell'area databricks-dbrx-instruct di lavoro.

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 \

Sdk per le distribuzioni mlflow

Importante

L'esempio seguente usa l'API predict() di MLflow Deployments SDK.

Di seguito è riportata una richiesta di chat per il modello DBRX Instruct reso disponibile dall'endpoint con pagamento in base al token delle API del modello foundation nell'area databricks-dbrx-instruct di lavoro.


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 genai sdk

Di seguito è riportata una richiesta di chat per il modello DBRX Instruct reso disponibile dall'endpoint con pagamento in base al token delle API del modello foundation nell'area databricks-dbrx-instruct di lavoro.

from databricks_genai_inference import ChatCompletion

# 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"

response = ChatCompletion.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=128)
print(f"response.message:{response.message}")

LangChain

Per eseguire una query su un endpoint del modello di base usando LangChain, è possibile eseguire una delle operazioni seguenti:

  • Importare la Databricks classe LLM e specificare e endpoint_nametransform_input_fn.
  • Importare la ChatDatabricks classe ChatModel e specificare .endpoint

Nell'esempio seguente viene usata la Databricks classe LLM in LangChain per eseguire query sull'endpoint con pagamento in base al token delle API del modello di base, databricks-dbrx-instruct. Le API del modello foundation prevedono messages nel dizionario delle richieste, mentre LangChain Databricks LLM per impostazione predefinita fornisce prompt nel dizionario delle richieste. Usare la transform_input funzione per preparare il dizionario delle richieste nel formato previsto.

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?")

Nell'esempio seguente viene utilizzata la ChatDatabricks classe ChatModel e viene specificato .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

Importante

Nell'esempio seguente viene usata la funzione SQL predefinita ai_query. Questa funzione è Anteprima pubblica e la definizione potrebbe cambiare. Vedere Eseguire query su un modello servito con ai_query().

Di seguito è riportata una richiesta di chat resa llama-2-70b-chat disponibile dall'endpoint con pagamento in base al token delle API del modello foundation nell'area databricks-llama-2-70b-chat di lavoro.

Nota

La ai_query() funzione non supporta gli endpoint di query che servono il modello DBRX o DBRX Instruct.

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

Di seguito è riportato il formato di richiesta previsto per un modello di chat. Per i modelli esterni, è possibile includere parametri aggiuntivi validi per un determinato provider e configurazione dell'endpoint. Vedere Parametri di query aggiuntivi.

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

Di seguito è riportato un formato di risposta previsto:

{
  "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
}

Sessione chat

Databricks GenAI SDK offre ChatSession la classe per gestire le conversazioni di chat a più round. Offre le funzioni seguenti:

Funzione Restituzione Descrizione
reply (string) Accetta un nuovo messaggio utente
last string Ultimo messaggio dall'assistente
history elenco dict Messaggi nella cronologia delle chat, inclusi i ruoli.
count int Numero di round di chat condotti finora.

Per inizializzare ChatSession, si usa lo stesso set di argomenti di ChatCompletione tali argomenti vengono usati in tutta la sessione di chat.


from databricks_genai_inference import ChatSession

chat = ChatSession(model="llama-2-70b-chat", system_message="You are a helpful assistant.", max_tokens=128)
chat.reply("Knock, knock!")
chat.last # return "Hello! Who's there?"
chat.reply("Guess who!")
chat.last # return "Okay, I'll play along! Is it a person, a place, or a thing?"

chat.history
# return: [
#     {'role': 'system', 'content': 'You are a helpful assistant.'},
#     {'role': 'user', 'content': 'Knock, knock.'},
#     {'role': 'assistant', 'content': "Hello! Who's there?"},
#     {'role': 'user', 'content': 'Guess who!'},
#     {'role': 'assistant', 'content': "Okay, I'll play along! Is it a person, a place, or a thing?"}
# ]

Eseguire query su un modello di incorporamento

Di seguito è riportata una richiesta di incorporamento per il bge-large-en modello reso disponibile dalle API del modello foundation.

Client Openai

Per usare il client OpenAI, specificare il nome dell'endpoint model di gestione del modello come input. L'esempio seguente presuppone che nel cluster sia installato un token openai API Databricks.


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"
)

API REST

Importante

L'esempio seguente usa i parametri dell'API REST per l'esecuzione di query sugli endpoint che servono i modelli di base. Questi parametri sono Anteprima pubblica e la definizione potrebbe cambiare. Vedere POST /serving-endpoints/{name}/chiamate.


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

Sdk per le distribuzioni mlflow

Importante

L'esempio seguente usa l'API predict() di MLflow Deployments SDK.


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 genai sdk


from databricks_genai_inference import Embedding

# 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"

response = Embedding.create(
    model="bge-large-en",
    input="3D ActionSLAM: wearable person tracking in multi-floor environments")
print(f'embeddings: {response.embeddings}')

LangChain

Per usare un modello di API modello di Databricks Foundation in LangChain come modello di incorporamento, importare la DatabricksEmbeddings classe e specificare il endpoint parametro come segue:

from langchain.embeddings import DatabricksEmbeddings

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

SQL

Importante

Nell'esempio seguente viene usata la funzione SQL predefinita ai_query. Questa funzione è Anteprima pubblica e la definizione potrebbe cambiare. Vedere Eseguire query su un modello servito con ai_query().


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

Di seguito è riportato il formato di richiesta previsto per un modello di incorporamento. Per i modelli esterni, è possibile includere parametri aggiuntivi validi per un determinato provider e configurazione dell'endpoint. Vedere Parametri di query aggiuntivi.


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

Di seguito è riportato il formato di risposta previsto:

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

Eseguire query su un modello di completamento del testo

Di seguito è riportata una richiesta di completamento per il databricks-mpt-30b-instruct modello reso disponibile dalle API del modello foundation. Per i parametri e la sintassi, vedere Attività completamento.

Client Openai

Per usare il client OpenAI, specificare il nome dell'endpoint model di gestione del modello come input. L'esempio seguente presuppone che nel cluster sia installato un token openai API Databricks.


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
)

API REST

Importante

L'esempio seguente usa i parametri dell'API REST per l'esecuzione di query sugli endpoint che servono i modelli di base. Questi parametri sono Anteprima pubblica e la definizione potrebbe cambiare. Vedere POST /serving-endpoints/{name}/chiamate.


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

Sdk per le distribuzioni mlflow

Importante

L'esempio seguente usa l'API predict() di MLflow Deployments SDK.


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")

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
    }
)

Databricks genai sdk


from databricks_genai_inference import Completion

# 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"

response = Completion.create(
    model="databricks-mpt-30b-instruct",
    prompt="Write 3 reasons why you should train an AI model on domain specific data sets.",
    max_tokens=128)
print(f"response.text:{response.text:}")

SQL

Importante

Nell'esempio seguente viene usata la funzione SQL predefinita ai_query. Questa funzione è Anteprima pubblica e la definizione potrebbe cambiare. Vedere Eseguire query su un modello servito con ai_query().

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

Di seguito è riportato il formato di richiesta previsto per un modello di completamento. Per i modelli esterni, è possibile includere parametri aggiuntivi validi per un determinato provider e configurazione dell'endpoint. Vedere Parametri di query aggiuntivi.

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

Di seguito è riportato il formato di risposta previsto:

{
  "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
  }
}

Chat con llms supportati con ai playground di intelligenza artificiale

È possibile interagire con i modelli linguistici di grandi dimensioni supportati usando AI Playground. AI Playground è un ambiente simile a una chat in cui è possibile testare, richiedere e confrontare IMS dall'area di lavoro di Azure Databricks.

Playground per intelligenza artificiale

Risorse aggiuntive