メインコンテンツまでスキップ

OpenAI と Databricks Unity Catalog ツールの統合

Databricks Unity Catalog を使用して、SQL 関数と Python 関数を OpenAI ワークフローのツールとして統合します。この統合により、Unity Catalog のガバナンスと OpenAI が組み合わされ、強力なジェネレーション AI アプリが生まれます。

必要条件

  • Python 3.10以降をインストールします。

Unity Catalog ツールを OpenAI と統合する

ノートブックまたは Python スクリプトで次のコードを実行して Unity Catalog ツールを作成し、OpenAI モデルを呼び出しながら使用します。

  1. OpenAI 用の Databricks Unity Catalog 統合パッケージをインストールします。

    Python
    %pip install unitycatalog-openai[databricks]
    %pip install mlflow -U
    dbutils.library.restartPython()
  2. Unity Catalog 関数クライアントのインスタンスを作成します。

    Python
    from unitycatalog.ai.core.base import get_uc_function_client

    client = get_uc_function_client()
  3. Python で記述された Unity Catalog 関数を作成します。

    Python
    CATALOG = "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
    )
  4. Unity Catalog 関数のインスタンスをツールキットとして作成し、関数を実行してツールが適切に動作することを確認します。

    Python
    from 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]
  5. ツールと共に OpenAI モデルに要求を送信します。

    Python
    import 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)
  6. OpenAI が応答を返した後、Unity Catalog 関数呼び出しを呼び出して、OpenAI に応答を返す応答を生成します。

    Python
    import 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)
  7. 回答が返されたら、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があります。

Python
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 引数を渡して、使用する選択肢エントリを選択できます。現在、多肢選択式エントリの処理はサポートされていません。