# Replace a file

> PUT /v1/knowledge-bases/{knowledge_base_id}/documents/{document_id}

Send a new version of a file, as `multipart/form-data`. It keeps its id and goes back to `pending`; agents keep answering from the old version until the new one is indexed — and if that fails, the old one stays, and `error` says why. Needs `knowledge:write` and a live key.

## Parameters

| Name | In | Type | Required | Description |
|---|---|---|---|---|
| `knowledge_base_id` | path | string (uuid) | Yes |  |
| `document_id` | path | string (uuid) | Yes |  |

## Body

Sent as `multipart/form-data`.

| Field | Type | Required | Description |
|---|---|---|---|
| `file` | string | Yes | The new version. |

## Answer

`202` with [KnowledgeDocument](/reference/objects/KnowledgeDocument).

## Errors

Every error is a [problem document](/errors) with a stable `code`.

| Status | When |
|---|---|
| `401` | The key is missing, mistyped, unknown, revoked or expired. |
| `403` | A test key, or a key limited to some agents. |
| `404` | This key reaches no such knowledge base. |
| `409` | The source is being indexed right now, came from a website rather than a file, the same bytes are another source in the base, or the project is frozen. |
| `413` | The file is over the size this deployment takes. |
| `415` | Not a file type the base reads, or a text file that is not UTF-8. |
| `422` | The file is empty, or the base holds as many sources as it may. |
| `429` | Too many files sent just now. Wait for `Retry-After`. |
| `500` | Something went wrong on our side. Quote the `request_id` to support. |

## Examples

**curl**

```sh
#!/bin/sh
# Replace a file with a new version. It keeps its id; agents answer from the old version until the new one is indexed.
curl -sS --fail-with-body -X PUT "https://api.aigently.ai/v1/knowledge-bases/6e8a0c2d-4f6b-4d8e-a0c2-4e6a8c0e2a4c/documents/7f9b1d3e-5a7c-4e9f-b1d3-5f7b9d1f3b5d" \
  -H "Authorization: Bearer $AIGENTLY_API_KEY" \
  -F "file=@opening-hours.md;type=text/markdown"
```

**JavaScript**

```js
import { readFile } from "node:fs/promises";

// Replace a file with a new version. It keeps its id; agents answer from the old version until the new one is indexed.
const form = new FormData();
form.append("file", new Blob([await readFile("opening-hours.md")], { type: "text/markdown" }), "opening-hours.md");

const response = await fetch("https://api.aigently.ai/v1/knowledge-bases/6e8a0c2d-4f6b-4d8e-a0c2-4e6a8c0e2a4c/documents/7f9b1d3e-5a7c-4e9f-b1d3-5f7b9d1f3b5d", {
  method: "PUT",
  headers: {
    Authorization: `Bearer ${process.env.AIGENTLY_API_KEY}`,
  },
  body: form,
});
const answer = await response.json();
if (!response.ok) throw new Error(`${answer.code}: ${answer.detail}`);
console.log(answer);
```

**Python**

```python
# Replace a file with a new version. It keeps its id; agents answer from the old version until the new one is indexed.
# pip install httpx
import os

import httpx

with open("opening-hours.md", "rb") as upload:
    response = httpx.put(
        "https://api.aigently.ai/v1/knowledge-bases/6e8a0c2d-4f6b-4d8e-a0c2-4e6a8c0e2a4c/documents/7f9b1d3e-5a7c-4e9f-b1d3-5f7b9d1f3b5d",
        headers={
            "Authorization": f"Bearer {os.environ['AIGENTLY_API_KEY']}",
        },
        files={"file": ("opening-hours.md", upload, "text/markdown")},
        timeout=60,
    )
if response.is_error:
    raise SystemExit(response.text)
print(response.json())
```

**Go**

```go
// Replace a file with a new version. It keeps its id; agents answer from the old version until the new one is indexed.
package main

import (
	"bytes"
	"fmt"
	"io"
	"mime/multipart"
	"net/http"
	"os"
)

func main() {
	var form bytes.Buffer
	writer := multipart.NewWriter(&form)
	part, _ := writer.CreateFormFile("file", "opening-hours.md")
	contents, err := os.ReadFile("opening-hours.md")
	if err != nil {
		panic(err)
	}
	part.Write(contents)
	writer.Close()
	request, err := http.NewRequest("PUT", "https://api.aigently.ai/v1/knowledge-bases/6e8a0c2d-4f6b-4d8e-a0c2-4e6a8c0e2a4c/documents/7f9b1d3e-5a7c-4e9f-b1d3-5f7b9d1f3b5d", &form)
	if err != nil {
		panic(err)
	}
	request.Header.Set("Authorization", "Bearer "+os.Getenv("AIGENTLY_API_KEY"))
	request.Header.Set("Content-Type", writer.FormDataContentType())
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()
	body, _ := io.ReadAll(response.Body)
	if response.StatusCode >= 400 {
		fmt.Fprintln(os.Stderr, string(body))
		os.Exit(1)
	}
	fmt.Println(string(body))
}
```

**Java**

```java
// Replace a file with a new version. It keeps its id; agents answer from the old version until the new one is indexed.
import java.io.ByteArrayOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {
    public static void main(String[] args) throws Exception {
        String boundary = Long.toHexString(System.nanoTime());
        ByteArrayOutputStream form = new ByteArrayOutputStream();
        form.write(("--" + boundary
            + "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"opening-hours.md\"\r\n"
            + "Content-Type: text/markdown\r\n\r\n").getBytes());
        form.write(Files.readAllBytes(Path.of("opening-hours.md")));
        form.write(("\r\n--" + boundary + "--\r\n").getBytes());
        HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.aigently.ai/v1/knowledge-bases/6e8a0c2d-4f6b-4d8e-a0c2-4e6a8c0e2a4c/documents/7f9b1d3e-5a7c-4e9f-b1d3-5f7b9d1f3b5d"))
            .header("Authorization", "Bearer " + System.getenv("AIGENTLY_API_KEY"))
            .header("Content-Type", "multipart/form-data; boundary=" + boundary)
            .method("PUT", HttpRequest.BodyPublishers.ofByteArray(form.toByteArray()))
            .build();
        // HTTP/1.1: on a plain-http address Java's default asks to upgrade, which not every
        // server allows.
        HttpClient client = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build();
        HttpResponse<String> response =
            client.send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() >= 400) {
            System.err.println(response.body());
            System.exit(1);
        }
        System.out.println(response.body());
    }
}
```

**C#**

```csharp
// Replace a file with a new version. It keeps its id; agents answer from the old version until the new one is indexed.
using System.Net.Http.Headers;
using System.Text;

var form = new MultipartFormDataContent();
var upload = new ByteArrayContent(File.ReadAllBytes("opening-hours.md"));
upload.Headers.ContentType = new MediaTypeHeaderValue("text/markdown");
form.Add(upload, "file", "opening-hours.md");

using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("AIGENTLY_API_KEY"));
var request = new HttpRequestMessage(HttpMethod.Put, "https://api.aigently.ai/v1/knowledge-bases/6e8a0c2d-4f6b-4d8e-a0c2-4e6a8c0e2a4c/documents/7f9b1d3e-5a7c-4e9f-b1d3-5f7b9d1f3b5d")
{
    Content = form,
};
var response = await client.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
    Console.Error.WriteLine(body);
    return 1;
}
Console.WriteLine(body);
return 0;
```

**PHP**

```php
<?php
// Replace a file with a new version. It keeps its id; agents answer from the old version until the new one is indexed.
$curl = curl_init("https://api.aigently.ai/v1/knowledge-bases/6e8a0c2d-4f6b-4d8e-a0c2-4e6a8c0e2a4c/documents/7f9b1d3e-5a7c-4e9f-b1d3-5f7b9d1f3b5d");
curl_setopt_array($curl, [
    CURLOPT_CUSTOMREQUEST => "PUT",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . getenv("AIGENTLY_API_KEY"),
    ],
    CURLOPT_POSTFIELDS => [
        "file" => new CURLFile("opening-hours.md", "text/markdown"),
    ],
]);
$body = curl_exec($curl);
if (curl_getinfo($curl, CURLINFO_RESPONSE_CODE) >= 400) {
    fwrite(STDERR, $body . "\n");
    exit(1);
}
echo $body, "\n";
```
