# Add a file to a knowledge base

> POST /v1/knowledge-bases/{knowledge_base_id}/documents

Send one file as `multipart/form-data`: text, Markdown, CSV, JSON, PDF or Word. The answer is `202` with the source, `pending`: it is indexed in the background, and agents answer from it once it reads `indexed`. The same bytes twice in one base are refused. Needs `knowledge:write` and a live key.

## Parameters

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

## Body

Sent as `multipart/form-data`.

| Field | Type | Required | Description |
|---|---|---|---|
| `file` | string | Yes | The file. |
| `generate_faqs` | boolean | No | Also write questions and answers from it. Each one costs credit. |

## 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 same file is already 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
# Add a file to a knowledge base. With a live key. It is indexed in the background: read it until it says indexed.
curl -sS --fail-with-body -X POST "https://api.aigently.ai/v1/knowledge-bases/6e8a0c2d-4f6b-4d8e-a0c2-4e6a8c0e2a4c/documents" \
  -H "Authorization: Bearer $AIGENTLY_API_KEY" \
  -F "file=@opening-hours.md;type=text/markdown"
```

**JavaScript**

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

// Add a file to a knowledge base. With a live key. It is indexed in the background: read it until it says 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", {
  method: "POST",
  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
# Add a file to a knowledge base. With a live key. It is indexed in the background: read it until it says indexed.
# pip install httpx
import os

import httpx

with open("opening-hours.md", "rb") as upload:
    response = httpx.post(
        "https://api.aigently.ai/v1/knowledge-bases/6e8a0c2d-4f6b-4d8e-a0c2-4e6a8c0e2a4c/documents",
        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
// Add a file to a knowledge base. With a live key. It is indexed in the background: read it until it says 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("POST", "https://api.aigently.ai/v1/knowledge-bases/6e8a0c2d-4f6b-4d8e-a0c2-4e6a8c0e2a4c/documents", &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
// Add a file to a knowledge base. With a live key. It is indexed in the background: read it until it says 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"))
            .header("Authorization", "Bearer " + System.getenv("AIGENTLY_API_KEY"))
            .header("Content-Type", "multipart/form-data; boundary=" + boundary)
            .method("POST", 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
// Add a file to a knowledge base. With a live key. It is indexed in the background: read it until it says 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.Post, "https://api.aigently.ai/v1/knowledge-bases/6e8a0c2d-4f6b-4d8e-a0c2-4e6a8c0e2a4c/documents")
{
    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
// Add a file to a knowledge base. With a live key. It is indexed in the background: read it until it says indexed.
$curl = curl_init("https://api.aigently.ai/v1/knowledge-bases/6e8a0c2d-4f6b-4d8e-a0c2-4e6a8c0e2a4c/documents");
curl_setopt_array($curl, [
    CURLOPT_POST => true,
    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";
```
