Databricks Lakehouse Platform은 데이터, 분석 및 AI를 하나의 플랫폼에 통합합니다.
이 가이드는 Databricks chat models 시작하기에 대한 간단한 개요를 제공합니다. ChatDatabricks의 모든 기능과 구성에 대한 자세한 문서는 API reference를 참조하세요.

Overview

ChatDatabricks class는 Databricks Model Serving에 호스팅된 chat model endpoint를 래핑합니다. 이 예제 노트북은 serving endpoint를 래핑하고 LangChain 애플리케이션에서 chat model로 사용하는 방법을 보여줍니다.

Integration details

ClassPackageLocalSerializableDownloadsVersion
ChatDatabricksdatabricks-langchainbetaPyPI - DownloadsPyPI - Version

Model features

Tool callingStructured outputJSON modeImage inputAudio inputVideo inputToken-level streamingNative asyncToken usageLogprobs

Supported Methods

ChatDatabricks는 async API를 포함한 ChatModel의 모든 메서드를 지원합니다.

Endpoint Requirement

ChatDatabricks가 래핑하는 serving endpoint는 OpenAI 호환 chat input/output 형식을 가져야 합니다(참조). input 형식이 호환되는 한, ChatDatabricksDatabricks Model Serving에 호스팅된 모든 endpoint 유형에 사용할 수 있습니다:
  1. Foundation Models - DRBX, Llama3, Mixtral-8x7B 등과 같은 최첨단 foundation model의 큐레이션된 목록입니다. 이러한 endpoint는 별도의 설정 없이 Databricks workspace에서 바로 사용할 수 있습니다.
  2. Custom Models - MLflow를 통해 LangChain, Pytorch, Transformers 등과 같은 원하는 프레임워크로 custom model을 serving endpoint에 배포할 수도 있습니다.
  3. External Models - Databricks endpoint는 OpenAI GPT4와 같은 독점 model 서비스처럼 Databricks 외부에 호스팅된 model을 proxy로 제공할 수 있습니다.

Setup

Databricks model에 액세스하려면 Databricks 계정을 생성하고, 자격 증명을 설정하고(Databricks workspace 외부에 있는 경우에만), 필요한 패키지를 설치해야 합니다.

Credentials (only if you are outside Databricks)

Databricks 내부에서 LangChain 앱을 실행하는 경우 이 단계를 건너뛸 수 있습니다. 그렇지 않은 경우, Databricks workspace hostname과 personal access token을 각각 DATABRICKS_HOSTDATABRICKS_TOKEN 환경 변수에 수동으로 설정해야 합니다. access token을 얻는 방법은 Authentication Documentation을 참조하세요.
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: "
    )
Enter your Databricks access token:  ········

Installation

LangChain Databricks integration은 databricks-langchain 패키지에 있습니다.
pip install -qU databricks-langchain
먼저 Foundation Models endpoint로 호스팅된 DBRX-instruct model을 ChatDatabricks로 쿼리하는 방법을 시연합니다. 다른 유형의 endpoint의 경우 endpoint 자체를 설정하는 방법에 약간의 차이가 있지만, endpoint가 준비되면 ChatDatabricks로 쿼리하는 방법에는 차이가 없습니다. 다른 유형의 endpoint에 대한 예제는 이 노트북의 하단을 참조하세요.

Instantiation

from databricks_langchain import ChatDatabricks

chat_model = ChatDatabricks(
    endpoint="databricks-dbrx-instruct",
    temperature=0.1,
    max_tokens=256,
    # See https://python.langchain.com/api_reference/community/chat_models/langchain_community.chat_models.databricks.ChatDatabricks.html for other supported parameters
)

Invocation

chat_model.invoke("What is MLflow?")
AIMessage(content='MLflow is an open-source platform for managing end-to-end machine learning workflows. It was introduced by Databricks in 2018. MLflow provides tools for tracking experiments, packaging and sharing code, and deploying models. It is designed to work with any machine learning library and can be used in a variety of environments, including local machines, virtual machines, and cloud-based clusters. MLflow aims to streamline the machine learning development lifecycle, making it easier for data scientists and engineers to collaborate and deploy models into production.', response_metadata={'prompt_tokens': 229, 'completion_tokens': 104, 'total_tokens': 333}, id='run-d3fb4d06-3e10-4471-83c9-c282cc62b74d-0')
# You can also pass a list of messages
messages = [
    ("system", "You are a chatbot that can answer questions about Databricks."),
    ("user", "What is Databricks Model Serving?"),
]
chat_model.invoke(messages)
AIMessage(content='Databricks Model Serving is a feature of the Databricks platform that allows data scientists and engineers to easily deploy machine learning models into production. With Model Serving, you can host, manage, and serve machine learning models as APIs, making it easy to integrate them into applications and business processes. It supports a variety of popular machine learning frameworks, including TensorFlow, PyTorch, and scikit-learn, and provides tools for monitoring and managing the performance of deployed models. Model Serving is designed to be scalable, secure, and easy to use, making it a great choice for organizations that want to quickly and efficiently deploy machine learning models into production.', response_metadata={'prompt_tokens': 35, 'completion_tokens': 130, 'total_tokens': 165}, id='run-b3feea21-223e-4105-8627-41d647d5ccab-0')

Chaining

다른 chat model과 마찬가지로 ChatDatabricks는 복잡한 chain의 일부로 사용할 수 있습니다.
from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_messages(
    [
        (
            "system",
            "You are a chatbot that can answer questions about {topic}.",
        ),
        ("user", "{question}"),
    ]
)

chain = prompt | chat_model
chain.invoke(
    {
        "topic": "Databricks",
        "question": "What is Unity Catalog?",
    }
)
AIMessage(content="Unity Catalog is a new data catalog feature in Databricks that allows you to discover, manage, and govern all your data assets across your data landscape, including data lakes, data warehouses, and data marts. It provides a centralized repository for storing and managing metadata, data lineage, and access controls for all your data assets. Unity Catalog enables data teams to easily discover and access the data they need, while ensuring compliance with data privacy and security regulations. It is designed to work seamlessly with Databricks' Lakehouse platform, providing a unified experience for managing and analyzing all your data.", response_metadata={'prompt_tokens': 32, 'completion_tokens': 118, 'total_tokens': 150}, id='run-82d72624-f8df-4c0d-a976-919feec09a55-0')

Invocation (streaming)

for chunk in chat_model.stream("How are you?"):
    print(chunk.content, end="|")
I|'m| an| AI| and| don|'t| have| feelings|,| but| I|'m| here| and| ready| to| assist| you|.| How| can| I| help| you| today|?||

Async Invocation

import asyncio

country = ["Japan", "Italy", "Australia"]
futures = [chat_model.ainvoke(f"Where is the capital of {c}?") for c in country]
await asyncio.gather(*futures)

Tool calling

ChatDatabricks는 tool과 그 인수를 설명하고 model이 호출할 tool과 해당 tool에 대한 입력이 포함된 JSON 객체를 반환하도록 하는 OpenAI 호환 tool calling API를 지원합니다. tool-calling은 tool을 사용하는 chain과 agent를 구축하고 일반적으로 model에서 구조화된 출력을 얻는 데 매우 유용합니다. ChatDatabricks.bind_tools를 사용하면 Pydantic class, dict schema, LangChain tool 또는 함수를 tool로 model에 쉽게 전달할 수 있습니다. 내부적으로 이들은 다음과 같은 OpenAI 호환 tool schema로 변환됩니다:
{
    "name": "...",
    "description": "...",
    "parameters": {...}  # JSONSchema
}
그리고 모든 model 호출에 전달됩니다.
from pydantic import BaseModel, Field


class GetWeather(BaseModel):
    """Get the current weather in a given location"""

    location: str = Field(..., description="The city and state, e.g. San Francisco, CA")


class GetPopulation(BaseModel):
    """Get the current population in a given location"""

    location: str = Field(..., description="The city and state, e.g. San Francisco, CA")


llm_with_tools = chat_model.bind_tools([GetWeather, GetPopulation])
ai_msg = llm_with_tools.invoke(
    "Which city is hotter today and which is bigger: LA or NY?"
)
print(ai_msg.tool_calls)

Wrapping Custom Model Endpoint

전제 조건: endpoint가 준비되면 사용 패턴은 Foundation Models와 동일합니다.
chat_model_custom = ChatDatabricks(
    endpoint="YOUR_ENDPOINT_NAME",
    temperature=0.1,
    max_tokens=256,
)

chat_model_custom.invoke("How are you?")

Wrapping External Models

전제 조건: Proxy Endpoint 생성 먼저, 대상 external model에 대한 요청을 프록시하는 새로운 Databricks serving endpoint를 생성합니다. external model을 프록시하는 경우 endpoint 생성이 상당히 빠릅니다. 이를 위해서는 다음과 같이 Databricks secret manager 내에 OpenAI API Key를 등록해야 합니다:
# Replace `<scope>` with your scope
databricks secrets create-scope <scope>
databricks secrets put-secret <scope> openai-api-key --string-value $OPENAI_API_KEY
Databricks CLI를 설정하고 secret을 관리하는 방법은 docs.databricks.com/en/security/secrets/secrets.html을 참조하세요.
from mlflow.deployments import get_deploy_client

client = get_deploy_client("databricks")

secret = "secrets/<scope>/openai-api-key"  # replace `<scope>` with your scope
endpoint_name = "my-chat"  # rename this if my-chat already exists
client.create_endpoint(
    name=endpoint_name,
    config={
        "served_entities": [
            {
                "name": "my-chat",
                "external_model": {
                    "name": "gpt-3.5-turbo",
                    "provider": "openai",
                    "task": "llm/v1/chat",
                    "openai_config": {
                        "openai_api_key": "{{" + secret + "}}",
                    },
                },
            }
        ],
    },
)
endpoint 상태가 “Ready”가 되면 다른 유형의 endpoint와 동일한 방식으로 endpoint를 쿼리할 수 있습니다.
chat_model_external = ChatDatabricks(
    endpoint=endpoint_name,
    temperature=0.1,
    max_tokens=256,
)
chat_model_external.invoke("How to use Databricks?")

Function calling on Databricks

Databricks Function Calling은 OpenAI 호환이며 Foundation Model API의 일부로 model serving 중에만 사용할 수 있습니다. 지원되는 model에 대해서는 Databricks function calling introduction을 참조하세요.
llm = ChatDatabricks(endpoint="databricks-meta-llama-3-70b-instruct")
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "Get the current weather in a given location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city and state, e.g. San Francisco, CA",
                    },
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                },
            },
        },
    }
]

# supported tool_choice values: "auto", "required", "none", function name in string format,
# or a dictionary as {"type": "function", "function": {"name": <<tool_name>>}}
model = llm.bind_tools(tools, tool_choice="auto")

messages = [{"role": "user", "content": "What is the current temperature of Chicago?"}]
print(model.invoke(messages))
chain에서 UC function을 사용하는 방법에 대해서는 Databricks Unity Catalog를 참조하세요.

API reference

ChatDatabricks의 모든 기능과 구성에 대한 자세한 문서는 API reference를 참조하세요: api-docs.databricks.com/python/databricks-ai-bridge/latest/databricks_langchain.html#databricks_langchain.ChatDatabricks
Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I