Skip to main content

Databricks Unity Catalog (UC)

This notebook shows how to use UC functions as LangChain tools.

See Databricks documentation (AWS|Azure|GCP) to learn how to create SQL or Python functions in UC. Do not skip function and parameter comments, which are critical for LLMs to call functions properly.

In this example notebook, we create a simple Python function that executes arbitrary code and use it as a LangChain tool:

code STRING COMMENT 'Python code to execute. Remember to print the final result to stdout.'
COMMENT 'Executes Python code and returns its stdout.'
AS $$
import sys
from io import StringIO
stdout = StringIO()
sys.stdout = stdout
return stdout.getvalue()

It runs in a secure and isolated environment within a Databricks SQL warehouse.

%pip install --upgrade --quiet databricks-sdk langchain-community langchain-openai
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-3.5-turbo")
API Reference:ChatOpenAI
from import UCFunctionToolkit

tools = (
# You can find the SQL warehouse ID in its UI after creation.
# Include functions as tools using their qualified names.
# You can use "{catalog_name}.{schema_name}.*" to get all functions in a schema.
API Reference:UCFunctionToolkit
from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_messages(
"You are a helpful assistant. Make sure to use tool for information.",
("placeholder", "{chat_history}"),
("human", "{input}"),
("placeholder", "{agent_scratchpad}"),

agent = create_tool_calling_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
agent_executor.invoke({"input": "36939 * 8922.4"})

> Entering new AgentExecutor chain...

Invoking: `main__tools__python_exec` with `{'code': 'print(36939 * 8922.4)'}`

{"format": "SCALAR", "value": "329584533.59999996\n", "truncated": false}The result of the multiplication 36939 * 8922.4 is 329,584,533.60.

> Finished chain.
{'input': '36939 * 8922.4',
'output': 'The result of the multiplication 36939 * 8922.4 is 329,584,533.60.'}

Was this page helpful?

You can also leave detailed feedback on GitHub.