Create a file knowledge source

Note

Foundry IQ (Azure AI Search) provides direct indexing and query APIs alongside higher-level knowledge source and knowledge base APIs for managed retrieval. Use the Azure portal, REST APIs, or Azure SDKs to configure these capabilities, or connect agents to knowledge bases in the Microsoft Foundry portal.

Important

Features or capabilities marked (preview) in this article are in Public Preview and are subject to the Supplemental Terms of Use for Microsoft Azure Previews. For preview terms specific to Foundry IQ (Azure AI Search), see Preview functionality.

A file knowledge source uploads small-to-medium file sets directly to Foundry IQ 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. Foundry IQ 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 based on permissions in Azure Storage.

Usage support

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

Prerequisites

  • A Foundry IQ 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 Foundry IQ 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.

  • For managed-identity calls to Azure OpenAI embeddings, assign Cognitive Services OpenAI User to the selected identity on the Azure OpenAI or parent Foundry resource that matches resourceUri. Content Understanding extraction requires separate permissions. See Assign a role.

    • If the Foundry resource has public network access disabled, use an eligible Dedicated service to create a foundry_account shared private link to the Foundry resource. Keep the resource's Allow Azure services on the trusted services list setting enabled. Serverless doesn't support this shared private link configuration. For supported public-endpoint access controls, see Network security perimeter; a perimeter doesn't create a private connection.

    • Check the knowledge-source configuration and tier matrix. File upload doesn't create an indexer, so the generated-indexer networking override doesn't apply.

  • If the knowledge source specifies the standard content extraction mode, review the requirements for the Azure Content Understanding skill.

    • 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

Foundry IQ detects the MIME type from file bytes.

minimal extraction accepts the supported document formats, including detected text/* types.

standard extraction has a narrower set based on the file formats supported by the Azure Content Understanding skill. Images require standard extraction and a supported detected format.

Supported extraction modes

minimal uses built-in extraction and is the default. standard sends every file through Content Understanding and requires aiServices configuration.

  • Content detected as image/* isn't supported in 2026-05-01-preview. In 2026-10-01, 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 and ingestion method.

Capability 2026-11-01-preview asynchronous 2026-10-01 synchronous 2026-08-01-preview synchronous
Maximum files per knowledge source 10,000 200 200
Maximum file size 512 MiB 50 MiB on Free and Basic; 100 MiB on other supported tiers 50 MiB on Free and Basic; 100 MiB on other supported Dedicated tiers and Serverless
Processing duration Poll until completion 180 seconds 180 seconds

A generated search index stores the uploaded content. For total storage limits by pricing tier, see Service limits. If you configure vectorization, model and downstream processing limits also apply.

Check for existing knowledge sources

The C# and Python examples use the November preview SDKs. For REST requests, set {{api-version}} to 2026-11-01-preview.

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

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)

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

Reference: Knowledge Sources - Create or Update

Expect 201 for a new source (200 updates an existing source). Read the definition back to confirm its name, kind, and generated index.

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

Reference: Knowledge sources

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. Foundry IQ manages the ingestion pipeline, using the Foundry resource specified in aiServices.

The C# and Python configuration examples use the November preview SDKs. The REST example uses 2026-11-01-preview. Review the Content Understanding requirements before using them.

Standard setup can add account-wide model mappings to the configured Content Understanding account. Check the shared configuration before you create or update a standard source. Minimal setup doesn't configure that account or use model credentials.

Standard extraction incurs Content Understanding charges and, when image verbalization is enabled, model usage charges. For more information, see billing and image description controls.

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

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)

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

Reference: Knowledge Sources - Create or Update

CORS for file operations

Set corsOptions on the complete source definition to allow a trusted browser origin for file upload, list, update, and delete.

Important

In the 2026-10-01 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.

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

Reference: Knowledge sources

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

Reference: Knowledge sources

Upload files

After you create the knowledge source, upload files directly to it with a multipart upload. Each upload is a synchronous call. Foundry IQ extracts the content, splits it into chunks, creates embeddings if needed, indexes the chunks, and saves the file metadata. You don't have to set up or run a separate ingestion pipeline.

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

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

Reference: Knowledge sources

Upload a raw file

Raw upload is available only in preview APIs. For GA file uploads, see Upload files.

The C# and Python raw examples use the November preview SDKs. The REST example uses the 2026-11-01-preview synchronous endpoint.

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;

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

Send raw file bytes to the preview synchronous endpoint. Use application/octet-stream even for text content.

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.

Reference: Knowledge sources

Upload a file with optional metadata

Use a multipart request to upload one binary file. Add one metadata part with a JSON object and one nonempty content part. The metadata part is required even if you don't have custom metadata; in that case, use {}. If you add custom metadata, use a flat bag of string values.

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

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

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

Reference: Knowledge Sources - Upload File

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.

List uploaded files

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

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

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

Reference: Knowledge sources

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.

List and filter files

When you list files, use these query parameters to filter and page through the results:

  • prefix: Performs a case-sensitive starts-with match on the full relative file name. Use prefix, not search, for paths that contain slashes or dots.
  • search: Performs a case-insensitive starts-with match on the full relative file name. It accepts only resource-name-prefix syntax: lowercase letters, digits, hyphens, and underscores, beginning with a letter or digit. Set searchType to prefix, its only supported value, to select this matching mode. This value applies to search, not the separate prefix parameter.
  • pageSize: Has a minimum of 1, a maximum of 3,000, and a default of 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);
}

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

Reference: Knowledge sources

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

Update a file by sending a PUT request with the returned fileId. Include fileName again to preserve the file name.

If you omit the custom metadata bag or set it to null, the previous custom metadata values are kept. If you supply a custom metadata bag, it replaces the previous bag instead of merging with it. To clear the custom metadata bag, supply "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

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

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

Reference: Knowledge Sources - Update File

If an update fails, the previous metadata record remains, but old indexed content might already be removed.

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 {{searchEndpoint}}/knowledgesources('my-file-ks')/files('{{fileId}}')?api-version=2026-10-01
Authorization: ******

Reference: Knowledge sources

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

Ingest files asynchronously (preview)

Use the separate :ingest actions to process files in the background. Asynchronous ingestion and operation monitoring require 2026-11-01-preview.

  • Asynchronous ingestion doesn't support customer-managed-key protected knowledge sources.
  • Asynchronous ingestion might return 503 during throttling.
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;

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

Reference: SearchIndexClient

Start ingestion and monitor completion

Upload one file with literal multipart metadata and content.

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

Reference: Knowledge sources

Expect 202. After the Retry-After delay, poll the URL in Operation-Location until the operation finishes.

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

Reference: Knowledge sources

A monitor returns HTTP 200 while ingestion is running and after it finishes. Check status for the outcome.

status Action
NotStarted, Running Wait for Retry-After, then poll the same URL again.
Succeeded Save result.fileId as {{asyncFileId}} and keep result.createdAt for replacement verification.
Failed Stop and inspect error.code (OperationFailed) and error.message.
Canceled Stop. The operation didn't succeed.

Replace a file asynchronously

Wait for the upload to succeed before replacing that file. Send a separate POST action with its returned file ID.

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

Reference: Knowledge sources

Expect 202. Save this response's Operation-Location as {{replacementOperationLocation}} and honor its Retry-After. Apply the same 40-GET-or-20-minute client policy and unresolved-outcome handling to replacement monitoring.

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

Reference: Knowledge sources

After Succeeded, verify that result.fileId and result.createdAt match the original file.

List retained operations

List monitors belonging to this knowledge source, separately from listing files.

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

Reference: Knowledge sources

Delete a knowledge source

The following C# and Python examples use the November preview SDKs. For REST requests, set {{api-version}} to 2026-11-01-preview.

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 Foundry IQ 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 Foundry IQ 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 Foundry IQ 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

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

Reference: Knowledge sources

Expect 204. Wait for every asynchronous operation to finish before cleanup.

Troubleshoot file operations

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

Status code Cause and action
400 Check for empty content, missing or duplicate multipart parts, invalid metadata JSON, unsafe relative paths, and invalid list queries.
404 The file, source, or operation monitor doesn't exist in the requested scope. Use the source and IDs from the actual response. Repeated file deletion also returns 404.
409 The effective file count is exhausted, or a mutation conflicts with active asynchronous ingestion. Wait for terminal operations before modifying or deleting their resources.
413 File bytes exceed the effective size limit for the endpoint and tier. Reduce the file size.
415 Synchronous upload detected an unsupported MIME type or used an unsupported outer content type. For images, select standard extraction and an explicitly supported format. Changing the supplied MIME type doesn't override detection.
503 Asynchronous ingestion is unavailable or has no eligible worker. An indexing dependency can also return this status.
504 Synchronous processing exceeded its configured deadline (180 seconds by default). Reduce file size or complexity. This isn't an asynchronous polling deadline.