代理常需查詢非結構化資料,如文件集合、知識庫或文字語料庫,以回答問題並提供情境感知的回應。
對於新的 Python 代理程式,建議使用 AI Bridge(建議)直接查詢 AI 搜尋索引。 關於現有的 MCP 整合,請參見 工作區 MCP 端點。 你也可以連接到 外部向量儲存 庫,或讀取 Unity Catalog 磁碟區的檔案。
用 AI Bridge 開發檢索器(建議)
對於查詢 Azure Databricks AI 搜尋索引的新 Python 代理,Azure Databricks 推薦 AI Bridge。 使用來自 databricks-langchain 或 databricks-openai 的 VectorSearchRetrieverTool 將索引公開為代理工具。
在執行這些範例之前,先 登入你的工作區 ,選擇一個可以查詢的 AI 搜尋索引 。 將範例索引名稱替換為其三部分名稱。 前面的範例使用 Azure Databricks 管理的嵌入和支援工具呼叫的模型端點。
在終端機執行安裝指令。 在 notebook 中,使用 %pip 而不是 pip,並在安裝後重新啟動 Python。
LangChain/LangGraph
安裝 databricks-langchain 和 LangGraph 的最新版本:
pip install --upgrade databricks-langchain langgraph
建立一個 retriever 工具,並給它一段描述,告訴代理程式何時搜尋。 此範例直接測試檢索,然後執行可呼叫工具並使用其結果的代理程式。
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)
查看輸出的對話內容,查看工具呼叫、取得的文件,以及根據這些文件得到的回答。
針對使用直接存取索引或使用自我管理內嵌的 Delta Sync 索引的案例,您必須設定 VectorSearchRetrieverTool 並指定自訂內嵌模型和文字數據行。 瞭解提供嵌入功能的選項。
下列範例示範如何使用VectorSearchRetrieverTool和columns金鑰來設定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.
)
如需其他詳細數據,請參閱 的 VectorSearchRetrieverTool。
OpenAI
安裝 databricks-openai 的最新版本:
pip install --upgrade databricks-openai
此範例使用相容 OpenAI 的 Azure Databricks 用戶端。 它執行模型的工具呼叫,並將檢索的文件回傳給模型。
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.")
針對使用直接存取索引或使用自我管理內嵌的 Delta Sync 索引的案例,您必須設定 VectorSearchRetrieverTool 並指定自訂內嵌模型和文字數據行。 瞭解提供嵌入功能的選項。
下列範例示範如何使用VectorSearchRetrieverTool和columns金鑰來設定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.
)
使用 Azure Databricks 嵌入端點時,請如上方代理迴圈中,將 openai_client=client 傳遞給 vs_tool.execute()。 使用建立索引向量的相同嵌入模型。
如需其他詳細數據,請參閱 的 VectorSearchRetrieverTool。
測試完檢索器後,把它加入你的 客製化代理。
查詢 Databricks 外部的向量搜尋索引
如果你的向量索引是託管在 Azure Databricks 之外,你可以建立一個 Unity 目錄連線來連接到外部服務,並在你的代理程式碼中使用這個連線。 請參閱 連線到外部 HTTP 服務。
以下範例透過 HTTP 連線查詢 Azure AI 搜尋服務 索引。 你需要一個連線,並且有權限查詢該索引,並且在該連線上具有 USE CONNECTION。 安裝 requests、databricks-sdk 和 mlflow 後,再執行 Python 範例。
使用 HTTP 連線設定建立一個 Unity Catalog 連接到 Azure AI 搜尋服務。 此範例使用持有人權杖;選擇您的 Azure AI 搜尋服務 部署所需的認證方式。
CREATE CONNECTION azure_search_connection TYPE HTTP OPTIONS ( host 'https://example.search.windows.net', base_path '/', bearer_token secret ('<secret-scope>','<secret-key>') );使用 Unity 目錄連線在代理程式代碼中定義擷取工具。 此範例會使用 MLflow 裝飾器來啟用代理程式追蹤。
Note
若要符合 MLflow 擷取器架構,擷取器函式應該會傳回
List[Document]物件,並使用metadataDocument 類別中的 欄位,將其他屬性新增至傳回的檔,例如doc_uri和similarity_score。 請參閱 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 ]產生一個與你索引相同的模型和維度的查詢嵌入。 將數值陣列儲存為
query-vector.json,然後執行擷取器: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)
在檢索工具中新增追蹤
新增 MLflow 追蹤以監視和偵錯您的擷取器。 追蹤可讓您檢視每個執行步驟的輸入、輸出和元數據。
上述範例會將 @mlflow.trace 裝飾器 新增至__call__和剖析方法兩者。 裝飾器會建立 範圍,該範圍會在函式被呼叫時啟動,並在函式回傳時結束。 MLflow 會自動記錄函式的輸入和輸出,以及引發的任何例外狀況。
Note
LangChain、LlamaIndex 和 OpenAI 函式庫的使用者除了使用裝飾器來手動定義操作記錄外,還可以使用 MLflow 自動記錄。 請參閱 追蹤概述。
回傳含有 metadata 和 Document 的 page_content 物件清單,如上文範例所示。 這遵循 MLflow 檢索器的 span 結構描述,因此評估與審查工具能辨識檢索到的文件。
讀取 Unity 目錄卷中的檔案
如果你的代理需要讀取儲存在 Unity 目錄卷中的非結構化檔案(文字文件、報告、設定檔等),你可以建立使用 Databricks SDK 檔案 API 來直接列出和讀取檔案的工具。
選擇一個現有磁碟區,並將 USE CATALOG、USE SCHEMA 和 READ VOLUME 授與你的代理程式身分。 在程式碼裡替換 <catalog>.<schema>.<volume> 。 在範例任務中,使用名為 about_databricks.txt 的 UTF-8 文字檔,或將提示改為你的磁碟區中的一個檔案。
以下範例為你的客服人員創造了兩個可用工具:
-
list_volume_files:列出本卷中的檔案與目錄。 -
read_volume_file:讀取卷中文字檔的內容。
LangChain/LangGraph
安裝包含 Databricks AI Bridge 的最新版本 databricks-langchain 。
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")
將工具綁定到 LLM,並執行一個工具呼叫迴圈:
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
安裝包含 Databricks AI Bridge 的最新版本 databricks-openai 。
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.")
使用 MCP 查詢 AI 搜尋索引
AI Search MCP 伺服器使用 workspace MCP 端點。 它需要一個具有 Azure Databricks 管理之嵌入的索引。 請參閱 「建立 AI 搜尋端點與索引」。
AI 搜尋的工作區 MCP URL 為 https://<workspace-hostname>/api/2.0/mcp/ai-search/{catalog}/{schema}/{index_name}。 連線到該系統並列出它所提供的工具:
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()
若要建立並部署使用此伺服器的代理程式,請參見從 Python 代理呼叫 MCP 工具。 在該索引的 Unity Catalog 可保護物件上,授予代理程式 SELECT 權限。
AI 搜尋前身為向量搜尋。 之前的 /api/2.0/mcp/vector-search/ 網址前綴仍然有效。
使用 UC 函式查詢 Databricks AI 搜尋(已棄用)
Note
對於新的 Python 代理,請使用 AI Bridge。 以下範例為現有整合的參考資料。
你可以建立一個 Unity Catalog 函式,將 AI 搜尋索引 查詢包裝起來。 此方法:
- 支援具備治理和便於探索性功能的生產使用案例
- 在幕後使用 vector_search() SQL 函式
- 支援 MLflow 的自動追蹤
在筆記本或 SQL 編輯器中執行下列程式代碼,以建立函式:
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
)
依照 函式工具設定,然後用 UCFunctionToolkit 包裝這個檢索器,以便在代理中使用。 這使得透過自動在 MLflow 記錄中生成 RETRIEVER 範圍類型,可以在 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
Unity 目錄擷取工具有下列注意事項:
- SQL 用戶端可能會限制回傳的最大列數或位元組數。 為防止資料截斷,請截斷 UDF 回傳的欄位值。 例如,您可以使用
substring(chunked_text, 0, 8192)來減少大型內容數據行的大小,並避免執行期間的數據列截斷。 - 由於此工具是
vector_search()函式的包裝器,因此受限於vector_search()函式的限制。 請參閱限制。
如需 UCFunctionToolkit 的詳細資訊,請參閱 Unity 目錄檔。
自訂檢索器結構描述(舊版)
mlflow.models.set_retriever_schema 已被取代。 對於新的擷取器,請使用 Document 回傳 物件。 以下設定是針對已存在的整合,會回傳自訂欄位。
若要手動設定擷取器架構:
當您定義代理程式時,請呼叫 mlflow.models.set_retriever_schema 。 使用
set_retriever_schema傳回資料表中的資料列名稱對應至 MLflow 的預期欄位,例如primary_key、text_column與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"], )提供
other_columns欄位的資料欄名稱清單,以指定擷取器架構中的其他欄位。如果您有多個擷取器,您可以使用每個擷取器架構的唯一名稱來定義多個架構。
代理程式建立期間所設定的擷取程式架構會影響下游應用程式和工作流程,例如檢閱應用程式和評估集。 具體而言,doc_uri 數據行可作為擷取器所傳回檔的主要標識碼。
-
檢閱應用程式 會顯示
doc_uri,以協助檢閱者評估回應和追蹤檔來源。 請參閱 檢查應用程式 使用者介面。 -
評估集 會使用
doc_uri來比較擷取器結果與預先定義的評估數據集,以判斷擷取器的召回率和精確度。 請參閱 評估資料集參考資料。