多くの場合、エージェントは、ドキュメント コレクション、ナレッジ ベース、テキスト コーパスなどの非構造化データに対してクエリを実行して質問に回答し、コンテキストに対応した応答を提供する必要があります。
新しいPythonエージェントの場合は、AI Bridge(推奨)を使ってAI検索インデックスを直接クエリしてください。 既存のMCP統合については、 ワークスペースMCPエンドポイントを参照してください。 外部ベクターストアに接続したり、Unityカタログのボリュームからファイルを読み取ったりすることもできます。
AI Bridgeでレトリバーを開発する(推奨)
Azure Databricks AI検索インデックスをクエリする新しいPythonエージェントに対して、Azure DatabricksはAI Bridgeを推奨しています。
databricks-langchain または databricks-openai の VectorSearchRetrieverTool を使用して、インデックスをエージェント ツールとして公開します。
これらの例を実行する前に、 ワークスペースにサインイン し、検索可能な AI検索インデックス を選択してください。 例のインデックス名を、3 部構成の名前で置き換えてください。 最初の例はAzure Databricksの管理型埋め込みとツール呼び出しをサポートするモデルエンドポイントを使用しています。
インストールコマンドをターミナルで実行してください。 ノートブックでは%pipではなくpipを使い、インストール後にPythonを再起動してください。
LangChain/LangGraph
最新バージョンの databricks-langchain とLangGraphをインストールしてください:
pip install --upgrade databricks-langchain langgraph
リトリーバーツールを作成し、エージェントがいつ検索すべきかを示す説明を付けてください。 この例では、直接検索をテストし、その後ツールを呼び出して結果を利用できるエージェントを実行します。
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)
印刷された会話を確認し、ツールコール、取得した文書、そしてそれらの文書に基づく回答を確認してください。
セルフマネージド埋め込みを使用して直接アクセス インデックスまたは差分同期インデックスを使用するシナリオでは、 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.")
セルフマネージド埋め込みを使用して直接アクセス インデックスまたは差分同期インデックスを使用するシナリオでは、 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 が必要です。 Python例を実行する前にrequests、databricks-sdk、mlflowをインストールしてください。
HTTP 接続設定を使ってAzure AI 検索へのUnity Catalog接続を作成します。 この例ではベアラートークンを使用します。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 レトリバー スキーマに準拠するには、retriever 関数は
List[Document]オブジェクトを返し、Document クラスのmetadataフィールドを使用して、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 トレースを追加して、レトリバーを監視およびデバッグします。 トレースを使用すると、実行の各ステップの入力、出力、およびメタデータを表示できます。
前の例では、 メソッドと解析メソッドの両方に __call__を追加しています。 デコレーターは、関数が呼び出されたときに開始し、戻ったときに終了する スパン を作成します。 MLflow は、関数の入力と出力、および発生した例外を自動的に記録します。
Note
LangChain、LlamaIndex、OpenAI ライブラリのユーザーは、デコレーターを使用してトレースを手動で定義するだけでなく、MLflow 自動ログを使用できます。 トレーシングの概要を参照してください。
上記の例のように、metadata と Document を持つ page_content オブジェクトのリストを返します。 これはMLflowリトリバーのスパンスキーマに従い、評価ツールとレビューツールが取得した文書を認識できるようにします。
Unity カタログ ボリュームからファイルを読み取る
Unity カタログ ボリュームに格納されている非構造化ファイル (テキスト ドキュメント、レポート、構成ファイルなど) をエージェントが読み取る必要がある場合は、Databricks SDK Files API を使用してファイルを直接一覧表示および読み取るツールを作成できます。
既存のボリュームを選択し、エージェントの ID USE CATALOG、USE SCHEMA、READ VOLUME に付与してください。 コードの <catalog>.<schema>.<volume> を置き換えてください。 サンプル タスクでは、about_databricks.txt という名前の UTF-8 テキストファイルを使用するか、プロンプトを自分のボリュームにあるファイルに変更してください。
次の例では、エージェントで使用できる 2 つのツールを作成します。
-
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検索MCPサーバーは ワークスペース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 Search は、以前はベクター検索でした。 以前の /api/2.0/mcp/vector-search/ URLプレフィックスは今も使えます。
UC 関数を使用して Databricks AI Search にクエリを実行する (非推奨)
Note
新しいPythonエージェントにはAI Bridgeを使いましょう。 以下の例は既存の統合の参考資料です。
AI検索インデックス クエリをラップするUnityカタログ関数を作成できます。 この方法の特徴は次のとおりです。
- ガバナンスと検出可能性を備えた運用環境のユース ケースをサポートします
- 内部で 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を使用して、返されたテーブル内の列名を、primary_key、text_column、doc_uriなどの MLflow の予期されるフィールドにマップします。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が表示されます。 アプリ UI の確認を参照してください。 -
評価セット では、
doc_uriを使用して、取得元の結果を定義済みの評価データセットと比較して、取得元の再現率と精度を判断します。 評価データセットのリファレンスを参照してください。