了解如何使用 MLflow 部署客户端或 Databricks OpenAI 客户端向已部署的代理发送请求。
若要了解如何部署代理,请参阅 为生成式 AI 应用程序部署代理。
MLflow 部署客户端(建议)
Databricks 建议使用 MLflow 部署客户端查询终结点。 MLflow 部署客户端具有以下优势:
- 允许提供可选的自定义输入。
- 允许你请求 MLflow 跟踪。
- 部署客户端的
predict
和predict_stream
方法与创作的代理的行为匹配。
以下示例演示如何使用 MLflow 部署客户端查询代理。 将messages
的内容替换为特定于您的代理的查询,并将<agent-endpoint-name
替换为您的终结点名称。 如果代理接受自定义输入,请在输入 Python 字典中包含它们。 请参阅 自定义输入和输出。
from mlflow.deployments import get_deploy_client
client = get_deploy_client()
input_example = {
"messages": [{"role": "user", "content": "What does Databricks do?"}],
## Optional: Include any custom inputs
## "custom_inputs": {"id": 5},
"databricks_options": {"return_trace": True},
}
endpoint = "<agent-endpoint-name>"
在设置请求格式后,针对非流式响应运行client.predict()
,针对流式响应运行client.predict_stream()
。 predict()
和 predict_stream()
调用您在撰写代理时定义的代理函数。 请参阅 流式处理输出代理。
## Call predict for non-streaming responses
response = client.predict(endpoint=endpoint, inputs=input_ex)
## Call predict_stream for streaming responses
streaming_response = client.predict_stream(endpoint=endpoint, inputs=input_ex)
Databricks OpenAI 客户端
或者,可以使用 Databricks OpenAI 客户端查询已部署的代理。 Databricks OpenAI 客户端仅支持聊天用例。 这意味着只能发送和接收消息。 不能使用 Databricks OpenAI 客户端来包含自定义输入或从终结点请求跟踪。
以下示例演示如何使用 Databricks OpenAI 客户端提交查询。 将messages
的内容替换为特定于您的代理的查询,并将<agent-endpoint-name
替换为您的终结点名称。
from databricks.sdk import WorkspaceClient
messages = [{"role": "user", "content": "What does Databricks do?"}]
endpoint = "<agent-endpoint-name>"
w = WorkspaceClient()
client = w.serving_endpoints.get_open_ai_client()
设置请求的格式后,运行 chat.completions.create()
。 包括参数 stream=True
用于流式响应。 chat.completion.create()
将调用您在创建代理时定义的 predict()
或 predict_stream()
函数。 请参阅 流式处理输出代理。
## Run for non-streaming responses
response = client.chat.completions.create(model=endpoint, messages=messages)
## Include stream=True for streaming responses
streaming_response = client.chat.completions.create(
model=endpoint, messages=msgs, stream=True
)