Pular para o conteúdo principal

tutorial: Criar endpoint de modelo externo para consultar modelos OpenAI

Este artigo fornece instruções passo a passo para configurar e consultar um modelo externo endpoint que serve modelos OpenAI para conclusões, bate-papo e embeddings usando o MLflow Deployments SDK. Saiba mais sobre modelos externos.

Se o senhor preferir usar a UI de serviço para realizar essa tarefa, consulte Criar um modelo de serviço externo endpoint.

Requisitos

  • Databricks Runtime 13,0 ML ou acima.
  • MLflow 2,9 ou acima.
  • OpenAI API key.
  • Instale a versão Databricks CLI versão 0.205 ou acima.

(Opcional) Etapa 0: Armazene o OpenAI API key usando o Databricks Secrets CLI

O senhor pode fornecer sua chave API como texto simples strings na Etapa 3 ou usando Databricks Secrets.

Para armazenar o OpenAI API key como um segredo, o senhor pode usar o Databricks Secrets CLI (versão 0.205 e acima). O senhor também pode usar a API REST para segredos.

A seguir, o senhor cria um escopo secreto chamado my_openai_secret_scope e, em seguida, cria o segredo openai_api_key nesse escopo.

sh
databricks secrets create-scope my_openai_secret_scope
databricks secrets put-secret my_openai_secret_scope openai_api_key

Etapa 1: Instalar o MLflow com suporte a modelos externos

Use o seguinte para instalar uma versão do MLflow com suporte a modelos externos:

sh
%pip install mlflow[genai]>=2.9.0

Etapa 2: Criar e gerenciar um endpoint de modelo externo

important

Os exemplos de código nesta seção demonstram o uso do Public Preview MLflow Deployments CRUD SDK.

Para criar um endpoint de modelo externo para um modelo de linguagem grande (LLM), use o método create_endpoint() do SDK do MLflow Deployments. O senhor também pode criar um endpoint de modelo externo na UI de serviço.

O trecho de código a seguir cria um endpoint de conclusões para o OpenAI gpt-3.5-turbo-instruct, conforme especificado na seção served_entities da configuração. Para seu endpoint, certifique-se de preencher name e openai_api_key com seus valores exclusivos para cada campo.

Python
import mlflow.deployments

client = mlflow.deployments.get_deploy_client("databricks")
client.create_endpoint(
name="openai-completions-endpoint",
config={
"served_entities": [{
"name": "openai-completions",
"external_model": {
"name": "gpt-3.5-turbo-instruct",
"provider": "openai",
"task": "llm/v1/completions",
"openai_config": {
"openai_api_key": "{{secrets/my_openai_secret_scope/openai_api_key}}"
}
}
}]
}
)

O seguinte trecho de código mostra como o senhor pode fornecer seu OpenAI API key como uma cadeia de caracteres de texto simples para uma maneira alternativa de criar as mesmas conclusões endpoint que o acima.

Python
import mlflow.deployments

client = mlflow.deployments.get_deploy_client("databricks")
client.create_endpoint(
name="openai-completions-endpoint",
config={
"served_entities": [{
"name": "openai-completions",
"external_model": {
"name": "gpt-3.5-turbo-instruct",
"provider": "openai",
"task": "llm/v1/completions",
"openai_config": {
"openai_api_key_plaintext": "sk-yourApiKey"
}
}
}]
}
)

Se estiver usando o Azure OpenAI, também é possível especificar o nome da implantação do Azure OpenAI, o URL do endpoint e a versão do API na seção openai_config da configuração.

Python
client.create_endpoint(
name="openai-completions-endpoint",
config={
"served_entities": [
{
"name": "openai-completions",
"external_model": {
"name": "gpt-3.5-turbo-instruct",
"provider": "openai",
"task": "llm/v1/completions",
"openai_config": {
"openai_api_type": "azure",
"openai_api_key": "{{secrets/my_openai_secret_scope/openai_api_key}}",
"openai_api_base": "https://my-azure-openai-endpoint.openai.azure.com",
"openai_deployment_name": "my-gpt-35-turbo-deployment",
"openai_api_version": "2023-05-15"
},
},
}
],
},
)

Para atualizar um endpoint, use update_endpoint(). O trecho de código a seguir demonstra como atualizar os limites de tarifa do site endpointpara 20 chamadas por minuto por usuário.

Python
client.update_endpoint(
endpoint="openai-completions-endpoint",
config={
"rate_limits": [
{
"key": "user",
"renewal_period": "minute",
"calls": 20
}
],
},
)

Etapa 3: Enviar solicitações para um endpoint de modelo externo

important

Os exemplos de código nesta seção demonstram o uso do método predict() do MLflow Deployments SDK.

O senhor pode enviar solicitações de bate-papo, conclusões e incorporações para um endpoint de modelo externo usando o método predict() do MLflow Deployments SDK.

O seguinte envia uma solicitação para gpt-3.5-turbo-instruct hospedada pela OpenAI.

Python
completions_response = client.predict(
endpoint="openai-completions-endpoint",
inputs={
"prompt": "What is the capital of France?",
"temperature": 0.1,
"max_tokens": 10,
"n": 2
}
)
completions_response == {
"id": "cmpl-8QW0hdtUesKmhB3a1Vel6X25j2MDJ",
"object": "text_completion",
"created": 1701330267,
"model": "gpt-3.5-turbo-instruct",
"choices": [
{
"text": "The capital of France is Paris.",
"index": 0,
"finish_reason": "stop",
"logprobs": None
},
{
"text": "Paris is the capital of France",
"index": 1,
"finish_reason": "stop",
"logprobs": None
},
],
"usage": {
"prompt_tokens": 7,
"completion_tokens": 16,
"total_tokens": 23
}
}

Etapa 4: comparar modelos de um fornecedor diferente

A servindo modelo oferece suporte a muitos provedores de modelos externos, incluindo Open AI, Anthropic, Cohere, Amazon Bedrock, Google Cloud Vertex AI, entre outros. O senhor pode comparar LLMs entre provedores, ajudando-o a otimizar a precisão, a velocidade e o custo de seus aplicativos usando o AI Playground.

O exemplo a seguir cria um endpoint para o Anthropic claude-2 e compara sua resposta a uma pergunta que usa o OpenAI gpt-3.5-turbo-instruct. Ambas as respostas têm o mesmo formato padrão, o que facilita a comparação.

Criar um endpoint para Anthropic claude-2

Python
import mlflow.deployments

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

client.create_endpoint(
name="anthropic-completions-endpoint",
config={
"served_entities": [
{
"name": "claude-completions",
"external_model": {
"name": "claude-2",
"provider": "anthropic",
"task": "llm/v1/completions",
"anthropic_config": {
"anthropic_api_key": "{{secrets/my_anthropic_secret_scope/anthropic_api_key}}"
},
},
}
],
},
)

Comparar as respostas de cada endpoint

Python

openai_response = client.predict(
endpoint="openai-completions-endpoint",
inputs={
"prompt": "How is Pi calculated? Be very concise."
}
)
anthropic_response = client.predict(
endpoint="anthropic-completions-endpoint",
inputs={
"prompt": "How is Pi calculated? Be very concise."
}
)
openai_response["choices"] == [
{
"text": "Pi is calculated by dividing the circumference of a circle by its diameter."
" This constant ratio of 3.14159... is then used to represent the relationship"
" between a circle's circumference and its diameter, regardless of the size of the"
" circle.",
"index": 0,
"finish_reason": "stop",
"logprobs": None
}
]
anthropic_response["choices"] == [
{
"text": "Pi is calculated by approximating the ratio of a circle's circumference to"
" its diameter. Common approximation methods include infinite series, infinite"
" products, and computing the perimeters of polygons with more and more sides"
" inscribed in or around a circle.",
"index": 0,
"finish_reason": "stop",
"logprobs": None
}
]

Recurso adicional

Modelos externos no Mosaic AI Model Serving.