註
Azure AI 搜尋服務 可透過 Azure 入口網站、REST API 及 Azure SDK 取得。 它同時也是 Foundry IQ 的基礎,這是一個管理式知識層,能將企業內容轉化為可重複使用、權限感知的知識庫,供 Microsoft Foundry 入口網站中的代理使用。
重要
標記(預覽)的功能、能力或屬性不受服務等級協議涵蓋,也不建議用於生產工作負載,且在正式上架前可能會有所變動或受限。 Azure AI 搜尋服務 預覽條款適用於所有預覽功能,無論是獨立功能還是正式推出功能的一部分。
學習如何打造一個智慧且支援 MCP 的解決方案,將 Azure AI 搜尋服務 整合至 Foundry Agent Service,實現 agentic 檢索。 你可以將此架構用於需要複雜推理、涵蓋大型知識領域的對話式應用,例如客戶支援或技術故障排除。
本教學在兩個地方使用預覽版 REST API 表面。 知識庫使用 output_mode 和 retrieval_reasoning_effort (預覽)來明確指定擷取式輸出和最小推理,雖然通常也能提供等效的行為。 專案連線使用RemoteTool(預覽)和專案管理身份來驗證 Azure AI 搜尋服務。
在這個教學中,你:
- 為 Azure AI 搜尋服務 與 Microsoft Foundry 設定基於角色的存取權限
- 在 Azure AI 搜尋服務 建立搜尋索引、知識來源及知識庫
- 建立一個專案連結,用於 Azure AI 搜尋服務 與 Microsoft Foundry 之間的 MCP 通訊
- 在 Microsoft Foundry 中建立一個使用 MCP 工具進行檢索的代理程式
- 請透過與客服人員聊天來測試解決方案
- 參閱解決方案的最佳化提示
提示
想馬上開始嗎? 在 GitHub 上複製 agentic-retrieval-pipeline-example Python 筆記本。 筆記本中包含了這個教學的程式碼,以現成格式呈現。
關於專注於入站與出站私有連接驗證的私有部署路徑,請參見 教學:Deploy private agentic retrieval for Foundry IQ。
先決條件
位於任何提供代理式擷取之區域的 Azure AI 搜尋服務。
一個Microsoft Foundry 專案和資源。 當你建立專案時,資源會自動建立。
一個部署到你的專案中的文本嵌入模型,用於 查詢時向量化。 此解使用
text-embedding-3-large。部署至專案供 Agent 使用的 LLM。 此解使用
gpt-5-mini。GPT-4 家族模型已被棄用。 關於 Microsoft Foundry 的退休日期及現況,請參見 Model 退休時間表 - Microsoft Foundry。
存取及管理 Azure AI 搜尋服務 及 Microsoft Foundry 資源的權限。 欲了解更多資訊,請參閱 「設定存取權限」。
Python 3.8 或更新版本。
Visual Studio Code ,並搭配Python 及Jupyter 擴充功能。Azure CLI 用於與 Microsoft Entra ID 的無金鑰認證。
重要
如果你停用搜尋服務的公開網路存取,並將其作為代理工具使用與網路隔離的 Microsoft Foundry 資源,你必須使用 Microsoft Foundry(新)入口網站、SDK 或 CLI 來建立代理程式。 Microsoft Foundry(經典版)入口網站不支援此情境。 欲了解更多資訊,請參閱 具備網路隔離的代理工具。
了解解決方案
此解決方案結合 Azure AI 搜尋服務 與 Microsoft Foundry,建立端對端檢索流程:
Azure AI 搜尋服務 托管你的知識庫,負責查詢規劃、查詢執行及結果綜合。 你建立一個用來儲存內容的搜尋索引、一個參考該索引的知識來源,以及一個從該知識來源進行混合檢索的知識庫。
Microsoft Foundry 托管你Azure OpenAI 模型部署、專案連線及代理程式。 你建立一個專案連線,指向知識庫的 MCP 端點,然後建立一個代理程式,使用 MCP 工具來存取知識庫。
使用者透過與客戶端應用程式(如聊天機器人)互動來啟動查詢處理,該應用程式會呼叫代理人。 代理程式使用 MCP 工具來協調向知識庫的請求並綜合回應。 當聊天機器人呼叫代理時,MCP 工具會呼叫 Azure AI 搜尋服務 中的知識庫,並將回應傳送給代理和聊天機器人。
設定存取權限
在開始之前,請確保你有權限存取內容和操作。 我們建議使用 Microsoft Entra ID 進行認證,並以角色為基礎存取授權。 您必須是 擁有者 或 使用者存取管理員 才能指派角色。 如果角色不可行,改用 金鑰驗證 。
要設定此解決方案的存取權限:
登入 Azure 入口網站。
啟用系統指派的管理身份 ,適用於你的搜尋服務和專案。 你可以在每個資源的 身份 頁面查詢。
-
角色 受派人 目的 搜尋服務貢獻者 你的使用者帳號 建立物件 搜尋索引資料貢獻者 你的使用者帳號 載入資料 搜尋索引資料閱讀器 您的使用者帳號與專案管理身份 閱讀已索引內容 在專案的父資源中,指派以下角色。
角色 受派人 目的 Foundry 使用者 你的使用者帳號 存取模型部署與建立代理 Foundry 專案管理員 你的使用者帳號 建立專案連結並在代理中使用 MCP 工具 認知服務使用者 搜尋服務受管理的身份識別 存取資料庫
重要
Foundry RBAC 角色最近已重新命名。 Foundry 用戶、Foundry 擁有者、Foundry Account Owner 以及 Foundry Project Manager 先前分別被稱為 Azure AI 使用者、Azure AI 擁有者、Azure AI 帳戶擁有者及 Azure AI Project 管理者。 在更名期間,你可能還會在某些地方看到之前的名字。角色 ID 與核心權限不會因命名而改變。
設定你的環境
在你本機系統上建立一個命名
tutorial-agentic-retrieval的資料夾。在 Visual Studio Code 中開啟該資料夾。
選擇 View>Command Palette,然後選擇 Python: Create Environment。 依照提示建立虛擬環境。
選取 [終端機]>[新增終端機]。
安裝所需的套件。
pip install azure-ai-projects==2.0.0b1 azure-mgmt-cognitiveservices azure-identity ipykernel python-dotenv azure-search-documents==11.7.0b2 requests openai在資料夾中建立一個命名
.envtutorial-agentic-retrieval的檔案。在
.env檔案中加入以下變數,將佔位符值替換成你自己的。AZURE_SEARCH_ENDPOINT = https://{your-service-name}.search.windows.net PROJECT_ENDPOINT = https://{your-resource-name}.services.ai.azure.com/api/projects/{your-project-name} PROJECT_RESOURCE_ID = /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/Microsoft.CognitiveServices/accounts/{account-name}/projects/{project-name} AZURE_OPENAI_ENDPOINT = https://{your-resource-name}.openai.azure.com AZURE_OPENAI_EMBEDDING_DEPLOYMENT = text-embedding-3-large AGENT_MODEL = gpt-5-mini你可以在 Azure 入口網站中找到端點和資源 ID:
AZURE_SEARCH_ENDPOINT在你的搜尋服務的 概覽 頁面。PROJECT_ENDPOINT在你專案的 端點 頁面上。PROJECT_RESOURCE_ID在你專案的 屬性 頁面上。AZURE_OPENAI_ENDPOINT位於您專案父資源的 端點 頁面。
若要使用 Microsoft Entra ID 進行無鑰匙認證,請登入您的 Azure 帳號。 如果你有多個訂閱,請選擇包含你 Azure AI 搜尋服務 和 Microsoft Foundry 資源的訂閱。
az login在資料夾中建立一個命名
tutorial.ipynbtutorial-agentic-retrieval的檔案。 你在下一節將程式碼儲存格加入這個檔案。
建構解決方案
在本節中,你將建立代理檢索解的組成部分。 將每個程式碼片段加入筆記本中的 tutorial.ipynb 獨立程式碼格,並依序執行這些格子。
本節步驟包括:
負載連接
以下程式碼會從你的 .env 檔案載入環境變數,並建立與 Azure AI 搜尋服務 和 Microsoft Foundry 的連線。
import os
from azure.identity import DefaultAzureCredential
from azure.mgmt.core.tools import parse_resource_id
from dotenv import load_dotenv
load_dotenv(override=True) # Take environment variables from .env
project_endpoint = os.environ["PROJECT_ENDPOINT"]
project_resource_id = os.environ["PROJECT_RESOURCE_ID"]
project_connection_name = os.getenv("PROJECT_CONNECTION_NAME", "earthknowledgeconnection")
agent_model = os.getenv("AGENT_MODEL", "gpt-5-mini")
agent_name = os.getenv("AGENT_NAME", "earth-knowledge-agent")
endpoint = os.environ["AZURE_SEARCH_ENDPOINT"]
credential = DefaultAzureCredential()
knowledge_source_name = os.getenv("AZURE_SEARCH_KNOWLEDGE_SOURCE_NAME", "earth-knowledge-source")
index_name = os.getenv("AZURE_SEARCH_INDEX", "earth-at-night")
azure_openai_endpoint = os.environ["AZURE_OPENAI_ENDPOINT"]
azure_openai_embedding_deployment = os.getenv("AZURE_OPENAI_EMBEDDING_DEPLOYMENT", "text-embedding-3-large")
azure_openai_embedding_model = os.getenv("AZURE_OPENAI_EMBEDDING_MODEL", "text-embedding-3-large")
base_name = os.getenv("AZURE_SEARCH_AGENT_NAME", "earth-knowledge-base")
# Parse the resource ID to extract subscription and other components
parsed_resource_id = parse_resource_id(project_resource_id)
subscription_id = parsed_resource_id['subscription']
resource_group = parsed_resource_id['resource_group']
account_name = parsed_resource_id['name']
project_name = parsed_resource_id['child_name_1']
建立搜尋索引
在 Azure AI 搜尋服務 中,索引是一組結構化的資料集合。 以下程式碼會建立一個索引,用來儲存你的知識庫中可搜尋的內容。
索引結構包含文件識別與頁面內容、嵌入及編號欄位。 該架構還包含語意排序與向量搜尋的配置,後者利用你的 text-embedding-3-large 部署方式將文字向量化並根據語意相似度匹配文件。
欲了解更多此步驟資訊,請參見 建立 Azure AI 搜尋服務 中的代理檢索索引。
from azure.search.documents.indexes import SearchIndexClient
from azure.search.documents.indexes.models import (
AzureOpenAIVectorizer, AzureOpenAIVectorizerParameters,
HnswAlgorithmConfiguration, SearchField, SearchIndex,
SemanticConfiguration, SemanticField, SemanticPrioritizedFields,
SemanticSearch, VectorSearch, VectorSearchProfile
)
index = SearchIndex(
name=index_name,
fields=[
SearchField(name="id", type="Edm.String", key=True, filterable=True, sortable=True, facetable=True),
SearchField(name="page_chunk", type="Edm.String", filterable=False, sortable=False, facetable=False),
SearchField(name="page_embedding_text_3_large", type="Collection(Edm.Single)", stored=False, vector_search_dimensions=3072, vector_search_profile_name="hnsw_text_3_large"),
SearchField(name="page_number", type="Edm.Int32", filterable=True, sortable=True, facetable=True)
],
vector_search=VectorSearch(
profiles=[VectorSearchProfile(name="hnsw_text_3_large", algorithm_configuration_name="alg", vectorizer_name="azure_openai_text_3_large")],
algorithms=[HnswAlgorithmConfiguration(name="alg")],
vectorizers=[
AzureOpenAIVectorizer(
vectorizer_name="azure_openai_text_3_large",
parameters=AzureOpenAIVectorizerParameters(
resource_url=azure_openai_endpoint,
deployment_name=azure_openai_embedding_deployment,
model_name=azure_openai_embedding_model
)
)
]
),
semantic_search=SemanticSearch(
default_configuration_name="semantic_config",
configurations=[
SemanticConfiguration(
name="semantic_config",
prioritized_fields=SemanticPrioritizedFields(
content_fields=[
SemanticField(field_name="page_chunk")
]
)
)
]
)
)
index_client = SearchIndexClient(endpoint=endpoint, credential=credential)
index_client.create_or_update_index(index)
print(f"Index '{index_name}' created or updated successfully")
將文件上傳至索引
目前,該指數是空白的。 以下程式碼將索引中填充來自 NASA 的《Earth at Night》電子書 的 JSON 文件。 依照 Azure AI 搜尋服務 的要求,每份文件都符合索引結構中定義的欄位與資料型態。
關於此步驟的更多資訊,請參見 「將資料推送至索引」。
import requests
from azure.search.documents import SearchIndexingBufferedSender
url = "https://raw.githubusercontent.com/Azure-Samples/azure-search-sample-data/refs/heads/main/nasa-e-book/earth-at-night-json/documents.json"
documents = requests.get(url).json()
with SearchIndexingBufferedSender(endpoint=endpoint, index_name=index_name, credential=credential) as client:
client.upload_documents(documents=documents)
print(f"Documents uploaded to index '{index_name}'")
建立知識來源
知識來源是可重複使用的來源資料參考。 以下程式碼會建立一個針對你先前建立的索引的知識來源。
source_data_fields 指定引用引用中包含哪些索引欄位。 此範例僅包含人類可讀欄位,以避免回應中冗長且無法解釋的嵌入。
欲了解更多此步驟資訊,請參閱 建立搜尋索引知識來源。
from azure.search.documents.indexes import SearchIndexClient
from azure.search.documents.indexes.models import (
SearchIndexFieldReference, SearchIndexKnowledgeSource,
SearchIndexKnowledgeSourceParameters
)
ks = SearchIndexKnowledgeSource(
name=knowledge_source_name,
description="Knowledge source for Earth at night data",
search_index_parameters=SearchIndexKnowledgeSourceParameters(
search_index_name=index_name,
semantic_configuration_name="semantic_config",
source_data_fields=[
SearchIndexFieldReference(name="id"),
SearchIndexFieldReference(name="page_chunk"),
SearchIndexFieldReference(name="page_number")
]
),
)
index_client = SearchIndexClient(endpoint=endpoint, credential=credential)
index_client.create_or_update_knowledge_source(knowledge_source=ks)
print(f"Knowledge source '{knowledge_source_name}' created or updated successfully.")
建立知識庫
以下程式碼建立一個知識庫,協調從你的知識來源進行代理檢索。 程式碼同時儲存知識庫的 MCP 端點,代理程式會用它存取知識庫。
為了與 Foundry Agent Service 整合,知識庫配置如下參數:
output_mode(預覽)設為擷取式資料,為代理程式提供逐字且未經處理的內容,作為依據並進行推理。 另一種模式是答案綜合,會回傳預設答案,限制代理人對來源內容的推理能力。retrieval_reasoning_effort(預覽版)設定為最小強度,這會略過 LLM 型查詢規劃,以降低成本和延遲。 在其他推理方面,知識庫會使用大型語言模型(LLM)重新表述使用者查詢,然後再進行檢索。
欲了解更多此步驟資訊,請參閱 建立知識庫於 Azure AI 搜尋服務。
from azure.search.documents.indexes import SearchIndexClient
from azure.search.documents.indexes.models import KnowledgeBase, KnowledgeSourceReference
from azure.search.documents.knowledgebases.models import KnowledgeRetrievalMinimalReasoningEffort
knowledge_base = KnowledgeBase(
name=base_name,
knowledge_sources=[
KnowledgeSourceReference(
name=knowledge_source_name
)
],
output_mode="extractiveData",
retrieval_reasoning_effort=KnowledgeRetrievalMinimalReasoningEffort()
)
index_client = SearchIndexClient(endpoint=endpoint, credential=credential)
index_client.create_or_update_knowledge_base(knowledge_base=knowledge_base)
print(f"Knowledge base '{base_name}' created or updated successfully")
mcp_endpoint = f"{endpoint.rstrip('/')}/knowledgebases/{base_name}/mcp?api-version=2026-08-01-preview"
建立專案客戶端
使用 AIProjectClient 建立與您的 Microsoft Foundry 專案的客戶端連線。 你的專案可能還沒有代理,但如果你已經完成這個教學,代理會列出在這裡。
from azure.ai.projects import AIProjectClient
project_client = AIProjectClient(endpoint=project_endpoint, credential=credential)
list(project_client.agents.list())
建立專案連結
以下程式碼會在 Microsoft Foundry 中建立RemoteTool一個專案連線(預覽),指向你知識庫中的 MCP 端點。 這個連線會用你的專案管理身份來驗證 Azure AI 搜尋服務。
import requests
from azure.identity import get_bearer_token_provider
bearer_token_provider = get_bearer_token_provider(credential, "https://management.azure.com/.default")
headers = {
"Authorization": f"Bearer {bearer_token_provider()}",
}
response = requests.put(
f"https://management.azure.com{project_resource_id}/connections/{project_connection_name}?api-version=2025-10-01-preview",
headers=headers,
json={
"name": project_connection_name,
"type": "Microsoft.MachineLearningServices/workspaces/connections",
"properties": {
"authType": "ProjectManagedIdentity",
"category": "RemoteTool",
"target": mcp_endpoint,
"isSharedToAll": True,
"audience": "https://search.azure.com/",
"metadata": { "ApiType": "Azure" }
}
}
)
response.raise_for_status()
print(f"Connection '{project_connection_name}' created or updated successfully.")
使用 MCP 工具建立代理
Warning
MCP 實作容易受到攻擊、連鎖故障及人力監督喪失等風險。 您可以透過審核 MCP 伺服器的安全性與可靠性,遵循 Microsoft 推薦的實務 及 產業最佳實務,並實施核准機制及監控連鎖行為來降低這些風險。
以下程式碼建立一個使用 MCP 工具配置的代理程式。 當代理收到使用者查詢時,可以透過 MCP 工具呼叫你的知識庫,取得相關內容以進行回應基礎。
代理定義包含指示,指定其行為及你先前建立的專案連線。 根據我們的實驗,這些指示有效提升知識庫調用的準確度,並確保引用格式正確。
欲了解更多此步驟資訊,請參閱 快速入門:建立新代理人。
from azure.ai.projects.models import PromptAgentDefinition, MCPTool
instructions = """
You are a helpful assistant that must use the knowledge base to answer all the questions from user. You must never answer from your own knowledge under any circumstances.
Every answer must always provide annotations for using the MCP knowledge base tool and render them as: `【message_idx:search_idx†source_name】`
If you cannot find the answer in the provided knowledge base you must respond with "I don't know".
"""
mcp_kb_tool = MCPTool(
server_label="knowledge-base",
server_url=mcp_endpoint,
require_approval="never",
allowed_tools=["knowledge_base_retrieve"],
project_connection_id=project_connection_name
)
agent = project_client.agents.create_version(
agent_name=agent_name,
definition=PromptAgentDefinition(
model=agent_model,
instructions=instructions,
tools=[mcp_kb_tool]
)
)
print(f"AI agent '{agent_name}' created or updated successfully")
(可選)使用每個請求的標頭強制執行權限
如果你的任何知識來源包含權限保護的內容,檢索引擎可以過濾結果,讓每位使用者只看到他們被授權存取的文件。 要啟用此篩選,請在 MCP 工具連線的標頭中轉發已登入使用者的身份憑證 x-ms-query-source-authorization 。 若無該令牌,授權來源會回傳未過濾的結果。 更多資訊請參閱查詢時強制執行權限(預覽)。
若要針對每個請求變更 MCP 標頭,例如在每次呼叫時傳遞不同使用者的權杖,請在代理程式定義中宣告 結構化輸入,並在工具的 headers 中將其參照為 {{placeholder}}。 呼叫者會提供每次召喚的數值。 此方法適用於綁定於專案連線的 MCP 工具。
若要對 MCP 伺服器進行個別使用者授權,也可以使用 OAuth 身分傳遞。
以下程式碼會更新前一步驟中的代理,使 MCP 工具能夠從結構化輸入中讀取其授權標頭。
from azure.ai.projects.models import StructuredInputDefinition
# Reference the token as a placeholder in the header
mcp_kb_tool = MCPTool(
server_label="knowledge-base",
server_url=mcp_endpoint,
require_approval="never",
allowed_tools=["knowledge_base_retrieve"],
project_connection_id=project_connection_name,
headers={
"x-ms-query-source-authorization": "{{search_auth_token}}"
}
)
# Declare the structured input so the caller can supply the token per request
agent = project_client.agents.create_version(
agent_name=agent_name,
definition=PromptAgentDefinition(
model=agent_model,
instructions=instructions,
tools=[mcp_kb_tool],
structured_inputs={
"search_auth_token": StructuredInputDefinition(
description="Per-user Azure AI Search bearer token",
required=True,
schema={"type": "string"},
)
}
)
)
print(f"AI agent '{agent_name}' created or updated successfully")
當你呼叫代理時,請輸入 Azure AI 搜尋服務 令牌structured_inputs。 此範例解析出當前 credential的標記。 對於多使用者應用程式,則改為傳遞每位登入使用者的令牌。 例如,使用透過代理者流程取得的權杖,讓擷取引擎能夠為該使用者篩選結果。
# Resolve an Azure AI Search token from the current credential (use a per-user token in production)
from azure.identity import get_bearer_token_provider
search_token = get_bearer_token_provider(credential, "https://search.azure.com/.default")()
openai_client = project_client.get_openai_client()
conversation = openai_client.conversations.create()
response = openai_client.responses.create(
conversation=conversation.id,
tool_choice="required",
input="{user_query}",
extra_body={
"agent_reference": {"name": agent.name, "type": "agent_reference"},
"structured_inputs": {"search_auth_token": search_token},
},
)
print(f"Response: {response.output_text}")
和經紀人聊聊
你的客戶端應用程式使用 Azure OpenAI 的對話和 Responses API 來與代理互動。
以下程式碼會建立對話並將使用者訊息傳達給客服人員,類似典型的聊天體驗。 代理會透過 MCP 工具決定何時呼叫你的知識庫,並回傳一個帶有參考文獻的自然語言回答。 設定確保 tool_choice="required" 代理在處理查詢時始終使用知識庫工具。
# Get the OpenAI client for responses and conversations
openai_client = project_client.get_openai_client()
conversation = openai_client.conversations.create()
# Send initial request that will trigger the MCP tool
response = openai_client.responses.create(
conversation=conversation.id,
tool_choice="required",
input="""
Why do suburban belts display larger December brightening than urban cores even though absolute light levels are higher downtown?
Why is the Phoenix nighttime street grid is so sharply visible from space, whereas large stretches of the interstate between midwestern cities remain comparatively dim?
""",
extra_body={"agent_reference": {"name": agent.name, "type": "agent_reference"}},
)
print(f"Response: {response.output_text}")
回應應該與以下範例相似。
Response: Here are evidence-based explanations to your questions:
---
**1. Why do suburban belts display larger December brightening than urban cores, even though absolute light levels are higher downtown?**
- Suburban belts show a *larger percentage increase* in night brightness during December compared to urban cores, largely because suburban residential areas feature more single-family homes and larger yards, which are typically decorated with holiday lights. These areas start from a lower baseline (less bright overall at night compared to dense urban centers), so the relative change (brightening) is much more noticeable.
- In contrast, the downtown core is already very bright at night due to dense commercial lighting and streetlights. While it also sees a December increase (often 20–30% brighter), the *absolute* change is less striking because it begins at a much higher base of illumination.
- This pattern is observed across U.S. cities, with the phenomenon driven by widespread cultural practices and the suburban landscape’s suitability for holiday lighting displays. The effect is visible in satellite data and was quantified at 20–50% brighter in December, especially in suburbs and city outskirts.
---
**2. Why is the Phoenix nighttime street grid so sharply visible from space, whereas large stretches of the interstate between midwestern cities remain comparatively dim?**
- Phoenix’s sharply visible nighttime street grid from space is a result of its urban layout: the city (like many western U.S. cities) was developed using a regular grid system, with extensive and uniform street lighting and strong urban sprawl. The grid pattern, and the dense network of intersecting surface streets, is brightly illuminated, particularly at intersections, commercial areas, and major thoroughfares.
- The interstate highways between midwestern cities, though significant in length and crucial to national infrastructure, traverse sparsely populated rural areas. These stretches typically have very little artificial lighting (due to low traffic volumes at night and cost considerations), making them much less visible in nighttime satellite imagery. Only nodes (cities and towns) along the route show as bright "pearls" in the darkness, while the "strings" (highways) connecting them remain faint or invisible.
- In summary:
- Urban areas like Phoenix stand out with strong, connected patterns of light due to dense development and extensive lighting.
- Rural interstates are sparsely lit, and only their endpoints—cities and large towns—generate notable light visible from space.
---
**References**:
- [Holiday Lights increase most dramatically in suburbs, not downtowns: earth_at_night_508_page_176_verbalized, page 160](4:5)
- [Lighting paths and urban grids are visible from space, while rural highways remain dim: earth_at_night_508_page_124_verbalized, page 108](4:3)
- [Phoenix’s grid and surrounding urban structure: earth_at_night_508_page_104_verbalized, page 88](4:1)
檢查回應
代理人的底層回應包含關於發送到知識庫的查詢及所找到的引用的元資料。 你可以檢視這些元資料,了解代理如何處理使用者輸入。
response.to_dict()
清理資源
當您在自己的訂用帳戶中工作時,建議您在完成專案後移除不再需要的資源。 若您讓資源繼續執行,則可能會產生費用。
在Azure入口網站中,從左側窗格選擇 所有資源或 資源群組以尋找並管理資源。 你可以單獨刪除資源,或是一次性刪除資源群組,移除所有資源。
你也可以執行以下程式碼來刪除個別物件:
# Delete the agent
project_client.agents.delete_version(agent.name, agent.version)
print(f"AI agent '{agent.name}' version '{agent.version}' deleted successfully")
# Delete the knowledge base
index_client.delete_knowledge_base(base_name)
print(f"Knowledge base '{base_name}' deleted successfully")
# Delete the knowledge source
index_client.delete_knowledge_source(knowledge_source=knowledge_source_name)
print(f"Knowledge source '{knowledge_source_name}' deleted successfully.")
# Delete the search index
index_client.delete_index(index_name)
print(f"Index '{index_name}' deleted successfully")
提升資料品質
預設情況下,來自知識庫的搜尋結果會整合成單一大型字串,供你傳遞給代理作為奠基依據。 Azure AI 搜尋服務 提供以下索引與相關性調整功能,幫助您產生高品質的結果。 你可以將這些功能實作在搜尋索引中,搜尋相關性的提升也反映在檢索回應的品質上。
得分設定 提供了內建的提升標準。 你的索引必須指定一個預設的評分輪廓,檢索引擎在查詢中包含與該輪廓相關的欄位時會使用該輪廓。
語義配置是必要的,但你決定優先排序和用於排名的欄位。
對於純文字內容,你可以使用 分析器 在索引時控制標記化。
對於多模態或影像內容,您可以使用影像語言描述來取得由 LLM 生成的影像描述,或在編製索引期間透過技能集進行傳統的 OCR 和影像分析。
控制子查詢數量
你可以透過在知識庫中設定檢索推理強度(預覽)來控制子查詢的數量。 推理努力決定了查詢規劃中LLM處理的層級,範圍從最低(無LLM處理)到中等(深入搜尋與後續迭代)。
對於非最小推理工作,LLM 會根據以下因素決定子查詢數量:
- 使用者查詢
- 聊天歷史
- 語意排序器輸入限制
控制傳送給代理的上下文
回應 API 控制傳送給代理與知識庫的內容。 為了優化效能與相關性,請調整代理指令,在傳送至 MCP 工具前,先彙總或過濾聊天歷史。
控制成本與限制操作
想了解查詢計畫,可以查看知識庫回應活動 陣列 中的輸出標記。
提升效能
為了優化效能並降低延遲,請考慮以下策略:
總結訊息串。
使用
gpt-5-mini或是較小且效能更快的型號。設定
maxOutputSize在 擷取動作 上,以控制回應的大小或maxRuntimeInSeconds時間限制處理。將大型文件分成較小的部分再進行索引。 超出產出預算的文件可以 被悄悄排除在有根據的結果之外。