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

创建文件知识源

注释

Foundry IQ (Azure AI 搜索) 提供直接索引和查询 API 以及用于托管检索的高级知识库和知识库 API。 使用 Azure 门户、REST API 或Azure SDK配置这些功能,或将代理连接到 Microsoft Foundry 门户中的知识库。

Important

本文中标记为(预览)的功能为公共预览版,受Microsoft Azure预览版补充使用条款的约束。 有关特定于 Foundry IQ(Azure AI 搜索)的预览术语,请参阅预览功能。

文件知识源将小到中型文件集直接上传到 Foundry IQ 进行代理检索。 知识来源独立创建,在知识库中被引用,并在运行时查询知识库时用作基础数据。

如果需要托管上传体验,而不是预配Azure 存储、配置访问权限以及通过外部容器创建索引器管道,则文件知识源非常有用。 Foundry IQ 处理上传的文件,以便从知识库中检索其提取的内容。

如果文件已存储在 Azure Blob 存储 或 Azure Data Lake Storage Gen2 中,如果文件集已超过或可能会超过 文件知识源限制,或者如果需要计划内引入,请改用 Blob 知识源。 如果想要使用Azure Blob 存储生命周期管理策略管理源 blob,或者需要基于Azure 存储中权限的文档级权限,请使用 blob 知识源。

使用支持

Azure 门户 Microsoft Foundry 门户 .NET SDK Python SDK Java SDK JavaScript SDK REST API
❌ ✔️ ✔️ ✔️ ✔️ ✔️ ✔️

先决条件

  • 在提供智能体检索的任意区域中的 Foundry IQ 服务。 文件知识源支持专用和无服务器定价模型。 有关模型和层详细信息,请参阅 “选择定价模型和服务层”。

  • 查看 Foundry IQ 成本。 模型调用、矢量化和其他 AI 处理可能会产生单独的费用。

  • 在无服务器环境中,成功的文件摄取操作会消耗计费计算资源。 失败的上传不会产生无服务器计算费用。

  • 如果需要超出每月免费津贴的付费代理检索, 请启用标准代理检索计划。 该 knowledgeRetrieval=standard 设置独立于无服务器计算和存储费用,不选择定价模型。

  • 受支持格式的文件。

  • 创建知识源的权限。 使用分配给用户帐户的搜索服务参与者角色(建议)或使用管理员 API 密钥配置无密钥身份验证。

  • 对于使用托管标识调用 Azure OpenAI 嵌入的情况,请在匹配 resourceUri 的 Azure OpenAI 或父级 Foundry 资源上,为所选标识分配认知服务 OpenAI 用户。 内容理解提取需要单独的权限。 请参阅分配角色。

    • 如果 Foundry 资源已禁用公用网络访问,请使用符合条件的专用服务创建foundry_account指向 Foundry 资源的共享专用链接。 保持资源的允许受信任服务列表中的 Azure 服务设置处于启用状态。 无服务器不支持此共享专用链接配置。 有关受支持的公共终结点访问控制,请参阅 网络安全外围;外围不会创建专用连接。

    • 请查看知识来源配置和层级矩阵。 文件上传不会创建索引器,因此生成的索引器网络覆盖设置不适用。

  • 如果知识源指定standard内容提取模式,请查看Azure内容理解技能的要求。

    • 对于本文中的示例,需要 Foundry 资源终结点和密钥,以及Azure OpenAI 嵌入和聊天完成模型信息。
  • 最新的 Azure.Search.Documents 预览包:dotnet add package Azure.Search.Documents --prerelease

  • 对于无密钥身份验证,请使用 Azure.Identity 软件包:dotnet add package Azure.Identity

  • 最新的 azure-search-documents 预览包:pip install --pre azure-search-documents

  • 对于无密钥身份验证,请使用 azure-identity 软件包:pip install azure-identity

文件支持和限制

在创建文件知识源之前,请查看影响文件上传、提取和管理的要求和限制。

支持的内容类型

Foundry IQ 从文件字节中检测 MIME 类型。

minimal 提取功能接受受支持的文档格式,包括检测到的 text/* 类型。

standard 提取的支持范围更窄,具体取决于 Azure 内容理解技能支持的文件格式。 图像需要 standard 提取以及受支持的检测格式。

支持的提取模式

minimal 使用内置提取,这是默认值。 standard 通过 Content Understanding 发送每个文件,并需要 aiServices 配置。

  • 检测为2026-05-01-preview的内容在image/*中不受支持。 在 2026-10-01 中,使用 standard 提取方式。 minimal 提取在两个版本中均返回 HTTP 状态 415。

限制和文件操作

限制和受支持的文件操作因 API 版本和引入方法而异。

能力 2026-11-01-preview 异步 2026-10-01 同步 2026-08-01-preview 同步
每个知识源的最大文件数 10,000 200 200
文件大小上限 512 MiB 免费版和基本版为 50 MiB;其他受支持层级为 100 MiB 50 MiB 免费版和基本版;其他支持的专用层和无服务器层上的 100 MiB
处理持续时间 轮询直到完成 180 秒 180 秒

生成的搜索索引存储上传的内容。 有关按定价层排序的总存储限制,请参阅 服务限制。 如果配置矢量化,模型和下游处理限制也适用。

检查现有知识源

C# 和 Python 示例使用的是 11 月预览版 SDK。 对于 REST 请求,将 {{api-version}} 设置为 2026-11-01-preview。

知识源是顶级可重用对象。 了解现有知识源有助于重复使用或命名新对象。

运行以下代码,按名称和类型列出知识源。

// List knowledge sources by name and type
using Azure.Search.Documents.Indexes;

var indexClient = new SearchIndexClient(new Uri(searchEndpoint), credential);
var knowledgeSources = indexClient.GetKnowledgeSourcesAsync();

Console.WriteLine("Knowledge Sources:");

await foreach (var ks in knowledgeSources)
{
    Console.WriteLine($"  Name: {ks.Name}, Type: {ks.GetType().Name}");
}

参考:SearchIndexClient

# List knowledge sources by name and type
from azure.core.credentials import AzureKeyCredential
from azure.search.documents.indexes import SearchIndexClient

index_client = SearchIndexClient(endpoint = "search_url", credential = AzureKeyCredential("api_key"))

for ks in index_client.list_knowledge_sources():
    print(f"  - {ks.name} ({ks.kind})")

参考:SearchIndexClient

### List knowledge sources by name and type
GET {{search-url}}/knowledgesources?api-version={{api-version}}&$select=name,kind
Authorization: Bearer {{token}}

参考:知识源 - 列表

还可以按名称返回单个知识源以查看其 JSON 定义。

using Azure.Search.Documents.Indexes;
using System.Text.Json;

var indexClient = new SearchIndexClient(new Uri(searchEndpoint), credential);

// Specify the knowledge source name to retrieve
string ksNameToGet = "earth-knowledge-source";

// Get its definition
var knowledgeSourceResponse = await indexClient.GetKnowledgeSourceAsync(ksNameToGet);
var ks = knowledgeSourceResponse.Value;

// Serialize to JSON for display
var jsonOptions = new JsonSerializerOptions 
{ 
    WriteIndented = true,
    DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.Never
};
Console.WriteLine(JsonSerializer.Serialize(ks, ks.GetType(), jsonOptions));

参考:SearchIndexClient

# Get a knowledge source definition
from azure.core.credentials import AzureKeyCredential
from azure.search.documents.indexes import SearchIndexClient
import json

index_client = SearchIndexClient(endpoint = "search_url", credential = AzureKeyCredential("api_key"))

ks = index_client.get_knowledge_source("knowledge_source_name")
print(json.dumps(ks.as_dict(), indent = 2))

参考:SearchIndexClient

### Get a knowledge source definition
GET {{search-url}}/knowledgesources('{{knowledge-source-name}}')?api-version={{api-version}}
Authorization: Bearer {{token}}

参考:知识来源 - 获取

以下 JSON 是文件知识源的示例响应。

{
  "name": "my-file-ks",
  "kind": "file",
  "description": "A sample file knowledge source.",
  "encryptionKey": null,
  "fileParameters": {
    "ingestionParameters": {
      "contentExtractionMode": "minimal",
      "embeddingModel": {
        "kind": "azureOpenAI",
        "azureOpenAIParameters": {
          "resourceUri": "<REDACTED>",
          "deploymentId": "text-embedding-3-large",
          "modelName": "text-embedding-3-large"
        }
      }
    }
  }
}

创建知识源

创建文件知识源,指定用于向量化上传内容的嵌入模型。

每个文件知识源都创建索引,但不是索引器或计划。 必须包含该 fileParameters.ingestionParameters 对象。 服务拒绝指定 networkAccessMode的请求。

using Azure.Identity;
using Azure.Search.Documents.Indexes;
using Azure.Search.Documents.Indexes.Models;
using Azure.Search.Documents.KnowledgeBases.Models;

var indexClient = new SearchIndexClient(new Uri(searchEndpoint), new DefaultAzureCredential());

var embeddingParams = new AzureOpenAIVectorizerParameters
{
    ResourceUri = new Uri(aoaiEndpoint),
    DeploymentName = aoaiEmbeddingDeployment,
    ModelName = aoaiEmbeddingModel
};

var ingestionParams = new KnowledgeSourceIngestionParameters
{
    ContentExtractionMode = "minimal",
    EmbeddingModel = new KnowledgeSourceAzureOpenAIVectorizer
    {
        AzureOpenAIParameters = embeddingParams
    }
};

var fileParams = new FileKnowledgeSourceParameters
{
    IngestionParameters = ingestionParams
};

var knowledgeSource = new FileKnowledgeSource(
    name: "my-file-ks",
    fileParameters: fileParams
)
{
    Description = "This knowledge source uses directly uploaded product manuals."
};

await indexClient.CreateOrUpdateKnowledgeSourceAsync(knowledgeSource);

参考:SearchIndexClient

from azure.identity import DefaultAzureCredential
from azure.search.documents.indexes import SearchIndexClient
from azure.search.documents.indexes.models import (
    AzureOpenAIVectorizerParameters,
    FileKnowledgeSource,
    FileKnowledgeSourceParameters,
)
from azure.search.documents.knowledgebases.models import (
    KnowledgeSourceAzureOpenAIVectorizer,
    KnowledgeSourceIngestionParameters,
)

index_client = SearchIndexClient(endpoint="<search-endpoint>", credential=DefaultAzureCredential())

embedding_params = AzureOpenAIVectorizerParameters(
    resource_url="<aoai-endpoint>",
    deployment_name="<aoai-embedding-deployment>",
    model_name="<aoai-embedding-model>",
)

ingestion_params = KnowledgeSourceIngestionParameters(
    content_extraction_mode="minimal",
    embedding_model=KnowledgeSourceAzureOpenAIVectorizer(
        azure_open_ai_parameters=embedding_params
    ),
)

knowledge_source = FileKnowledgeSource(
    name="my-file-ks",
    description="This knowledge source uses directly uploaded product manuals.",
    file_parameters=FileKnowledgeSourceParameters(ingestion_parameters=ingestion_params),
)

index_client.create_or_update_knowledge_source(knowledge_source=knowledge_source)

参考:SearchIndexClient

PUT {{searchEndpoint}}/knowledgesources('my-file-ks')?api-version=2026-10-01
Authorization: ******
Content-Type: application/json
Prefer: return=representation

{
  "name": "my-file-ks",
  "kind": "file",
  "description": "This knowledge source uses directly uploaded product manuals.",
  "encryptionKey": null,
  "fileParameters": {
    "ingestionParameters": {
      "embeddingModel": {
        "kind": "azureOpenAI",
        "azureOpenAIParameters": {
          "resourceUri": "{{aoai-endpoint}}",
          "deploymentId": "{{aoai-embedding-deployment}}",
          "modelName": "{{aoai-embedding-model}}"
        }
      },
      "contentExtractionMode": "minimal"
    }
  }
}

参考:知识源 - 创建或更新

对于新源,应为 201(200 会更新现有源)。 读回定义,确认其名称、种类和生成的索引。

GET {{searchEndpoint}}/knowledgesources('my-file-ks')?api-version=2026-10-01
Authorization: ******

参考:知识来源

配置标准提取

从 2026-08-01-preview API 版本开始, standard 提取使用内容理解来提取、语义化区块和扩充上传的文件。 Foundry IQ 负责管理引入管道,并使用 aiServices 中指定的 Foundry 资源。

C# 和 Python 配置示例使用的是 11 月预览版 SDK。 REST 示例使用 2026-11-01-preview。 在使用内容理解要求之前,请先查阅这些要求。

标准设置可将帐户范围的模型映射添加到已配置的 Content Understanding 帐户。 在创建或更新标准源之前,请检查共享配置。 最少的设置不会配置该帐户或使用模型凭据。

标准提取会产生内容理解费用,并在启用图像语言化时产生模型使用费用。 有关详细信息,请参阅 计费和映像说明控件。

using Azure.Identity;
using Azure.Search.Documents.Indexes;
using Azure.Search.Documents.Indexes.Models;
using Azure.Search.Documents.KnowledgeBases.Models;

var indexClient = new SearchIndexClient(new Uri(searchEndpoint), new DefaultAzureCredential());

var embeddingParameters = new AzureOpenAIVectorizerParameters
{
  ResourceUri = new Uri(aoaiEndpoint),
  DeploymentName = aoaiEmbeddingDeployment,
  ModelName = aoaiEmbeddingModel
};

var ingestionParameters = new KnowledgeSourceIngestionParameters
{
  ContentExtractionMode = KnowledgeSourceContentExtractionMode.Standard,
  AiServices = new AIServices(new Uri(foundryEndpoint)) { ApiKey = foundryKey },
  EmbeddingModel = new KnowledgeSourceAzureOpenAIVectorizer
  {
    AzureOpenAIParameters = embeddingParameters
  },
  ChatCompletionModel = new KnowledgeBaseAzureOpenAIModel(
    new AzureOpenAIVectorizerParameters
    {
      ResourceUri = new Uri(aoaiEndpoint),
      DeploymentName = aoaiChatDeployment,
      ModelName = aoaiChatModel
    })
};

var knowledgeSource = new FileKnowledgeSource(
  "my-file-ks",
  new FileKnowledgeSourceParameters { IngestionParameters = ingestionParameters });

await indexClient.CreateOrUpdateKnowledgeSourceAsync(knowledgeSource);

参考:SearchIndexClient

from azure.identity import DefaultAzureCredential
from azure.search.documents.indexes import SearchIndexClient
from azure.search.documents.indexes.models import (
  AzureOpenAIVectorizerParameters,
  FileKnowledgeSource,
  FileKnowledgeSourceParameters,
  KnowledgeBaseAzureOpenAIModel,
)
from azure.search.documents.knowledgebases.models import (
  AIServices,
  KnowledgeSourceAzureOpenAIVectorizer,
  KnowledgeSourceIngestionParameters,
)

index_client = SearchIndexClient(endpoint="<search-endpoint>", credential=DefaultAzureCredential())

embedding_parameters = AzureOpenAIVectorizerParameters(
  resource_url="<aoai-endpoint>",
  deployment_name="<aoai-embedding-deployment>",
  model_name="<aoai-embedding-model>",
)
ingestion_parameters = KnowledgeSourceIngestionParameters(
  content_extraction_mode="standard",
  ai_services=AIServices(
    uri="<foundry-resource-endpoint>",
    api_key="<foundry-resource-key>",
  ),
  embedding_model=KnowledgeSourceAzureOpenAIVectorizer(
    azure_open_ai_parameters=embedding_parameters
  ),
  chat_completion_model=KnowledgeBaseAzureOpenAIModel(
    azure_open_ai_parameters=AzureOpenAIVectorizerParameters(
      resource_url="<aoai-endpoint>",
      deployment_name="<aoai-gpt-deployment>",
      model_name="<aoai-gpt-model>",
    )
  ),
)
knowledge_source = FileKnowledgeSource(
  name="my-file-ks",
  file_parameters=FileKnowledgeSourceParameters(
    ingestion_parameters=ingestion_parameters
  ),
)

index_client.create_or_update_knowledge_source(knowledge_source)

参考:SearchIndexClient

PUT {{searchEndpoint}}/knowledgesources('my-file-ks')?api-version=2026-11-01-preview
Content-Type: application/json
Authorization: Bearer {{search-access-token}}
Prefer: return=representation

{
  "name": "my-file-ks",
  "kind": "file",
  "description": "This knowledge source uses standard extraction.",
  "fileParameters": {
    "ingestionParameters": {
      "embeddingModel": {
        "kind": "azureOpenAI",
        "azureOpenAIParameters": {
          "resourceUri": "{{aoai-endpoint}}",
          "deploymentId": "{{aoai-embedding-deployment}}",
          "modelName": "{{aoai-embedding-model}}"
        }
      },
      "chatCompletionModel": {
        "kind": "azureOpenAI",
        "azureOpenAIParameters": {
          "resourceUri": "{{aoai-endpoint}}",
          "deploymentId": "{{aoai-gpt-deployment}}",
          "modelName": "{{aoai-gpt-model}}"
        }
      },
      "contentExtractionMode": "standard",
      "aiServices": {
        "uri": "{{foundry-resource-endpoint}}",
        "apiKey": "{{foundry-resource-key}}"
      }
    }
  }
}

参考:知识源 - 创建或更新

用于文件操作的 CORS

在完整的源定义上设置 corsOptions,以允许受信任的浏览器源进行文件上传、列出、更新和删除。

Important

在 2026-10-01 API 版本中, corsOptions 适用于独立于提取模式的文件上传、列出、更新和删除终结点。 如果省略 corsOptions,则文件知识源没有浏览器跨源策略。 CORS 不授权请求。 启用源可以在浏览器上下文中公开服务操作和数据,并引入安全风险。 仅指定受信任的源,并且不要在生产中使用通配符源。 对于浏览器请求,请使用 Microsoft Entra 令牌身份验证,并按需分配最低角色。 切勿在浏览器代码中公开访问令牌或服务密钥。

PUT {{searchEndpoint}}/knowledgesources('my-file-ks')?api-version=2026-10-01
api-key: {{searchAdminKey}}
Content-Type: application/json

{
  "name": "my-file-ks",
  "kind": "file",
  "fileParameters": {
    "ingestionParameters": {
      "embeddingModel": {
        "kind": "azureOpenAI",
        "azureOpenAIParameters": {
          "resourceUri": "{{aoai-endpoint}}",
          "deploymentId": "{{aoai-embedding-deployment}}",
          "modelName": "{{aoai-embedding-model}}"
        }
      },
      "contentExtractionMode": "minimal"
    }
  },
  "corsOptions": {
    "allowedOrigins": ["https://files.example.com"],
    "maxAgeInSeconds": 300
  }
}

参考:知识来源

OPTIONS {{searchEndpoint}}/knowledgesources('my-file-ks')/files?api-version=2026-10-01
Origin: https://files.example.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: authorization,content-type

参考:知识来源

上传文件

创建知识源后,使用多部分上传将文件直接上传到它。 每个上传都是同步调用。 Foundry IQ 提取内容,将其拆分为块,根据需要创建嵌入,为这些块编制索引,并保存文件元数据。 无需设置或运行单独的数据引入管道。

有关上传和管理文件相关的错误的帮助,请参阅 文件操作疑难解答。

POST {{searchEndpoint}}/knowledgesources('my-file-ks')/files?api-version=2026-10-01
Authorization: ******
Content-Type: multipart/form-data; boundary=file-boundary

--file-boundary
Content-Disposition: form-data; name="metadata"
Content-Type: application/json

{
  "fileName": "manuals/handbook.txt"
}
--file-boundary
Content-Disposition: form-data; name="content"; filename="handbook.txt"
Content-Type: application/octet-stream

Employees request production access through the engineering access portal.
--file-boundary--

参考:知识来源

上传原始文件

原始上传仅在预览 API 中可用。 有关 GA 文件上传,请参阅 “上传文件”。

C# 和 Python 原始示例使用 11 月预览版 SDK。 REST 示例使用 2026-11-01-preview 同步终结点。

文件名可以包含相对路径,例如 manuals/installation-guide.pdf。 服务将反斜杠规范化为正斜杠。 它会以 HTTP 状态 400 拒绝绝对路径、空路径段、.. 段或 . 段、包含冒号的路径段以及无效的文件名字符。

using Azure.Identity;
using Azure.Search.Documents.Indexes;
using Azure.Search.Documents.Indexes.Models;

var indexClient = new SearchIndexClient(new Uri(searchEndpoint), new DefaultAzureCredential());

string fileName = "installation-guide.pdf";
byte[] fileBytes = await File.ReadAllBytesAsync(fileName);
string contentDisposition = $"attachment; filename=\"{fileName}\"";

KnowledgeSourceFile uploadedFile = (await indexClient.UploadKnowledgeSourceFileAsync(
    "my-file-ks",
    contentDisposition,
    BinaryData.FromBytes(fileBytes))).Value;

Reference:SearchIndexClient.UploadKnowledgeSourceFileAsync

from pathlib import Path

from azure.identity import DefaultAzureCredential
from azure.search.documents.indexes import SearchIndexClient

index_client = SearchIndexClient(endpoint="<search-endpoint>", credential=DefaultAzureCredential())

file_path = Path("installation-guide.pdf")
uploaded_file = index_client.upload_knowledge_source_file(
    "my-file-ks",
    file_path.read_bytes(),
    filename=file_path.name,
)

Reference:SearchIndexClient.upload_knowledge_source_file

将原始文件字节发送到预览同步终结点。 即使对于文本内容,也请使用 application/octet-stream。

POST {{searchEndpoint}}/knowledgesources('my-file-ks')/files?api-version=2026-11-01-preview
Authorization: ******
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="manuals/raw-handbook.txt"

Employees request production access through the engineering access portal.

参考:知识来源

上传具有可选元数据的文件

使用多部分请求上传一个二进制文件。 添加一个包含 JSON 对象的 metadata 部件和一个非空的 content 部件。 metadata即使没有自定义元数据,也需要该部件;在这种情况下,请使用{}。 如果添加自定义元数据,请使用字符串值的扁平包。

如果同时指定了两个名称, metadata.fileName 则优先于部件 content 上的文件名。 如果未指定这两个名称,服务将分配自动生成的文件名。

using Azure.Identity;
using Azure.Search.Documents.Indexes;
using Azure.Search.Documents.Indexes.Models;

var indexClient = new SearchIndexClient(new Uri(searchEndpoint), new DefaultAzureCredential());
var metadata = new FileUploadMetadata
{
  FileName = "installation-guide.pdf",
  Metadata =
  {
    ["department"] = "support",
    ["product"] = "contoso-100"
  }
};

#pragma warning disable SCME0004
var request = new UploadKnowledgeSourceFileMultipartRequest(
  metadata,
  "installation-guide.pdf");
KnowledgeSourceFile uploadedFile = (await indexClient
  .UploadKnowledgeSourceFileMultipartAsync("my-file-ks", request)).Value;
#pragma warning restore SCME0004

参考:SearchIndexClient.UploadKnowledgeSourceFileMultipartAsync

from pathlib import Path

from azure.identity import DefaultAzureCredential
from azure.search.documents.indexes import SearchIndexClient
from azure.search.documents.indexes.models import (
  FileUploadMetadata,
  UploadKnowledgeSourceFileMultipartRequest,
)

index_client = SearchIndexClient(endpoint="<search-endpoint>", credential=DefaultAzureCredential())
file_path = Path("installation-guide.pdf")
request = UploadKnowledgeSourceFileMultipartRequest(
  metadata=FileUploadMetadata(
    file_name=file_path.name,
    metadata={"department": "support", "product": "contoso-100"},
  ),
  content=(file_path.name, file_path.read_bytes(), "application/pdf"),
)

uploaded_file = index_client.upload_knowledge_source_file_multipart(
  name="my-file-ks",
  body=request,
)

Reference:SearchIndexClient.upload_knowledge_source_file_multipart

POST {{search-endpoint}}/knowledgesources('my-file-ks')/files?api-version=2026-11-01-preview
Authorization: Bearer {{search-access-token}}
Content-Type: multipart/form-data; boundary=file-boundary

--file-boundary
Content-Disposition: form-data; name="metadata"
Content-Type: application/json

{
  "fileName": "installation-guide.pdf",
  "metadata": {
    "department": "support",
    "product": "contoso-100"
  }
}
--file-boundary
Content-Disposition: form-data; name="content"; filename="installation-guide.pdf"
Content-Type: application/octet-stream

< ./installation-guide.pdf
--file-boundary--

参考:知识源 - 上传文件

上传文件不会替换现有文件,即使重复使用相同 fileName文件也是如此。 每次成功上传都会创建一个带有其自身 fileId 的新文件,因此已上传文件的列表中可能包含多个共享同一 fileName 的条目。

列出上传的文件

列出知识源上的文件以检查上传的文件集。

using System.Collections.Generic;
using Azure.Identity;
using Azure.Search.Documents.Indexes;
using Azure.Search.Documents.Indexes.Models;

var indexClient = new SearchIndexClient(new Uri(searchEndpoint), new DefaultAzureCredential());
var files = new List<KnowledgeSourceFile>();
await foreach (KnowledgeSourceFile file in indexClient.GetAllKnowledgeSourceFilesAsync("my-file-ks"))
{
  files.Add(file);
}

参考:SearchIndexClient

from azure.identity import DefaultAzureCredential
from azure.search.documents.indexes import SearchIndexClient

index_client = SearchIndexClient(endpoint="<search-endpoint>", credential=DefaultAzureCredential())
files = list(index_client.list_knowledge_source_files("my-file-ks"))

Reference:SearchIndexClient.list_knowledge_source_files

GET {{searchEndpoint}}/knowledgesources('my-file-ks')/files?api-version=2026-10-01
Authorization: ******

参考:知识来源

响应包括每个上传文件的元数据。 成功列出的文件的 errorMessage 值为 null。

{
  "value": [
    {
      "fileId": "file-abc123",
      "fileName": "installation-guide.pdf",
      "fileSizeBytes": 1048576,
      "createdAt": "2026-05-07T18:10:00Z",
      "lastUpdatedAt": "2026-05-07T18:14:00.803Z",
      "errorMessage": null
    }
  ]
}

如果新的上传失败,请求将返回错误,并且不会创建文件元数据记录。

列出和筛选文件

列出文件时,使用这些查询参数来筛选结果并对其进行分页:

  • prefix:对完整相对文件名执行区分大小写的开头匹配项。 对于包含斜杠或点的路径,请使用 prefix,而不是 search。
  • search:对完整相对文件名执行不区分大小写的开头匹配项。 它仅接受资源名称前缀语法:小写字母、数字、连字符和下划线,以字母或数字开头。 将 prefix 设置为其唯一支持的值 searchType,以选择此匹配模式。 此值适用于 search,不适用于单独的 prefix 参数。
  • pageSize:至少为 1,最多 3,000,默认值为 3,000。
using System.Collections.Generic;
using Azure.Identity;
using Azure.Search.Documents.Indexes;
using Azure.Search.Documents.Indexes.Models;

var indexClient = new SearchIndexClient(new Uri(searchEndpoint), new DefaultAzureCredential());
var filteredFiles = new List<KnowledgeSourceFile>();
await foreach (KnowledgeSourceFile file in indexClient.GetAllKnowledgeSourceFilesAsync(
  "my-file-ks",
  prefix: "manuals/",
  pageSize: 100))
{
  filteredFiles.Add(file);
}

参考:SearchIndexClient

from azure.identity import DefaultAzureCredential
from azure.search.documents.indexes import SearchIndexClient

index_client = SearchIndexClient(endpoint="<search-endpoint>", credential=DefaultAzureCredential())

files = list(index_client.list_knowledge_source_files(
  "my-file-ks",
  prefix="manuals/",
  page_size=100,
))

Reference:SearchIndexClient.list_knowledge_source_files

GET {{searchEndpoint}}/knowledgesources('my-file-ks')/files?api-version=2026-10-01&prefix=manuals%2F&search=manuals&searchType=prefix&pageSize=1
Authorization: ******

参考:知识来源

响应包括服务选择的分析和提取模式,以及用于文件管理的用户元数据。 用户元数据不可搜索或可筛选。

{
  "value": [
    {
      "fileId": "file-abc123",
      "fileName": "manuals/installation-guide.md",
      "prefix": "manuals/",
      "metadata": {
        "department": "support",
        "product": "contoso-100"
      },
      "parsingMode": "markdown",
      "extractionMode": "minimal",
      "fileSizeBytes": 1048576,
      "createdAt": "2026-08-03T18:10:00Z",
      "lastUpdatedAt": "2026-08-03T18:14:00Z",
      "errorMessage": null
    }
  ],
  "@odata.nextLink": "<service-generated continuation URL>"
}

若要检索所有结果,请持续跟进 @odata.nextLink,直到其不再出现。 按原样发送返回的完整 URL,不要更改查询参数。

更新上传的文件

通过发送包含返回的 fileId 的 PUT 请求来更新文件。 再次加入 fileName 以保留文件名。

如果省略自定义 metadata 包或将其设置为 null,则会保留之前的自定义元数据值。 如果提供自定义 metadata bag,它会替换之前的 bag,而不是与其合并。 要清除自定义元数据包,请提供 "metadata": {}。

using Azure.Identity;
using Azure.Search.Documents.Indexes;
using Azure.Search.Documents.Indexes.Models;

var indexClient = new SearchIndexClient(new Uri(searchEndpoint), new DefaultAzureCredential());
var metadata = new FileUploadMetadata
{
  FileName = "installation-guide.pdf",
  Metadata =
  {
    ["department"] = "support",
    ["product"] = "contoso-200"
  }
};

#pragma warning disable SCME0004
var request = new UpdateKnowledgeSourceFileRequest(
  metadata,
  "installation-guide.pdf");
KnowledgeSourceFile updatedFile = (await indexClient.UpdateKnowledgeSourceFileAsync(
  fileId,
  "my-file-ks",
  request)).Value;
#pragma warning restore SCME0004

参考:SearchIndexClient.UpdateKnowledgeSourceFileAsync

from pathlib import Path

from azure.identity import DefaultAzureCredential
from azure.search.documents.indexes import SearchIndexClient
from azure.search.documents.indexes.models import (
  FileUploadMetadata,
  UpdateKnowledgeSourceFileRequest,
)

index_client = SearchIndexClient(endpoint="<search-endpoint>", credential=DefaultAzureCredential())
file_path = Path("installation-guide.pdf")
request = UpdateKnowledgeSourceFileRequest(
  metadata=FileUploadMetadata(
    file_name=file_path.name,
    metadata={"department": "support", "product": "contoso-200"},
  ),
  content=(file_path.name, file_path.read_bytes(), "application/pdf"),
)

updated_file = index_client.update_knowledge_source_file(
  name="my-file-ks",
  file_id=file_id,
  body=request,
)

参考:SearchIndexClient.update_knowledge_source_file

PUT {{search-endpoint}}/knowledgesources('my-file-ks')/files('{{file-id}}')?api-version=2026-11-01-preview
Authorization: Bearer {{search-access-token}}
Content-Type: multipart/form-data; boundary=file-boundary

--file-boundary
Content-Disposition: form-data; name="metadata"
Content-Type: application/json

{
  "fileName": "installation-guide.pdf",
  "metadata": {
    "department": "support",
    "product": "contoso-200"
  }
}
--file-boundary
Content-Disposition: form-data; name="content"; filename="installation-guide.pdf"
Content-Type: application/octet-stream

< ./installation-guide.pdf
--file-boundary--

参考:知识来源 - 更新文件

如果更新失败,之前的元数据记录仍会保留,但旧的已编入索引的内容可能已被删除。

删除上传的文件

当不再需要它们可供检索时,请从知识源中删除文件。

using Azure.Identity;
using Azure.Search.Documents.Indexes;

var indexClient = new SearchIndexClient(new Uri(searchEndpoint), new DefaultAzureCredential());

await indexClient.DeleteKnowledgeSourceFileAsync("my-file-ks", "file-abc123");

参考:SearchIndexClient.DeleteKnowledgeSourceFileAsync

from azure.identity import DefaultAzureCredential
from azure.search.documents.indexes import SearchIndexClient

index_client = SearchIndexClient(endpoint="<search-endpoint>", credential=DefaultAzureCredential())

index_client.delete_knowledge_source_file("my-file-ks", "file-abc123")

Reference:SearchIndexClient.delete_knowledge_source_file

DELETE {{searchEndpoint}}/knowledgesources('my-file-ks')/files('{{fileId}}')?api-version=2026-10-01
Authorization: ******

参考:知识来源

如果对知识源感到满意, 请将其添加到知识库。

异步引入文件(预览版)

使用单独的 :ingest 操作在后台处理文件。 异步采集和操作监视需要 2026-11-01-preview。

  • 异步引入不支持受客户管理的密钥保护的知识源。
  • 异步引入在限制期间可能返回 503。
using Azure;
using Azure.Identity;
using Azure.Search.Documents.Indexes;
using Azure.Search.Documents.Indexes.Models;

var asyncIndexClient = new SearchIndexClient(
  new Uri(searchEndpoint),
  new DefaultAzureCredential());

var initialMetadata = new FileUploadMetadata
{
  FileName = "manuals/async-handbook.txt",
  Metadata = { ["stage"] = "initial" }
};

var ingestRequest = new UploadKnowledgeSourceFileMultipartRequest(
  initialMetadata,
  BinaryData.FromString(
    "Employees request production access through the engineering access portal."));
Operation<KnowledgeSourceFile> ingestOperation = await asyncIndexClient
  .IngestKnowledgeSourceFileMultipartAsync(
    WaitUntil.Completed,
    "my-file-ks",
    ingestRequest);
KnowledgeSourceFile ingestedFile = ingestOperation.Value;

var updatedMetadata = new FileUploadMetadata
{
  FileName = "manuals/async-handbook.txt",
  Metadata = { ["stage"] = "updated" }
};
var replacementRequest = new UpdateKnowledgeSourceFileRequest(
  updatedMetadata,
  BinaryData.FromString(
    "Employees request production access through the engineering access portal. " +
    "Manager approval is required before access is granted."));
Operation<KnowledgeSourceFile> replacementOperation = await asyncIndexClient
  .IngestKnowledgeSourceFileReplacementAsync(
    WaitUntil.Completed,
    "my-file-ks",
    ingestedFile.FileId,
    replacementRequest);
KnowledgeSourceFile replacedFile = replacementOperation.Value;

参考:SearchIndexClient

from azure.identity import DefaultAzureCredential
from azure.search.documents.indexes import SearchIndexClient
from azure.search.documents.indexes.models import (
  FileUploadMetadata,
  UpdateKnowledgeSourceFileRequest,
  UploadKnowledgeSourceFileMultipartRequest,
)

async_index_client = SearchIndexClient(
  endpoint="<search-endpoint>",
  credential=DefaultAzureCredential(),
)

ingest_request = UploadKnowledgeSourceFileMultipartRequest(
  metadata=FileUploadMetadata(
    file_name="manuals/async-handbook.txt",
    metadata={"stage": "initial"},
  ),
  content=(
    "handbook.txt",
    b"Employees request production access through the engineering access portal.",
    "application/octet-stream",
  ),
)
ingest_poller = async_index_client.begin_ingest_knowledge_source_file_multipart(
  name="my-file-ks",
  body=ingest_request,
)
ingested_file = ingest_poller.result()

replacement_request = UpdateKnowledgeSourceFileRequest(
  metadata=FileUploadMetadata(
    file_name="manuals/async-handbook.txt",
    metadata={"stage": "updated"},
  ),
  content=(
    "handbook.txt",
    (
      b"Employees request production access through the engineering access portal. "
      b"Manager approval is required before access is granted."
    ),
    "application/octet-stream",
  ),
)
replacement_poller = (
  async_index_client.begin_ingest_knowledge_source_file_replacement(
    name="my-file-ks",
    file_id=ingested_file.file_id,
    body=replacement_request,
  )
)
replaced_file = replacement_poller.result()

参考:SearchIndexClient

开始数据引入并监控完成情况

上传包含字面 multipart 元数据和内容的一个文件。

POST {{searchEndpoint}}/knowledgesources('my-file-ks')/files:ingest?api-version=2026-11-01-preview
Authorization: ******
Content-Type: multipart/form-data; boundary=file-boundary

--file-boundary
Content-Disposition: form-data; name="metadata"
Content-Type: application/json

{
  "fileName": "manuals/async-handbook.txt",
  "metadata": {
    "stage": "initial"
  }
}
--file-boundary
Content-Disposition: form-data; name="content"; filename="handbook.txt"
Content-Type: application/octet-stream

Employees request production access through the engineering access portal.
--file-boundary--

参考:知识来源

敬请期待 202。 Retry-After延迟后,轮询 URLOperation-Location,直到操作完成。

GET {{operationLocation}}
Authorization: ******
Accept: application/json

参考:知识来源

监视器在数据摄取运行期间以及完成后返回 HTTP 200。 查看 status 中的结果。

status Action
NotStarted、Running 等待 Retry-After,然后再次轮询相同的 URL。
Succeeded 将result.fileId另存为{{asyncFileId}}并保留result.createdAt进行替换验证。
Failed 停止和检查 error.code (OperationFailed) 和 error.message。
Canceled 停。 操作未成功。

异步替换文件

在替换该文件之前,请等待上传成功。 使用其返回的文件 ID 单独发送一个 POST 操作。

POST {{searchEndpoint}}/knowledgesources('my-file-ks')/files('{{asyncFileId}}'):ingest?api-version=2026-11-01-preview
Authorization: ******
Content-Type: multipart/form-data; boundary=file-boundary

--file-boundary
Content-Disposition: form-data; name="metadata"
Content-Type: application/json

{
  "fileName": "manuals/async-handbook.txt",
  "metadata": {
    "stage": "updated"
  }
}
--file-boundary
Content-Disposition: form-data; name="content"; filename="handbook.txt"
Content-Type: application/octet-stream

Employees request production access through the engineering access portal. Manager approval is required before access is granted.
--file-boundary--

参考:知识来源

敬请期待 202。 将此响应的 Operation-Location 另存为 {{replacementOperationLocation}} 并遵循它的 Retry-After。 对替换监视应用相同的 40 次 GET 或 20 分钟客户端策略以及未解决结果处理。

GET {{replacementOperationLocation}}
Authorization: ******
Accept: application/json

参考:知识来源

在 Succeeded 之后,请验证 result.fileId 和 result.createdAt 是否匹配原始文件。

列出保留的操作

列出属于此知识源的监视器,与列出文件分开。

GET {{searchEndpoint}}/knowledgesources('my-file-ks')/files/operations?api-version=2026-11-01-preview
Authorization: ******

参考:知识来源

删除知识源

以下 C# 和Python示例使用 11 月预览版 SDK。 对于 REST 请求,将 {{api-version}} 设置为 2026-11-01-preview。

在删除知识源之前,必须删除引用它的任何知识库或更新知识库定义来去除该引用。 对于生成索引和索引器管道的知识源,所有 生成的对象 都会被删除。 但是,如果使用现有索引创建知识源,则不会删除索引。

如果尝试删除正在使用的知识源,该操作将失败并返回受影响的知识库列表。

要删除知识源,请执行以下步骤:

  1. 获取 Foundry IQ 服务上所有知识库的列表。

    using Azure.Search.Documents.Indexes;
    
    var indexClient = new SearchIndexClient(new Uri(searchEndpoint), credential);
    var knowledgeBases = indexClient.GetKnowledgeBasesAsync();
    
    Console.WriteLine("Knowledge Bases:");
    
    await foreach (var kb in knowledgeBases)
    {
        Console.WriteLine($"  - {kb.Name}");
    }
    

    参考:SearchIndexClient

    示例响应可能如下所示:

     {
         "@odata.context": "https://my-search-service.search.windows.net/$metadata#knowledgebases(name)",
         "value": [
         {
             "name": "my-kb"
         },
         {
             "name": "my-kb-2"
         }
         ]
     }
    
  2. 获取单个知识库的定义,以检查知识源引用。

    using Azure.Search.Documents.Indexes;
    using System.Text.Json;
    
    var indexClient = new SearchIndexClient(new Uri(searchEndpoint), credential);
    
    // Specify the knowledge base name to retrieve
    string kbNameToGet = "earth-knowledge-base";
    
    // Get a specific knowledge base definition
    var knowledgeBaseResponse = await indexClient.GetKnowledgeBaseAsync(kbNameToGet);
    var kb = knowledgeBaseResponse.Value;
    
    // Serialize to JSON for display
    string json = JsonSerializer.Serialize(kb, new JsonSerializerOptions { WriteIndented = true });
    Console.WriteLine(json);
    

    参考:SearchIndexClient

    示例响应可能如下所示:

     {
       "Name": "earth-knowledge-base",
       "KnowledgeSources": [
         {
           "Name": "earth-knowledge-source"
         }
       ],
       "Models": [
         {}
       ],
       "RetrievalReasoningEffort": {},
       "OutputMode": {},
       "ETag": "\u00220x8DE278629D782B3\u0022",
       "EncryptionKey": null,
       "Description": null,
       "RetrievalInstructions": null,
       "AnswerInstructions": null
     }
    
  3. 删除知识库,或者如果有多个知识库,请更新知识库以删除源。 此示例显示删除。

    using Azure.Search.Documents.Indexes;
    var indexClient = new SearchIndexClient(new Uri(searchEndpoint), credential);
    
    await indexClient.DeleteKnowledgeBaseAsync(knowledgeBaseName);
    System.Console.WriteLine($"Knowledge base '{knowledgeBaseName}' deleted successfully.");
    

    参考:SearchIndexClient

  4. 删除知识源。

    await indexClient.DeleteKnowledgeSourceAsync(knowledgeSourceName);
    System.Console.WriteLine($"Knowledge source '{knowledgeSourceName}' deleted successfully.");
    

    参考:SearchIndexClient

  1. 获取 Foundry IQ 服务上所有知识库的列表。

    # Get knowledge bases
    from azure.core.credentials import AzureKeyCredential
    from azure.search.documents.indexes import SearchIndexClient
    
    index_client = SearchIndexClient(endpoint = "search_url", credential = AzureKeyCredential("api_key"))
    
    print("Knowledge Bases:")
    for kb in index_client.list_knowledge_bases():
        print(f"  - {kb.name}")
    

    参考:SearchIndexClient

    示例响应可能如下所示:

     {
         "@odata.context": "https://my-search-service.search.windows.net/$metadata#knowledgebases(name)",
         "value": [
         {
             "name": "my-kb"
         },
         {
             "name": "my-kb-2"
         }
         ]
     }
    
  2. 获取单个知识库的定义,以检查知识源引用。

    # Get a knowledge base definition
    from azure.core.credentials import AzureKeyCredential
    from azure.search.documents.indexes import SearchIndexClient
    
    index_client = SearchIndexClient(endpoint = "search_url", credential = AzureKeyCredential("api_key"))
    kb = index_client.get_knowledge_base("knowledge_base_name")
    print(kb)
    

    参考:SearchIndexClient

    示例响应可能如下所示:

     {
       "name": "my-kb",
       "description": null,
       "retrievalInstructions": null,
       "answerInstructions": null,
       "outputMode": null,
       "knowledgeSources": [
         {
           "name": "my-blob-ks"
         }
       ],
       "models": [],
       "encryptionKey": null,
       "retrievalReasoningEffort": {
         "kind": "low"
       }
     }
    
  3. 删除知识库,或者如果有多个知识库,请更新知识库以删除源。 此示例显示删除。

    # Delete a knowledge base
    from azure.core.credentials import AzureKeyCredential 
    from azure.search.documents.indexes import SearchIndexClient
    
    index_client = SearchIndexClient(endpoint = "search_url", credential = AzureKeyCredential("api_key"))
    index_client.delete_knowledge_base("knowledge_base_name")
    print(f"Knowledge base deleted successfully.")
    

    参考:SearchIndexClient

  4. 删除知识源。

    # Delete a knowledge source
    from azure.core.credentials import AzureKeyCredential 
    from azure.search.documents.indexes import SearchIndexClient
    
    index_client = SearchIndexClient(endpoint = "search_url", credential = AzureKeyCredential("api_key"))
    index_client.delete_knowledge_source("knowledge_source_name")
    print(f"Knowledge source deleted successfully.")
    

    参考:SearchIndexClient

  1. 获取 Foundry IQ 服务上所有知识库的列表。

    ### Get knowledge bases
    GET {{search-url}}/knowledgebases?api-version={{api-version}}&$select=name
    Authorization: Bearer {{token}}
    

    参考:知识库 - 列表

    示例响应可能如下所示:

     {
         "@odata.context": "https://my-search-service.search.windows.net/$metadata#knowledgebases(name)",
         "value": [
         {
             "name": "my-kb"
         },
         {
             "name": "my-kb-2"
         }
         ]
     }
    
  2. 获取单个知识库的定义,以检查知识源引用。

    ### Get a knowledge base definition
    GET {{search-url}}/knowledgebases('{{knowledge-base-name}}')?api-version={{api-version}}
    Authorization: Bearer {{token}}
    

    参考:知识库 - 获取

    示例响应可能如下所示:

     {
       "name": "my-kb",
       "description": null,
       "retrievalInstructions": null,
       "answerInstructions": null,
       "outputMode": null,
       "knowledgeSources": [
         {
           "name": "my-blob-ks"
         }
       ],
       "models": [],
       "encryptionKey": null,
       "retrievalReasoningEffort": {
         "kind": "low"
       }
     }
    
  3. 删除知识库,或者如果有多个知识库,请更新知识库以删除源。 此示例显示删除。

    ### Delete a knowledge base
    DELETE {{search-url}}/knowledgebases('{{knowledge-base-name}}')?api-version={{api-version}}
    Authorization: Bearer {{token}}
    

    参考:知识库 - 删除

  4. 删除知识源。

    ### Delete a knowledge source
    DELETE {{search-url}}/knowledgesources('{{knowledge-source-name}}')?api-version={{api-version}}
    Authorization: Bearer {{token}}
    

    参考:知识源 - 删除

DELETE {{searchEndpoint}}/knowledgesources('my-file-ks')?api-version=2026-10-01
Authorization: ******

参考:知识来源

敬请期待 204。 在清理前等待每个异步操作完成。

文件操作疑难解答

以下状态代码特定于文件知识源操作。

状态代码 原因和操作
400 检查空内容、缺少或重复的多部分、无效的元数据 JSON、不安全的相对路径和无效的列表查询。
404 请求的范围中不存在文件、源或操作监视器。 使用实际响应中的源和 ID。 重复的文件删除也返回 404。
409 有效文件数已耗尽,或某项突变与正在进行的异步引入冲突。 在修改或删除资源之前,请等待终端操作完成。
413 文件字节数超出该终结点和层级的有效大小限制。 减小文件大小。
415 同步上传检测到不支持的 MIME 类型或使用了不受支持的外部内容类型。 对于图像,请选择标准提取和显式支持的格式。 更改提供的 MIME 类型不会替代检测。
503 异步引入不可用或没有符合条件的辅助角色。 索引依赖项还可以返回此状态。
504 同步处理已超过其配置的截止时间(默认为 180 秒)。 减小文件大小或复杂性。 这不是异步轮询截止时间。