Conectar agentes a dados não estruturados

Os agentes geralmente precisam consultar dados não estruturados, como coleções de documentos, bases de dados de conhecimento ou corporação de texto, para responder a perguntas e fornecer respostas com reconhecimento de contexto.

Para novos agentes Python, use o AI Bridge (recomendado) para consultar diretamente os índices do AI Search. Para integrações MCP existentes, veja o endpoint MCP do workspace. Você também pode se conectar a lojas vetoriais externas ou ler arquivos de volumes do Unity Catalog.

Desenvolva um retriever com AI Bridge (recomendado)

Para novos agentes Python que consultam índices do Azure Databricks AI Search, o Azure Databricks recomenda o AI Bridge. Use VectorSearchRetrieverTool de databricks-langchain ou databricks-openai para expor um índice como uma ferramenta de agente.

Antes de executar esses exemplos, faça login no seu espaço de trabalho e escolha um índice de busca por IA que você possa consultar. Substitua o nome do índice de exemplo pelo nome em três partes. Os primeiros exemplos usam embeddings gerenciados do Azure Databricks e um endpoint de modelo que suporta chamada de ferramentas.

Execute os comandos de instalação em um terminal. Em um notebook, use %pip em vez de pip e reinicie o Python após a instalação.

LangChain/LangGraph

Instale a versão mais recente do databricks-langchain e LangGraph:

pip install --upgrade databricks-langchain langgraph

Crie uma ferramenta retriever e dê uma descrição que diga ao agente quando buscar. Este exemplo testa a recuperação diretamente, depois executa um agente que pode chamar a ferramenta e usar seus resultados.

from databricks_langchain import VectorSearchRetrieverTool, ChatDatabricks
from langgraph.prebuilt import create_react_agent

vs_tool = VectorSearchRetrieverTool(
    index_name="catalog.schema.my_databricks_docs_index",
    tool_name="databricks_docs_retriever",
    tool_description="Search Databricks documentation to answer product questions.",
)
print(vs_tool.invoke("What is Databricks Agent Framework?"))

agent = create_react_agent(
    ChatDatabricks(endpoint="databricks-claude-sonnet-4-5"),
    tools=[vs_tool],
)
result = agent.invoke({"messages": [{
    "role": "user",
    "content": "Search the documentation and explain Databricks Agent Framework.",
}]})
for message in result["messages"]:
    print(message)

Verifique a conversa impressa para uma chamada de ferramenta, documentos recuperados e uma resposta baseada nesses documentos.

Para cenários que usam índices de acesso direto ou índices de Sincronização Delta usando embeddings autogeridos, você deve configurar o VectorSearchRetrieverTool, especificar um modelo de embedding personalizado e uma coluna de texto. Confira as opções para fornecer integrações.

O exemplo a seguir mostra como configurar um VectorSearchRetrieverTool com chaves columns e embedding.

from databricks_langchain import VectorSearchRetrieverTool
from databricks_langchain import DatabricksEmbeddings

embedding_model = DatabricksEmbeddings(
    endpoint="databricks-bge-large-en",
)

vs_tool = VectorSearchRetrieverTool(
  index_name="catalog.schema.index_name", # Index name in the format 'catalog.schema.index'
  num_results=5, # Max number of documents to return
  columns=["primary_key", "text_column"], # List of columns to include in the search
  filters={"text_column LIKE": "Databricks"}, # Filters to apply to the query
  query_type="ANN", # Query type ("ANN" or "HYBRID").
  tool_name="databricks_docs_retriever", # Used by the LLM to understand the purpose of the tool
  tool_description="Purpose of the tool", # Used by the LLM to understand the purpose of the tool
  text_column="text_column", # Specify text column for embeddings. Required for direct-access index or delta-sync index with self-managed embeddings.
  embedding=embedding_model # The embedding model. Required for direct-access index or delta-sync index with self-managed embeddings.
)

Para obter detalhes adicionais, consulte os documentos da API para VectorSearchRetrieverTool.

OpenAI

Instale a versão mais recente de databricks-openai:

pip install --upgrade databricks-openai

Este exemplo utiliza o cliente Azure Databricks compatível com OpenAI. Ele executa as chamadas de ferramenta do modelo e retorna os documentos recuperados ao modelo.

import json
from databricks_openai import DatabricksOpenAI, VectorSearchRetrieverTool

client = DatabricksOpenAI()
dbvs_tool = VectorSearchRetrieverTool(
    index_name="catalog.schema.my_databricks_docs_index",
    tool_name="databricks_docs_retriever",
    tool_description="Search Databricks documentation to answer product questions.",
)
messages = [{
    "role": "user",
    "content": "Search the documentation and explain Databricks Agent Framework.",
}]

for _ in range(10):
    response = client.chat.completions.create(
        model="databricks-claude-sonnet-4-5",
        messages=messages,
        tools=[dbvs_tool.tool],
    )
    message = response.choices[0].message
    messages.append(message.model_dump(exclude_none=True))
    if not message.tool_calls:
        print(message.content)
        break
    for call in message.tool_calls:
        if call.function.name != dbvs_tool.tool["function"]["name"]:
            raise ValueError(f"Unknown tool: {call.function.name}")
        args = json.loads(call.function.arguments)
        documents = dbvs_tool.execute(**args, openai_client=client)
        print(documents)
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": json.dumps(documents),
        })
else:
    raise RuntimeError("The agent reached the tool-calling limit.")

Para cenários que usam índices de acesso direto ou índices de Sincronização Delta usando embeddings autogeridos, você deve configurar o VectorSearchRetrieverTool, especificar um modelo de embedding personalizado e uma coluna de texto. Confira as opções para fornecer integrações.

O exemplo a seguir mostra como configurar um VectorSearchRetrieverTool com chaves columns e embedding.

from databricks_openai import VectorSearchRetrieverTool

vs_tool = VectorSearchRetrieverTool(
    index_name="catalog.schema.index_name", # Index name in the format 'catalog.schema.index'
    num_results=5, # Max number of documents to return
    columns=["primary_key", "text_column"], # List of columns to include in the search
    filters={"text_column LIKE": "Databricks"}, # Filters to apply to the query
    query_type="ANN", # Query type ("ANN" or "HYBRID").
    tool_name="databricks_docs_retriever", # Used by the LLM to understand the purpose of the tool
    tool_description="Purpose of the tool", # Used by the LLM to understand the purpose of the tool
    text_column="text_column", # Specify text column for embeddings. Required for direct-access index or delta-sync index with self-managed embeddings.
    embedding_model_name="databricks-bge-large-en" # The embedding model. Required for direct-access index or delta-sync index with self-managed embeddings.
)

Ao usar um endpoint de embedding do Azure Databricks, passe openai_client=client para vs_tool.execute(), como no loop agente acima. Use o mesmo modelo de embedding que criou os vetores de índice.

Para obter detalhes adicionais, consulte os documentos da API para VectorSearchRetrieverTool.

Depois de testar o retriever, adicione-o ao seu agente personalizado.

Consultar um índice de busca vetorial fora dos Databricks

Se o índice de vetor estiver hospedado fora do Azure Databricks, você poderá criar uma conexão do Unity Catalog para se conectar ao serviço externo e usar a conexão no código do agente. Consulte Conectar-se a serviços HTTP externos.

O exemplo a seguir consulta um índice do Pesquisa de IA do Azure  por meio de uma conexão HTTP. Você precisa de uma conexão com permissão para consultar esse índice e USE CONNECTION na conexão. Instale requests, databricks-sdk, e mlflow antes de rodar o exemplo em Python.

  1. Crie uma conexão do Unity Catalog para o Pesquisa de IA do Azure  usando a configuração de conexão HTTP. Este exemplo usa um token bearer; escolha o método de autenticação que sua implantação no Pesquisa de IA do Azure  exige.

    CREATE CONNECTION azure_search_connection
    TYPE HTTP
    OPTIONS (
      host 'https://example.search.windows.net',
      base_path '/',
      bearer_token secret ('<secret-scope>','<secret-key>')
    );
    
  2. Defina a ferramenta de recuperação no código do agente usando a conexão do Unity Catalog. Este exemplo usa decoradores MLflow para habilitar o rastreamento de agente.

    Note

    Para estar em conformidade com o esquema de recuperador do MLflow, a função retriever deve retornar um List[Document] objeto e usar o metadata campo na classe Document para adicionar atributos adicionais ao documento retornado, como doc_uri e similarity_score. Consulte o Documento do MLflow.

    import mlflow
    import requests
    from databricks.sdk import WorkspaceClient
    from mlflow.entities import Document
    
    class VectorSearchRetriever:
        def __init__(self, connection_name, index_name):
            self.workspace = WorkspaceClient()
            self.connection_name = connection_name
            self.index_name = index_name
    
        @mlflow.trace(span_type="RETRIEVER", name="vector_search")
        def __call__(self, query_vector: list[float], score_threshold: float = 0.0) -> list[Document]:
            response = requests.post(
                f"{self.workspace.config.host}/api/2.0/unity-catalog/connections/"
                f"{self.connection_name}/proxy/indexes/{self.index_name}/docs/search",
                params={"api-version": "2024-07-01"},
                headers=self.workspace.config.authenticate(),
                json={
                    "select": "HotelId,HotelName,Description,Category",
                    "vectorQueries": [{
                        "vector": query_vector,
                        "k": 7,
                        "fields": "DescriptionVector",
                        "kind": "vector",
                        "exhaustive": True,
                    }],
                },
                timeout=30,
            )
            response.raise_for_status()
            return self.parse_results(response.json(), score_threshold)
    
        @mlflow.trace(span_type="PARSER")
        def parse_results(self, results, score_threshold) -> list[Document]:
            return [
                Document(
                    page_content=item.get("Description", ""),
                    id=item.get("HotelId"),
                    metadata={
                        "similarity_score": item.get("@search.score", 0),
                        "HotelName": item.get("HotelName"),
                        "Category": item.get("Category"),
                    },
                )
                for item in results.get("value", [])
                if item.get("@search.score", 0) >= score_threshold
            ]
    
  3. Gere uma embedding de consulta com o mesmo modelo e dimensões usados pelo seu índice. Salve o array numérico como query-vector.json, então execute o retriever:

    import json
    from pathlib import Path
    
    query_vector = json.loads(Path("query-vector.json").read_text())
    retriever = VectorSearchRetriever("azure_search_connection", "hotels_vector_index")
    results = retriever(query_vector, score_threshold=0.1)
    for document in results:
        print(document.page_content)
    

Adicione rastreamento a uma ferramenta de recuperação

Adicione o rastreamento do MLflow para monitorar e depurar o recuperador. O rastreamento permite exibir entradas, saídas e metadados para cada etapa de execução.

O exemplo anterior adiciona o decorador @mlflow.trace aos métodos __call__ e de análise. O decorador cria um intervalo que começa quando a função é invocada e termina quando retorna. O MLflow registra automaticamente a entrada e a saída da função e todas as exceções geradas.

Note

Os usuários das bibliotecas LangChain, LlamaIndex e OpenAI podem usar o registro automático do MLflow, além de definir manualmente os traços com o decorador. Veja visão geral do rastreamento.

Retorne uma lista de Document objetos com page_content e metadata, como o exemplo acima faz. Isso segue o esquema de span do recuperador MLflow, para que ferramentas de avaliação e revisão possam reconhecer os documentos recuperados.

Ler arquivos de um volume do Catálogo do Unity

Se o agente precisar ler arquivos não estruturados (documentos de texto, relatórios, arquivos de configuração etc.) armazenados em um volume do Catálogo do Unity, você poderá criar ferramentas que usam a API de Arquivos do SDK do Databricks para listar e ler arquivos diretamente.

Escolha um volume existente e conceda a identidade USE CATALOGdo seu agente , USE SCHEMA, e READ VOLUME. Substitua <catalog>.<schema>.<volume> no código. Para a tarefa de exemplo, use um arquivo de texto UTF-8 chamado about_databricks.txt, ou mude o prompt para um arquivo no seu volume.

Os exemplos a seguir criam duas ferramentas que seu agente pode usar:

  • list_volume_files: lista arquivos e diretórios no volume.
  • read_volume_file: lê o conteúdo de um arquivo de texto a partir do volume.

LangChain/LangGraph

Instale a versão mais recente do databricks-langchain que inclui o Databricks AI Bridge.

pip install --upgrade databricks-langchain langgraph
from pathlib import PurePosixPath
from databricks.sdk import WorkspaceClient
from langchain_core.tools import tool

VOLUME = "<catalog>.<schema>.<volume>"
w = WorkspaceClient()


def volume_path(relative_path: str = "") -> str:
    path = PurePosixPath(relative_path)
    if path.is_absolute() or ".." in path.parts:
        raise ValueError("Use a path relative to the configured volume.")
    return str(PurePosixPath("/Volumes", *VOLUME.split(".")) / path)


@tool
def list_volume_files(directory: str = "") -> str:
    """Lists files and directories in the Unity Catalog volume.
    Provide a relative directory path, or leave empty to list the volume root."""
    path = volume_path(directory)
    entries = []
    for f in w.files.list_directory_contents(path):
        kind = "dir" if f.is_directory else "file"
        size = f" ({f.file_size} bytes)" if not f.is_directory else ""
        entries.append(f"  [{kind}] {f.name}{size}")
    return "\n".join(entries) if entries else "No files found."


@tool
def read_volume_file(file_path: str) -> str:
    """Reads a text file from the Unity Catalog volume.
    Provide the path relative to the volume root, for example 'reports/q1_summary.txt'."""
    full_path = volume_path(file_path)
    resp = w.files.download(full_path)
    return resp.contents.read().decode("utf-8")

Associe as ferramentas a uma LLM e execute um loop de chamada de ferramentas:

from databricks_langchain import ChatDatabricks
from langchain_core.messages import HumanMessage, ToolMessage

llm = ChatDatabricks(endpoint="databricks-claude-sonnet-4-5")
llm_with_tools = llm.bind_tools([list_volume_files, read_volume_file])

messages = [HumanMessage(content="What files are in the volume? Can you read about_databricks.txt and summarize it in 2 sentences?")]
tool_map = {"list_volume_files": list_volume_files, "read_volume_file": read_volume_file}

for _ in range(5):  # max iterations
    response = llm_with_tools.invoke(messages)
    messages.append(response)
    if not response.tool_calls:
        break
    for tc in response.tool_calls:
        result = tool_map[tc["name"]].invoke(tc["args"])
        messages.append(ToolMessage(content=result, tool_call_id=tc["id"]))

else:
    raise RuntimeError("The agent reached the tool-calling limit.")

print(response.content)

OpenAI

Instale a versão mais recente do databricks-openai que inclui o Databricks AI Bridge.

pip install --upgrade databricks-openai
import json
from pathlib import PurePosixPath
from databricks.sdk import WorkspaceClient
from databricks_openai import DatabricksOpenAI

VOLUME = "<catalog>.<schema>.<volume>"
w = WorkspaceClient()
client = DatabricksOpenAI()

# Define the tool specifications
tools = [
    {
        "type": "function",
        "function": {
            "name": "list_volume_files",
            "description": "Lists files and directories in the Unity Catalog volume. Provide a relative directory path, or leave empty to list the volume root.",
            "parameters": {
                "type": "object",
                "properties": {
                    "directory": {
                        "type": "string",
                        "description": "Relative directory path within the volume. Leave empty for root.",
                    }
                },
                "required": [],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "read_volume_file",
            "description": "Reads a text file from the Unity Catalog volume. Provide the path relative to the volume root, for example 'reports/q4_summary.txt'.",
            "parameters": {
                "type": "object",
                "properties": {
                    "file_path": {
                        "type": "string",
                        "description": "Path to the file relative to the volume root.",
                    }
                },
                "required": ["file_path"],
            },
        },
    },
]


def volume_path(relative_path: str = "") -> str:
    path = PurePosixPath(relative_path)
    if path.is_absolute() or ".." in path.parts:
        raise ValueError("Use a path relative to the configured volume.")
    return str(PurePosixPath("/Volumes", *VOLUME.split(".")) / path)


def execute_tool(name: str, args: dict) -> str:
    if name == "list_volume_files":
        directory = args.get("directory", "")
        path = volume_path(directory)
        entries = []
        for f in w.files.list_directory_contents(path):
            kind = "dir" if f.is_directory else "file"
            size = f" ({f.file_size} bytes)" if not f.is_directory else ""
            entries.append(f"[{kind}] {f.name}{size}")
        return "\n".join(entries) if entries else "No files found."
    elif name == "read_volume_file":
        full_path = volume_path(args["file_path"])
        resp = w.files.download(full_path)
        return resp.contents.read().decode("utf-8")
    return f"Unknown tool: {name}"


# Call the model with tools
messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "List the files in the volume, then read about_databricks.txt and summarize it."},
]

for _ in range(10):
    response = client.chat.completions.create(
        model="databricks-claude-sonnet-4-5", messages=messages, tools=tools
    )
    message = response.choices[0].message
    messages.append(message.model_dump(exclude_none=True))
    if not message.tool_calls:
        print(message.content)
        break
    for call in message.tool_calls:
        args = json.loads(call.function.arguments)
        result = execute_tool(call.function.name, args)
        messages.append({"role": "tool", "tool_call_id": call.id, "content": result})
else:
    raise RuntimeError("The agent reached the tool-calling limit.")

Consultar um índice do AI Search usando MCP

O servidor MCP de busca por IA utiliza um endpoint MCP de workspace. Ele requer um índice com embeddings gerenciados pelo Azure Databricks. Consulte Criar pontos de extremidade e índices da Pesquisa de IA.

A URL do MCP do workspace para AI Search é https://<workspace-hostname>/api/2.0/mcp/ai-search/{catalog}/{schema}/{index_name}. Conecte-se a ele e liste as ferramentas que ele expõe:

from databricks.sdk import WorkspaceClient
from databricks_mcp import DatabricksMCPClient

workspace_client = WorkspaceClient()
host = workspace_client.config.host

mcp_client = DatabricksMCPClient(
    server_url=f"{host}/api/2.0/mcp/ai-search/<catalog>/<schema>/<index-name>",
    workspace_client=workspace_client,
)
tools = mcp_client.list_tools()

Para construir e implantar um agente que use esse servidor, veja Chamar ferramentas MCP a partir de um agente Python. Conceda ao agente SELECT acesso ao Catálogo do Unity do índice.

Busca por IA era anteriormente chamada de Vector Search. O prefixo da URL anterior /api/2.0/mcp/vector-search/ ainda funciona.

Consultar o Databricks AI Search usando funções do UC (obsoletas)

Note

Para novos agentes Python, use o AI Bridge. O exemplo a seguir é uma referência para integrações existentes.

Você pode criar uma função do Catálogo do Unity que encapsula uma consulta de índice de Pesquisa de IA. Essa abordagem:

  • Dá suporte a casos de uso de produção com governança e capacidade de descoberta
  • Usa a função SQL vector_search() nos bastidores
  • Dá suporte ao rastreamento automático do MLflow
    • Você deve alinhar a saída da função ao Esquema de recuperação do MLflow usando os aliases page_content e metadata.
    • Quaisquer colunas de metadados adicionais devem ser adicionadas à metadata coluna usando a função de mapa SQL, em vez de como chaves de saída de nível superior.

Execute o seguinte código em um notebook ou editor sql para criar a função:

CREATE OR REPLACE FUNCTION main.default.databricks_docs_vector_search (
  -- The agent uses this comment to determine how to generate the query string parameter.
  query STRING
  COMMENT 'The query string for searching Databricks documentation.'
) RETURNS TABLE
-- The agent uses this comment to determine when to call this tool. It describes the types of documents and information contained within the index.
COMMENT 'Executes a search on Databricks documentation to retrieve text documents most relevant to the input query.' RETURN
SELECT
  chunked_text as page_content,
  map('doc_uri', url, 'chunk_id', chunk_id) as metadata
FROM
  vector_search(
    -- Specify your AI Search index name here
    index => 'catalog.schema.databricks_docs_index',
    query => query,
    num_results => 5
  )

Siga a configuração da ferramenta de função e, em seguida, encapsule este recuperador com UCFunctionToolkit para usá-lo em seu agente. Isso permite o rastreamento automático por meio do MLflow ao gerar automaticamente tipos de span RETRIEVER nos logs do MLflow..

from databricks_langchain import UCFunctionToolkit
from unitycatalog.ai.core.databricks import DatabricksFunctionClient

toolkit = UCFunctionToolkit(
    function_names=[
        "main.default.databricks_docs_vector_search"
    ],
    client=DatabricksFunctionClient(),
)
tools = toolkit.tools

As ferramentas de recuperação do Catálogo do Unity têm as seguintes ressalvas:

  • Os clientes SQL podem limitar o número máximo de linhas ou bytes retornados. Para evitar truncamento de dados, trunque os valores de coluna retornados pela UDF. Por exemplo, você pode usar substring(chunked_text, 0, 8192) para reduzir o tamanho de colunas de conteúdo grandes e evitar truncamento de linha durante a execução.
  • Como essa ferramenta é um wrapper para a vector_search() função, ela está sujeita às mesmas limitações que a vector_search() função. Confira Limitações.

Para obter mais informações sobre UCFunctionToolkit, consulte Documentação do Catálogo do Unity.

Esquemas retriever personalizados (legado)

mlflow.models.set_retriever_schema está obsoleto. Para novos retrievers, retorne Document objetos usando o esquema padrão do retriever. A configuração a seguir é para integrações existentes que retornam campos personalizados.

Para definir o esquema do recuperador manualmente:

  1. Chame mlflow.models.set_retriever_schema quando definir seu agente. Use set_retriever_schema para mapear os nomes de coluna na tabela retornada para os campos esperados do MLflow, como primary_key, text_columne doc_uri.

    import mlflow
    
    # Define the retriever's schema by providing your column names
    mlflow.models.set_retriever_schema(
      name="vector_search",
      primary_key="chunk_id",
      text_column="text_column",
      doc_uri="doc_uri"
      # other_columns=["column1", "column2"],
    )
    
  2. Especifique colunas adicionais no esquema do seu recuperador fornecendo uma lista de nomes de colunas usando o campo other_columns.

  3. Se você tiver vários buscadores, poderá definir vários esquemas usando nomes exclusivos para cada esquema de recuperação.

O esquema de recuperação definido durante a criação do agente afeta aplicativos downstream e fluxos de trabalho, como o aplicativo de revisão e os conjuntos de avaliação. Especificamente, a coluna doc_uri serve como o identificador primário para documentos retornados pelo buscador.