> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tensorpro.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Grounding answers in documents

> Use EDN project documents as context for AI answers, with citations that link each answer to its sources.

EDN lets your application use its own documents as memory for AI answers. By placing documents in a project and building a Session Initialization Package (SIP), you can give your model relevant context and citations that point back to the original sources.

### 1. Create a project

Use **Create a project** to create a project for your documents. The response includes an `id`, which you pass as `project_id` in later API calls.

```bash cURL theme={"theme":"github-light"}
# EDN_API_KEY: your API key (see the Quickstart).
EDN_PROJECT_ID=$(curl -s https://api.tensorpro.ai/api/v1/projects \
  -H "Authorization: Bearer $EDN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name": "Client handbook"}' | jq -r '.id')
echo "$EDN_PROJECT_ID"
```

```python Python theme={"theme":"github-light"}
import os
import requests

EDN = "https://api.tensorpro.ai/api/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['EDN_API_KEY']}"}

project = requests.post(
    f"{EDN}/projects",
    headers=HEADERS,
    json={"name": "Client handbook"},
).json()
project_id = project["id"]
```

```typescript TypeScript theme={"theme":"github-light"}
const EDN = "https://api.tensorpro.ai/api/v1";
const HEADERS = {
  Authorization: `Bearer ${process.env.EDN_API_KEY}`,
  "Content-Type": "application/json",
};

const project = await (
  await fetch(`${EDN}/projects`, {
    method: "POST",
    headers: HEADERS,
    body: JSON.stringify({ name: "Client handbook" }),
  })
).json();
const projectId = project.id;
```

### 2. Upload your documents

Use **Upload a document** to add files to the project. This endpoint accepts `multipart/form-data`, not JSON.

The request accepts these fields:

* `file`: Required. A PDF, Word (DOCX), Excel (XLSX), PowerPoint (PPTX), Markdown, plain text, HTML, CSV or image (PNG, JPEG, TIFF, BMP, WebP) file, up to 5 MB and 30 pages, with up to 8 scanned pages. See [Supported files](https://docs.tensorpro.ai/api-reference/ingest-document.md#supported-files).
* `session_id`: Required.
* `project_id`: Optional. Associates the document with your project. Without it, the document goes into general memory.
* `domain`: Optional.

EDN splits the document text into sections and saves each section as a `DOCUMENT_VERIFIED` memory.

The response includes `chunks_stored`, the number of memories made from the file (for a file that is already in the project, the number in the existing source), and `source_id`, the project source identifier. When no `project_id` is supplied, `source_id` is null.

```bash cURL theme={"theme":"github-light"}
# EDN_SESSION_ID: your session ID (see the Quickstart).
# EDN_PROJECT_ID: from step 1. handbook.pdf: a file in the current folder.
curl https://api.tensorpro.ai/api/v1/document/ingest \
  -H "Authorization: Bearer $EDN_API_KEY" \
  -F "file=@handbook.pdf" \
  -F "session_id=$EDN_SESSION_ID" \
  -F "project_id=$EDN_PROJECT_ID"
```

```python Python theme={"theme":"github-light"}
# EDN, HEADERS and project_id: from step 1.
session_id = os.environ["EDN_SESSION_ID"]

with open("handbook.pdf", "rb") as f:
    upload = requests.post(
        f"{EDN}/document/ingest",
        headers=HEADERS,
        files={"file": ("handbook.pdf", f)},
        data={"session_id": session_id, "project_id": project_id},
    ).json()

source_id = upload["source_id"]
print(upload["chunks_stored"], source_id)
```

```typescript TypeScript theme={"theme":"github-light"}
import { readFile } from "node:fs/promises";

// EDN and projectId: from step 1.
const sessionId = process.env.EDN_SESSION_ID;

const form = new FormData();
form.append("file", new Blob([await readFile("handbook.pdf")]), "handbook.pdf");
form.append("session_id", sessionId);
form.append("project_id", projectId);

// No Content-Type header: fetch sets the multipart boundary itself.
const upload = await (
  await fetch(`${EDN}/document/ingest`, {
    method: "POST",
    headers: { Authorization: `Bearer ${process.env.EDN_API_KEY}` },
    body: form,
  })
).json();

const sourceId = upload.source_id;
console.log(upload.chunks_stored, sourceId);
```

An upload can return these errors:

* `400`: The document could not be read (`INVALID_DOCUMENT`), is a password-protected PDF (`PASSWORD_PROTECTED`) or has no usable text (`NO_USABLE_CONTENT`).
* `409`: The same file is already being processed in the project (`DUPLICATE_IN_PROGRESS`).
* `413`: The file is over 5 MB (`FILE_TOO_LARGE`), has more than 30 pages (`TOO_MANY_PAGES`), has more than 8 scanned pages (`TOO_MANY_SCANNED_PAGES`) or contains too much content (`TOO_MUCH_CONTENT`). Split it into parts.
* `415`: The file type is not supported.
* `503`: EDN is processing another document (`BUSY`), or the save did not finish and nothing was stored (`WRITE_TIMEOUT`, `WRITE_INCOMPLETE`). Documents are processed one at a time, so upload them one after another, and retry after the `Retry-After` header.

Uploading a file that is already a ready source of the project stores nothing new and returns `already_present: true`.

### 3. Check that the documents are ready

Use **List project documents** to retrieve the project's documents, newest first.

Each document includes:

* `ingest_status`: `pending` while EDN processes the document, `ready` when it can be searched, or `failed` if it could not be read.
* `chunk_count`: The number of memory records created from the document.
* `error_code` and `error_message`: Why a `failed` document was not stored. Some failures are stored as `PROCESSING_FAILED`, and documents that failed before these fields existed have `null`. Uploading the same file again retries it.

Check that `ingest_status` is `ready` before using the document for retrieval.

```bash cURL theme={"theme":"github-light"}
# EDN_PROJECT_ID: from step 1.
curl -s "https://api.tensorpro.ai/api/v1/projects/$EDN_PROJECT_ID/sources" \
  -H "Authorization: Bearer $EDN_API_KEY" \
  | jq -r '.sources[] | "\(.title): \(.ingest_status), \(.chunk_count) records"'
```

```python Python theme={"theme":"github-light"}
# EDN, HEADERS and project_id: from step 1.
sources = requests.get(
    f"{EDN}/projects/{project_id}/sources",
    headers=HEADERS,
).json()["sources"]

for source in sources:
    print(source["title"], source["ingest_status"], source["chunk_count"])

all_ready = all(source["ingest_status"] == "ready" for source in sources)
```

```typescript TypeScript theme={"theme":"github-light"}
// EDN, HEADERS and projectId: from step 1.
const { sources } = await (
  await fetch(`${EDN}/projects/${projectId}/sources`, { headers: HEADERS })
).json();

for (const source of sources) {
  console.log(source.title, source.ingest_status, source.chunk_count);
}

const allReady = sources.every((source) => source.ingest_status === "ready");
```

### 4. Build a SIP from the project

Use **Build a SIP** to retrieve the memory relevant to the user's question.

Send:

* `query`: What the user just asked.
* `session_id`: The conversation session.
* `project_id`: The project containing your documents.

With `project_id`, EDN uses only that project's memory and documents. Set `include_global` to `true` to also use general memory.

The response includes:

* `sip`: The context text to place in the model's prompt, ahead of the user's message.
* `records_used`: The number of memory records included in the SIP.
* `citations`: The sources associated with numbered items in the SIP.
* `grounded`: `true` when `project_id` was supplied.

EDN numbers each citable item `[1]`, `[2]` and so on. Citable memories are `DOCUMENT_VERIFIED`, `USER_STATED` and `USER_CONFIRMED`. All sections of the same document share one citation number.

Saved exchanges (`ROUND`) appear without a number and are never cited. Unconfirmed AI memories, replaced memories and deleted memories are never included.

```bash cURL theme={"theme":"github-light"}
# EDN_SESSION_ID: see the Quickstart. EDN_PROJECT_ID: from step 1.
# Saves the response to sip.json for the next steps.
curl -s https://api.tensorpro.ai/api/v1/sip/build \
  -H "Authorization: Bearer $EDN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "What is the refund period?",
    "session_id": "'"$EDN_SESSION_ID"'",
    "project_id": "'"$EDN_PROJECT_ID"'"
  }' -o sip.json
```

```python Python theme={"theme":"github-light"}
# EDN, HEADERS and project_id: from step 1. session_id: from step 2.
user_text = "What is the refund period?"

sip = requests.post(
    f"{EDN}/sip/build",
    headers=HEADERS,
    json={"query": user_text, "session_id": session_id, "project_id": project_id},
).json()

print(sip["grounded"], sip["records_used"], len(sip["citations"]))
```

```typescript TypeScript theme={"theme":"github-light"}
// EDN, HEADERS and projectId: from step 1. sessionId: from step 2.
const userText = "What is the refund period?";

const sip = await (
  await fetch(`${EDN}/sip/build`, {
    method: "POST",
    headers: HEADERS,
    body: JSON.stringify({
      query: userText,
      session_id: sessionId,
      project_id: projectId,
    }),
  })
).json();

console.log(sip.grounded, sip.records_used, sip.citations.length);
```

### 5. Ask the model to cite its sources

Place the returned `sip` in the model's prompt, ahead of the user's message. Ask the model to cite the numbered sources `[n]` it uses in its answer.

The `citations` response contains one entry for each citation number, with these fields:

* `index`: The number represented by `[n]`.
* `summary`: The memory content associated with the citation.
* `provenance`: The memory's provenance class.
* `source_id`: The document source identifier, or null for other memory.
* `source_title`: The document title, or null for other memory.
* `record_id`: The memory record identifier.
* `supporting_record_ids`: Every memory record from that source that was used.

Use `index` to match each `[n]` in the model's answer to its source. Display `source_title` to show the user which document supports the cited information.

```bash cURL theme={"theme":"github-light"}
# sip.json: from step 4. Writes the system prompt for your model to a file.
jq -r '"Answer using only the sources below. Cite each source you use with its number, for example [1].\n\n" + .sip' \
  sip.json > system_prompt.txt
```

```python Python theme={"theme":"github-light"}
# sip and user_text: from step 4.
system_prompt = (
    "Answer using only the sources below. Cite each source you use with its "
    "number, for example [1].\n\n" + sip["sip"]
)
# Send system_prompt to your model as the system prompt and user_text as the
# user message. Keep the model's answer text as reply.
```

```typescript TypeScript theme={"theme":"github-light"}
// sip and userText: from step 4.
const systemPrompt =
  "Answer using only the sources below. Cite each source you use with its " +
  `number, for example [1].\n\n${sip.sip}`;
// Send systemPrompt to your model as the system prompt and userText as the
// user message. Keep the model's answer text as reply.
```

```bash cURL theme={"theme":"github-light"}
# sip.json: from step 4. Lists every citation number with its source title.
jq -r '.citations[] | "[\(.index)] \(.source_title // "not from a document")"' sip.json
```

```python Python theme={"theme":"github-light"}
import re

# sip: from step 4. reply: your model's answer text.
titles = {c["index"]: c["source_title"] for c in sip["citations"]}

for n in sorted({int(m) for m in re.findall(r"\[(\d+)\]", reply)}):
    print(f"[{n}]", titles.get(n) or "not from a document")
```

```typescript TypeScript theme={"theme":"github-light"}
// sip: from step 4. reply: your model's answer text.
const titles = new Map(sip.citations.map((c) => [c.index, c.source_title]));

const cited = [...new Set([...reply.matchAll(/\[(\d+)\]/g)].map((m) => Number(m[1])))];
for (const n of cited.sort((a, b) => a - b)) {
  console.log(`[${n}]`, titles.get(n) ?? "not from a document");
}
```

### 6. When the project has no answer

When a project SIP build finds nothing relevant to the question, the response sets `abstain` to `true`.

The SIP instructs the model to answer only from the project's sources and to state plainly that the project has no sources on that topic, rather than guessing.

```bash cURL theme={"theme":"github-light"}
# sip.json: from step 4.
jq -r 'if .abstain then "No project sources match this question." else "\(.citations | length) sources found." end' sip.json
```

```python Python theme={"theme":"github-light"}
# sip: from step 4.
if sip["abstain"]:
    # sip["sip"] already tells the model to say the project has no sources on
    # this topic. Send it to your model as usual; there are no citations.
    print("No project sources match this question.")
```

```typescript TypeScript theme={"theme":"github-light"}
// sip: from step 4.
if (sip.abstain) {
  // sip.sip already tells the model to say the project has no sources on
  // this topic. Send it to your model as usual; there are no citations.
  console.log("No project sources match this question.");
}
```

### 7. Keep the conversation in the project

Use **Save a conversation turn** after each user-assistant exchange, passing the same `project_id`.

This saves the exchange in the project so later SIPs for that project can use it as context.

```bash cURL theme={"theme":"github-light"}
# EDN_SESSION_ID: see the Quickstart. EDN_PROJECT_ID: from step 1.
curl https://api.tensorpro.ai/api/v1/memory/ingest \
  -H "Authorization: Bearer $EDN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "user_message": "What is the refund period?",
    "assistant_message": "The refund period is 30 days [1].",
    "session_id": "'"$EDN_SESSION_ID"'",
    "project_id": "'"$EDN_PROJECT_ID"'"
  }'
```

```python Python theme={"theme":"github-light"}
# EDN, HEADERS and project_id: from step 1. session_id: from step 2.
# user_text: from step 4. reply: your model's answer text.
saved = requests.post(
    f"{EDN}/memory/ingest",
    headers=HEADERS,
    json={
        "user_message": user_text,
        "assistant_message": reply,
        "session_id": session_id,
        "project_id": project_id,
    },
).json()
```

```typescript TypeScript theme={"theme":"github-light"}
// EDN, HEADERS and projectId: from step 1. sessionId: from step 2.
// userText: from step 4. reply: your model's answer text.
const saved = await (
  await fetch(`${EDN}/memory/ingest`, {
    method: "POST",
    headers: HEADERS,
    body: JSON.stringify({
      user_message: userText,
      assistant_message: reply,
      session_id: sessionId,
      project_id: projectId,
    }),
  })
).json();
```

### 8. Remove a document

Use **Remove a project document** to remove a document from the project.

Provide the `source_id` returned by **Upload a document** or **List project documents**.

EDN removes the document and every memory created from it, so none of them is used again in SIPs, search or lists. Signed records of earlier SIPs keep the text those SIPs contained.

The response includes `records_removed`, the number of memory records removed.

```bash cURL theme={"theme":"github-light"}
# EDN_PROJECT_ID: from step 1. YOUR_SOURCE_ID: the source_id from step 2 or 3.
curl -X DELETE \
  "https://api.tensorpro.ai/api/v1/projects/$EDN_PROJECT_ID/sources/YOUR_SOURCE_ID" \
  -H "Authorization: Bearer $EDN_API_KEY"
```

```python Python theme={"theme":"github-light"}
# EDN, HEADERS and project_id: from step 1. source_id: from step 2.
removed = requests.delete(
    f"{EDN}/projects/{project_id}/sources/{source_id}",
    headers=HEADERS,
).json()
print(removed["records_removed"])
```

```typescript TypeScript theme={"theme":"github-light"}
// EDN, HEADERS and projectId: from step 1. sourceId: from step 2.
const removed = await (
  await fetch(`${EDN}/projects/${projectId}/sources/${sourceId}`, {
    method: "DELETE",
    headers: HEADERS,
  })
).json();
console.log(removed.records_removed);
```

***

**Next steps:** See [Build a SIP](https://docs.tensorpro.ai/api-reference/build-sip.md) and [Upload a document](https://docs.tensorpro.ai/api-reference/ingest-document.md) for the API reference.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.