Compartir a través de


Integración de LangChain con herramientas del Databricks Unity Catalog

Use databricks Unity Catalog para integrar funciones de SQL y Python como herramientas en flujos de trabajo de LangChain y LangGraph. Esta integración combina la gobernanza del catálogo de Unity con funcionalidades de LangChain para crear aplicaciones eficaces basadas en LLM.

Requisitos

  • Instale Python 3.10 y versiones posteriores.

Integración de LangChain con databricks Unity Catalog

En este ejemplo, creará una herramienta del Catálogo de Unity, probará su funcionalidad y la agregará a un agente. Ejecute el código siguiente en un cuaderno de Databricks.

Instalación de dependencias

Instale los paquetes de IA del Catálogo de Unity con la opción de Databricks e instale el paquete de integración de LangChain.

En este ejemplo se usa LangChain, pero se puede aplicar un enfoque similar a otras bibliotecas. Consulte Integración de herramientas de Catálogo de Unity con marcos de IA generativos de terceros.

# Install the Unity Catalog AI integration package with the Databricks extra
%pip install unitycatalog-langchain[databricks]

# Install Databricks Langchain integration package
%pip install databricks-langchain
dbutils.library.restartPython()

Inicializa el cliente de funciones de Databricks

Inicialice el cliente de función de Databricks.

from unitycatalog.ai.core.base import get_uc_function_client

client = get_uc_function_client()

Definición de la lógica de la herramienta

Cree una función de catálogo de Unity que contenga la lógica de la herramienta.


CATALOG = "my_catalog"
SCHEMA = "my_schema"

def add_numbers(number_1: float, number_2: float) -> float:
  """
  A function that accepts two floating point numbers adds them,
  and returns the resulting sum as a float.

  Args:
    number_1 (float): The first of the two numbers to add.
    number_2 (float): The second of the two numbers to add.

  Returns:
    float: The sum of the two input numbers.
  """
  return number_1 + number_2

function_info = client.create_python_function(
  func=add_numbers,
  catalog=CATALOG,
  schema=SCHEMA,
  replace=True
)

Prueba de la función

Pruebe la función para comprobar que funciona según lo previsto:

result = client.execute_function(
  function_name=f"{CATALOG}.{SCHEMA}.add_numbers",
  parameters={"number_1": 36939.0, "number_2": 8922.4}
)

result.value # OUTPUT: '45861.4'

Envuelva la función usando el UCFunctionToolKit

Ajuste la función mediante UCFunctionToolkit para que sea accesible para las bibliotecas de creación de agentes. El kit de herramientas garantiza la coherencia en diferentes bibliotecas y agrega características útiles, como el seguimiento automático para los recuperadores.

from databricks_langchain import UCFunctionToolkit

# Create a toolkit with the Unity Catalog function
func_name = f"{CATALOG}.{SCHEMA}.add_numbers"
toolkit = UCFunctionToolkit(function_names=[func_name])

tools = toolkit.tools

Uso de la herramienta en un agente

Agregue la herramienta a un agente de LangChain utilizando la propiedad tools de UCFunctionToolkit.

En este ejemplo se crea un agente sencillo mediante la API de AgentExecutor LangChain para simplificar. En el caso de las cargas de trabajo de producción, use el flujo de trabajo de creación del agente que se muestra en ResponsesAgent ejemplos.

from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain.prompts import ChatPromptTemplate
from databricks_langchain import (
  ChatDatabricks,
  UCFunctionToolkit,
)
import mlflow

# Initialize the LLM (replace with your LLM of choice, if desired)
LLM_ENDPOINT_NAME = "databricks-meta-llama-3-3-70b-instruct"
llm = ChatDatabricks(endpoint=LLM_ENDPOINT_NAME, temperature=0.1)

# Define the prompt
prompt = ChatPromptTemplate.from_messages(
  [
    (
      "system",
      "You are a helpful assistant. Make sure to use tools for additional functionality.",
    ),
    ("placeholder", "{chat_history}"),
    ("human", "{input}"),
    ("placeholder", "{agent_scratchpad}"),
  ]
)

# Enable automatic tracing
mlflow.langchain.autolog()

# Define the agent, specifying the tools from the toolkit above
agent = create_tool_calling_agent(llm, tools, prompt)

# Create the agent executor
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
agent_executor.invoke({"input": "What is 36939.0 + 8922.4?"})