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

# The memory turn loop

> Learn how to integrate EDN memory into every exchange, from building context to saving the user's message and the AI response.

The memory turn loop is the sequence of EDN calls your application makes around each exchange. It builds a Session Initialization Package (SIP) for your model, saves the conversation as memory and processes the AI response.

Follow these seven steps in order:

1. Save the user's message to the session.
2. Build a SIP.
3. Call your model.
4. Save the exchange.
5. Classify the reply.
6. Save a generated statement, when applicable.
7. Save the AI response to the session.

Use the same `session_id` for every exchange in the same conversation. EDN creates the session the first time a new `session_id` is used.

To keep a conversation inside a project, send the same `project_id` to **Build a SIP**, **Save a conversation turn**, **Classify an AI response** and **Save a generated statement**.

### 1. Save the user's message to the session

Use **Add a message to a session** to save the user's message before building context.

Send:

* `role`: Set to `user`.
* `content`: The user's message, up to 100,000 characters.

Saved messages form the session's transcript. They are not memory.

Saving the user's message helps **Build a SIP** find relevant memory when the user asks a short follow-up question.

```bash cURL theme={"theme":"github-light"}
# EDN_API_KEY and EDN_SESSION_ID: see the Quickstart.
curl -s "https://api.tensorpro.ai/api/v1/sessions/$EDN_SESSION_ID/messages" \
  -H "Authorization: Bearer $EDN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"role": "user", "content": "Who manages the website project?"}'
```

```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']}"}
session_id = os.environ["EDN_SESSION_ID"]
project_id = os.environ.get("EDN_PROJECT_ID")  # None: general memory
user_text = "Who manages the website project?"

requests.post(
    f"{EDN}/sessions/{session_id}/messages",
    headers=HEADERS,
    json={"role": "user", "content": user_text},
)
```

```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 sessionId = process.env.EDN_SESSION_ID;
const projectId = process.env.EDN_PROJECT_ID ?? null; // null: general memory
const userText = "Who manages the website project?";

const userMessageResp = await fetch(`${EDN}/sessions/${sessionId}/messages`, {
  method: "POST",
  headers: HEADERS,
  body: JSON.stringify({ role: "user", content: userText }),
});
const savedUserMessage = await userMessageResp.json();
```

### 2. Build a SIP

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

Send:

* `query`: The user's message.
* `session_id`: The conversation session.
* `project_id`: Optional. The project containing the conversation's memory.

The response includes:

* `sip`: The context text to place in the model's prompt, ahead of the user's message.
* `grounded`: `true` when `project_id` was supplied.
* `citations`: One entry per numbered item in a project SIP.

Building a SIP counts against the daily SIP quota.

```bash cURL theme={"theme":"github-light"}
# To use a project, add "project_id" to the JSON body.
curl -s https://api.tensorpro.ai/api/v1/sip/build \
  -H "Authorization: Bearer $EDN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"query": "Who manages the website project?", "session_id": "'"$EDN_SESSION_ID"'"}'
```

```python Python theme={"theme":"github-light"}
# EDN, HEADERS, session_id, project_id and user_text: from step 1.
sip_body = requests.post(
    f"{EDN}/sip/build",
    headers=HEADERS,
    json={"query": user_text, "session_id": session_id, "project_id": project_id},
).json()

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

```typescript TypeScript theme={"theme":"github-light"}
// EDN, HEADERS, sessionId, projectId and userText: from step 1.
const sipResp = await fetch(`${EDN}/sip/build`, {
  method: "POST",
  headers: HEADERS,
  body: JSON.stringify({ query: userText, session_id: sessionId, project_id: projectId }),
});
const sipBody = await sipResp.json();

const sip = sipBody.sip;
console.log(sipBody.grounded, sipBody.citations.length);
```

### 3. Call your model

EDN never calls your model and never answers questions for you.

Place the returned `sip` in your model's prompt, ahead of the user's message, and call your model as usual. EDN works with any model.

```bash cURL theme={"theme":"github-light"}
# Replace PASTE_THE_SIP_HERE with the sip value from step 2.
curl https://api.openai.com/v1/chat/completions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {"role": "system", "content": "Use this memory to answer the user.\n\nPASTE_THE_SIP_HERE"},
      {"role": "user", "content": "Who manages the website project?"}
    ]
  }'
```

```python Python theme={"theme":"github-light"}
from openai import OpenAI

# sip: from step 2. user_text: from step 1.
client = OpenAI()  # reads OPENAI_API_KEY
completion = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": f"Use this memory to answer the user.\n\n{sip}"},
        {"role": "user", "content": user_text},
    ],
)
reply = completion.choices[0].message.content
print(reply)
```

```typescript TypeScript theme={"theme":"github-light"}
import OpenAI from "openai";

// sip: from step 2. userText: from step 1.
const openai = new OpenAI(); // reads OPENAI_API_KEY
const completion = await openai.chat.completions.create({
  model: "gpt-4o",
  messages: [
    { role: "system", content: `Use this memory to answer the user.\n\n${sip}` },
    { role: "user", content: userText },
  ],
});
const reply = completion.choices[0].message.content ?? "";
console.log(reply);
```

### 4. Save the exchange

After receiving the model's reply, use **Save a conversation turn** to store the exchange as memory.

Send:

* `user_message`: The user's message.
* `assistant_message`: The model's reply.
* `session_id`: The conversation session.
* `project_id`: The project, when applicable.

EDN saves the exchange as a `ROUND` memory and returns its `record_id`.

EDN also checks the user's message for new facts and corrections. When it saves a fact, the response includes a `fact` object containing:

* `record_id`: The ID of the saved fact.
* `replaces`: The ID of the older memory it replaced, or null.

When no fact was saved, `fact` is null.

```bash cURL theme={"theme":"github-light"}
# To use a project, add "project_id" to the JSON body.
curl -s https://api.tensorpro.ai/api/v1/memory/ingest \
  -H "Authorization: Bearer $EDN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "user_message": "Who manages the website project?",
    "assistant_message": "Sara manages the website project.",
    "session_id": "'"$EDN_SESSION_ID"'"
  }'
```

```python Python theme={"theme":"github-light"}
# EDN, HEADERS, session_id, project_id and user_text: from step 1. reply: from step 3.
turn = 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()

print(turn["record_id"])
if turn["fact"]:
    print(turn["fact"]["record_id"], turn["fact"]["replaces"])
```

```typescript TypeScript theme={"theme":"github-light"}
// EDN, HEADERS, sessionId, projectId and userText: from step 1. reply: from step 3.
const turnResp = await fetch(`${EDN}/memory/ingest`, {
  method: "POST",
  headers: HEADERS,
  body: JSON.stringify({
    user_message: userText,
    assistant_message: reply,
    session_id: sessionId,
    project_id: projectId,
  }),
});
const savedTurn = await turnResp.json();

console.log(savedTurn.record_id);
if (savedTurn.fact) {
  console.log(savedTurn.fact.record_id, savedTurn.fact.replaces);
}
```

### 5. Classify the reply

Use **Classify an AI response** to check whether the model's reply answered a factual question from the user.

Send:

* `user_message`: The user's message.
* `assistant_message`: The model's reply.
* `session_id`: The conversation session.
* `sip`: The context returned in step 2.
* `project_id`: The project, when applicable.

EDN uses `sip` to check whether specific facts in the reply are supported by the supplied context. Without it, factual claims cannot be verified.

When the reply answers a factual question and is supported by the SIP, EDN saves it as an `AI_INFERRED` memory. The response contains:

* `saved`: `true`.
* `provenance`: `AI_INFERRED`.
* `record_id`: The ID of the saved memory.

An `AI_INFERRED` memory is not used in SIPs until the user confirms it.

Otherwise, `saved` is `false`, and `reason` explains why:

* `not_an_answer`: The reply does not answer a factual question from the user.
* `abstention`: The reply states that it does not know.
* `unsupported_claim`: A fact in the reply is not supported by the supplied SIP.

When the reply is not a factual answer, `provenance` is `AI_GENERATED`.

```bash cURL theme={"theme":"github-light"}
# Replace PASTE_THE_SIP_HERE with the sip value from step 2.
# To use a project, add "project_id" to the JSON body.
curl -s https://api.tensorpro.ai/api/v1/memory/infer \
  -H "Authorization: Bearer $EDN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "user_message": "Who manages the website project?",
    "assistant_message": "Sara manages the website project.",
    "session_id": "'"$EDN_SESSION_ID"'",
    "sip": "PASTE_THE_SIP_HERE"
  }'
```

```python Python theme={"theme":"github-light"}
# EDN, HEADERS, session_id, project_id and user_text: from step 1.
# sip: from step 2. reply: from step 3.
classified = requests.post(
    f"{EDN}/memory/infer",
    headers=HEADERS,
    json={
        "user_message": user_text,
        "assistant_message": reply,
        "session_id": session_id,
        "sip": sip,
        "project_id": project_id,
    },
).json()

if classified["saved"]:
    print("Saved as AI_INFERRED:", classified["record_id"])
else:
    print(classified["provenance"], classified["reason"])
```

```typescript TypeScript theme={"theme":"github-light"}
// EDN, HEADERS, sessionId, projectId and userText: from step 1.
// sip: from step 2. reply: from step 3.
const inferResp = await fetch(`${EDN}/memory/infer`, {
  method: "POST",
  headers: HEADERS,
  body: JSON.stringify({
    user_message: userText,
    assistant_message: reply,
    session_id: sessionId,
    sip: sip,
    project_id: projectId,
  }),
});
const classified = await inferResp.json();

if (classified.saved) {
  console.log("Saved as AI_INFERRED:", classified.record_id);
} else {
  console.log(classified.provenance, classified.reason);
}
```

### 6. Save a generated statement

When **Classify an AI response** returns `AI_GENERATED` as the `provenance`, you can use **Save a generated statement** to store the reply.

Send:

* `assistant_message`: The model's reply.
* `session_id`: The conversation session.
* `project_id`: The project, when applicable.

EDN saves the reply as an `AI_GENERATED` memory. This includes assistant output such as suggestions or drafts.

An `AI_GENERATED` memory is never used in a SIP until the user confirms it.

Saving a generated statement counts against the daily ingest quota.

```bash cURL theme={"theme":"github-light"}
# Run this only when step 5 returned "provenance": "AI_GENERATED".
# To use a project, add "project_id" to the JSON body.
curl -s https://api.tensorpro.ai/api/v1/memory/generated \
  -H "Authorization: Bearer $EDN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "assistant_message": "Here is a draft plan for the launch.",
    "session_id": "'"$EDN_SESSION_ID"'"
  }'
```

```python Python theme={"theme":"github-light"}
# EDN, HEADERS, session_id and project_id: from step 1.
# reply: from step 3. classified: from step 5.
if classified["provenance"] == "AI_GENERATED":
    generated = requests.post(
        f"{EDN}/memory/generated",
        headers=HEADERS,
        json={
            "assistant_message": reply,
            "session_id": session_id,
            "project_id": project_id,
        },
    ).json()
    print("Saved as AI_GENERATED:", generated["record_id"])
```

```typescript TypeScript theme={"theme":"github-light"}
// EDN, HEADERS, sessionId and projectId: from step 1.
// reply: from step 3. classified: from step 5.
if (classified.provenance === "AI_GENERATED") {
  const generatedResp = await fetch(`${EDN}/memory/generated`, {
    method: "POST",
    headers: HEADERS,
    body: JSON.stringify({
      assistant_message: reply,
      session_id: sessionId,
      project_id: projectId,
    }),
  });
  const generated = await generatedResp.json();
  console.log("Saved as AI_GENERATED:", generated.record_id);
}
```

### 7. Save the AI response to the session

Use **Add a message to a session** again to save the model's reply to the session transcript.

Send:

* `role`: Set to `assistant`.
* `content`: The model's reply.

When EDN checks the next user message for a correction, it uses the latest assistant message saved to that session.

Saving both sides of the conversation helps EDN detect corrections in later exchanges.

```bash cURL theme={"theme":"github-light"}
curl -s "https://api.tensorpro.ai/api/v1/sessions/$EDN_SESSION_ID/messages" \
  -H "Authorization: Bearer $EDN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"role": "assistant", "content": "Sara manages the website project."}'
```

```python Python theme={"theme":"github-light"}
# EDN, HEADERS and session_id: from step 1. reply: from step 3.
requests.post(
    f"{EDN}/sessions/{session_id}/messages",
    headers=HEADERS,
    json={"role": "assistant", "content": reply},
)
```

```typescript TypeScript theme={"theme":"github-light"}
// EDN, HEADERS and sessionId: from step 1. reply: from step 3.
const replyMessageResp = await fetch(`${EDN}/sessions/${sessionId}/messages`, {
  method: "POST",
  headers: HEADERS,
  body: JSON.stringify({ role: "assistant", content: reply }),
});
const savedReplyMessage = await replyMessageResp.json();
```

### The complete loop

```bash cURL theme={"theme":"github-light"}
#!/usr/bin/env bash
# One exchange of the memory loop. Needs curl and jq.
# EDN_API_KEY and EDN_SESSION_ID: see the Quickstart. OPENAI_API_KEY: your model key.
# EDN_PROJECT_ID: optional; leave it unset to use general memory.
set -euo pipefail

EDN="https://api.tensorpro.ai/api/v1"
USER_TEXT="Who manages the website project?"

edn_post() {  # edn_post PATH JSON
  curl -s "$EDN$1" \
    -H "Authorization: Bearer $EDN_API_KEY" \
    -H "Content-Type: application/json" \
    -d "$2"
}

with_project() {  # adds project_id to a JSON object when EDN_PROJECT_ID is set
  jq --arg p "${EDN_PROJECT_ID:-}" 'if $p == "" then . else . + {project_id: $p} end'
}

# 1. Save the user's message to the session.
edn_post "/sessions/$EDN_SESSION_ID/messages" \
  "$(jq -n --arg c "$USER_TEXT" '{role: "user", content: $c}')" > /dev/null

# 2. Build a SIP.
SIP=$(edn_post "/sip/build" \
  "$(jq -n --arg q "$USER_TEXT" --arg s "$EDN_SESSION_ID" '{query: $q, session_id: $s}' | with_project)" \
  | jq -r '.sip')

# 3. Call your model.
REPLY=$(curl -s https://api.openai.com/v1/chat/completions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d "$(jq -n --arg sip "$SIP" --arg u "$USER_TEXT" '{
        model: "gpt-4o",
        messages: [
          {role: "system", content: ("Use this memory to answer the user.\n\n" + $sip)},
          {role: "user", content: $u}
        ]
      }')" \
  | jq -r '.choices[0].message.content')
echo "$REPLY"

# 4. Save the exchange.
edn_post "/memory/ingest" \
  "$(jq -n --arg u "$USER_TEXT" --arg a "$REPLY" --arg s "$EDN_SESSION_ID" \
      '{user_message: $u, assistant_message: $a, session_id: $s}' | with_project)" > /dev/null

# 5. Classify the reply.
PROVENANCE=$(edn_post "/memory/infer" \
  "$(jq -n --arg u "$USER_TEXT" --arg a "$REPLY" --arg s "$EDN_SESSION_ID" --arg sip "$SIP" \
      '{user_message: $u, assistant_message: $a, session_id: $s, sip: $sip}' | with_project)" \
  | jq -r '.provenance')

# 6. Save a generated statement, when applicable.
if [ "$PROVENANCE" = "AI_GENERATED" ]; then
  edn_post "/memory/generated" \
    "$(jq -n --arg a "$REPLY" --arg s "$EDN_SESSION_ID" \
        '{assistant_message: $a, session_id: $s}' | with_project)" > /dev/null
fi

# 7. Save the AI response to the session.
edn_post "/sessions/$EDN_SESSION_ID/messages" \
  "$(jq -n --arg c "$REPLY" '{role: "assistant", content: $c}')" > /dev/null
```

```python Python theme={"theme":"github-light"}
"""One exchange of the memory loop.

EDN_API_KEY and EDN_SESSION_ID: see the Quickstart. OPENAI_API_KEY: your model key.
EDN_PROJECT_ID: optional; leave it unset to use general memory.
"""

import os

import requests
from openai import OpenAI

EDN = "https://api.tensorpro.ai/api/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['EDN_API_KEY']}"}
session_id = os.environ["EDN_SESSION_ID"]
project_id = os.environ.get("EDN_PROJECT_ID")
user_text = "Who manages the website project?"


def edn_post(path: str, payload: dict) -> dict:
    resp = requests.post(f"{EDN}{path}", headers=HEADERS, json=payload)
    resp.raise_for_status()
    return resp.json()


# 1. Save the user's message to the session.
edn_post(f"/sessions/{session_id}/messages", {"role": "user", "content": user_text})

# 2. Build a SIP.
sip = edn_post(
    "/sip/build",
    {"query": user_text, "session_id": session_id, "project_id": project_id},
)["sip"]

# 3. Call your model.
client = OpenAI()  # reads OPENAI_API_KEY
completion = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": f"Use this memory to answer the user.\n\n{sip}"},
        {"role": "user", "content": user_text},
    ],
)
reply = completion.choices[0].message.content
print(reply)

# 4. Save the exchange.
edn_post(
    "/memory/ingest",
    {
        "user_message": user_text,
        "assistant_message": reply,
        "session_id": session_id,
        "project_id": project_id,
    },
)

# 5. Classify the reply.
classified = edn_post(
    "/memory/infer",
    {
        "user_message": user_text,
        "assistant_message": reply,
        "session_id": session_id,
        "sip": sip,
        "project_id": project_id,
    },
)

# 6. Save a generated statement, when applicable.
if classified["provenance"] == "AI_GENERATED":
    edn_post(
        "/memory/generated",
        {"assistant_message": reply, "session_id": session_id, "project_id": project_id},
    )

# 7. Save the AI response to the session.
edn_post(f"/sessions/{session_id}/messages", {"role": "assistant", "content": reply})
```

```typescript TypeScript theme={"theme":"github-light"}
// One exchange of the memory loop.
// EDN_API_KEY and EDN_SESSION_ID: see the Quickstart. OPENAI_API_KEY: your model key.
// EDN_PROJECT_ID: optional; leave it unset to use general memory.
import OpenAI from "openai";

const loopBaseUrl = "https://api.tensorpro.ai/api/v1";
const loopHeaders = {
  Authorization: `Bearer ${process.env.EDN_API_KEY}`,
  "Content-Type": "application/json",
};
const loopSessionId = process.env.EDN_SESSION_ID;
const loopProjectId = process.env.EDN_PROJECT_ID ?? null;
const loopUserText = "Who manages the website project?";

const ednPost = async (path: string, payload: object) => {
  const res = await fetch(`${loopBaseUrl}${path}`, {
    method: "POST",
    headers: loopHeaders,
    body: JSON.stringify(payload),
  });
  if (!res.ok) throw new Error(`${path}: ${res.status}`);
  return res.json();
};

// 1. Save the user's message to the session.
await ednPost(`/sessions/${loopSessionId}/messages`, { role: "user", content: loopUserText });

// 2. Build a SIP.
const loopSipBody = await ednPost("/sip/build", {
  query: loopUserText,
  session_id: loopSessionId,
  project_id: loopProjectId,
});
const loopSip = loopSipBody.sip;

// 3. Call your model.
const loopClient = new OpenAI(); // reads OPENAI_API_KEY
const loopCompletion = await loopClient.chat.completions.create({
  model: "gpt-4o",
  messages: [
    { role: "system", content: `Use this memory to answer the user.\n\n${loopSip}` },
    { role: "user", content: loopUserText },
  ],
});
const loopReply = loopCompletion.choices[0].message.content ?? "";
console.log(loopReply);

// 4. Save the exchange.
await ednPost("/memory/ingest", {
  user_message: loopUserText,
  assistant_message: loopReply,
  session_id: loopSessionId,
  project_id: loopProjectId,
});

// 5. Classify the reply.
const loopClassified = await ednPost("/memory/infer", {
  user_message: loopUserText,
  assistant_message: loopReply,
  session_id: loopSessionId,
  sip: loopSip,
  project_id: loopProjectId,
});

// 6. Save a generated statement, when applicable.
if (loopClassified.provenance === "AI_GENERATED") {
  await ednPost("/memory/generated", {
    assistant_message: loopReply,
    session_id: loopSessionId,
    project_id: loopProjectId,
  });
}

// 7. Save the AI response to the session.
await ednPost(`/sessions/${loopSessionId}/messages`, { role: "assistant", content: loopReply });
```

***

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


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