共用方式為


整合 LlamaIndex 與 Databricks Unity 目錄工具

使用 Databricks Unity 目錄,將 SQL 和 Python 函式整合為 LlamaIndex 工作流程中的工具。 此整合將 Unity Catalog 的數據管理功能與 LlamaIndex 的能力結合,目的是為大型語言模型(LLM)編製索引並查詢大型數據集。

需求

  • 安裝 Python 3.10 或更新版本。

整合 Unity 目錄工具與 LlamaIndex

在筆記本或 Python 腳本中執行下列程式代碼,以建立 Unity 目錄工具,並在 LlamaIndex 代理程式中使用它。

  1. 安裝適用於 LlamaIndex 的 Databricks Unity 目錄整合套件。

    %pip install unitycatalog-llamaindex[databricks]
    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.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. 藉由將 Unity 目錄函式定義為 LlamaIndex 工具集合的一部分,以使用 LlamaIndex ReActAgent 中的工具。 然後呼叫 LlamaIndex 工具集合,確認代理程式的行為正確。

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