This notebook shows how to use UC functions as LangChain tools, with both LangChain and LangGraph agent APIs.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:
Copy
Ask AI
CREATE FUNCTION main.tools.python_exec ( code STRING COMMENT 'Python code to execute. Remember to print the final result to stdout.')RETURNS STRINGLANGUAGE PYTHONCOMMENT 'Executes Python code and returns its stdout.'AS $$ import sys from io import StringIO stdout = StringIO() sys.stdout = stdout exec(code) return stdout.getvalue()$$
It runs in a secure and isolated environment within a Databricks SQL warehouse.
Note: you may need to restart the kernel to use updated packages.
Copy
Ask AI
from databricks_langchain import ChatDatabricksllm = ChatDatabricks(endpoint="databricks-meta-llama-3-70b-instruct")
Copy
Ask AI
from databricks_langchain.uc_ai import ( DatabricksFunctionClient, UCFunctionToolkit, set_uc_function_client,)client = DatabricksFunctionClient()set_uc_function_client(client)tools = UCFunctionToolkit( # Include functions as tools using their qualified names. # You can use "{catalog_name}.{schema_name}.*" to get all functions in a schema. function_names=["main.tools.python_exec"]).tools
(Optional) To increase the retry time for getting a function execution response, set environment variable UC_TOOL_CLIENT_EXECUTION_TIMEOUT. Default retry time value is 120s.
from langgraph.prebuilt import create_react_agentagent = create_react_agent( llm, tools, prompt="You are a helpful assistant. Make sure to use tool for information.",)agent.invoke({"messages": [{"role": "user", "content": "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 is:329584533.59999996> Finished chain.
Copy
Ask AI
{'input': '36939 * 8922.4', 'output': 'The result of the multiplication is:\n\n329584533.59999996'}
Assistant
Responses are generated using AI and may contain mistakes.