다음을 통해 공유


Databricks Unity 카탈로그 도구와 OpenAI 통합

Databricks Unity 카탈로그를 사용하여 SQL 및 Python 함수를 OpenAI 워크플로의 도구로 통합합니다. 이 통합은 Unity 카탈로그의 거버넌스와 OpenAI를 결합하여 강력한 세대 AI 앱을 만듭니다.

요구 사항

  • Python 3.10 이상을 설치합니다.

OpenAI와 Unity 카탈로그 도구 통합

Notebook 또는 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 카탈로그 함수의 인스턴스를 도구 키트로 만들고 함수를 실행하여 도구가 제대로 작동하는지 확인합니다.

    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 카탈로그 함수 호출을 호출하여 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 인수를 전달하여 사용할 선택 항목을 선택할 수 있습니다. 현재는 다중 선택 항목 처리를 지원하지 않습니다.