你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

将 Foundry IQ 知识库连接到 Foundry 代理服务

重要

本文中标记了“(预览版)”的项目目前为公共预览版。 此预览版未提供服务级别协议,不建议将其用于生产工作负载。 某些功能可能不受支持或者受限。 有关详细信息,请参阅 Microsoft Azure 预览版补充使用条款

本文介绍如何将 Microsoft Foundry 中的代理连接到由 Azure AI 搜索提供支持的 Foundry IQ 知识库。 连接使用模型上下文协议(MCP)促进工具调用。 代理调用时,知识库会协调以下检索作:

  • 对用户查询进行计划并将其分解为子查询。
  • 使用关键字、矢量或混合技术同时处理子查询。
  • 应用语义重新调整以识别最相关的结果。
  • 使用源引用将结果合成到统一响应中。

智能体使用响应来基于企业数据或 web 源提供答复,通过源归属确保事实的准确性和透明度。

有关集成 Azure AI 搜索和 Foundry 代理服务进行知识检索的端到端示例,请参阅 GitHub 上的 agentic-retrieval-pipeline-example Python 示例。

先决条件

身份验证和权限

建议对生产部署使用基于角色的访问控制。 如果角色不可行,请跳过本部分,改用基于密钥的身份验证。

  • 在项目的父资源上,必须具有 Azure AI 用户 角色才能访问模型部署和创建代理。 创建资源时,会自动为 所有者 授予此分配。 其他用户需要特定的角色分配。 有关详细信息,请参阅 Foundry 门户中基于角色的访问控制

  • 在项目的父资源上,必须具有 Azure AI 项目经理 角色才能为 MCP 身份验证创建项目连接,Azure AI 用户Azure AI 项目经理 才能在代理中使用 MCP 工具。

  • 在项目中,创建系统分配的托管标识,以便与 Azure AI 搜索进行交互。

了解知识

知识通过集成以下服务,实现对企业内容的智能体基础设置和推理:

  • Azure AI 搜索 提供知识源(检索什么)和知识库(如何 检索)。 知识库计划和执行子查询,并输出带引文的格式结果。

    尽管知识库支持 答案合成,但我们建议提取数据输出模式与 Foundry 代理服务集成。 此模式可确保代理接收逐字内容而不是预生成的答案,从而完全控制响应格式和质量。

  • Foundry 代理服务 通过 MCP 工具协调对知识库的调用,并合成最终答案。 在运行时,代理仅调用知识库,而不是基础知识源的数据平台(例如 Azure Blob 存储或 Microsoft OneLake)。 知识库处理所有检索操作。

创建项目连接

首先,在 Microsoft Foundry 项目上创建 RemoteTool 连接。 此连接使用项目的托管标识以知识库的 MCP 终结点为目标,使代理能够安全地与 Azure AI 搜索通信以检索作。

import requests
from azure.identity import DefaultAzureCredential, get_bearer_token_provider

# Provide connection details
credential = DefaultAzureCredential()
project_resource_id = "{project_resource_id}" # e.g. /subscriptions/{subscription}/resourceGroups/{resource_group}/providers/Microsoft.MachineLearningServices/workspaces/{account_name}/projects/{project_name}
project_connection_name = "{project_connection_name}"
mcp_endpoint = "{search_service_endpoint}/knowledgebases/{knowledge_base_name}/mcp?api-version=2025-11-01-preview" # This endpoint enables the MCP connection between the agent and knowledge base

# Get bearer token for authentication
bearer_token_provider = get_bearer_token_provider(credential, "https://management.azure.com/.default")
headers = {
  "Authorization": f"Bearer {bearer_token_provider()}",
}

# Create project connection
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.")

优化智能助手的知识检索指令

若要最大程度地提高知识库调用的准确性并确保正确的引文格式,请使用优化的代理说明。 根据试验,我们建议使用以下指令模板作为起点:

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 工具调用速率:显式指令可确保代理一致地调用知识库工具,而不是依赖其训练数据。
  • 正确的批注格式:指定的引文格式可确保代理在响应中包含来源信息,并明确使用了哪些知识来源。

小窍门

虽然此模板提供了坚实的基础,但我们建议根据您的特定用例和目标评估并迭代完善指导说明。 测试不同的变体,以找出最适合你情境的方法。

使用 MCP 工具创建代理

下一步是创建将知识库作为 MCP 工具集成的代理。 代理使用系统提示来指示何时以及如何调用知识库,按照有关如何回答问题的说明进行作,并在会话会话之间自动维护其工具配置和设置。

将知识库 MCP 工具添加到您之前创建的项目连接中。 此工具协调跨配置的知识源的查询规划、分解和检索。 代理使用此工具回答查询。

注释

Azure AI 搜索知识库公开 knowledge_base_retrieve MCP 工具用于代理集成。 这是目前唯一支持用于 Foundry 代理服务的工具。

from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import PromptAgentDefinition, MCPTool
from azure.identity import DefaultAzureCredential

# Provide agent configuration details
credential = DefaultAzureCredential()
mcp_endpoint = "{search_service_endpoint}/knowledgebases/{knowledge_base_name}/mcp?api-version=2025-11-01-preview"
project_endpoint = "{project_endpoint}" # e.g. https://your-foundry-resource.services.ai.azure.com/api/projects/your-foundry-project
project_connection_name = "{project_connection_name}"
agent_name = "{agent_name}"
agent_model = "{deployed_LLM}" # e.g. gpt-4.1-mini

# Create project client
project_client = AIProjectClient(endpoint = project_endpoint, credential = credential)

# Define agent instructions (see "Optimize agent instructions" section for guidance)
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".
"""

# Create MCP tool with knowledge base connection
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
)

# Create agent with MCP tool
agent = project_client.agents.create_version(
    agent_name = agent_name,
    definition = PromptAgentDefinition(
        model = agent_model,
        instructions = instructions,
        tools = [mcp_kb_tool]
    )
)

print(f"Agent '{agent_name}' created or updated successfully.")

连接到远程 SharePoint 知识源

如果您的知识库包含远程 SharePoint 知识源,则在 MCP 工具连接中也必须包含 x-ms-query-source-authorization 头。

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": get_bearer_token_provider(credential, "https://search.azure.com/.default")()
    }
)

使用查询调用代理

创建会话并将用户查询发送到代理。 如果适用,代理会协调对 MCP 工具的调用,以从知识库中检索相关内容。 然后,代理将此内容合成为引用源文档的自然语言响应。

# Get the OpenAI client for responses and conversations
openai_client = project_client.get_openai_client()

# Create conversation
conversation = openai_client.conversations.create()

# Send request to trigger the MCP tool
response = openai_client.responses.create(
    conversation = conversation.id,
    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": {"name": agent.name, "type": "agent_reference"}},
)

print(f"Response: {response.output_text}")

输出应与以下内容类似:

Response: Suburban belts display larger December brightening than urban cores, even though absolute light levels are higher downtown, primarily because holiday lights increase most dramatically in the suburbs and outskirts of major cities. This is due to more yard space and a prevalence of single-family homes in suburban areas, which results in greater use of decorative holiday lighting. By contrast, central urban areas experience a smaller increase in lighting during the holidays, typically 20 to 30 percent brightening, because of their different building structures and possibly less outdoor space for such decorations. This pattern holds true across the United States as part of the nationally shared tradition of increased holiday lighting in December (Sources: earth_at_night_508_page_174, earth_at_night_508_page_176, earth_at_night_508_page_175).

The Phoenix nighttime street grid is sharply visible from space due to the city's layout along a regular grid of city blocks and streets with extensive street lighting. The major street grid is oriented mostly north-south, with notable diagonal thoroughfares like Grand Avenue that are also brightly lit. The illuminated grid reflects the widespread suburban and residential development fueled by automobile use in the 20th century, which led to optimal access routes to new real estate on the city's borders. Large shopping centers, strip malls, gas stations, and other commercial properties at major intersections also contribute to the brightness. Additionally, parts of the Phoenix metropolitan area remain dark where there are parks, recreational land, and agricultural fields, providing contrast that highlights the lit urban grid (Sources: earth_at_night_508_page_104, earth_at_night_508_page_105).

In contrast, large stretches of the interstate between Midwestern cities remain comparatively dim because although the transportation corridors are well-established, many rural and agricultural areas lack widespread nighttime lighting. The interstate highways are visible but do not have the same continuous bright lighting found in the dense urban grids and commercial suburban zones. The transportation network is extensive, but many roadways running through less populated regions have limited illumination, which renders them less visible in nighttime satellite imagery (Sources: earth_at_night_508_page_124, earth_at_night_508_page_125).

References:
- earth_at_night_508_page_174, earth_at_night_508_page_176, earth_at_night_508_page_175 (Holiday lighting and suburban December brightening)
- earth_at_night_508_page_104, earth_at_night_508_page_105 (Phoenix urban grid visibility)
- earth_at_night_508_page_124, earth_at_night_508_page_125 (Interstate lighting and Midwestern dim stretches)

删除代理和项目连接

# Delete the agent
project_client.agents.delete_version(agent.name, agent.version)
print(f"Agent '{agent.name}' version '{agent.version}' deleted successfully.")

# Delete the project connection
mgmt_client.project_connections.delete(
    resource_group_name = resource_group,
    account_name = account_name,
    project_name = project_name,
    connection_name = project_connection_name
)
print(f"Project connection '{project_connection_name}' deleted successfully.")

注释

删除代理和项目连接不会删除知识库或其构成知识源,必须在 Azure AI 搜索服务上单独删除该知识库。 有关详细信息,请参阅 “删除知识库 ”和 “删除知识库”。