次の方法で共有


OpenAI と Databricks Unity カタログ ツールの統合

Databricks Unity カタログを使用して、OpenAI ワークフローのツールとして SQL 関数と Python 関数を統合します。 この統合は、Unity カタログのガバナンスと OpenAI を組み合わせて、強力な Gen AI アプリを作成します。

必要条件

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

Unity カタログ ツールを OpenAI と統合する

ノートブックまたは Python スクリプトで次のコードを実行して、Unity カタログ ツールを作成し、OpenAI モデルの呼び出し中に使用します。

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

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

    from unitycatalog.ai.core.base import get_uc_function_client
    
    client = get_uc_function_client()
    
  3. Python で記述された Unity カタログ関数を作成します。

    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 関数のインスタンスをツールキットとして作成し、関数を実行してツールが正しく動作することを確認します。

    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 モデルに要求を送信します。

    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 に返す応答を生成します。

    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 への後続の呼び出しの応答ペイロードを構築できます。

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