CURIOUS_DE
Databricks Partner

 

Steps Explained: Connect LangChain with Databricks Unity Catalog

1. Install Required Packages

pip install langchain databricks-sql-connector

2. Configure Access to Databricks Unity Catalog

Use Databricks SQL Connector to connect to Unity Catalog tables.

from databricks import sql

conn = sql.connect(
    server_hostname = "<your-databricks-workspace-url>",  # e.g. "adb-1234567890123456.7.azuredatabricks.net"
    http_path       = "<sql-endpoint-http-path>",         # From Databricks SQL Warehouse
    access_token    = "<your-personal-access-token>"      # Or use Databricks secrets
)

cursor = conn.cursor()
cursor.execute("SELECT * FROM catalog_name.schema_name.table_name LIMIT 5")
result = cursor.fetchall()

for row in result:
    print(row)

NOTE PS:This works for tables registered in Unity Catalog — ensure the SQL Warehouse you're using has access to the correct catalog/schema/table.

3.Use with LangChain: SQLDatabaseChain

Now you can use LangChain's SQLDatabaseChain to query your Delta tables.

from langchain.chains import SQLDatabaseChain
from langchain.agents.agent_toolkits import SQLDatabaseToolkit
from langchain.sql_database import SQLDatabase
from langchain.chat_models import ChatOpenAI

db = SQLDatabase.from_databricks(
    catalog="your_catalog",
    schema="your_schema",
    token="<your-access-token>",
    host="adb-xxx.azuredatabricks.net",
    http_path="<your-http-path>"
)

llm = ChatOpenAI(temperature=0)

db_chain = SQLDatabaseChain.from_llm(llm, db, verbose=True)

# Ask a question
db_chain.run("What is the average usage in the last 7 days?")

 

Databricks Solution Architect