Databricks
Databricks Lakehouse Platform 將數據、分析和 AI 統一在一個平台上。
本筆記本提供了一個快速入門的概述,用於開始使用 Databricks LLM 模型。 有關所有功能和配置的詳細文檔,請前往 API 參考。
概述 (Overview)
Databricks
LLM 類別封裝了一個作為以下兩種端點類型之一託管的完成端點
- Databricks 模型服務,建議用於生產和開發,
- 叢集驅動程式代理應用程式,建議用於互動式開發。
這個範例筆記本展示了如何封裝您的 LLM 端點並將其用作 LangChain 應用程式中的 LLM。
限制 (Limitations)
Databricks
LLM 類別是 *舊版* 實作,並且在功能相容性方面存在一些限制。
- 僅支援同步調用。 不支援串流或非同步 API。
- 不支援
batch
API。
要使用這些功能,請改用新的 ChatDatabricks 類別。 ChatDatabricks
支援 ChatModel
的所有 API,包括串流、非同步、批次等。
設定 (Setup)
要存取 Databricks 模型,您需要建立一個 Databricks 帳戶,設定憑證(僅當您在 Databricks 工作區之外時),並安裝所需的套件。
憑證(僅當您在 Databricks 之外時)(Credentials (only if you are outside Databricks))
如果您在 Databricks 內部執行 LangChain 應用程式,您可以跳過此步驟。
否則,您需要手動將 Databricks 工作區主機名稱和個人存取權杖分別設定為 DATABRICKS_HOST
和 DATABRICKS_TOKEN
環境變數。 有關如何取得存取權杖,請參閱 身份驗證文檔。
import getpass
import os
os.environ["DATABRICKS_HOST"] = "https://your-workspace.cloud.databricks.com"
if "DATABRICKS_TOKEN" not in os.environ:
os.environ["DATABRICKS_TOKEN"] = getpass.getpass(
"Enter your Databricks access token: "
)
或者,您可以在初始化 Databricks
類別時傳遞這些參數。
from langchain_community.llms import Databricks
databricks = Databricks(
host="https://your-workspace.cloud.databricks.com",
# We strongly recommend NOT to hardcode your access token in your code, instead use secret management tools
# or environment variables to store your access token securely. The following example uses Databricks Secrets
# to retrieve the access token that is available within the Databricks notebook.
token=dbutils.secrets.get(scope="YOUR_SECRET_SCOPE", key="databricks-token"), # noqa: F821
)
安裝 (Installation)
LangChain Databricks 整合位於 langchain-community
套件中。 此外,執行此筆記本中的程式碼需要 mlflow >= 2.9
。
%pip install -qU langchain-community mlflow>=2.9.0
封裝模型服務端點 (Wrapping Model Serving Endpoint)
先決條件:
- 已註冊 LLM 並部署到 Databricks 服務端點。
- 您擁有該端點的 「可查詢」權限。
預期的 MLflow 模型簽章為
- 輸入 (inputs):
[{"name": "prompt", "type": "string"}, {"name": "stop", "type": "list[string]"}]
- 輸出 (outputs):
[{"type": "string"}]
呼叫 (Invocation)
from langchain_community.llms import Databricks
llm = Databricks(endpoint_name="YOUR_ENDPOINT_NAME")
llm.invoke("How are you?")
'I am happy to hear that you are in good health and as always, you are appreciated.'
llm.invoke("How are you?", stop=["."])
'Good'
轉換輸入與輸出 (Transform Input and Output)
有時您可能想要包裝具有不相容模型簽章的服務端點,或者您想要插入額外的配置。您可以使用 transform_input_fn
和 transform_output_fn
參數來定義額外的前/後處理。
# Use `transform_input_fn` and `transform_output_fn` if the serving endpoint
# expects a different input schema and does not return a JSON string,
# respectively, or you want to apply a prompt template on top.
def transform_input(**request):
full_prompt = f"""{request["prompt"]}
Be Concise.
"""
request["prompt"] = full_prompt
return request
def transform_output(response):
return response.upper()
llm = Databricks(
endpoint_name="YOUR_ENDPOINT_NAME",
transform_input_fn=transform_input,
transform_output_fn=transform_output,
)
llm.invoke("How are you?")
'I AM DOING GREAT THANK YOU.'