llama-index-memory-pastdotdev 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,12 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.py[cod]
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ .coverage
7
+ coverage.xml
8
+ htmlcov/
9
+ dist/
10
+ build/
11
+ *.egg-info/
12
+ .DS_Store
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 past.dev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,130 @@
1
+ Metadata-Version: 2.5
2
+ Name: llama-index-memory-pastdotdev
3
+ Version: 0.1.0
4
+ Summary: past dev memory block for LlamaIndex agents: recall and ingest long-term memory with the past dev Memory API
5
+ Project-URL: Homepage, https://past.dev
6
+ Project-URL: Documentation, https://past.dev/docs/memory-api/quickstart
7
+ Project-URL: API reference, https://past.dev/docs/memory-api/api-reference
8
+ Project-URL: Repository, https://github.com/pastdotdev/llama-index-pastdotdev
9
+ Author-email: "past.dev" <louis@past.dev>
10
+ Maintainer-email: "past.dev" <louis@past.dev>
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ Keywords: agent memory,llama-index,llamaindex,long-term memory,memory,past dev,past.dev
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Requires-Python: <4.0,>=3.10
19
+ Requires-Dist: httpx<1,>=0.27
20
+ Requires-Dist: llama-index-core<0.15,>=0.13.0
21
+ Description-Content-Type: text/markdown
22
+
23
+ # LlamaIndex Memory Integration: past dev
24
+
25
+ past dev is a memory API for AI agents. This package gives a LlamaIndex agent
26
+ long-term memory in [past dev](https://past.dev), as a memory block for the
27
+ LlamaIndex `Memory` class.
28
+
29
+ - **Get:** the block does a past dev **Recall**. The query is the latest user
30
+ message. The recalled memory goes into the system message, with the date,
31
+ the kind and the quoted evidence of each entry.
32
+ - **Put:** when the `Memory` flushes old messages from its short-term queue,
33
+ the block does a past dev **Ingest** of the user and assistant text, as one
34
+ data point.
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ pip install llama-index-memory-pastdotdev
40
+ ```
41
+
42
+ ## Get a key
43
+
44
+ 1. Sign up at [past.dev](https://past.dev) and open a project.
45
+ 2. Make a project API key. It starts with `past_sk_`.
46
+ 3. Set it in the environment as `PAST_API_KEY`, or give it to the block as `api_key`.
47
+
48
+ ## Use
49
+
50
+ ```python
51
+ from llama_index.core.agent.workflow import FunctionAgent
52
+ from llama_index.core.memory import Memory
53
+ from llama_index.llms.openai import OpenAI
54
+ from llama_index.memory.pastdotdev import PastDevMemoryBlock
55
+
56
+ memory = Memory.from_defaults(
57
+ session_id="session-42",
58
+ token_limit=30000,
59
+ memory_blocks=[
60
+ PastDevMemoryBlock(
61
+ identity=current_user.id, # your id for the end user, from your own user record
62
+ )
63
+ ],
64
+ )
65
+
66
+ agent = FunctionAgent(tools=[], llm=OpenAI(model="gpt-4.1-mini"))
67
+ response = await agent.run("How should you contact me?", memory=memory)
68
+ ```
69
+
70
+ ### The identity
71
+
72
+ past dev keeps memory per identity: your id for the end user. Recall needs an
73
+ identity, and the first ingest for an identity creates it.
74
+
75
+ Set `identity` in your code, from your trigger or your user record. Do not let
76
+ the model choose it. The block has no tool and no prompt that can change the
77
+ identity, so each user reads and writes only their own memory.
78
+
79
+ ## Parameters
80
+
81
+ | Parameter | Default | Description |
82
+ | --- | --- | --- |
83
+ | `identity` | (required) | Your id for the end user. |
84
+ | `api_key` | `PAST_API_KEY` | A past dev project API key (`past_sk_...`). |
85
+ | `api_host` | `PAST_API_HOST`, else `https://api.past.dev` | The API base URL. Change it only if you run past dev in your own cloud. |
86
+ | `audience` | none | The audience slug for ingested memory. Without it, the memory is visible to the project. |
87
+ | `level` | `low` (on the server) | The recall evidence budget: `low`, `medium`, `high` or `extra-high`. |
88
+ | `max_tokens` | none | An explicit recall evidence budget in tokens. Use `level` or `max_tokens`, not both. |
89
+ | `limit` | 100 (on the server) | The maximum number of recalled documents. |
90
+ | `label` | `LlamaIndex chat` | The label of each ingested data point. |
91
+ | `name` | `past_dev_memory` | The name of the block in the memory template. |
92
+ | `priority` | `0` | The `BaseMemoryBlock` truncation priority. `0` means never truncate. |
93
+ | `raise_on_error` | `True` | When `False`, the block logs an API error and continues without memory. |
94
+
95
+ ## What the block sends
96
+
97
+ - **Recall** (`POST /api/v1/recall`): `query` (the latest user message),
98
+ `identity`, and `level`, `maxTokens` or `limit` if you set them.
99
+ - **Ingest** (`POST /api/v1/ingest`): `content` (the flushed user and assistant
100
+ messages as `role: text` lines; system and tool messages are not sent),
101
+ `identity`, `timestamp`, `label`, `audience` if you set it, and `metadata`
102
+ with `{"source": "llama-index", "sessionId": ...}`.
103
+
104
+ The `timestamp` is the `timestamp` of the first flushed message, if your
105
+ application puts one in `message.additional_kwargs["timestamp"]`. Otherwise it
106
+ is the time of the flush.
107
+
108
+ ## Credits
109
+
110
+ Each recall and each ingest spends credits on your past dev plan. The block
111
+ recalls once each time the agent reads its memory, and ingests once each time
112
+ the `Memory` flushes messages.
113
+
114
+ ## Errors
115
+
116
+ An API error raises `PastDevError`, with the error `code`, the HTTP `status`,
117
+ the message and the `X-Request-Id` of the request. The block retries a `429`
118
+ once, after its `Retry-After` delay. It does not retry other errors, for
119
+ example `402 out-of-credits` or a `400`.
120
+
121
+ ## Links
122
+
123
+ - [Quickstart](https://past.dev/docs/memory-api/quickstart)
124
+ - [API reference](https://past.dev/docs/memory-api/api-reference)
125
+ - [LlamaIndex memory guide](https://developers.llamaindex.ai/python/framework/module_guides/deploying/agents/memory/)
126
+ - Tools for the same API: [`llama-index-tools-pastdotdev`](https://pypi.org/project/llama-index-tools-pastdotdev/)
127
+
128
+ ## License
129
+
130
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,108 @@
1
+ # LlamaIndex Memory Integration: past dev
2
+
3
+ past dev is a memory API for AI agents. This package gives a LlamaIndex agent
4
+ long-term memory in [past dev](https://past.dev), as a memory block for the
5
+ LlamaIndex `Memory` class.
6
+
7
+ - **Get:** the block does a past dev **Recall**. The query is the latest user
8
+ message. The recalled memory goes into the system message, with the date,
9
+ the kind and the quoted evidence of each entry.
10
+ - **Put:** when the `Memory` flushes old messages from its short-term queue,
11
+ the block does a past dev **Ingest** of the user and assistant text, as one
12
+ data point.
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ pip install llama-index-memory-pastdotdev
18
+ ```
19
+
20
+ ## Get a key
21
+
22
+ 1. Sign up at [past.dev](https://past.dev) and open a project.
23
+ 2. Make a project API key. It starts with `past_sk_`.
24
+ 3. Set it in the environment as `PAST_API_KEY`, or give it to the block as `api_key`.
25
+
26
+ ## Use
27
+
28
+ ```python
29
+ from llama_index.core.agent.workflow import FunctionAgent
30
+ from llama_index.core.memory import Memory
31
+ from llama_index.llms.openai import OpenAI
32
+ from llama_index.memory.pastdotdev import PastDevMemoryBlock
33
+
34
+ memory = Memory.from_defaults(
35
+ session_id="session-42",
36
+ token_limit=30000,
37
+ memory_blocks=[
38
+ PastDevMemoryBlock(
39
+ identity=current_user.id, # your id for the end user, from your own user record
40
+ )
41
+ ],
42
+ )
43
+
44
+ agent = FunctionAgent(tools=[], llm=OpenAI(model="gpt-4.1-mini"))
45
+ response = await agent.run("How should you contact me?", memory=memory)
46
+ ```
47
+
48
+ ### The identity
49
+
50
+ past dev keeps memory per identity: your id for the end user. Recall needs an
51
+ identity, and the first ingest for an identity creates it.
52
+
53
+ Set `identity` in your code, from your trigger or your user record. Do not let
54
+ the model choose it. The block has no tool and no prompt that can change the
55
+ identity, so each user reads and writes only their own memory.
56
+
57
+ ## Parameters
58
+
59
+ | Parameter | Default | Description |
60
+ | --- | --- | --- |
61
+ | `identity` | (required) | Your id for the end user. |
62
+ | `api_key` | `PAST_API_KEY` | A past dev project API key (`past_sk_...`). |
63
+ | `api_host` | `PAST_API_HOST`, else `https://api.past.dev` | The API base URL. Change it only if you run past dev in your own cloud. |
64
+ | `audience` | none | The audience slug for ingested memory. Without it, the memory is visible to the project. |
65
+ | `level` | `low` (on the server) | The recall evidence budget: `low`, `medium`, `high` or `extra-high`. |
66
+ | `max_tokens` | none | An explicit recall evidence budget in tokens. Use `level` or `max_tokens`, not both. |
67
+ | `limit` | 100 (on the server) | The maximum number of recalled documents. |
68
+ | `label` | `LlamaIndex chat` | The label of each ingested data point. |
69
+ | `name` | `past_dev_memory` | The name of the block in the memory template. |
70
+ | `priority` | `0` | The `BaseMemoryBlock` truncation priority. `0` means never truncate. |
71
+ | `raise_on_error` | `True` | When `False`, the block logs an API error and continues without memory. |
72
+
73
+ ## What the block sends
74
+
75
+ - **Recall** (`POST /api/v1/recall`): `query` (the latest user message),
76
+ `identity`, and `level`, `maxTokens` or `limit` if you set them.
77
+ - **Ingest** (`POST /api/v1/ingest`): `content` (the flushed user and assistant
78
+ messages as `role: text` lines; system and tool messages are not sent),
79
+ `identity`, `timestamp`, `label`, `audience` if you set it, and `metadata`
80
+ with `{"source": "llama-index", "sessionId": ...}`.
81
+
82
+ The `timestamp` is the `timestamp` of the first flushed message, if your
83
+ application puts one in `message.additional_kwargs["timestamp"]`. Otherwise it
84
+ is the time of the flush.
85
+
86
+ ## Credits
87
+
88
+ Each recall and each ingest spends credits on your past dev plan. The block
89
+ recalls once each time the agent reads its memory, and ingests once each time
90
+ the `Memory` flushes messages.
91
+
92
+ ## Errors
93
+
94
+ An API error raises `PastDevError`, with the error `code`, the HTTP `status`,
95
+ the message and the `X-Request-Id` of the request. The block retries a `429`
96
+ once, after its `Retry-After` delay. It does not retry other errors, for
97
+ example `402 out-of-credits` or a `400`.
98
+
99
+ ## Links
100
+
101
+ - [Quickstart](https://past.dev/docs/memory-api/quickstart)
102
+ - [API reference](https://past.dev/docs/memory-api/api-reference)
103
+ - [LlamaIndex memory guide](https://developers.llamaindex.ai/python/framework/module_guides/deploying/agents/memory/)
104
+ - Tools for the same API: [`llama-index-tools-pastdotdev`](https://pypi.org/project/llama-index-tools-pastdotdev/)
105
+
106
+ ## License
107
+
108
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,4 @@
1
+ from llama_index.memory.pastdotdev.base import PastDevMemoryBlock
2
+ from llama_index.memory.pastdotdev.client import PastDevError
3
+
4
+ __all__ = ["PastDevMemoryBlock", "PastDevError"]
@@ -0,0 +1,180 @@
1
+ """past dev memory block for the LlamaIndex Memory class."""
2
+
3
+ import logging
4
+ from datetime import datetime
5
+ from typing import Any, Dict, List, Literal, Optional
6
+
7
+ import httpx
8
+ from llama_index.core.base.llms.types import ChatMessage, MessageRole
9
+ from llama_index.core.bridge.pydantic import Field, PrivateAttr, model_validator
10
+ from llama_index.core.memory.memory import BaseMemoryBlock
11
+
12
+ from llama_index.memory.pastdotdev.client import (
13
+ DEFAULT_API_HOST,
14
+ AsyncPastDevClient,
15
+ PastDevError,
16
+ format_recall_results,
17
+ now_iso,
18
+ resolve_api_key,
19
+ to_iso,
20
+ )
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+ __version__ = "0.1.0"
25
+
26
+ DEFAULT_NAME = "past_dev_memory"
27
+ DEFAULT_DESCRIPTION = (
28
+ "Long-term memory recalled from past dev for the current user. "
29
+ "Each entry has a rank, a date and a kind; evidence lines quote the source."
30
+ )
31
+ DEFAULT_LABEL = "LlamaIndex chat"
32
+ INGESTED_ROLES = (MessageRole.USER, MessageRole.ASSISTANT)
33
+
34
+
35
+ class PastDevMemoryBlock(BaseMemoryBlock[str]):
36
+ """
37
+ A memory block that keeps long-term memory in past dev.
38
+
39
+ On get, it recalls with the latest user message as the query. On put (the
40
+ messages that the Memory flushes from its short-term queue), it ingests the
41
+ user and assistant text as one data point. The identity is fixed when you
42
+ make the block: the model never chooses it.
43
+
44
+ Args:
45
+ identity: Your id for the end user. Recall reads, and ingest writes, as this identity.
46
+ api_key: A past dev project API key (past_sk_...). Defaults to PAST_API_KEY.
47
+ api_host: The API base URL. Defaults to PAST_API_HOST, else https://api.past.dev.
48
+ audience: The audience slug for ingested memory. Omit it for project-visible memory.
49
+ level: The recall evidence budget: low, medium, high or extra-high.
50
+ max_tokens: An explicit recall evidence budget in tokens. Send level or max_tokens, not both.
51
+ limit: The maximum number of recalled documents.
52
+ label: The label of each ingested data point.
53
+ raise_on_error: When False, an API error is logged and the block returns nothing.
54
+
55
+ """
56
+
57
+ name: str = Field(default=DEFAULT_NAME, description="The name of the memory block.")
58
+ description: Optional[str] = Field(default=DEFAULT_DESCRIPTION)
59
+ identity: str = Field(
60
+ description="The end user's id. Fixed by the builder, never by the model."
61
+ )
62
+ api_key: Optional[str] = Field(default=None, exclude=True, repr=False)
63
+ api_host: Optional[str] = Field(
64
+ default=None, description=f"Defaults to PAST_API_HOST, else {DEFAULT_API_HOST}."
65
+ )
66
+ audience: Optional[str] = Field(default=None)
67
+ level: Optional[Literal["low", "medium", "high", "extra-high"]] = Field(default=None)
68
+ max_tokens: Optional[int] = Field(default=None, ge=1)
69
+ limit: Optional[int] = Field(default=None, ge=1, le=200)
70
+ label: str = Field(default=DEFAULT_LABEL)
71
+ timeout: float = Field(default=30.0, gt=0)
72
+ raise_on_error: bool = Field(default=True)
73
+
74
+ _client: AsyncPastDevClient = PrivateAttr()
75
+
76
+ def __init__(self, http_client: Optional[httpx.AsyncClient] = None, **data: Any) -> None:
77
+ super().__init__(**data)
78
+ self._client = AsyncPastDevClient(
79
+ api_key=resolve_api_key(self.api_key),
80
+ api_host=self.api_host,
81
+ timeout=self.timeout,
82
+ user_agent=f"llama-index-memory-pastdotdev/{__version__}",
83
+ http_client=http_client,
84
+ )
85
+
86
+ @model_validator(mode="after")
87
+ def _check(self) -> "PastDevMemoryBlock":
88
+ if not self.identity or not self.identity.strip():
89
+ raise ValueError("identity is required: set it from your user record.")
90
+ if self.level is not None and self.max_tokens is not None:
91
+ raise ValueError("Set level or max_tokens, never both.")
92
+ return self
93
+
94
+ @classmethod
95
+ def class_name(cls) -> str:
96
+ return "PastDevMemoryBlock"
97
+
98
+ async def _aget(self, messages: Optional[List[ChatMessage]] = None, **block_kwargs: Any) -> str:
99
+ query = _latest_user_text(messages or [])
100
+ if not query:
101
+ return ""
102
+ try:
103
+ response = await self._client.recall(
104
+ query=query,
105
+ identity=self.identity,
106
+ limit=self.limit,
107
+ level=self.level,
108
+ max_tokens=self.max_tokens,
109
+ )
110
+ except (PastDevError, httpx.HTTPError) as error:
111
+ if self.raise_on_error:
112
+ raise
113
+ logger.warning("past dev recall failed: %s", error)
114
+ return ""
115
+ return "\n\n".join(format_recall_results(response.get("results") or []))
116
+
117
+ async def _aput(self, messages: List[ChatMessage]) -> None:
118
+ content = _transcript(messages)
119
+ if not content:
120
+ return
121
+ try:
122
+ await self._client.ingest(
123
+ content=content,
124
+ identity=self.identity,
125
+ timestamp=_first_timestamp(messages) or now_iso(),
126
+ audience=self.audience,
127
+ label=self.label,
128
+ metadata=_metadata(messages),
129
+ )
130
+ except (PastDevError, httpx.HTTPError) as error:
131
+ if self.raise_on_error:
132
+ raise
133
+ logger.warning("past dev ingest failed: %s", error)
134
+
135
+ async def atruncate(self, content: str, tokens_to_truncate: int) -> Optional[str]:
136
+ """Drop the lowest-ranked entries until about tokens_to_truncate tokens are gone."""
137
+ entries = content.split("\n\n") if content else []
138
+ to_remove = tokens_to_truncate * 4 # about four characters a token
139
+ while entries and to_remove > 0:
140
+ to_remove -= len(entries.pop()) + 2
141
+ return "\n\n".join(entries) or None
142
+
143
+
144
+ def _text(message: ChatMessage) -> str:
145
+ return (message.content or "").strip()
146
+
147
+
148
+ def _latest_user_text(messages: List[ChatMessage]) -> str:
149
+ for message in reversed(messages):
150
+ if message.role == MessageRole.USER and _text(message):
151
+ return _text(message)
152
+ return ""
153
+
154
+
155
+ def _transcript(messages: List[ChatMessage]) -> str:
156
+ lines = [
157
+ f"{message.role.value}: {_text(message)}"
158
+ for message in messages
159
+ if message.role in INGESTED_ROLES and _text(message)
160
+ ]
161
+ return "\n\n".join(lines)
162
+
163
+
164
+ def _first_timestamp(messages: List[ChatMessage]) -> Optional[str]:
165
+ """Use a timestamp that the application put on a message, if there is one."""
166
+ for message in messages:
167
+ value = message.additional_kwargs.get("timestamp")
168
+ if isinstance(value, (datetime, str)):
169
+ return to_iso(value)
170
+ return None
171
+
172
+
173
+ def _metadata(messages: List[ChatMessage]) -> Dict[str, Any]:
174
+ metadata: Dict[str, Any] = {"source": "llama-index"}
175
+ for message in messages:
176
+ session_id = message.additional_kwargs.get("session_id")
177
+ if isinstance(session_id, str):
178
+ metadata["sessionId"] = session_id
179
+ break
180
+ return metadata
@@ -0,0 +1,311 @@
1
+ """A small HTTP client for the past dev Memory API.
2
+
3
+ This file is the same in llama-index-memory-pastdotdev and
4
+ llama-index-tools-pastdotdev, so that each package installs without the other.
5
+ """
6
+
7
+ import asyncio
8
+ import os
9
+ import time
10
+ from datetime import datetime, timezone
11
+ from typing import Any, Dict, List, Optional
12
+
13
+ import httpx
14
+
15
+ DEFAULT_API_HOST = "https://api.past.dev"
16
+ API_KEY_ENV = "PAST_API_KEY"
17
+ API_HOST_ENV = "PAST_API_HOST"
18
+ RECALL_LEVELS = ("low", "medium", "high", "extra-high")
19
+ RECALL_SORTS = ("relevance", "chronological")
20
+
21
+ # A 429 is retried once, after the Retry-After delay, when that delay is short.
22
+ MAX_RETRY_AFTER_SECONDS = 30.0
23
+
24
+
25
+ class PastDevError(Exception):
26
+ """An error response from the past dev Memory API."""
27
+
28
+ def __init__(
29
+ self,
30
+ code: str,
31
+ status: int,
32
+ message: Optional[str] = None,
33
+ request_id: Optional[str] = None,
34
+ data: Any = None,
35
+ ) -> None:
36
+ self.code = code
37
+ self.status = status
38
+ self.message = message
39
+ self.request_id = request_id
40
+ self.data = data
41
+ text = f"past dev error {code} (HTTP {status})"
42
+ if message:
43
+ text += f": {message}"
44
+ if request_id:
45
+ text += f" [request id {request_id}]"
46
+ super().__init__(text)
47
+
48
+
49
+ def resolve_api_key(api_key: Optional[str]) -> str:
50
+ key = api_key or os.environ.get(API_KEY_ENV)
51
+ if not key:
52
+ raise ValueError(
53
+ "past dev needs a project API key: pass api_key or set the "
54
+ f"{API_KEY_ENV} environment variable."
55
+ )
56
+ return key
57
+
58
+
59
+ def resolve_api_host(api_host: Optional[str]) -> str:
60
+ host = api_host or os.environ.get(API_HOST_ENV) or DEFAULT_API_HOST
61
+ return host.rstrip("/")
62
+
63
+
64
+ def to_iso(value: Any) -> Optional[str]:
65
+ """Return an ISO 8601 string for a datetime or a string, else None."""
66
+ if value is None:
67
+ return None
68
+ if isinstance(value, datetime):
69
+ if value.tzinfo is None:
70
+ value = value.replace(tzinfo=timezone.utc)
71
+ return value.isoformat()
72
+ if isinstance(value, str) and value.strip():
73
+ return value.strip()
74
+ return None
75
+
76
+
77
+ def now_iso() -> str:
78
+ return datetime.now(timezone.utc).isoformat()
79
+
80
+
81
+ def build_recall_body(
82
+ query: str,
83
+ identity: str,
84
+ limit: Optional[int] = None,
85
+ level: Optional[str] = None,
86
+ max_tokens: Optional[int] = None,
87
+ query_timestamp: Optional[str] = None,
88
+ occurred_from: Optional[str] = None,
89
+ occurred_to: Optional[str] = None,
90
+ sort: Optional[str] = None,
91
+ ) -> Dict[str, Any]:
92
+ if level is not None and max_tokens is not None:
93
+ raise ValueError("Send level or max_tokens to recall, never both.")
94
+ if level is not None and level not in RECALL_LEVELS:
95
+ raise ValueError(f"level must be one of {', '.join(RECALL_LEVELS)}.")
96
+ if sort is not None and sort not in RECALL_SORTS:
97
+ raise ValueError(f"sort must be one of {', '.join(RECALL_SORTS)}.")
98
+ body: Dict[str, Any] = {"query": query, "identity": identity}
99
+ optional = {
100
+ "limit": limit,
101
+ "level": level,
102
+ "maxTokens": max_tokens,
103
+ "queryTimestamp": query_timestamp,
104
+ "occurredFrom": occurred_from,
105
+ "occurredTo": occurred_to,
106
+ "sort": sort,
107
+ }
108
+ body.update({key: value for key, value in optional.items() if value is not None})
109
+ return body
110
+
111
+
112
+ def build_ingest_body(
113
+ content: str,
114
+ identity: str,
115
+ timestamp: Optional[str] = None,
116
+ source_id: Optional[str] = None,
117
+ audience: Optional[str] = None,
118
+ label: Optional[str] = None,
119
+ metadata: Any = None,
120
+ idempotency_key: Optional[str] = None,
121
+ ) -> Dict[str, Any]:
122
+ if not content or not content.strip():
123
+ raise ValueError("past dev refuses empty content: send some text to ingest.")
124
+ body: Dict[str, Any] = {"content": content, "identity": identity}
125
+ optional = {
126
+ "timestamp": timestamp,
127
+ "id": source_id,
128
+ "audience": audience,
129
+ "label": label,
130
+ "metadata": metadata,
131
+ "idempotencyKey": idempotency_key,
132
+ }
133
+ body.update({key: value for key, value in optional.items() if value is not None})
134
+ return body
135
+
136
+
137
+ def format_recall(response: Dict[str, Any]) -> str:
138
+ """Render a recall response as plain text for a model to read."""
139
+ results = response.get("results") or []
140
+ return "\n\n".join(format_recall_results(results))
141
+
142
+
143
+ def format_recall_results(results: List[Dict[str, Any]]) -> List[str]:
144
+ rendered = []
145
+ for result in results:
146
+ content = (result.get("content") or "").strip()
147
+ if not content:
148
+ continue
149
+ artifact = result.get("artifact") or {}
150
+ kind = artifact.get("kind") or "memory"
151
+ head = (
152
+ f"[{result.get('rank', len(rendered) + 1)}] {_date(result.get('occurredAt'))} · {kind}"
153
+ )
154
+ superseded = artifact.get("supersededAt")
155
+ if superseded:
156
+ head += f" · superseded {_date(superseded)}"
157
+ lines = [head, content]
158
+ for source in result.get("sources") or []:
159
+ where = source.get("label") or source.get("sourceId") or "source"
160
+ when = _date(source.get("occurredAt"))
161
+ for excerpt in source.get("excerpts") or []:
162
+ lines.append(f' evidence ({where}, {when}): "{excerpt}"')
163
+ rendered.append("\n".join(lines))
164
+ return rendered
165
+
166
+
167
+ def _date(value: Optional[str]) -> str:
168
+ return value[:10] if isinstance(value, str) else "undated"
169
+
170
+
171
+ class _Base:
172
+ def __init__(
173
+ self,
174
+ api_key: Optional[str] = None,
175
+ api_host: Optional[str] = None,
176
+ timeout: float = 30.0,
177
+ user_agent: str = "llama-index-pastdotdev",
178
+ ) -> None:
179
+ self.api_host = resolve_api_host(api_host)
180
+ self._headers = {
181
+ "Authorization": f"Bearer {resolve_api_key(api_key)}",
182
+ "Accept": "application/json",
183
+ "User-Agent": user_agent,
184
+ }
185
+ self.timeout = timeout
186
+
187
+ def _url(self, path: str) -> str:
188
+ return f"{self.api_host}{path}"
189
+
190
+ @staticmethod
191
+ def _retry_delay(response: httpx.Response) -> Optional[float]:
192
+ if response.status_code != 429:
193
+ return None
194
+ header = response.headers.get("Retry-After", "1")
195
+ try:
196
+ delay = float(header)
197
+ except ValueError:
198
+ return None
199
+ return delay if 0 <= delay <= MAX_RETRY_AFTER_SECONDS else None
200
+
201
+ @staticmethod
202
+ def _result(response: httpx.Response) -> Any:
203
+ if response.is_success:
204
+ return response.json() if response.content else None
205
+ request_id = response.headers.get("X-Request-Id")
206
+ try:
207
+ body = response.json()
208
+ except ValueError:
209
+ body = None
210
+ if isinstance(body, dict) and body.get("code"):
211
+ raise PastDevError(
212
+ code=str(body["code"]),
213
+ status=int(body.get("status") or response.status_code),
214
+ message=body.get("debugMessage"),
215
+ request_id=request_id,
216
+ data=body.get("data"),
217
+ )
218
+ raise PastDevError(
219
+ code="http-error",
220
+ status=response.status_code,
221
+ message=response.text[:200] or None,
222
+ request_id=request_id,
223
+ )
224
+
225
+
226
+ class PastDevClient(_Base):
227
+ """Synchronous client."""
228
+
229
+ def __init__(
230
+ self, *args: Any, http_client: Optional[httpx.Client] = None, **kwargs: Any
231
+ ) -> None:
232
+ super().__init__(*args, **kwargs)
233
+ self._http = http_client or httpx.Client(timeout=self.timeout)
234
+
235
+ def request(self, method: str, path: str, json: Any = None, params: Any = None) -> Any:
236
+ for attempt in range(2):
237
+ response = self._http.request(
238
+ method, self._url(path), json=json, params=params, headers=self._headers
239
+ )
240
+ delay = self._retry_delay(response)
241
+ if delay is None or attempt == 1:
242
+ return self._result(response)
243
+ time.sleep(delay)
244
+ return None # pragma: no cover
245
+
246
+ def ingest(self, **kwargs: Any) -> Dict[str, Any]:
247
+ return self.request("POST", "/api/v1/ingest", json=build_ingest_body(**kwargs))
248
+
249
+ def recall(self, **kwargs: Any) -> Dict[str, Any]:
250
+ return self.request("POST", "/api/v1/recall", json=build_recall_body(**kwargs))
251
+
252
+ def delete_data_point(self, source_id: str) -> Dict[str, Any]:
253
+ return self.request("DELETE", f"/api/v1/data-points/{_path(source_id)}")
254
+
255
+ def list_audiences(self) -> Dict[str, Any]:
256
+ """List the project's audiences. It costs no credits, so it also tests a key."""
257
+ return self.request("GET", "/api/v1/audiences")
258
+
259
+ def list_identities(self, after: Optional[str] = None) -> Dict[str, Any]:
260
+ return self.request("GET", "/api/v1/identities", params={"after": after} if after else None)
261
+
262
+ def close(self) -> None:
263
+ self._http.close()
264
+
265
+
266
+ class AsyncPastDevClient(_Base):
267
+ """Asynchronous client."""
268
+
269
+ def __init__(
270
+ self, *args: Any, http_client: Optional[httpx.AsyncClient] = None, **kwargs: Any
271
+ ) -> None:
272
+ super().__init__(*args, **kwargs)
273
+ self._http = http_client or httpx.AsyncClient(timeout=self.timeout)
274
+
275
+ async def request(self, method: str, path: str, json: Any = None, params: Any = None) -> Any:
276
+ for attempt in range(2):
277
+ response = await self._http.request(
278
+ method, self._url(path), json=json, params=params, headers=self._headers
279
+ )
280
+ delay = self._retry_delay(response)
281
+ if delay is None or attempt == 1:
282
+ return self._result(response)
283
+ await asyncio.sleep(delay)
284
+ return None # pragma: no cover
285
+
286
+ async def ingest(self, **kwargs: Any) -> Dict[str, Any]:
287
+ return await self.request("POST", "/api/v1/ingest", json=build_ingest_body(**kwargs))
288
+
289
+ async def recall(self, **kwargs: Any) -> Dict[str, Any]:
290
+ return await self.request("POST", "/api/v1/recall", json=build_recall_body(**kwargs))
291
+
292
+ async def delete_data_point(self, source_id: str) -> Dict[str, Any]:
293
+ return await self.request("DELETE", f"/api/v1/data-points/{_path(source_id)}")
294
+
295
+ async def list_audiences(self) -> Dict[str, Any]:
296
+ """List the project's audiences. It costs no credits, so it also tests a key."""
297
+ return await self.request("GET", "/api/v1/audiences")
298
+
299
+ async def list_identities(self, after: Optional[str] = None) -> Dict[str, Any]:
300
+ return await self.request(
301
+ "GET", "/api/v1/identities", params={"after": after} if after else None
302
+ )
303
+
304
+ async def aclose(self) -> None:
305
+ await self._http.aclose()
306
+
307
+
308
+ def _path(segment: str) -> str:
309
+ from urllib.parse import quote
310
+
311
+ return quote(segment, safe="")
@@ -0,0 +1,65 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [dependency-groups]
6
+ dev = [
7
+ "pytest>=8",
8
+ "pytest-asyncio>=0.23",
9
+ "pytest-cov>=6.1.1",
10
+ "ruff>=0.11",
11
+ ]
12
+
13
+ [project]
14
+ name = "llama-index-memory-pastdotdev"
15
+ version = "0.1.0"
16
+ description = "past dev memory block for LlamaIndex agents: recall and ingest long-term memory with the past dev Memory API"
17
+ authors = [{name = "past.dev", email = "louis@past.dev"}]
18
+ maintainers = [{name = "past.dev", email = "louis@past.dev"}]
19
+ requires-python = ">=3.10,<4.0"
20
+ readme = "README.md"
21
+ license = "MIT"
22
+ license-files = ["LICENSE"]
23
+ keywords = ["llama-index", "llamaindex", "past dev", "past.dev", "memory", "agent memory", "long-term memory"]
24
+ classifiers = [
25
+ "Development Status :: 4 - Beta",
26
+ "Intended Audience :: Developers",
27
+ "Programming Language :: Python :: 3",
28
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
29
+ ]
30
+ dependencies = [
31
+ "llama-index-core>=0.13.0,<0.15",
32
+ "httpx>=0.27,<1",
33
+ ]
34
+
35
+ [project.urls]
36
+ Homepage = "https://past.dev"
37
+ Documentation = "https://past.dev/docs/memory-api/quickstart"
38
+ "API reference" = "https://past.dev/docs/memory-api/api-reference"
39
+ Repository = "https://github.com/pastdotdev/llama-index-pastdotdev"
40
+
41
+ [tool.hatch.build.targets.sdist]
42
+ include = ["llama_index/", "tests/", "README.md", "LICENSE"]
43
+
44
+ [tool.hatch.build.targets.wheel]
45
+ include = ["llama_index/"]
46
+
47
+ [tool.llamahub]
48
+ contains_example = false
49
+ import_path = "llama_index.memory.pastdotdev"
50
+
51
+ [tool.llamahub.class_authors]
52
+ PastDevMemoryBlock = "pastdotdev"
53
+
54
+ [tool.pytest.ini_options]
55
+ asyncio_mode = "auto"
56
+ markers = ["live: calls the real past dev API; skipped unless PAST_API_KEY is set"]
57
+
58
+ [tool.ruff]
59
+ line-length = 100
60
+ target-version = "py310"
61
+
62
+ [tool.ruff.lint]
63
+ select = ["E", "F", "I", "B"]
64
+ # The formatter wraps code; long lines left are docstrings, which the model reads.
65
+ ignore = ["E501"]
File without changes
@@ -0,0 +1,78 @@
1
+ import json
2
+ from typing import List
3
+
4
+ import httpx
5
+ import pytest
6
+
7
+ from llama_index.memory.pastdotdev.client import (
8
+ AsyncPastDevClient,
9
+ PastDevClient,
10
+ build_recall_body,
11
+ )
12
+
13
+
14
+ def recorder(requests: List[httpx.Request]) -> httpx.MockTransport:
15
+ def handler(request: httpx.Request) -> httpx.Response:
16
+ requests.append(request)
17
+ if request.method == "DELETE":
18
+ return httpx.Response(202, json={"operationId": "op-1", "ids": ["chat/1"]})
19
+ if request.url.path == "/api/v1/identities":
20
+ return httpx.Response(200, json={"identities": [], "hasMore": False, "endCursor": None})
21
+ return httpx.Response(200, json={"audiences": []})
22
+
23
+ return httpx.MockTransport(handler)
24
+
25
+
26
+ def test_sync_client_paths() -> None:
27
+ requests: List[httpx.Request] = []
28
+ client = PastDevClient(
29
+ api_key="past_sk_test", http_client=httpx.Client(transport=recorder(requests))
30
+ )
31
+ assert client.delete_data_point("chat/1")["ids"] == ["chat/1"]
32
+ assert client.list_audiences() == {"audiences": []}
33
+ assert client.list_identities(after="cursor-1")["hasMore"] is False
34
+ client.close()
35
+ assert [(r.method, r.url.raw_path.decode()) for r in requests] == [
36
+ ("DELETE", "/api/v1/data-points/chat%2F1"),
37
+ ("GET", "/api/v1/audiences"),
38
+ ("GET", "/api/v1/identities?after=cursor-1"),
39
+ ]
40
+
41
+
42
+ async def test_async_client_paths() -> None:
43
+ requests: List[httpx.Request] = []
44
+ client = AsyncPastDevClient(
45
+ api_key="past_sk_test", http_client=httpx.AsyncClient(transport=recorder(requests))
46
+ )
47
+ await client.delete_data_point("chat/1")
48
+ await client.list_audiences()
49
+ await client.list_identities()
50
+ await client.aclose()
51
+ assert [(r.method, r.url.raw_path.decode()) for r in requests] == [
52
+ ("DELETE", "/api/v1/data-points/chat%2F1"),
53
+ ("GET", "/api/v1/audiences"),
54
+ ("GET", "/api/v1/identities"),
55
+ ]
56
+
57
+
58
+ def test_recall_body_uses_api_keys() -> None:
59
+ body = build_recall_body(
60
+ query="q",
61
+ identity="u",
62
+ max_tokens=500,
63
+ query_timestamp="2026-10-01T00:00:00Z",
64
+ occurred_to="2026-09-01T00:00:00Z",
65
+ sort="chronological",
66
+ )
67
+ assert json.loads(json.dumps(body)) == {
68
+ "query": "q",
69
+ "identity": "u",
70
+ "maxTokens": 500,
71
+ "queryTimestamp": "2026-10-01T00:00:00Z",
72
+ "occurredTo": "2026-09-01T00:00:00Z",
73
+ "sort": "chronological",
74
+ }
75
+ with pytest.raises(ValueError):
76
+ build_recall_body(query="q", identity="u", level="huge")
77
+ with pytest.raises(ValueError):
78
+ build_recall_body(query="q", identity="u", sort="random")
@@ -0,0 +1,34 @@
1
+ """One smoke test against the real past dev API.
2
+
3
+ It is skipped unless PAST_API_KEY is set. It spends a few credits: one ingest and one recall.
4
+ """
5
+
6
+ import os
7
+
8
+ import pytest
9
+ from llama_index.core.base.llms.types import ChatMessage, MessageRole
10
+
11
+ from llama_index.memory.pastdotdev import PastDevMemoryBlock
12
+
13
+ pytestmark = [
14
+ pytest.mark.live,
15
+ pytest.mark.skipif(not os.environ.get("PAST_API_KEY"), reason="PAST_API_KEY is not set"),
16
+ ]
17
+
18
+
19
+ async def test_live_put_and_get() -> None:
20
+ block = PastDevMemoryBlock(identity="llama-index-smoke-test", label="LlamaIndex smoke test")
21
+ # The connection test: listing audiences costs no credits.
22
+ audiences = await block._client.list_audiences()
23
+ assert isinstance(audiences["audiences"], list)
24
+
25
+ await block.aput(
26
+ [
27
+ ChatMessage(role=MessageRole.USER, content="My favourite colour is teal."),
28
+ ChatMessage(role=MessageRole.ASSISTANT, content="Noted: teal."),
29
+ ]
30
+ )
31
+ content = await block.aget(
32
+ [ChatMessage(role=MessageRole.USER, content="What is my favourite colour?")]
33
+ )
34
+ assert isinstance(content, str)
@@ -0,0 +1,302 @@
1
+ import json
2
+ from typing import Any, Callable, Dict, List
3
+
4
+ import httpx
5
+ import pytest
6
+ from llama_index.core.base.llms.types import ChatMessage, MessageRole
7
+ from llama_index.core.memory import Memory
8
+ from llama_index.core.memory.memory import BaseMemoryBlock
9
+
10
+ from llama_index.memory.pastdotdev import PastDevError, PastDevMemoryBlock
11
+
12
+ KEY = "past_sk_test"
13
+
14
+ RECALL_RESPONSE = {
15
+ "asOf": "2026-10-16T12:00:00Z",
16
+ "usedEvidenceTokens": 42,
17
+ "results": [
18
+ {
19
+ "id": "7f1c3a4e-0000-4000-8000-000000000001",
20
+ "rank": 1,
21
+ "occurredAt": "2026-10-01T09:00:00Z",
22
+ "content": "Ada prefers email to phone calls.",
23
+ "artifact": {
24
+ "id": "7f1c3a4e-0000-4000-8000-000000000001",
25
+ "kind": "observation",
26
+ "occurredAt": "2026-10-01T09:00:00Z",
27
+ },
28
+ "sources": [
29
+ {
30
+ "sourceId": "chat-1",
31
+ "occurredAt": "2026-10-01T09:00:00Z",
32
+ "label": "Support chat",
33
+ "excerpts": ["please email me, never call"],
34
+ }
35
+ ],
36
+ },
37
+ {
38
+ "id": "7f1c3a4e-0000-4000-8000-000000000002",
39
+ "rank": 2,
40
+ "occurredAt": "2026-09-01T09:00:00Z",
41
+ "content": "Ada lives in Lyon.",
42
+ "artifact": {
43
+ "id": "7f1c3a4e-0000-4000-8000-000000000002",
44
+ "kind": "claim",
45
+ "occurredAt": "2026-09-01T09:00:00Z",
46
+ "supersededAt": "2026-10-02T09:00:00Z",
47
+ },
48
+ "sources": [],
49
+ },
50
+ ],
51
+ }
52
+
53
+ INGEST_RESPONSE = {
54
+ "projectId": 1,
55
+ "ingestionId": "7f1c3a4e-0000-4000-8000-0000000000aa",
56
+ "sourceId": "abc",
57
+ "status": "queued",
58
+ }
59
+
60
+
61
+ class FakeApi:
62
+ """Records each request and answers with a handler."""
63
+
64
+ def __init__(self, handler: Callable[[httpx.Request], httpx.Response]) -> None:
65
+ self.handler = handler
66
+ self.requests: List[httpx.Request] = []
67
+
68
+ def __call__(self, request: httpx.Request) -> httpx.Response:
69
+ self.requests.append(request)
70
+ return self.handler(request)
71
+
72
+ def bodies(self, path: str) -> List[Dict[str, Any]]:
73
+ return [json.loads(r.content) for r in self.requests if r.url.path == path]
74
+
75
+
76
+ def default_handler(request: httpx.Request) -> httpx.Response:
77
+ if request.url.path == "/api/v1/recall":
78
+ return httpx.Response(200, json=RECALL_RESPONSE)
79
+ if request.url.path == "/api/v1/ingest":
80
+ return httpx.Response(202, json=INGEST_RESPONSE)
81
+ return httpx.Response(404, json={"code": "not-found", "status": 404})
82
+
83
+
84
+ def make_block(api: FakeApi, **kwargs: Any) -> PastDevMemoryBlock:
85
+ kwargs.setdefault("api_key", KEY)
86
+ kwargs.setdefault("identity", "user-ada")
87
+ return PastDevMemoryBlock(
88
+ http_client=httpx.AsyncClient(transport=httpx.MockTransport(api)), **kwargs
89
+ )
90
+
91
+
92
+ def test_is_a_memory_block() -> None:
93
+ names = [b.__name__ for b in PastDevMemoryBlock.__mro__]
94
+ assert BaseMemoryBlock.__name__ in names
95
+
96
+
97
+ def test_requires_identity() -> None:
98
+ with pytest.raises(ValueError):
99
+ make_block(FakeApi(default_handler), identity=" ")
100
+
101
+
102
+ def test_requires_api_key(monkeypatch: pytest.MonkeyPatch) -> None:
103
+ monkeypatch.delenv("PAST_API_KEY", raising=False)
104
+ with pytest.raises(ValueError, match="PAST_API_KEY"):
105
+ PastDevMemoryBlock(identity="user-ada")
106
+
107
+
108
+ def test_reads_key_and_host_from_environment(monkeypatch: pytest.MonkeyPatch) -> None:
109
+ monkeypatch.setenv("PAST_API_KEY", "past_sk_from_env")
110
+ monkeypatch.setenv("PAST_API_HOST", "https://memory.example.com/")
111
+ api = FakeApi(default_handler)
112
+ block = PastDevMemoryBlock(
113
+ identity="user-ada", http_client=httpx.AsyncClient(transport=httpx.MockTransport(api))
114
+ )
115
+ assert block._client.api_host == "https://memory.example.com"
116
+
117
+
118
+ def test_refuses_level_and_max_tokens_together() -> None:
119
+ with pytest.raises(ValueError):
120
+ make_block(FakeApi(default_handler), level="high", max_tokens=1000)
121
+
122
+
123
+ def test_api_key_is_not_serialized() -> None:
124
+ block = make_block(FakeApi(default_handler))
125
+ assert KEY not in json.dumps(block.model_dump())
126
+ assert KEY not in repr(block)
127
+
128
+
129
+ async def test_get_recalls_with_latest_user_message() -> None:
130
+ api = FakeApi(default_handler)
131
+ block = make_block(api, level="medium", limit=5)
132
+ content = await block.aget(
133
+ [
134
+ ChatMessage(role=MessageRole.USER, content="Where does Ada live?"),
135
+ ChatMessage(role=MessageRole.ASSISTANT, content="Let me check."),
136
+ ChatMessage(role=MessageRole.USER, content="How should I contact Ada?"),
137
+ ]
138
+ )
139
+ assert api.bodies("/api/v1/recall") == [
140
+ {
141
+ "query": "How should I contact Ada?",
142
+ "identity": "user-ada",
143
+ "level": "medium",
144
+ "limit": 5,
145
+ }
146
+ ]
147
+ request = api.requests[0]
148
+ assert request.method == "POST"
149
+ assert request.url.host == "api.past.dev"
150
+ assert request.headers["Authorization"] == f"Bearer {KEY}"
151
+ assert "Ada prefers email to phone calls." in content
152
+ assert '"please email me, never call"' in content
153
+ assert "Support chat" in content
154
+ assert "superseded 2026-10-02" in content
155
+
156
+
157
+ async def test_get_without_user_message_calls_nothing() -> None:
158
+ api = FakeApi(default_handler)
159
+ block = make_block(api)
160
+ assert await block.aget([ChatMessage(role=MessageRole.SYSTEM, content="Be kind.")]) == ""
161
+ assert await block.aget(None) == ""
162
+ assert api.requests == []
163
+
164
+
165
+ async def test_put_ingests_conversation_text() -> None:
166
+ api = FakeApi(default_handler)
167
+ block = make_block(api, audience="support-team", label="Support chat")
168
+ await block.aput(
169
+ [
170
+ ChatMessage(role=MessageRole.SYSTEM, content="You are a helpful agent."),
171
+ ChatMessage(
172
+ role=MessageRole.USER,
173
+ content="Please email me, never call.",
174
+ additional_kwargs={"timestamp": "2026-10-01T09:00:00Z"},
175
+ ),
176
+ ChatMessage(role=MessageRole.TOOL, content='{"ok": true}'),
177
+ ChatMessage(role=MessageRole.ASSISTANT, content="Noted: email only."),
178
+ ],
179
+ session_id="session-1",
180
+ )
181
+ assert api.bodies("/api/v1/ingest") == [
182
+ {
183
+ "content": "user: Please email me, never call.\n\nassistant: Noted: email only.",
184
+ "identity": "user-ada",
185
+ "timestamp": "2026-10-01T09:00:00Z",
186
+ "audience": "support-team",
187
+ "label": "Support chat",
188
+ "metadata": {"source": "llama-index", "sessionId": "session-1"},
189
+ }
190
+ ]
191
+
192
+
193
+ async def test_put_defaults_timestamp_to_now() -> None:
194
+ api = FakeApi(default_handler)
195
+ await make_block(api).aput([ChatMessage(role=MessageRole.USER, content="Hello")])
196
+ body = api.bodies("/api/v1/ingest")[0]
197
+ assert body["timestamp"].startswith("20")
198
+ assert body["label"] == "LlamaIndex chat"
199
+ assert "audience" not in body
200
+
201
+
202
+ async def test_put_with_no_text_calls_nothing() -> None:
203
+ api = FakeApi(default_handler)
204
+ await make_block(api).aput([ChatMessage(role=MessageRole.TOOL, content="result")])
205
+ assert api.requests == []
206
+
207
+
208
+ async def test_out_of_credits_is_raised_and_not_retried() -> None:
209
+ def handler(request: httpx.Request) -> httpx.Response:
210
+ return httpx.Response(
211
+ 402,
212
+ json={"code": "out-of-credits", "status": 402, "debugMessage": "No credits left."},
213
+ headers={"X-Request-Id": "req-123"},
214
+ )
215
+
216
+ api = FakeApi(handler)
217
+ with pytest.raises(PastDevError) as caught:
218
+ await make_block(api).aget([ChatMessage(role=MessageRole.USER, content="Hi")])
219
+ assert caught.value.code == "out-of-credits"
220
+ assert caught.value.status == 402
221
+ assert caught.value.request_id == "req-123"
222
+ assert "No credits left." in str(caught.value)
223
+ assert len(api.requests) == 1
224
+
225
+
226
+ async def test_rate_limit_is_retried_once_after_retry_after() -> None:
227
+ calls = {"n": 0}
228
+
229
+ def handler(request: httpx.Request) -> httpx.Response:
230
+ calls["n"] += 1
231
+ if calls["n"] == 1:
232
+ return httpx.Response(
233
+ 429, json={"code": "rate-limited", "status": 429}, headers={"Retry-After": "0"}
234
+ )
235
+ return httpx.Response(200, json=RECALL_RESPONSE)
236
+
237
+ api = FakeApi(handler)
238
+ content = await make_block(api).aget([ChatMessage(role=MessageRole.USER, content="Hi")])
239
+ assert len(api.requests) == 2
240
+ assert "Ada" in content
241
+
242
+
243
+ async def test_long_retry_after_is_raised() -> None:
244
+ def handler(request: httpx.Request) -> httpx.Response:
245
+ return httpx.Response(
246
+ 429, json={"code": "rate-limited", "status": 429}, headers={"Retry-After": "3600"}
247
+ )
248
+
249
+ api = FakeApi(handler)
250
+ with pytest.raises(PastDevError, match="rate-limited"):
251
+ await make_block(api).aget([ChatMessage(role=MessageRole.USER, content="Hi")])
252
+ assert len(api.requests) == 1
253
+
254
+
255
+ async def test_errors_can_be_logged_instead_of_raised() -> None:
256
+ def handler(request: httpx.Request) -> httpx.Response:
257
+ return httpx.Response(503, json={"code": "unavailable", "status": 503})
258
+
259
+ api = FakeApi(handler)
260
+ block = make_block(api, raise_on_error=False)
261
+ assert await block.aget([ChatMessage(role=MessageRole.USER, content="Hi")]) == ""
262
+ await block.aput([ChatMessage(role=MessageRole.USER, content="Hi")])
263
+ assert len(api.requests) == 2
264
+
265
+
266
+ async def test_non_json_error_is_reported() -> None:
267
+ api = FakeApi(lambda request: httpx.Response(502, text="Bad gateway"))
268
+ with pytest.raises(PastDevError) as caught:
269
+ await make_block(api).aget([ChatMessage(role=MessageRole.USER, content="Hi")])
270
+ assert caught.value.code == "http-error"
271
+ assert caught.value.status == 502
272
+
273
+
274
+ async def test_truncate_drops_lowest_ranked_entries() -> None:
275
+ block = make_block(FakeApi(default_handler))
276
+ content = "[1] first\n\n[2] second\n\n[3] third"
277
+ assert await block.atruncate(content, 2) == "[1] first\n\n[2] second"
278
+ assert await block.atruncate(content, 1000) is None
279
+
280
+
281
+ async def test_works_inside_llama_index_memory() -> None:
282
+ api = FakeApi(default_handler)
283
+ memory = Memory.from_defaults(
284
+ session_id="session-1",
285
+ token_limit=60,
286
+ chat_history_token_ratio=0.5,
287
+ token_flush_size=20,
288
+ memory_blocks=[make_block(api)],
289
+ )
290
+ for turn in range(4):
291
+ await memory.aput(ChatMessage(role=MessageRole.USER, content=f"Question {turn} about Ada?"))
292
+ await memory.aput(ChatMessage(role=MessageRole.ASSISTANT, content=f"Answer {turn}."))
293
+
294
+ ingested = api.bodies("/api/v1/ingest")
295
+ assert ingested, "the memory flushed no messages to the block"
296
+ assert ingested[0]["identity"] == "user-ada"
297
+ assert ingested[0]["metadata"]["sessionId"] == "session-1"
298
+ assert ingested[0]["content"].startswith("user: Question 0 about Ada?")
299
+
300
+ messages = await memory.aget()
301
+ assert "Ada prefers email to phone calls." in str(messages[0].content)
302
+ assert api.bodies("/api/v1/recall")[-1]["query"] == "Question 3 about Ada?"