> ## Documentation Index
> Fetch the complete documentation index at: https://cndoc-langchain.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Databricks 集成

> 使用 LangChain Python 与 Databricks LLM 进行集成。

> [Databricks](https://www.databricks.com/) Lakehouse 平台将数据、分析和 AI 统一在一个平台上。

本指南提供了快速入门 Databricks [LLM 模型](https://python.langchain.com/docs/concepts/text_llms)的概览。有关所有功能和配置的详细文档，请参阅 [API 参考](https://reference.langchain.com/python/langchain-community/llms/databricks/Databricks)。

## 概述

`Databricks` LLM 类封装了一个托管为以下两种端点类型之一的补全端点：

* [Databricks 模型服务](https://docs.databricks.com/en/machine-learning/model-serving/index.html)，推荐用于生产和开发，
* 集群驱动程序代理应用，推荐用于交互式开发。

此示例笔记本展示了如何封装您的 LLM 端点并将其用作 LangChain 应用程序中的 LLM。

## 限制

`Databricks` LLM 类是*遗留*实现，在功能兼容性方面存在一些限制。

* 仅支持同步调用。不支持流式或异步 API。
* 不支持 `batch` API。

要使用这些功能，请改用新的 [ChatDatabricks](https://python.langchain.com/docs/integrations/chat/databricks) 类。`ChatDatabricks` 支持 `ChatModel` 的所有 API，包括流式、异步、批处理等。

## 设置

要访问 Databricks 模型，您需要创建一个 Databricks 帐户、设置凭据（仅当您在 Databricks 工作区之外时），并安装所需的包。

### 凭据（仅当您在 Databricks 之外时）

如果您在 Databricks 内部运行 LangChain 应用程序，可以跳过此步骤。

否则，您需要手动将 Databricks 工作区主机名和个人访问令牌分别设置为 `DATABRICKS_HOST` 和 `DATABRICKS_TOKEN` 环境变量。有关如何获取访问令牌，请参阅[身份验证文档](https://docs.databricks.com/en/dev-tools/auth/index.html#databricks-personal-access-tokens)。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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` 类时传递这些参数。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_community.llms import Databricks

databricks = Databricks(
    host="https://your-workspace.cloud.databricks.com",
    # 我们强烈建议不要在代码中硬编码您的访问令牌，而是使用密钥管理工具
    # 或环境变量来安全地存储您的访问令牌。以下示例使用 Databricks Secrets
    # 来检索在 Databricks 笔记本中可用的访问令牌。
    token=dbutils.secrets.get(scope="YOUR_SECRET_SCOPE", key="databricks-token"),
)
```

### 安装

LangChain Databricks 集成位于 `langchain-community` 包中。此外，运行此笔记本中的代码需要 `mlflow >= 2.9`。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pip install -qU langchain-community mlflow>=2.9.0
```

## 封装模型服务端点

### 先决条件

* 一个 LLM 已注册并部署到 [Databricks 服务端点](https://docs.databricks.com/machine-learning/model-serving/index.html)。
* 您拥有对该端点的 ["Can Query" 权限](https://docs.databricks.com/security/auth-authz/access-control/serving-endpoint-acl.html)。

预期的 MLflow 模型签名是：

* 输入：`[{"name": "prompt", "type": "string"}, {"name": "stop", "type": "list[string]"}]`
* 输出：`[{"type": "string"}]`

### 调用

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_community.llms import Databricks

llm = Databricks(endpoint_name="YOUR_ENDPOINT_NAME")
llm.invoke("How are you?")
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
'I am happy to hear that you are in good health and as always, you are appreciated.'
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
llm.invoke("How are you?", stop=["."])
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
'Good'
```

### 转换输入和输出

有时您可能想要封装一个模型签名不兼容的服务端点，或者您想要插入额外的配置。您可以使用 `transform_input_fn` 和 `transform_output_fn` 参数来定义额外的预处理/后处理。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# 如果服务端点期望不同的输入模式且不返回 JSON 字符串，
# 或者您想在顶部应用提示模板，请使用 `transform_input_fn` 和 `transform_output_fn`。


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

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
'I AM DOING GREAT THANK YOU.'
```

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档连接](/use-these-docs)到 Claude、VSCode 等，通过 MCP 获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/python/integrations/llms/databricks.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
