Pular para o conteúdo principal

Integrar o OpenAI com as ferramentas do Databricks Unity Catalog

Use Databricks Unity Catalog para integrar as funções SQL e Python como ferramentas no fluxo de trabalho do OpenAI. Essa integração combina a governança do Unity Catalog com a OpenAI para criar aplicativos avançados do gênero AI.

Requisitos

  • Instale o Python 3.10 ou o acima.

Integrar as ferramentas do Unity Catalog com o OpenAI

Execute o seguinte código em um Notebook ou script Python para criar uma ferramenta Unity Catalog e use-a ao chamar um modelo OpenAI.

  1. Instale o pacote de integração do Databricks Unity Catalog para o OpenAI.

    Python
    %pip install unitycatalog-openai[databricks]
    %pip install mlflow -U
    dbutils.library.restartPython()
  2. Crie uma instância do cliente de funções do Unity Catalog.

    Python
    from unitycatalog.ai.core.base import get_uc_function_client

    client = get_uc_function_client()
  3. Crie uma função do Unity Catalog escrita em Python.

    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. Crie uma instância da função Unity Catalog como um kit de ferramentas e verifique se a ferramenta se comporta corretamente executando a função.

    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. Envie a solicitação para o modelo OpenAI junto com as ferramentas.

    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. Depois que a OpenAI retornar uma resposta, invoque a chamada de função do Unity Catalog para gerar a resposta de volta à 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. Depois que a resposta for retornada, você poderá criar a carga útil de resposta para chamadas subsequentes para o 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"]
    )

utilidades

Para simplificar o processo de elaboração da resposta da ferramenta, o pacote ucai-openai tem um utilitário, generate_tool_call_messages, que converte as mensagens de resposta do OpenAI ChatCompletion para que possam ser usadas na geração de respostas.

Python
from unitycatalog.ai.openai.utils import generate_tool_call_messages

messages = generate_tool_call_messages(response=response, client=client)
print(messages)
nota

Se a resposta contiver entradas de múltipla escolha, você poderá passar o argumento choice_index ao chamar generate_tool_call_messages para escolher qual entrada de escolha utilizar. Atualmente, não há suporte para o processamento de entradas de múltipla escolha.