本 notebook 展示如何使用 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.在此示例中 notebook, we create a simple Python function that executes arbitrary code and use it as a LangChain tool:
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.
from databricks_langchain import ChatDatabricksllm = ChatDatabricks(endpoint="databricks-meta-llama-3-70b-instruct")
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 langchain.agents import create_agentagent = create_agent( llm, tools, system_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.
{'input': '36939 * 8922.4', 'output': 'The result of the multiplication is:\n\n329584533.59999996'}
Connect these docs to Claude, VSCode, and more via MCP for real-time answers.