使用 Databricks Unity Catalog 将 SQL 和 Python 函数集成为 Anthropic SDK LLM 调用中的工具。 此集成将 Unity Catalog 的治理与 Anthropic 模型相结合,以创建强大的 gen AI 应用程序。
要求
- 使用 Databricks Runtime 15.0 及更高版本。
将 Unity Catalog 工具与 Anthropic 集成
在笔记本或 Python 脚本中运行以下代码以创建 Unity Catalog 工具,并在调用 Anthropic 模型时使用它。
安装适用于 Anthropic 的 Databricks Unity Catalog 集成包。
%pip install unitycatalog-anthropic[databricks] dbutils.library.restartPython()
创建 Unity 目录函数客户端的实例。
from unitycatalog.ai.core.base import get_uc_function_client client = get_uc_function_client()
创建用 Python 编写的 Unity 目录函数。
CATALOG = "your_catalog" SCHEMA = "your_schema" func_name = f"{CATALOG}.{SCHEMA}.weather_function" def weather_function(___location: str) -> str: """ Fetches the current weather from a given ___location in degrees Celsius. Args: ___location (str): The ___location to fetch the current weather from. Returns: str: The current temperature for the ___location provided in Celsius. """ return f"The current temperature for {___location} is 24.5 celsius" client.create_python_function( func=weather_function, catalog=CATALOG, schema=SCHEMA, replace=True )
将 Unity Catalog 函数的实例创建为工具包。
from unitycatalog.ai.anthropic.toolkit import UCFunctionToolkit # Create an instance of the toolkit toolkit = UCFunctionToolkit(function_names=[func_name], client=client)
在 Anthropic 中使用工具调用。
import anthropic # Initialize the Anthropic client with your API key anthropic_client = anthropic.Anthropic(api_key="YOUR_ANTHROPIC_API_KEY") # User's question question = [{"role": "user", "content": "What's the weather in New York City?"}] # Make the initial call to Anthropic response = anthropic_client.messages.create( model="claude-3-5-sonnet-20240620", # Specify the model max_tokens=1024, # Use 'max_tokens' instead of 'max_tokens_to_sample' tools=toolkit.tools, messages=question # Provide the conversation history ) # Print the response content print(response)
构造工具响应。 如果需要调用工具,则来自 Claude 模型的响应包含一个工具请求元数据块。
from unitycatalog.ai.anthropic.utils import generate_tool_call_messages
# Call the UC function and construct the required formatted response
tool_messages = generate_tool_call_messages(
response=response,
client=client,
conversation_history=question
)
# Continue the conversation with Anthropic
tool_response = anthropic_client.messages.create(
model="claude-3-5-sonnet-20240620",
max_tokens=1024,
tools=toolkit.tools,
messages=tool_messages,
)
print(tool_response)
该 unitycatalog.ai-anthropic
包包括一个消息处理程序实用程序,用于简化对 Unity Catalog 函数的调用的解析和处理。 该实用程序执行以下作:
- 检测工具调用要求。
- 从查询中提取工具调用信息。
- 执行对 Unity Catalog 函数的调用。
- 分析来自 Unity Catalog 函数的响应。
- 制作下一个消息格式以继续与 Claude 的对话。
注释
必须在 API 的generate_tool_call_messages
参数中提供conversation_history
整个对话历史记录。 Claude 模型需要初始化对话(原始用户输入问题)以及所有后续 LLM 生成的响应和多轮次工具调用结果。