Freigeben über


Integrieren von LlamaIndex in Databricks Unity-Katalogtools

Verwenden Sie databricks Unity Catalog, um SQL- und Python-Funktionen als Tools in LlamaIndex-Workflows zu integrieren. Diese Integration kombiniert Unity Catalog Governance mit den Funktionen von LlamaIndex zum Indizieren und Abfragen großer Datasets für LLMs.

Anforderungen

  • Installieren Sie Python 3.10 oder höher.

Integrieren von Unity-Katalogtools in LlamaIndex

Führen Sie den folgenden Code in einem Notizbuch oder Python-Skript aus, um ein Unity Catalog-Tool zu erstellen und es in einem LlamaIndex-Agent zu verwenden.

  1. Installieren Sie das Integrationspaket "Databricks Unity Catalog" für LlamaIndex.

    %pip install unitycatalog-llamaindex[databricks]
    dbutils.library.restartPython()
    
  2. Erstellen Sie eine Instanz des Unity Catalog-Funktionsclients.

    from unitycatalog.ai.core.base import get_uc_function_client
    
    client = get_uc_function_client()
    
  3. Erstellen Sie eine Unity Catalog-Funktion, die in Python geschrieben wurde.

    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. Erstellen Sie eine Instanz der Funktion "Unity Catalog" als Toolkit, und führen Sie sie aus, um zu überprüfen, ob sich das Tool ordnungsgemäß verhält.

    from 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"}
    
  5. Verwenden Sie das Tool in einem LlamaIndex ReActAgent, indem Sie die Unity-Katalogfunktion als Teil einer LlamaIndex-Toolsammlung definieren. Überprüfen Sie dann, ob sich der Agent ordnungsgemäß verhält, indem Sie die LlamaIndex-Toolsammlung aufrufen.

    from 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)`")