Unity Catalogツールをサードパーティの生成AIフレームワークと統合してください。
Unity Catalog AI エージェントツールは、LangChain、LlamaIndex、OpenAI、Anthropic などの人気のある生成AIライブラリで使用できます。これらの統合は、Unity Catalog ツールのガバナンスとサードパーティのエージェントオーサリングフレームワークの機能を組み合わせたものです。例えば:
- LangChainでは、Unity Catalog 関数は、データをクエリしたり変換したりするタスクを実行するために、エージェントのワークフローの一部になります。
- OpenAIまたはAnthropicの統合では、実行中にAIモデルによって関数が直接呼び出されます。
次のタブでフレームワークを選択し、Unity Catalog ツールを作成してそのフレームワークで使用します。Databricks ノートブックまたは Python スクリプトでコードを実行します。
要件
- Python 3.10 以降をインストールします。
- LangChain
- LlamaIndex
- OpenAI
- Anthropic
Databricks Unity Catalog を使用して、SQL 関数と Python 関数を LangChain および LangGraph ワークフローのツールとして統合します。この統合により、Unity Catalog のガバナンスと LangChain の機能が組み合わされ、強力な LLM ベースのアプリケーションを構築できます。
この例では、Unity Catalog ツールを作成し、その機能をテストして、エージェントに追加します。
依存関係をインストールする
Databricks オプションを使用して Unity Catalog AI パッケージをインストールし、LangChain 統合パッケージをインストールします。
# Install the Unity Catalog AI integration package with the Databricks extra
%pip install unitycatalog-langchain[databricks]
# Install Databricks Langchain integration package
%pip install databricks-langchain
dbutils.library.restartPython()
Databricks ファンクションクライアントを初期化
Databricks 関数クライアントを初期化します。
from unitycatalog.ai.core.base import get_uc_function_client
client = get_uc_function_client()
ツールのロジックを定義します。
ツールのロジックを含む Unity Catalog 関数を作成します。
CATALOG = "my_catalog"
SCHEMA = "my_schema"
def add_numbers(number_1: float, number_2: float) -> float:
"""
A function that accepts two floating point numbers adds them,
and returns the resulting sum as a float.
Args:
number_1 (float): The first of the two numbers to add.
number_2 (float): The second of the two numbers to add.
Returns:
float: The sum of the two input numbers.
"""
return number_1 + number_2
function_info = client.create_python_function(
func=add_numbers,
catalog=CATALOG,
schema=SCHEMA,
replace=True
)
関数をテストする
期待通りに機能することを確認するために、関数をテストしてください。
result = client.execute_function(
function_name=f"{CATALOG}.{SCHEMA}.add_numbers",
parameters={"number_1": 36939.0, "number_2": 8922.4}
)
result.value # OUTPUT: '45861.4'
UCFunctionToolKitを使用して関数をラップします。
UCFunctionToolkitを使用して関数をラップして、エージェントオーサリングライブラリからアクセスできるようにします。このツールキットは、異なるライブラリ間での一貫性を確保し、レトリーバーの自動トレースなどの便利な機能を追加します。
from databricks_langchain import UCFunctionToolkit
# Create a toolkit with the Unity Catalog function
func_name = f"{CATALOG}.{SCHEMA}.add_numbers"
toolkit = UCFunctionToolkit(function_names=[func_name])
tools = toolkit.tools
エージェントでツールを使用します
UCFunctionToolkit の tools プロパティを使用して、ツールを LangChain エージェントに追加します。
この例では、わかりやすくするためにLangChainのAgentExecutor APIを使用してシンプルなエージェントを作成します。本番運用ワークロードの場合は、「AIエージェントを作成してDatabricks Appsにデプロイする」に示されているエージェント作成ワークフローを使用してください。
from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain.prompts import ChatPromptTemplate
from databricks_langchain import (
ChatDatabricks,
UCFunctionToolkit,
)
import mlflow
# Initialize the LLM (replace with your LLM of choice, if desired)
LLM_ENDPOINT_NAME = "databricks-meta-llama-3-3-70b-instruct"
llm = ChatDatabricks(endpoint=LLM_ENDPOINT_NAME, temperature=0.1)
# Define the prompt
prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are a helpful assistant. Make sure to use tools for additional functionality.",
),
("placeholder", "{chat_history}"),
("human", "{input}"),
("placeholder", "{agent_scratchpad}"),
]
)
# Enable automatic tracing
mlflow.langchain.autolog()
# Define the agent, specifying the tools from the toolkit above
agent = create_tool_calling_agent(llm, tools, prompt)
# Create the agent executor
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
agent_executor.invoke({"input": "What is 36939.0 + 8922.4?"})
Databricks Unity Catalog を使用して、SQL および Python 関数を LlamaIndex ワークフローのツールとして統合します。この統合により、Unity Catalog のガバナンスと LlamaIndex の、LLM 向けに大規模なデータセットをインデックス化してクエリする機能が組み合わせられます。
-
LlamaIndex 用の Databricks Unity Catalog 統合パッケージをインストールします。
Python%pip install unitycatalog-llamaindex[databricks]
dbutils.library.restartPython() -
Unity Catalog関数クライアントのインスタンスを作成します。
Pythonfrom unitycatalog.ai.core.base import get_uc_function_client
client = get_uc_function_client() -
Python で記述された Unity Catalog 関数を作成します。
PythonCATALOG = "your_catalog"
SCHEMA = "your_schema"
func_name = f"{CATALOG}.{SCHEMA}.code_function"
def code_function(code: str) -> str:
"""
Runs Python code.
Args:
code (str): The Python code to run.
Returns:
str: The result of running the Python code.
"""
import sys
from io import StringIO
stdout = StringIO()
sys.stdout = stdout
exec(code)
return stdout.getvalue()
client.create_python_function(
func=code_function,
catalog=CATALOG,
schema=SCHEMA,
replace=True
) -
Unity Catalog 関数をツールキットとしてインスタンスを作成し、実行してツールが適切に動作することを確認します。
Pythonfrom unitycatalog.ai.llama_index.toolkit import UCFunctionToolkit
import mlflow
# Enable traces
mlflow.llama_index.autolog()
# Create a UCFunctionToolkit that includes the UC function
toolkit = UCFunctionToolkit(function_names=[func_name])
# Fetch the tools stored in the toolkit
tools = toolkit.tools
python_exec_tool = tools[0]
# Run the tool directly
result = python_exec_tool.call(code="print(1 + 1)")
print(result) # Outputs: {"format": "SCALAR", "value": "2\n"} -
Unity Catalog関数をLlamaIndexツールコレクションの一部として定義することにより、LlamaIndex ReActAgentでツールを使用します。次に、LlamaIndexツールコレクションを呼び出すことによって、エージェントが適切に動作することを確認します。
Pythonfrom llama_index.llms.openai import OpenAI
from llama_index.core.agent import ReActAgent
llm = OpenAI()
agent = ReActAgent.from_tools(tools, llm=llm, verbose=True)
agent.chat("Please run the following python code: `print(1 + 1)`")
Databricks Unity Catalog を使用して、SQL 関数と Python 関数を OpenAI ワークフローのツールとして統合します。この統合により、Unity Catalog のガバナンスと OpenAI が組み合わされ、強力な生成AI アプリが生まれます。
-
OpenAI 用の Databricks Unity Catalog 統合パッケージをインストールします。
Python%pip install unitycatalog-openai[databricks]
%pip install mlflow -U
dbutils.library.restartPython() -
Unity Catalog関数クライアントのインスタンスを作成します。
Pythonfrom unitycatalog.ai.core.base import get_uc_function_client
client = get_uc_function_client() -
Python で記述された Unity Catalog 関数を作成します。
PythonCATALOG = "your_catalog"
SCHEMA = "your_schema"
func_name = f"{CATALOG}.{SCHEMA}.code_function"
def code_function(code: str) -> str:
"""
Runs Python code.
Args:
code (str): The python code to run.
Returns:
str: The result of running the Python code.
"""
import sys
from io import StringIO
stdout = StringIO()
sys.stdout = stdout
exec(code)
return stdout.getvalue()
client.create_python_function(
func=code_function,
catalog=CATALOG,
schema=SCHEMA,
replace=True
) -
Unity Catalog 関数のインスタンスをツールキットとして作成し、その関数を実行してツールが正しく動作することを確認します。
Pythonfrom unitycatalog.ai.openai.toolkit import UCFunctionToolkit
import mlflow
# Enable tracing
mlflow.openai.autolog()
# Create a UCFunctionToolkit that includes the UC function
toolkit = UCFunctionToolkit(function_names=[func_name])
# Fetch the tools stored in the toolkit
tools = toolkit.tools
client.execute_function = tools[0] -
ツールとともにOpenAIモデルにリクエストを送信します。
Pythonimport openai
messages = [
{
"role": "system",
"content": "You are a helpful customer support assistant. Use the supplied tools to assist the user.",
},
{"role": "user", "content": "What is the result of 2**10?"},
]
response = openai.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
tools=tools,
)
# check the model response
print(response) -
OpenAI から応答が返されたら、Unity Catalog 関数呼び出しを呼び出して、生成された応答を OpenAI に返します。
Pythonimport json
# OpenAI sends only a single request per tool call
tool_call = response.choices[0].message.tool_calls[0]
# Extract arguments that the Unity Catalog function needs to run
arguments = json.loads(tool_call.function.arguments)
# Run the function based on the arguments
result = client.execute_function(func_name, arguments)
print(result.value) -
回答が返されたら、その後のOpenAIへの呼び出しのために応答ペイロードを構築できます。
Python# Create a message containing the result of the function call
function_call_result_message = {
"role": "tool",
"content": json.dumps({"content": result.value}),
"tool_call_id": tool_call.id,
}
assistant_message = response.choices[0].message.to_dict()
completion_payload = {
"model": "gpt-4o-mini",
"messages": [*messages, assistant_message, function_call_result_message],
}
# Generate final response
openai.chat.completions.create(
model=completion_payload["model"], messages=completion_payload["messages"]
)
ユーティリティ
ツール応答の作成プロセスを簡素化するために、ucai-openaiパッケージには、OpenAI ChatCompletion応答メッセージを応答生成に使用できるように変換するgenerate_tool_call_messagesというユーティリティがあります。
from unitycatalog.ai.openai.utils import generate_tool_call_messages
messages = generate_tool_call_messages(response=response, client=client)
print(messages)
応答に複数選択エントリが含まれている場合は、generate_tool_call_messagesを呼び出すときにchoice_index引数を渡して、どの選択エントリを利用するかを選択できます。現在、複数選択エントリの処理はサポートされていません。
Databricks Unity Catalog を使用して、SQL 関数と Python 関数を Anthropic SDK LLM 呼び出しのツールとして統合します。この統合により、Unity Catalog のガバナンスと Anthropic モデルが組み合わされ、強力な生成 AI アプリが作成されます。
Anthropic 統合には、Databricks Runtime 15.0 以降が必要です。
-
Anthropic 用の Databricks Unity Catalog 統合パッケージをインストールします。
Python%pip install unitycatalog-anthropic[databricks]
dbutils.library.restartPython() -
Unity Catalog関数クライアントのインスタンスを作成します。
Pythonfrom unitycatalog.ai.core.base import get_uc_function_client
client = get_uc_function_client() -
Python で記述された Unity Catalog 関数を作成します。
PythonCATALOG = "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関数のインスタンスを作成します。
Pythonfrom unitycatalog.ai.anthropic.toolkit import UCFunctionToolkit
# Create an instance of the toolkit
toolkit = UCFunctionToolkit(function_names=[func_name], client=client) -
Anthropicでツール呼び出しを使用します。
Pythonimport 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モデルからの応答にはツールリクエストメタデータブロックが含まれます。
Pythonfrom 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との会話を続けるために、次のメッセージ形式を作成します。
generate_tool_call_messages API の conversation_history 引数で会話履歴全体を提供する必要があります。Claude モデルでは、会話の初期化(元のユーザー入力の質問)、および後続のすべての LLM 生成応答と複数ターンのツール呼び出し結果が必要です。