pyagent-context API Reference¶
pyagent_context
¶
PyAgent Context — three-tier memory with trust-aware context ledger.
CompressionPolicy
¶
Bases: StrEnum
Available compression strategies.
Source code in packages/pyagent-context/src/pyagent_context/compression.py
ContextCompressor
¶
Apply compression policies to a ContextLedger.
The compressor monitors token usage and compresses when a threshold is reached.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
CompressionPolicy
|
Compression strategy. |
FIFO
|
threshold_tokens
|
int
|
Token count that triggers compression. |
10000
|
floor_tokens
|
int
|
Token target after compression (for SAWTOOTH/FIFO). |
5000
|
preserve_trust
|
TrustLevel
|
Items at or above this trust level are never dropped. |
VERIFIED
|
Source code in packages/pyagent-context/src/pyagent_context/compression.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 | |
should_compress(ledger)
¶
Check if the ledger's token count exceeds the threshold.
Source code in packages/pyagent-context/src/pyagent_context/compression.py
compress(ledger)
¶
Apply the compression policy and return a new (compressed) ledger.
The original ledger is not mutated.
Source code in packages/pyagent-context/src/pyagent_context/compression.py
ContextItem
dataclass
¶
A single piece of context with trust and lifecycle metadata.
Attributes:
| Name | Type | Description |
|---|---|---|
content |
str
|
The text content. |
source |
str
|
Origin — agent name, tool name, or |
timestamp |
float
|
Creation time ( |
trust_level |
TrustLevel
|
How much to trust this item. |
sensitivity |
Sensitivity
|
Data classification for redaction decisions. |
expires_at |
float | None
|
Expiration timestamp, or |
derived_from |
str | None
|
Parent item ID if this was derived from another. |
token_estimate |
int
|
Rough token count ( |
Source code in packages/pyagent-context/src/pyagent_context/item.py
is_expired
property
¶
Check if this item has passed its expiry time.
age_seconds
property
¶
Time since creation in seconds.
to_dict()
¶
Serialize to a JSON-compatible dict.
Source code in packages/pyagent-context/src/pyagent_context/item.py
from_dict(data)
classmethod
¶
Deserialize from a dict.
Source code in packages/pyagent-context/src/pyagent_context/item.py
Sensitivity
¶
TrustLevel
¶
Bases: StrEnum
Trust classification for context items.
Source code in packages/pyagent-context/src/pyagent_context/item.py
ContextLedger
¶
Append-only ledger of context items.
Supports querying by trust level, age, and source. Converts items
to Message lists for use with patterns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
list[ContextItem] | None
|
Optional initial items. |
None
|
Source code in packages/pyagent-context/src/pyagent_context/ledger.py
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 | |
total_tokens
property
¶
Sum of token estimates across all items.
append(item)
¶
add(content, source, trust_level=TrustLevel.INFERRED, **kwargs)
¶
Create and append a new item in one step.
Returns:
| Type | Description |
|---|---|
ContextItem
|
The created |
Source code in packages/pyagent-context/src/pyagent_context/ledger.py
query(*, min_trust=None, max_age_seconds=None, source=None)
¶
Filter items by trust level, age, and/or source.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
min_trust
|
TrustLevel | None
|
Only return items at or above this trust level. |
None
|
max_age_seconds
|
float | None
|
Only return items newer than this. |
None
|
source
|
str | None
|
Only return items from this source. |
None
|
Returns:
| Type | Description |
|---|---|
list[ContextItem]
|
Filtered list of items (chronological order). |
Source code in packages/pyagent-context/src/pyagent_context/ledger.py
to_messages(max_tokens=None)
¶
Convert ledger items to a list of Messages.
If max_tokens is set, include items from most recent backward
until the budget is exhausted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_tokens
|
int | None
|
Optional token budget. |
None
|
Returns:
| Type | Description |
|---|---|
list[Message]
|
List of |
Source code in packages/pyagent-context/src/pyagent_context/ledger.py
snapshot()
¶
Serialize the full ledger to a JSON-compatible dict.
Source code in packages/pyagent-context/src/pyagent_context/ledger.py
from_snapshot(data)
classmethod
¶
Restore a ledger from a snapshot dict.
ContextLifecycle
¶
Manage the lifecycle of context items.
Provides:
- Expiry sweep: remove items past their expires_at.
- Freshness decay: reduce token budgets for old items.
- Consolidation: merge items from the same source with similar content.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
consolidation_threshold
|
float
|
Minimum keyword overlap ratio (0.0-1.0) to consider two items similar enough to merge. |
0.6
|
Source code in packages/pyagent-context/src/pyagent_context/lifecycle.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 | |
sweep_expired(ledger)
¶
Remove expired items from the ledger.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ledger
|
ContextLedger
|
The context ledger. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ContextLedger, list[ContextItem]]
|
Tuple of (new ledger without expired items, list of expired items). |
Source code in packages/pyagent-context/src/pyagent_context/lifecycle.py
apply_freshness_decay(ledger, half_life_seconds=3600.0, min_tokens=1)
¶
Reduce token estimates based on age.
Older items get smaller token budgets, making them less likely
to survive compression. Items retain at least min_tokens.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ledger
|
ContextLedger
|
The context ledger. |
required |
half_life_seconds
|
float
|
Seconds for token estimate to halve. |
3600.0
|
min_tokens
|
int
|
Minimum token estimate after decay. |
1
|
Returns:
| Type | Description |
|---|---|
ContextLedger
|
New ledger with decayed token estimates. |
Source code in packages/pyagent-context/src/pyagent_context/lifecycle.py
consolidate(ledger)
¶
Merge similar items from the same source.
When two items from the same source have high keyword overlap, they are merged into one with combined content and the higher trust level.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ledger
|
ContextLedger
|
The context ledger. |
required |
Returns:
| Type | Description |
|---|---|
ContextLedger
|
New ledger with consolidated items. |
Source code in packages/pyagent-context/src/pyagent_context/lifecycle.py
InMemorySemanticStore
¶
In-memory semantic store using TF-IDF cosine similarity.
No external dependencies — suitable for testing and small datasets. For production, use a vector DB adapter (ChromaDB, Pinecone, etc.).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stop_words
|
set[str] | None
|
Optional set of words to ignore in scoring. |
None
|
Source code in packages/pyagent-context/src/pyagent_context/memory/semantic.py
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 | |
SemanticMemoryProtocol
¶
Bases: Protocol
Interface for any vector-backed semantic memory store.
Source code in packages/pyagent-context/src/pyagent_context/memory/semantic.py
SessionMemory
¶
Session-scoped memory that persists across turns.
Supports two backends:
- json: simple JSON file per session (default)
- sqlite: SQLite database for concurrent-safe access
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str
|
Unique session identifier. |
required |
backend
|
str
|
|
'json'
|
storage_path
|
str | Path
|
Directory for storage files. Defaults to |
'.pyagent_sessions'
|
Source code in packages/pyagent-context/src/pyagent_context/memory/session.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 | |
WorkingMemory
¶
Bounded working memory for a single pattern run.
Evicts the oldest items when capacity is exceeded (either by count or by total token estimate).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_items
|
int
|
Maximum number of items to keep. |
100
|
max_tokens
|
int
|
Maximum total token estimate before eviction. |
50000
|
Source code in packages/pyagent-context/src/pyagent_context/memory/working.py
utilization
property
¶
Token utilization as a fraction of max_tokens.
add(item)
¶
Add an item, evicting oldest if necessary.
Returns:
| Type | Description |
|---|---|
list[ContextItem]
|
List of evicted items (empty if none were evicted). |
Source code in packages/pyagent-context/src/pyagent_context/memory/working.py
ContextRedactor
¶
Redact or filter context items based on sensitivity.
Items above the allowed sensitivity threshold are either fully redacted (content replaced) or excluded entirely.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_sensitivity
|
Sensitivity
|
Maximum allowed sensitivity level. Items above this are redacted. |
INTERNAL
|
redaction_text
|
str
|
Replacement text for redacted items. |
'[REDACTED]'
|
exclude_above
|
bool
|
If |
False
|
Source code in packages/pyagent-context/src/pyagent_context/redaction.py
redact_item(item)
¶
Redact a single item if it exceeds the sensitivity threshold.
Returns:
| Type | Description |
|---|---|
ContextItem | None
|
The original item if within threshold, a redacted copy if above, |
ContextItem | None
|
or |
Source code in packages/pyagent-context/src/pyagent_context/redaction.py
redact_ledger(ledger)
¶
Apply redaction to all items in a ledger.
Returns:
| Type | Description |
|---|---|
ContextLedger
|
New ledger with redacted/filtered items. |
Source code in packages/pyagent-context/src/pyagent_context/redaction.py
ScoredItem
dataclass
¶
A context item with a composite retrieval score.
Attributes:
| Name | Type | Description |
|---|---|---|
item |
ContextItem
|
The context item. |
score |
float
|
Composite score (0.0-1.0). |
trust_score |
float
|
Trust component of the score. |
recency_score |
float
|
Recency component of the score. |
relevance_score |
float
|
Relevance component of the score. |
Source code in packages/pyagent-context/src/pyagent_context/retrieval.py
TrustAwareRetriever
¶
Retrieve context items scored by trust, recency, and keyword relevance.
Scoring formula
score = w_trust * trust + w_recency * recency + w_relevance * relevance
Where:
- trust = TRUST_ORDER[item.trust_level] / 3.0
- recency = exp(-age_seconds / half_life)
- relevance = keyword overlap ratio with query
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weight_trust
|
float
|
Weight for trust component. |
0.3
|
weight_recency
|
float
|
Weight for recency component. |
0.3
|
weight_relevance
|
float
|
Weight for relevance component. |
0.4
|
recency_half_life
|
float
|
Seconds for recency score to halve. |
3600.0
|
Source code in packages/pyagent-context/src/pyagent_context/retrieval.py
retrieve(ledger, query, *, top_k=10, min_score=0.0)
¶
Score and rank all items in the ledger against a query.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ledger
|
ContextLedger
|
The context ledger to search. |
required |
query
|
str
|
The query string for relevance scoring. |
required |
top_k
|
int
|
Maximum results to return. |
10
|
min_score
|
float
|
Minimum composite score to include. |
0.0
|
Returns:
| Type | Description |
|---|---|
list[ScoredItem]
|
Ranked list of |