Muokkaa

Create a file knowledge source (preview)

Note

Azure AI Search is available through the Azure portal, REST APIs, and Azure SDKs. It also underpins Foundry IQ, the managed knowledge layer that transforms enterprise content into reusable, permission-aware knowledge bases for agents in the Microsoft Foundry portal.

Important

These features and functionality are part of the 2026-08-01-preview REST API. The 2026-08-01-preview is licensed to you as part of your Azure subscription and is subject to the terms applicable to "Previews" in the Microsoft Product Terms, the Microsoft Products and Services Data Protection Addendum ("DPA"), and the Supplemental Terms of Use for Microsoft Azure Previews.

The preview APIs support connections to other Microsoft services and third-party services. Use of these services is subject to their respective terms and might result in data processing or storage outside of the Azure compliance boundary, as well as data flowing into the Azure compliance boundary.

It's your responsibility to manage whether your data will flow outside of your organization's compliance and geographic boundaries and any related implications, and that appropriate permissions, boundaries, and approvals are provisioned.

You're responsible for carefully reviewing and testing applications you build in the context of your specific use cases and making all appropriate decisions and customizations. This includes implementing your own responsible AI mitigations, such as metaprompts, content filters, or other safety systems, and ensuring your applications meet appropriate quality, reliability, security, and trustworthiness standards. For more information, see the Azure AI Search Transparency Note.

A file knowledge source (preview) uploads small-to-medium file sets directly to Azure AI Search for agentic retrieval. Knowledge sources are created independently, referenced in a knowledge base, and used as grounding data when the knowledge base is queried at runtime.

File knowledge sources are useful when you want a managed upload experience instead of provisioning Azure Storage, configuring access, and creating an indexer pipeline over an external container. Azure AI Search processes uploaded files so their extracted content can be retrieved from a knowledge base.

Use a blob knowledge source instead when your files are already in Azure Blob Storage or Azure Data Lake Storage Gen2, when your file set exceeds or is likely to exceed the file knowledge source limits, or when you need scheduled ingestion. Also use a blob knowledge source when you want to manage source blobs with Azure Blob Storage lifecycle management policies or when you need document-level permissions (preview) based on permissions in Azure Storage.

Usage support

Azure portal Microsoft Foundry portal .NET SDK Python SDK Java SDK JavaScript SDK REST API
✔️ ✔️ ✔️ ✔️ ✔️ ✔️

Prerequisites

  • An Azure AI Search service in any region that provides agentic retrieval. File knowledge sources support both the Dedicated and Serverless pricing models. For model and tier details, see Choose a pricing model and service tier.

  • Review Azure AI Search costs. Model calls, vectorization, and other AI processing can incur separate charges.

  • On Serverless, successful file ingestion operations consume billable compute. Failed uploads don't incur Serverless compute charges.

  • If you need paid agentic retrieval beyond the monthly free allowance, enable the standard agentic retrieval plan. The knowledgeRetrieval=standard setting is separate from Serverless compute and storage charges and doesn't select a pricing model.

  • Files in a supported format.

  • Permission to create knowledge sources. Configure keyless authentication with the Search Service Contributor role assigned to your user account (recommended) or use an admin API key.

  • If the knowledge source specifies an Azure OpenAI model for embeddings, the search service must have a managed identity with Cognitive Services User permissions on the Microsoft Foundry resource.

    • If the Foundry resource has public network access disabled, create a foundry_account shared private link from the search service to the Foundry resource and keep the resource's Allow Azure services on the trusted services list setting enabled.
  • If the knowledge source specifies the standard content extraction mode, review the requirements for the Azure Content Understanding skill.

    • Usage is charged at Azure Content Understanding in Foundry Tools pricing to the Foundry resource configured through aiServices.

    • The 20-document daily free allowance available to some built-in skills doesn't apply.

    • For the example in this article, you need the Foundry resource endpoint and key, plus Azure OpenAI embedding and chat completion model information.

  • The latest Azure.Search.Documents preview package: dotnet add package Azure.Search.Documents --prerelease

  • For keyless authentication, the Azure.Identity package: dotnet add package Azure.Identity

File support and limits

Before you create a file knowledge source, review the requirements and limits that affect file upload, extraction, and management.

Supported content types

File knowledge sources accept files based on detected content type. A caller-provided content type doesn't override detection.

Supported content types include:

  • PDF
  • Word (.doc, .docx)
  • PowerPoint (.ppt, .pptx)
  • Excel (.xls, .xlsx)
  • JSON
  • Shell scripts
  • Content detected as text/*, such as .txt, .md, .html, and .csv

Supported extraction modes

  • For the listed content types, both 2026-05-01-preview and 2026-08-01-preview support minimal. standard is available only in 2026-08-01-preview.

  • Content detected as image/* isn't supported in 2026-05-01-preview. In 2026-08-01-preview, use standard extraction. minimal extraction returns HTTP status 415 in both versions.

Limits and file operations

Limits and supported file operations differ by API version.

Capability 2026-05-01-preview 2026-08-01-preview
Maximum files per knowledge source 100 200
Maximum file size 50 MB on all supported pricing tiers 50 MB on Free and Basic; 100 MB on other supported Dedicated tiers and Serverless
Processing duration Upload can run for up to 180 seconds Upload and update can run for up to 180 seconds
Upload content and metadata Raw file content Raw file content or multipart content with metadata
List uploaded files List files Filter by path or file name, and return richer file details
Replace existing file content Delete and re-upload Use update operation
Browser access to file operations CORS isn't available Configure CORS

Note

  • The generated search index stores the uploaded content. For total storage limits by pricing tier, see Service limits.
  • If you configure the file knowledge source to chunk or vectorize uploaded content, model and downstream processing limits also apply.

Check for existing knowledge sources

A knowledge source is a top-level, reusable object. Knowing about existing knowledge sources is helpful for either reuse or naming new objects.

Run the following code to list knowledge sources by name and type.

// 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}");
}

Reference: 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})")

Reference: SearchIndexClient

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

Reference: Knowledge Sources - List

You can also return a single knowledge source by name to review its JSON definition.

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));

Reference: 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))

Reference: SearchIndexClient

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

Reference: Knowledge Sources - Get

The following JSON is an example response for a file knowledge source.

{
  "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"
        }
      }
    }
  }
}

Create a knowledge source

Create a file knowledge source that specifies the embedding model used to vectorize uploaded content.

Each file knowledge source creates an index, but not an indexer or schedule. You must include the fileParameters.ingestionParameters object. The service rejects requests that specify networkAccessMode.

using Azure.Identity;
using Azure.Search.Documents.Indexes;
using Azure.Search.Documents.Indexes.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);
Console.WriteLine($"Knowledge source '{knowledgeSource.Name}' created or updated successfully.");

Reference: 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)
print(f"Knowledge source '{knowledge_source.name}' created or updated successfully.")

Reference: SearchIndexClient

PUT {{search-endpoint}}/knowledgesources/my-file-ks?api-version=2026-08-01-preview
Authorization: Bearer {{search-access-token}}
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"
    }
  }
}

Reference: Knowledge Sources - Create or Update

Configure standard extraction

Starting with the 2026-08-01-preview API version, standard extraction uses Content Understanding to extract, semantically chunk, and enrich uploaded files. Azure AI Search manages this processing as part of the knowledge source, and Content Understanding charges apply separately.

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);
Console.WriteLine($"Configured standard extraction for '{knowledgeSource.Name}'.");

Reference: 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)
print(f"Configured standard extraction for '{knowledge_source.name}'.")

Reference: SearchIndexClient

PUT {{search-endpoint}}/knowledgesources/my-file-ks?api-version=2026-08-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}}"
      }
    }
  }
}

Reference: Knowledge Sources - Create or Update

CORS for file operations

To allow browser-based file operations, set corsOptions on the file knowledge source with the trusted origins and maximum preflight cache duration for your application.

Important

In the 2026-08-01-preview API version, corsOptions applies to file upload, list, update, and delete endpoints independently of the extraction mode. If you omit corsOptions, the file knowledge source has no browser cross-origin policy. CORS doesn't authorize requests. Enabling origins can expose service operations and data in a browser context and introduce security risks. Specify only trusted origins, and don't use a wildcard origin in production. For browser requests, use Microsoft Entra token authentication with the minimum required role. Never expose access tokens or service keys in browser code.

Upload files

After you create the knowledge source, upload files directly to it. Each upload is a synchronous call: Azure AI Search extracts content, chunks it, creates embeddings when needed, indexes the chunks, and persists file metadata before the call returns. You don't have to configure or run a separate ingestion pipeline.

For help with errors related to uploading and managing files, see Troubleshoot file operations.

Upload a raw file

For a raw upload, the listed fileName comes from the Content-Disposition: attachment; filename="..." header. REST calls and the .NET SDK set this header directly, while the Python SDK accepts a filename parameter and builds the header automatically. If you don't provide a file name, the service assigns an autogenerated fileName.

File names can include a relative path, such as manuals/installation-guide.pdf. The service normalizes backslashes to forward slashes. It rejects absolute paths, empty path segments, . or .. segments, colon-containing segments, and invalid file-name characters with HTTP status 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;

Console.WriteLine($"Uploaded file ID: {uploadedFile.FileId}");

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,
)
print(f"Uploaded file ID: {uploaded_file.file_id}")

Reference: SearchIndexClient.upload_knowledge_source_file

POST {{search-endpoint}}/knowledgesources/my-file-ks/files?api-version=2026-08-01-preview
Authorization: Bearer {{search-access-token}}
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="installation-guide.pdf"

<binary file content>

Reference: Knowledge Sources - Upload File

Upload a file with optional metadata

Starting with the 2026-08-01-preview API version, use a multipart request to upload one binary file with optional custom metadata. The request includes exactly one content part and an optional JSON metadata part.

If both names are specified, metadata.fileName takes precedence over the filename on the content part. If neither is specified, the service assigns an autogenerated file name.

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

Console.WriteLine($"Uploaded file ID: {uploadedFile.FileId}");

Reference: 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,
)
print(f"Uploaded file ID: {uploaded_file.file_id}")

Reference: SearchIndexClient.upload_knowledge_source_file_multipart

POST {{search-endpoint}}/knowledgesources('my-file-ks')/files?api-version=2026-08-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--

Reference: Knowledge Sources - Upload File

Note

Uploading a file doesn't replace an existing file, even if you reuse the same fileName. Each successful upload creates a new file with its own fileId, so the list of uploaded files can contain multiple entries that share a fileName.

With 2026-05-01-preview, replace content by deleting the prior file and uploading the replacement. With 2026-08-01-preview, use the update operation.

List uploaded files

List files on the knowledge source to inspect the uploaded file set.

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

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

await foreach (KnowledgeSourceFile file in indexClient.GetKnowledgeSourceFilesAsync("my-file-ks"))
{
    Console.WriteLine($"{file.FileName} ({file.FileSizeBytes} bytes) error={file.ErrorMessage}");
}

Reference: SearchIndexClient.GetKnowledgeSourceFilesAsync

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

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

for file in index_client.list_knowledge_source_files("my-file-ks"):
    print(f"{file.file_name} ({file.file_size_bytes} bytes) error={file.error_message}")

Reference: SearchIndexClient.list_knowledge_source_files

GET {{search-endpoint}}/knowledgesources/my-file-ks/files?api-version=2026-08-01-preview
Authorization: Bearer {{search-access-token}}

Reference: Knowledge Sources - List Files

The response includes metadata for each uploaded file. Successfully listed files have an errorMessage value of 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
    }
  ]
}

If a new upload fails, the request returns an error and doesn't create a file metadata record. The failed upload doesn't appear in later list results and isn't billed.

If a model access failure occurs and the Foundry resource that hosts the embedding model uses private networking, confirm that the foundry_account shared private link is approved and the trusted-services bypass is enabled. A disabled bypass returns 403 Public access is disabled. For setup details, see Prerequisites.

List and filter files

Starting with the 2026-08-01-preview API version, use prefix to filter files by relative path or search to filter by file-name prefix. Set pageSize to control the number of results.

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

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

await foreach (KnowledgeSourceFile file in indexClient.GetKnowledgeSourceFilesAsync(
  "my-file-ks",
  prefix: "manuals/",
  pageSize: 100))
{
  Console.WriteLine($"{file.FileName} ({file.FileId})");
}

Reference: SearchIndexClient.GetKnowledgeSourceFilesAsync

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

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

files = index_client.list_knowledge_source_files(
  "my-file-ks",
  prefix="manuals/",
  page_size=100,
)
for file in files:
  print(f"{file.file_name} ({file.file_id})")

Reference: SearchIndexClient.list_knowledge_source_files

GET {{search-endpoint}}/knowledgesources('my-file-ks')/files?api-version=2026-08-01-preview&prefix=manuals/&pageSize=100
Authorization: Bearer {{search-access-token}}

Reference: Knowledge Sources - List Files

The response includes service-selected parsing and extraction modes, as well as user metadata for file management. User metadata isn't searchable or filterable.

{
  "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>"
}

To retrieve all results, follow @odata.nextLink until it's absent. Send the complete URL exactly as returned, without changing the query parameters.

Update an uploaded file

Starting with the 2026-08-01-preview API version, update a file by its fileId. The multipart request requires the binary content part. The metadata JSON part is optional, so a content-only update is supported. A metadata-only update isn't supported.

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

Console.WriteLine($"Updated file ID: {updatedFile.FileId}");

Reference: 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,
)
print(f"Updated file ID: {updated_file.file_id}")

Reference: SearchIndexClient.update_knowledge_source_file

PUT {{search-endpoint}}/knowledgesources('my-file-ks')/files('{{file-id}}')?api-version=2026-08-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--

Reference: Knowledge Sources - Update File

If an update fails, the previous metadata record remains. Don't assume that an update changes indexed content transactionally.

Delete uploaded files

Delete files from the knowledge source when you no longer want them available for retrieval.

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");

Reference: 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 {{search-endpoint}}/knowledgesources/my-file-ks/files/file-abc123?api-version=2026-08-01-preview
Authorization: Bearer {{search-access-token}}

Reference: Knowledge Sources - Delete File

Assign to a knowledge base

If you're satisfied with the knowledge source, add it to a knowledge base.

Query a knowledge base

After the knowledge base is configured, call the retrieve action or MCP endpoint to query the knowledge source.

Delete a knowledge source

Before you can delete a knowledge source, you must delete any knowledge base that references it or update the knowledge base definition to remove the reference. For knowledge sources that generate an index and indexer pipeline, all generated objects are also deleted. However, if you used an existing index to create a knowledge source, your index isn't deleted.

If you try to delete a knowledge source that's in use, the action fails and returns a list of affected knowledge bases.

To delete a knowledge source:

  1. Get a list of all knowledge bases on your search service.

    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}");
    }
    

    Reference: SearchIndexClient

    An example response might look like the following:

     {
         "@odata.context": "https://my-search-service.search.windows.net/$metadata#knowledgebases(name)",
         "value": [
         {
             "name": "my-kb"
         },
         {
             "name": "my-kb-2"
         }
         ]
     }
    
  2. Get an individual knowledge base definition to check for knowledge source references.

    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);
    

    Reference: SearchIndexClient

    An example response might look like the following:

     {
       "Name": "earth-knowledge-base",
       "KnowledgeSources": [
         {
           "Name": "earth-knowledge-source"
         }
       ],
       "Models": [
         {}
       ],
       "RetrievalReasoningEffort": {},
       "OutputMode": {},
       "ETag": "\u00220x8DE278629D782B3\u0022",
       "EncryptionKey": null,
       "Description": null,
       "RetrievalInstructions": null,
       "AnswerInstructions": null
     }
    
  3. Either delete the knowledge base or, if you have multiple knowledge sources, update the knowledge base to remove the source. This example shows deletion.

    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.");
    

    Reference: SearchIndexClient

  4. Delete the knowledge source.

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

    Reference: SearchIndexClient

  1. Get a list of all knowledge bases on your search service.

    # 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}")
    

    Reference: SearchIndexClient

    An example response might look like the following:

     {
         "@odata.context": "https://my-search-service.search.windows.net/$metadata#knowledgebases(name)",
         "value": [
         {
             "name": "my-kb"
         },
         {
             "name": "my-kb-2"
         }
         ]
     }
    
  2. Get an individual knowledge base definition to check for knowledge source references.

    # 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)
    

    Reference: SearchIndexClient

    An example response might look like the following:

     {
       "name": "my-kb",
       "description": null,
       "retrievalInstructions": null,
       "answerInstructions": null,
       "outputMode": null,
       "knowledgeSources": [
         {
           "name": "my-blob-ks"
         }
       ],
       "models": [],
       "encryptionKey": null,
       "retrievalReasoningEffort": {
         "kind": "low"
       }
     }
    
  3. Either delete the knowledge base or, if you have multiple knowledge sources, update the knowledge base to remove the source. This example shows deletion.

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

    Reference: SearchIndexClient

  4. Delete the knowledge source.

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

    Reference: SearchIndexClient

  1. Get a list of all knowledge bases on your search service.

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

    Reference: Knowledge Bases - List

    An example response might look like the following:

     {
         "@odata.context": "https://my-search-service.search.windows.net/$metadata#knowledgebases(name)",
         "value": [
         {
             "name": "my-kb"
         },
         {
             "name": "my-kb-2"
         }
         ]
     }
    
  2. Get an individual knowledge base definition to check for knowledge source references.

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

    Reference: Knowledge Bases - Get

    An example response might look like the following:

     {
       "name": "my-kb",
       "description": null,
       "retrievalInstructions": null,
       "answerInstructions": null,
       "outputMode": null,
       "knowledgeSources": [
         {
           "name": "my-blob-ks"
         }
       ],
       "models": [],
       "encryptionKey": null,
       "retrievalReasoningEffort": {
         "kind": "low"
       }
     }
    
  3. Either delete the knowledge base or, if you have multiple knowledge sources, update the knowledge base to remove the source. This example shows deletion.

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

    Reference: Knowledge Bases - Delete

  4. Delete the knowledge source.

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

    Reference: Knowledge Sources - Delete

Troubleshoot file operations

The following status codes are specific to file knowledge source operations.

Status code Cause and action
400 The file is empty, contains no extractable text, has an unsafe relative path, or has an invalid continuation request. Verify the file has supported, readable content and a valid file name. For list operations, follow @odata.nextLink exactly as returned. Don't combine $skiptoken with search or pageSize.
409 The file knowledge source reached the file limit for the API version. Delete files before uploading more.
415 The service detected an unsupported MIME type, or it detected an image while the knowledge source uses minimal extraction. Use a supported format. For images, use standard extraction. Changing only the caller-provided content type doesn't override detection.
429 The processing queue is full. Use bounded parallelism and retry with exponential backoff. The service doesn't guarantee a Retry-After header.
504 Processing exceeded 180 seconds during file upload or update. Reduce the file size or complexity and try again.