Note
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 portal | Microsoft Foundry 入口網站 | .NET SDK | Python SDK | Java SDK | JavaScript SDK | REST API |
|---|---|---|---|---|---|---|
| ❌ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
先決條件
任何提供代理式擷取的區域中的 Foundry IQ 服務。 檔案知識來源支援專用與無伺服器定價模式。 關於型號與層級的詳細資訊,請參見 「選擇定價模式與服務層級」。
檢視 Foundry IQ 的費用。 模型呼叫、向量化及其他 AI 處理可能會產生獨立費用。
在無伺服器模式下,成功的檔案擷取操作會消耗可計費的運算。 上傳失敗不會產生無伺服器運算費用。
如果你需要付費的代理檢索,超出每月免費津貼,請 啟用標準代理檢索方案。 這個
knowledgeRetrieval=standard設定與無伺服器的運算和儲存費用是分開的,也不會選擇定價模式。支援 格式的檔案。
允許建立知識來源。 設定無金鑰驗證,並將搜尋服務參與者角色指派給您的使用者帳戶(建議),或使用管理員 API 金鑰。
對於對 Azure OpenAI 嵌入進行受控識別呼叫,請將認知服務 OpenAI 使用者指派給所選識別,該識別位於符合
resourceUri的 Azure OpenAI 或其父 Foundry 資源上。 內容理解擷取需要獨立權限。 請參閱「指派角色」。如果 Foundry 資源已停用公開網路存取,請使用符合資格的專用服務建立
foundry_account與 Foundry 資源的共用私有連結。 保持資源的「允許 Azure 服務於受信任服務清單」設定為啟用。 無伺服器不支援此共享私有連結設定。 有關支援的公共端點存取控制,請參閱 網路安全邊界;邊界不會建立私人連線。檢查 知識來源設定與分層矩陣。 檔案上傳不會建立索引器,因此 generated-indexer 網路覆寫不適用。
如果知識來源指定
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
搜尋服務 REST API 的 2026-10-01 版本。
對於無金鑰認證,請在
Authorization每個 HTTP 請求的標頭中加入 Microsoft Entra ID 令牌。
檔案支援與限制
在建立檔案知識來源前,請先檢視影響檔案上傳、擷取與管理的需求與限制。
支援的內容類型
Foundry IQ 會從檔案位元組中偵測 MIME 類型。
minimal 擷取可接受 支援的文件格式,包括偵測到的 text/* 類型。
standard擷取則根據 Azure 內容理解技能所支援的檔案格式,範圍較窄。 影像需要 standard 擷取,且偵測到的格式受支援。
支援的擷取模式
minimal 使用內建擷取功能,且是預設。
standard 將每個檔案都透過 Content Understanding 傳送,並需要 aiServices 設定。
- 偵測為
image/*的內容不受2026-05-01-preview支援。 在2026-10-01中,使用standard擷取。minimalextraction 在兩個版本中都會回傳 HTTP 狀態415。
限制與檔案操作
限制與支援的檔案操作會依 API 版本與擷取方式而異。
| Capability |
2026-11-01-preview 非同步 |
2026-10-01 同步的 |
2026-08-01-preview 同步的 |
|---|---|---|---|
| 每個知識來源的最大檔案數 | 10,000 | 200 | 200 |
| 檔案大小上限 | 512 百萬兆基 | 免費與基礎模式可達 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}");
}
# 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})")
### 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));
# 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))
### 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);
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)
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 會管理匯入管線,使用 Foundry 中 aiServices指定的資源。
C# 和 Python 的配置範例使用 11 月的預覽版 SDK。 REST 範例使用 2026-11-01-preview。 使用前,請先檢閱內容理解需求。
標準設定可為已設定的內容理解帳戶新增全帳戶模型對應。 在建立或更新標準來源之前,請先檢查共用設定。 最小化設定不會設定該帳號或使用模型憑證。
標準擷取會產生內容理解費用,啟用影像文字化時,則會產生模型使用費用。 如需更多資訊,請參閱 帳單與影像描述控制項。
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);
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)
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;
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,
)
將原始檔案位元組傳送至預覽同步端點。 即使是文字內容也要使用 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,
)
參考資料: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);
}
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"))
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: 對完整相對檔名執行大小寫不區分的開頭匹配。 它只接受資源名稱前綴語法:小寫字母、數字、連字號和底線,且以字母或數字開頭。 將searchType設為其唯一支援的值prefix,以選擇此匹配模式。 此值適用於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);
}
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,
))
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,且不要更改查詢參數。
更新已上傳的檔案
透過傳送 PUT 要求並附上傳回的 fileId,即可更新檔案。 再次加入 fileName 以保留檔名。
如果您省略自訂 metadata 袋子或將其設為 null,先前的自訂元資料值會被保留。 如果你提供自訂 metadata 集合,它會取代先前的集合,而不是與其合併。 要清除自訂元資料包,請提供 "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
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,
)
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");
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")
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;
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()
開始導入並監控完成
上傳一個含有常值 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 延遲之後,繼續輪詢 Operation-Location 中的 URL,直到作業完成。
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。
在刪除知識來源之前,必須刪除所有引用該來源的知識庫,或更新知識庫定義以移除該參考。 對於產生索引與索引管線的知識來源,所有 產生的物件 也會被刪除。 不過,如果你用現有的索引建立知識來源,你的索引不會被刪除。
如果你嘗試刪除正在使用的知識來源,該動作會失敗,並回傳一份受影響的知識庫清單。
刪除知識來源:
取得您 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}"); }範例回應可能如下所示:
{ "@odata.context": "https://my-search-service.search.windows.net/$metadata#knowledgebases(name)", "value": [ { "name": "my-kb" }, { "name": "my-kb-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);範例回應可能如下所示:
{ "Name": "earth-knowledge-base", "KnowledgeSources": [ { "Name": "earth-knowledge-source" } ], "Models": [ {} ], "RetrievalReasoningEffort": {}, "OutputMode": {}, "ETag": "\u00220x8DE278629D782B3\u0022", "EncryptionKey": null, "Description": null, "RetrievalInstructions": null, "AnswerInstructions": null }要麼刪除知識庫,要麼如果你有多個知識來源,就更新知識庫來移除該來源。 這個例子顯示刪除。
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.");刪除知識來源。
await indexClient.DeleteKnowledgeSourceAsync(knowledgeSourceName); System.Console.WriteLine($"Knowledge source '{knowledgeSourceName}' deleted successfully.");
取得您 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}")範例回應可能如下所示:
{ "@odata.context": "https://my-search-service.search.windows.net/$metadata#knowledgebases(name)", "value": [ { "name": "my-kb" }, { "name": "my-kb-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)範例回應可能如下所示:
{ "name": "my-kb", "description": null, "retrievalInstructions": null, "answerInstructions": null, "outputMode": null, "knowledgeSources": [ { "name": "my-blob-ks" } ], "models": [], "encryptionKey": null, "retrievalReasoningEffort": { "kind": "low" } }要麼刪除知識庫,要麼如果你有多個知識來源,就更新知識庫來移除該來源。 這個例子顯示刪除。
# 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.")刪除知識來源。
# 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.")
取得您 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" } ] }取得一個獨立的知識庫定義,以檢查是否有知識來源的參考。
### 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" } }要麼刪除知識庫,要麼如果你有多個知識來源,就更新知識庫來移除該來源。 這個例子顯示刪除。
### Delete a knowledge base DELETE {{search-url}}/knowledgebases('{{knowledge-base-name}}')?api-version={{api-version}} Authorization: Bearer {{token}}參考資料:知識庫 - 刪除
刪除知識來源。
### 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 |
檔案、來源或操作監視器不存在於所要求的範圍中。 使用實際回應中的來源和識別碼。 重複刪除檔案也會回傳 404。 |
409 |
有效檔案數量已耗盡,或某項變更作業與進行中的非同步擷取發生衝突。 請等待最終作業完成後再修改或刪除其資源。 |
413 |
檔案位元組超過端點與層級的有效大小限制。 縮小檔案大小。 |
415 |
同步上傳偵測到 MIME 類型不受支援,或使用了不受支援的外層內容類型。 對於影像,請選擇標準擷取以及明確支援的格式。 更改所附的 MIME 類型不會覆蓋偵測。 |
503 |
非同步擷取無法使用或沒有符合資格的工作程序。 索引相依關係也可以回傳此狀態。 |
504 |
同步處理超過了設定的截止時間(預設為 180 秒)。 減少檔案大小或複雜度。 這不是非同步輪詢期限。 |