hebbrix 2.7.0__tar.gz → 2.9.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.
- {hebbrix-2.7.0 → hebbrix-2.9.0}/CHANGELOG.md +15 -0
- {hebbrix-2.7.0/hebbrix.egg-info → hebbrix-2.9.0}/PKG-INFO +56 -4
- {hebbrix-2.7.0 → hebbrix-2.9.0}/README.md +55 -3
- {hebbrix-2.7.0 → hebbrix-2.9.0}/hebbrix/__init__.py +27 -2
- hebbrix-2.9.0/hebbrix/answers.py +397 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/hebbrix/client.py +11 -2
- hebbrix-2.9.0/hebbrix/models.py +138 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/hebbrix/resources.py +28 -3
- {hebbrix-2.7.0 → hebbrix-2.9.0}/hebbrix/sync_client.py +13 -1
- {hebbrix-2.7.0 → hebbrix-2.9.0/hebbrix.egg-info}/PKG-INFO +56 -4
- {hebbrix-2.7.0 → hebbrix-2.9.0}/hebbrix.egg-info/SOURCES.txt +3 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/pyproject.toml +1 -1
- hebbrix-2.9.0/tests/test_answer_context.py +210 -0
- hebbrix-2.9.0/tests/test_answer_decision.py +426 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/tests/test_customer_developer_experience.py +1 -1
- hebbrix-2.7.0/hebbrix/models.py +0 -61
- {hebbrix-2.7.0 → hebbrix-2.9.0}/LICENSE +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/MANIFEST.in +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/contracts/openapi-routes.json +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/docs/native-experience-operations.md +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/examples/native_reflection_worker.py +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/hebbrix/_advice.py +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/hebbrix/chat.py +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/hebbrix/exceptions.py +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/hebbrix/execution.py +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/hebbrix/experience.py +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/hebbrix/openai_reflection.py +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/hebbrix/reflection_worker.py +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/hebbrix/workflow.py +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/hebbrix.egg-info/dependency_links.txt +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/hebbrix.egg-info/entry_points.txt +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/hebbrix.egg-info/requires.txt +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/hebbrix.egg-info/top_level.txt +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/setup.cfg +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/tests/test_advanced_resources.py +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/tests/test_advisor_integrity.py +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/tests/test_chat_answer_options.py +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/tests/test_compact_search_default.py +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/tests/test_evidence_loop_resource.py +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/tests/test_evidence_safety_boundary.py +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/tests/test_execution_permission.py +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/tests/test_experience_request.py +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/tests/test_experience_workflow.py +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/tests/test_followup_helpers.py +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/tests/test_memories_resource.py +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/tests/test_openai_reflection.py +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/tests/test_openapi_parity.py +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/tests/test_outcome_advice_resource.py +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/tests/test_procedural_resource.py +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/tests/test_reflection_worker_cli.py +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/tests/test_release_version.py +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/tests/test_sync_client.py +0 -0
- {hebbrix-2.7.0 → hebbrix-2.9.0}/tests/test_workflow_route_contract.py +0 -0
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 2.9.0 — 2026-11-11 (high-stakes readiness, history and suggestions)
|
|
4
|
+
|
|
5
|
+
- `should_answer(response, require_ready=True)` (also on `usable_memories` and `answer_context`): for high-stakes flows, holds the answer with action `retry` and reason `index_not_ready` until `indexing.status` is `ready` and `indexing.answer_risk` is `none`. A response that does not report its indexing is not ready.
|
|
6
|
+
- Behaviour change: `history=True` now applies only when the server answered or marked the response `superseded`; it no longer overrides `unverified`, `no_relevant_memory` or `indexing`.
|
|
7
|
+
- A Reason result for a suggestion or plan (`grounding.answerability: "context_only"`) returns action `use_as_context` with its memories in `context`; `answer_context` lists them as context that is neither an established fact nor permission to act.
|
|
8
|
+
- `answer_context` says when recent writes could not be reflected in the profile (`projection.status: "failed"`, server 1.4.25).
|
|
9
|
+
|
|
10
|
+
## 2.8.0 — 2026-11-11 (answer decisions and answer context)
|
|
11
|
+
|
|
12
|
+
- New `hebbrix.should_answer(response)`: decides in code whether a `search_with_proof()` or `reason()` response may be answered from, returning an `AnswerDecision` with `action` (`answer`, `say_unknown`, `abstain`, `verify_authorization`, `ask_user`, `retry` or `say_no_longer_current`), `reason`, the usable `memories` and the `context` rows never to answer from. `history=True` counts superseded and historical versions for questions about the past.
|
|
13
|
+
- New `hebbrix.answer_context(response, decision)`: renders the end user's standing profile (facts with category, confidence and date, topics to avoid, scope, and whether it is still being projected or unavailable) beside the rows the decision allows, each with its date, memory type, subject and support.
|
|
14
|
+
- New `hebbrix.usable_memories(response)` and the response types `AnswerStatus`, `RevisionStatus`, `MemoryRow`, `MemoryStatus` and `ScopeIndexing`.
|
|
15
|
+
- `MemoryClient.search_with_proof()` accepts `include_profile` and `include_superseded`, as the synchronous client and `search()` already did.
|
|
16
|
+
- Docs: `memories.create()` stores verbatim unless `infer=True`, while `POST /v1/memories` extracts by default; examples pass `infer` and `wait_for_index` explicitly.
|
|
17
|
+
|
|
3
18
|
## 2.7.0 — 2026-10-19 (compact responses, entity scope, chat answers)
|
|
4
19
|
|
|
5
20
|
- Behaviour change: `search()` and `search_with_proof()` now request `view="compact"` by default (rows keep content, identity, score, rank, timestamps, `low_confidence` and entity scope; the safety envelope and proof context are unchanged; ranking diagnostics need `debug=True`). Pass `view="full"` for the previous per-row metadata. `search()` returns rows only and no longer requests the unused ProofLoop token unless `include_proof_context=True`.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: hebbrix
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.9.0
|
|
4
4
|
Summary: Typed Python client for Hebbrix memory, retrieval, and outcome-learning APIs
|
|
5
5
|
Author-email: Hebbrix Team <support@hebbrix.com>
|
|
6
6
|
Maintainer-email: Hebbrix Team <support@hebbrix.com>
|
|
@@ -65,14 +65,14 @@ Dynamic: license-file
|
|
|
65
65
|
|
|
66
66
|
Typed Python client for Hebbrix memory, retrieval, and outcome-learning APIs.
|
|
67
67
|
|
|
68
|
-
The current stable package is **2.
|
|
68
|
+
The current stable package is **2.9.0**. Start with memory storage and search, or
|
|
69
69
|
the three-call outcome-learning workflow below. Advanced evidence and execution
|
|
70
70
|
permission transports are opt-in; installing the SDK never permits an action.
|
|
71
71
|
|
|
72
72
|
## Install
|
|
73
73
|
|
|
74
74
|
```bash
|
|
75
|
-
pip install hebbrix==2.
|
|
75
|
+
pip install hebbrix==2.9.0
|
|
76
76
|
```
|
|
77
77
|
|
|
78
78
|
Python 3.8+ is supported. `MemoryClient` is asynchronous. `SyncMemoryClient`
|
|
@@ -92,7 +92,8 @@ async def main():
|
|
|
92
92
|
memory = await client.memories.create(
|
|
93
93
|
collection_id=collection["id"],
|
|
94
94
|
content="Customer prefers concise replies",
|
|
95
|
-
|
|
95
|
+
infer=False, # store verbatim (the SDK default; REST defaults to True)
|
|
96
|
+
wait_for_index=True, # return once it is searchable
|
|
96
97
|
idempotency_key="customer-42-preference-v1",
|
|
97
98
|
)
|
|
98
99
|
results = await client.search(
|
|
@@ -104,6 +105,56 @@ async def main():
|
|
|
104
105
|
asyncio.run(main())
|
|
105
106
|
```
|
|
106
107
|
|
|
108
|
+
> **`memories.create()` and `POST /v1/memories` have different defaults.** The
|
|
109
|
+
> SDK stores the content verbatim as one memory unless you pass `infer=True`;
|
|
110
|
+
> the REST endpoint called without `infer` extracts facts with the server's
|
|
111
|
+
> language model (`infer` defaults to `true` there). Pass `infer` and
|
|
112
|
+
> `wait_for_index` explicitly, as above, so a call reads the same through the
|
|
113
|
+
> SDK and over HTTP. Use `infer=True` (or `/v1/memories/process`) for
|
|
114
|
+
> conversations; `infer=False` for a fact you already have in final form.
|
|
115
|
+
|
|
116
|
+
## Decide before you invoke your model
|
|
117
|
+
|
|
118
|
+
A model told to abstain can still answer. Decide in code, and give it only the rows
|
|
119
|
+
that passed. `search()` returns only the rows, so use `search_with_proof()` or
|
|
120
|
+
`reason()`, which keep the fields this reads:
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
from hebbrix import answer_context, should_answer
|
|
124
|
+
|
|
125
|
+
response = await client.search_with_proof(
|
|
126
|
+
question, user_id="customer-42", include_profile=True
|
|
127
|
+
)
|
|
128
|
+
decision = should_answer(response)
|
|
129
|
+
if not decision:
|
|
130
|
+
# decision.action: ask_user, say_no_longer_current, say_unknown, retry,
|
|
131
|
+
# verify_authorization or abstain. decision.reason says why;
|
|
132
|
+
# decision.context holds the rows, never to answer from.
|
|
133
|
+
return my_reply_for(decision.action)
|
|
134
|
+
# The user's standing profile plus the rows you may answer from, each with its
|
|
135
|
+
# date, memory type, subject and support.
|
|
136
|
+
return await my_llm(question, context=answer_context(response, decision))
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
`answer_context(response, decision)` keeps the end user's standing profile
|
|
140
|
+
(`include_profile=True`) beside the rows: preferences such as "keep answers
|
|
141
|
+
short" reach your model even when they did not rank for this message. It lists
|
|
142
|
+
each fact with its category, confidence and date, the topics to avoid, the
|
|
143
|
+
profile's `scope`, and says so when the profile is still being updated
|
|
144
|
+
(`projection.status: "pending"`) or could not be read, so a missing preference
|
|
145
|
+
is not taken as absent. When the decision is not to answer it returns the
|
|
146
|
+
profile alone. `usable_memories(response)` returns just the rows. Pass
|
|
147
|
+
`history=True` for a question about the past, when superseded and historical
|
|
148
|
+
versions should count (it never overrides `unverified`, `no_relevant_memory`,
|
|
149
|
+
`indexing` or `conflicting`). Pass `require_ready=True` for a high-stakes flow:
|
|
150
|
+
the answer is then also held, with action `retry`, until `indexing.status` is
|
|
151
|
+
`ready` and `indexing.answer_risk` is `none`. A Reason suggestion or plan
|
|
152
|
+
(`context_only`) returns action `use_as_context`: its memories shape what your
|
|
153
|
+
model suggests, and are never a fact or a permission. `reason()` takes
|
|
154
|
+
`deadline_ms`; a `timed_out` response is an abstention. `verify_authorization` means the returned rule limits the action
|
|
155
|
+
to a group the store cannot place the user in: use the rule, and check the
|
|
156
|
+
permission in your own system.
|
|
157
|
+
|
|
107
158
|
## Learn from outcomes in three calls
|
|
108
159
|
|
|
109
160
|
Use server-side selection when Hebbrix should choose. Read-only advice is for a
|
|
@@ -191,6 +242,7 @@ from hebbrix import IndexingTimeoutError
|
|
|
191
242
|
try:
|
|
192
243
|
created = await client.memories.create(
|
|
193
244
|
content="Customer prefers concise replies",
|
|
245
|
+
infer=False,
|
|
194
246
|
wait_for_index=True,
|
|
195
247
|
idempotency_key="customer-42-preference-v1",
|
|
196
248
|
index_timeout=5,
|
|
@@ -2,14 +2,14 @@
|
|
|
2
2
|
|
|
3
3
|
Typed Python client for Hebbrix memory, retrieval, and outcome-learning APIs.
|
|
4
4
|
|
|
5
|
-
The current stable package is **2.
|
|
5
|
+
The current stable package is **2.9.0**. Start with memory storage and search, or
|
|
6
6
|
the three-call outcome-learning workflow below. Advanced evidence and execution
|
|
7
7
|
permission transports are opt-in; installing the SDK never permits an action.
|
|
8
8
|
|
|
9
9
|
## Install
|
|
10
10
|
|
|
11
11
|
```bash
|
|
12
|
-
pip install hebbrix==2.
|
|
12
|
+
pip install hebbrix==2.9.0
|
|
13
13
|
```
|
|
14
14
|
|
|
15
15
|
Python 3.8+ is supported. `MemoryClient` is asynchronous. `SyncMemoryClient`
|
|
@@ -29,7 +29,8 @@ async def main():
|
|
|
29
29
|
memory = await client.memories.create(
|
|
30
30
|
collection_id=collection["id"],
|
|
31
31
|
content="Customer prefers concise replies",
|
|
32
|
-
|
|
32
|
+
infer=False, # store verbatim (the SDK default; REST defaults to True)
|
|
33
|
+
wait_for_index=True, # return once it is searchable
|
|
33
34
|
idempotency_key="customer-42-preference-v1",
|
|
34
35
|
)
|
|
35
36
|
results = await client.search(
|
|
@@ -41,6 +42,56 @@ async def main():
|
|
|
41
42
|
asyncio.run(main())
|
|
42
43
|
```
|
|
43
44
|
|
|
45
|
+
> **`memories.create()` and `POST /v1/memories` have different defaults.** The
|
|
46
|
+
> SDK stores the content verbatim as one memory unless you pass `infer=True`;
|
|
47
|
+
> the REST endpoint called without `infer` extracts facts with the server's
|
|
48
|
+
> language model (`infer` defaults to `true` there). Pass `infer` and
|
|
49
|
+
> `wait_for_index` explicitly, as above, so a call reads the same through the
|
|
50
|
+
> SDK and over HTTP. Use `infer=True` (or `/v1/memories/process`) for
|
|
51
|
+
> conversations; `infer=False` for a fact you already have in final form.
|
|
52
|
+
|
|
53
|
+
## Decide before you invoke your model
|
|
54
|
+
|
|
55
|
+
A model told to abstain can still answer. Decide in code, and give it only the rows
|
|
56
|
+
that passed. `search()` returns only the rows, so use `search_with_proof()` or
|
|
57
|
+
`reason()`, which keep the fields this reads:
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
from hebbrix import answer_context, should_answer
|
|
61
|
+
|
|
62
|
+
response = await client.search_with_proof(
|
|
63
|
+
question, user_id="customer-42", include_profile=True
|
|
64
|
+
)
|
|
65
|
+
decision = should_answer(response)
|
|
66
|
+
if not decision:
|
|
67
|
+
# decision.action: ask_user, say_no_longer_current, say_unknown, retry,
|
|
68
|
+
# verify_authorization or abstain. decision.reason says why;
|
|
69
|
+
# decision.context holds the rows, never to answer from.
|
|
70
|
+
return my_reply_for(decision.action)
|
|
71
|
+
# The user's standing profile plus the rows you may answer from, each with its
|
|
72
|
+
# date, memory type, subject and support.
|
|
73
|
+
return await my_llm(question, context=answer_context(response, decision))
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
`answer_context(response, decision)` keeps the end user's standing profile
|
|
77
|
+
(`include_profile=True`) beside the rows: preferences such as "keep answers
|
|
78
|
+
short" reach your model even when they did not rank for this message. It lists
|
|
79
|
+
each fact with its category, confidence and date, the topics to avoid, the
|
|
80
|
+
profile's `scope`, and says so when the profile is still being updated
|
|
81
|
+
(`projection.status: "pending"`) or could not be read, so a missing preference
|
|
82
|
+
is not taken as absent. When the decision is not to answer it returns the
|
|
83
|
+
profile alone. `usable_memories(response)` returns just the rows. Pass
|
|
84
|
+
`history=True` for a question about the past, when superseded and historical
|
|
85
|
+
versions should count (it never overrides `unverified`, `no_relevant_memory`,
|
|
86
|
+
`indexing` or `conflicting`). Pass `require_ready=True` for a high-stakes flow:
|
|
87
|
+
the answer is then also held, with action `retry`, until `indexing.status` is
|
|
88
|
+
`ready` and `indexing.answer_risk` is `none`. A Reason suggestion or plan
|
|
89
|
+
(`context_only`) returns action `use_as_context`: its memories shape what your
|
|
90
|
+
model suggests, and are never a fact or a permission. `reason()` takes
|
|
91
|
+
`deadline_ms`; a `timed_out` response is an abstention. `verify_authorization` means the returned rule limits the action
|
|
92
|
+
to a group the store cannot place the user in: use the rule, and check the
|
|
93
|
+
permission in your own system.
|
|
94
|
+
|
|
44
95
|
## Learn from outcomes in three calls
|
|
45
96
|
|
|
46
97
|
Use server-side selection when Hebbrix should choose. Read-only advice is for a
|
|
@@ -128,6 +179,7 @@ from hebbrix import IndexingTimeoutError
|
|
|
128
179
|
try:
|
|
129
180
|
created = await client.memories.create(
|
|
130
181
|
content="Customer prefers concise replies",
|
|
182
|
+
infer=False,
|
|
131
183
|
wait_for_index=True,
|
|
132
184
|
idempotency_key="customer-42-preference-v1",
|
|
133
185
|
index_timeout=5,
|
|
@@ -5,10 +5,16 @@ production OpenAPI and ``GET /v1/users/me/capabilities``. The experimental
|
|
|
5
5
|
World Model is intentionally absent from this release.
|
|
6
6
|
"""
|
|
7
7
|
|
|
8
|
-
__version__ = "2.
|
|
8
|
+
__version__ = "2.9.0"
|
|
9
9
|
__author__ = "Hebbrix Team"
|
|
10
10
|
__license__ = "MIT"
|
|
11
11
|
|
|
12
|
+
from hebbrix.answers import (
|
|
13
|
+
AnswerDecision,
|
|
14
|
+
answer_context,
|
|
15
|
+
should_answer,
|
|
16
|
+
usable_memories,
|
|
17
|
+
)
|
|
12
18
|
from hebbrix.chat import MemoryChat
|
|
13
19
|
from hebbrix.client import MemoryClient
|
|
14
20
|
from hebbrix.exceptions import (
|
|
@@ -21,7 +27,17 @@ from hebbrix.exceptions import (
|
|
|
21
27
|
ServerError,
|
|
22
28
|
ValidationError,
|
|
23
29
|
)
|
|
24
|
-
from hebbrix.models import
|
|
30
|
+
from hebbrix.models import (
|
|
31
|
+
ActionAdviceReceipt,
|
|
32
|
+
AnswerStatus,
|
|
33
|
+
EvidenceClaim,
|
|
34
|
+
GroundingReceipt,
|
|
35
|
+
MemoryRow,
|
|
36
|
+
MemoryStatus,
|
|
37
|
+
RevisionStatus,
|
|
38
|
+
ScopeIndexing,
|
|
39
|
+
SearchSafetyEnvelope,
|
|
40
|
+
)
|
|
25
41
|
from hebbrix.sync_client import SyncMemoryClient
|
|
26
42
|
|
|
27
43
|
__all__ = [
|
|
@@ -40,4 +56,13 @@ __all__ = [
|
|
|
40
56
|
"EvidenceClaim",
|
|
41
57
|
"SearchSafetyEnvelope",
|
|
42
58
|
"ActionAdviceReceipt",
|
|
59
|
+
"AnswerDecision",
|
|
60
|
+
"AnswerStatus",
|
|
61
|
+
"MemoryRow",
|
|
62
|
+
"MemoryStatus",
|
|
63
|
+
"RevisionStatus",
|
|
64
|
+
"ScopeIndexing",
|
|
65
|
+
"answer_context",
|
|
66
|
+
"should_answer",
|
|
67
|
+
"usable_memories",
|
|
43
68
|
]
|
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
"""Decide in code what a search or Reason response lets you do.
|
|
2
|
+
|
|
3
|
+
A model that is told "abstain_recommended: true" can still answer. Call
|
|
4
|
+
``should_answer`` before invoking the model and give it only
|
|
5
|
+
``decision.memories``: when the decision is not to answer, the model is never
|
|
6
|
+
called, so it cannot ignore the flag.
|
|
7
|
+
|
|
8
|
+
response = await client.search_with_proof(
|
|
9
|
+
question, user_id=user_id, include_profile=True
|
|
10
|
+
)
|
|
11
|
+
decision = should_answer(response)
|
|
12
|
+
if not decision:
|
|
13
|
+
return reply_for(decision.action) # your own fixed reply per action
|
|
14
|
+
return await my_llm(question, context=answer_context(response, decision))
|
|
15
|
+
|
|
16
|
+
``answer_context`` renders the end user's standing profile beside those rows,
|
|
17
|
+
so a preference that did not rank for this message still reaches the model.
|
|
18
|
+
|
|
19
|
+
``search()`` returns only the rows, without the fields this needs; use
|
|
20
|
+
``search_with_proof()`` or ``reason()``. The decision is derived from the
|
|
21
|
+
response alone: nothing here calls the API, and it fails closed on a response it
|
|
22
|
+
does not understand.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from dataclasses import dataclass, field
|
|
26
|
+
from typing import Any, Dict, List, Mapping, Optional, Tuple
|
|
27
|
+
|
|
28
|
+
ANSWER_STATUSES = (
|
|
29
|
+
"answerable",
|
|
30
|
+
"conflicting",
|
|
31
|
+
"superseded",
|
|
32
|
+
"unverified",
|
|
33
|
+
"indexing",
|
|
34
|
+
"no_relevant_memory",
|
|
35
|
+
)
|
|
36
|
+
REVISION_STATUSES = ("current", "superseded", "conflicting", "historical")
|
|
37
|
+
|
|
38
|
+
# What to do instead of answering, for each ``answer_status``.
|
|
39
|
+
ACTIONS = {
|
|
40
|
+
"answerable": "answer",
|
|
41
|
+
"conflicting": "ask_user",
|
|
42
|
+
"superseded": "say_no_longer_current",
|
|
43
|
+
"unverified": "abstain",
|
|
44
|
+
"indexing": "retry",
|
|
45
|
+
"no_relevant_memory": "say_unknown",
|
|
46
|
+
}
|
|
47
|
+
# A permission question answered by a rule that restricts the act to a group no
|
|
48
|
+
# memory ties the asker to (``confidence_reason`` "authorization_not_verifiable"):
|
|
49
|
+
# the rule is in ``context``; check the asker's role in your own system.
|
|
50
|
+
AUTHORIZATION_NOT_VERIFIABLE = "authorization_not_verifiable"
|
|
51
|
+
VERIFY_AUTHORIZATION = "verify_authorization"
|
|
52
|
+
# A Reason request for a suggestion or plan ("Can you suggest accessories for my
|
|
53
|
+
# camera?") has no stored answer: its sources are the memories that should shape
|
|
54
|
+
# what your model composes (``grounding.answerability`` "context_only"). They are
|
|
55
|
+
# context, never a verified fact or a permission.
|
|
56
|
+
CONTEXT_ONLY = "context_only"
|
|
57
|
+
USE_AS_CONTEXT = "use_as_context"
|
|
58
|
+
# ``require_ready``: the scope's index is not complete, or the server says the
|
|
59
|
+
# answer may still change (``indexing.answer_risk``).
|
|
60
|
+
INDEX_NOT_READY = "index_not_ready"
|
|
61
|
+
# Set by the SDK on a response whose rows it kept although it is degraded: not a
|
|
62
|
+
# malformed envelope, so it is not a reason to fail closed on its own.
|
|
63
|
+
_PRESERVED = "degraded_evidence_preserved"
|
|
64
|
+
_PAST = frozenset({"superseded", "historical"})
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass(frozen=True)
|
|
68
|
+
class AnswerDecision:
|
|
69
|
+
"""What a response lets you do; true only when you may answer from it."""
|
|
70
|
+
|
|
71
|
+
answer: bool
|
|
72
|
+
reason: str
|
|
73
|
+
action: str
|
|
74
|
+
# Safe to pass to a model as evidence; empty unless ``answer`` is true.
|
|
75
|
+
memories: List[Dict[str, Any]] = field(default_factory=list)
|
|
76
|
+
# The other rows returned, each with its revision_status and low_confidence:
|
|
77
|
+
# to show or to ask about ("which of these holds?"), never to answer from.
|
|
78
|
+
context: List[Dict[str, Any]] = field(default_factory=list)
|
|
79
|
+
# Reason only: context for a decision it could not verify, with citations.
|
|
80
|
+
cited_context: Optional[str] = None
|
|
81
|
+
|
|
82
|
+
def __bool__(self) -> bool:
|
|
83
|
+
return self.answer
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _rows(response: Mapping[str, Any]) -> Tuple[List[Dict[str, Any]], bool]:
|
|
87
|
+
"""The response's rows, and whether they are search rows (which always say
|
|
88
|
+
``low_confidence``) rather than Reason's cited sources."""
|
|
89
|
+
|
|
90
|
+
results = response.get("results")
|
|
91
|
+
if isinstance(results, list):
|
|
92
|
+
return [row for row in results if isinstance(row, dict)], True
|
|
93
|
+
sources = response.get("sources")
|
|
94
|
+
if isinstance(sources, list):
|
|
95
|
+
return [row for row in sources if isinstance(row, dict)], False
|
|
96
|
+
return [], False
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _is_evidence(row: Mapping[str, Any], *, search_row: bool) -> bool:
|
|
100
|
+
"""A current row established as evidence. A row that does not say so is not."""
|
|
101
|
+
|
|
102
|
+
if row.get("revision_status") != "current" or row.get("is_current") is False:
|
|
103
|
+
return False
|
|
104
|
+
confidence = row.get("low_confidence")
|
|
105
|
+
return confidence is False if search_row else confidence is not True
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _is_history(row: Mapping[str, Any], *, search_row: bool) -> bool:
|
|
109
|
+
"""A row a question about the past may read: an earlier version, labelled as
|
|
110
|
+
one (the server flags those low_confidence for the present), or evidence."""
|
|
111
|
+
|
|
112
|
+
return row.get("revision_status") in _PAST or _is_evidence(
|
|
113
|
+
row, search_row=search_row
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _ready(response: Mapping[str, Any]) -> bool:
|
|
118
|
+
"""Whether the response says its scope is fully indexed with nothing that
|
|
119
|
+
could change the answer. A response that does not say is not ready."""
|
|
120
|
+
|
|
121
|
+
indexing = response.get("indexing")
|
|
122
|
+
if not isinstance(indexing, Mapping):
|
|
123
|
+
return False
|
|
124
|
+
return indexing.get("status") == "ready" and indexing.get("answer_risk") in (
|
|
125
|
+
None,
|
|
126
|
+
"none",
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def should_answer(
|
|
131
|
+
response: Optional[Mapping[str, Any]],
|
|
132
|
+
*,
|
|
133
|
+
history: bool = False,
|
|
134
|
+
require_ready: bool = False,
|
|
135
|
+
) -> AnswerDecision:
|
|
136
|
+
"""Whether you may answer from ``response`` (a ``search_with_proof`` or
|
|
137
|
+
``reason`` result), the rows to answer from, and what to do when you may not.
|
|
138
|
+
|
|
139
|
+
Every server signal is enforced: ``answer_status``, ``no_match``,
|
|
140
|
+
``abstain_recommended``, ``decision_abstained``, ``confidence_reason`` and
|
|
141
|
+
each row's ``low_confidence`` and ``revision_status``.
|
|
142
|
+
|
|
143
|
+
``require_ready=True`` is for high-stakes flows (money, health, actions):
|
|
144
|
+
the answer is also held, with action ``retry``, until ``indexing.status`` is
|
|
145
|
+
``ready`` and ``indexing.answer_risk`` is ``none``. Without it an answer
|
|
146
|
+
from a scope still indexing is allowed when the server allows it
|
|
147
|
+
(``answer_risk`` ``may_change``), and a count, total or list is always held
|
|
148
|
+
while indexing (``answer_status`` ``indexing``).
|
|
149
|
+
|
|
150
|
+
``history=True`` is for a question about the past that your application
|
|
151
|
+
recognises ("Where did I live before?"). It overrides one thing: a
|
|
152
|
+
superseded or historical row then counts as evidence, so a response the
|
|
153
|
+
server answered or marked ``superseded`` can be answered from its earlier
|
|
154
|
+
versions. It never overrides ``unverified``, ``no_relevant_memory``,
|
|
155
|
+
``indexing``, ``conflicting`` or ``authorization_not_verifiable``. Keep each
|
|
156
|
+
row's ``revision_status`` and ``stated_at`` in what you pass to the model, so
|
|
157
|
+
it can tell the versions apart.
|
|
158
|
+
|
|
159
|
+
A Reason result for a suggestion or plan (``context_only``) returns action
|
|
160
|
+
``use_as_context``: give ``decision.context`` to your model to shape what it
|
|
161
|
+
suggests, never as an established fact or a permission to act.
|
|
162
|
+
"""
|
|
163
|
+
|
|
164
|
+
if not isinstance(response, Mapping) or "answer_status" not in response:
|
|
165
|
+
return AnswerDecision(False, "unsupported_response", "abstain")
|
|
166
|
+
status = response.get("answer_status")
|
|
167
|
+
safety = response.get("sdk_safety_reason")
|
|
168
|
+
if status not in ANSWER_STATUSES or (safety and safety != _PRESERVED):
|
|
169
|
+
return AnswerDecision(False, "malformed_response", "abstain")
|
|
170
|
+
rows, search_rows = _rows(response)
|
|
171
|
+
cited = response.get("cited_context")
|
|
172
|
+
cited = cited if isinstance(cited, str) and cited else None
|
|
173
|
+
|
|
174
|
+
def declined(reason: str, action: str) -> AnswerDecision:
|
|
175
|
+
return AnswerDecision(False, reason, action, [], rows, cited)
|
|
176
|
+
|
|
177
|
+
if status == "conflicting":
|
|
178
|
+
return declined(status, ACTIONS[status])
|
|
179
|
+
if response.get("confidence_reason") == AUTHORIZATION_NOT_VERIFIABLE:
|
|
180
|
+
return declined(AUTHORIZATION_NOT_VERIFIABLE, VERIFY_AUTHORIZATION)
|
|
181
|
+
grounding = response.get("grounding")
|
|
182
|
+
if isinstance(grounding, Mapping) and grounding.get("answerability") == CONTEXT_ONLY:
|
|
183
|
+
return declined(CONTEXT_ONLY, USE_AS_CONTEXT)
|
|
184
|
+
if require_ready and not _ready(response):
|
|
185
|
+
return declined(INDEX_NOT_READY, "retry")
|
|
186
|
+
if history and status in ("answerable", "superseded"):
|
|
187
|
+
usable = [row for row in rows if _is_history(row, search_row=search_rows)]
|
|
188
|
+
if usable:
|
|
189
|
+
others = [row for row in rows if row not in usable]
|
|
190
|
+
return AnswerDecision(True, "history", "answer", usable, others, cited)
|
|
191
|
+
if status != "answerable":
|
|
192
|
+
return declined(status, ACTIONS[status])
|
|
193
|
+
for flag in ("no_match", "abstain_recommended", "decision_abstained"):
|
|
194
|
+
if response.get(flag) is True:
|
|
195
|
+
return declined(flag, "abstain")
|
|
196
|
+
usable = [row for row in rows if _is_evidence(row, search_row=search_rows)]
|
|
197
|
+
if not usable:
|
|
198
|
+
return declined("no_usable_memories", "abstain")
|
|
199
|
+
others = [row for row in rows if row not in usable]
|
|
200
|
+
return AnswerDecision(True, status, "answer", usable, others, cited)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def usable_memories(
|
|
204
|
+
response: Optional[Mapping[str, Any]],
|
|
205
|
+
*,
|
|
206
|
+
history: bool = False,
|
|
207
|
+
require_ready: bool = False,
|
|
208
|
+
) -> List[Dict[str, Any]]:
|
|
209
|
+
"""The rows of ``response`` safe to pass to a model as evidence; empty when
|
|
210
|
+
``should_answer`` says not to answer."""
|
|
211
|
+
|
|
212
|
+
return should_answer(
|
|
213
|
+
response, history=history, require_ready=require_ready
|
|
214
|
+
).memories
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _day(value: Any) -> Optional[str]:
|
|
218
|
+
"""The calendar date of an ISO timestamp (the API's dates are ISO 8601)."""
|
|
219
|
+
|
|
220
|
+
return str(value)[:10] if isinstance(value, str) and value else None
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _count(value: Any) -> int:
|
|
224
|
+
try:
|
|
225
|
+
return int(float(value or 0))
|
|
226
|
+
except (TypeError, ValueError):
|
|
227
|
+
return 0
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _profile_lines(profile: Any) -> List[str]:
|
|
231
|
+
if not isinstance(profile, Mapping):
|
|
232
|
+
return []
|
|
233
|
+
if profile.get("status") != "ok":
|
|
234
|
+
# Unreadable is not empty: a preference may exist that was not returned.
|
|
235
|
+
return ["Standing profile of this user: unavailable for this request."]
|
|
236
|
+
facts = [
|
|
237
|
+
fact
|
|
238
|
+
for fact in profile.get("facts") or []
|
|
239
|
+
if isinstance(fact, Mapping) and fact.get("value") not in (None, "")
|
|
240
|
+
]
|
|
241
|
+
avoid = [t for t in profile.get("avoid_topics") or [] if isinstance(t, str) and t]
|
|
242
|
+
projection = profile.get("projection")
|
|
243
|
+
projection = projection if isinstance(projection, Mapping) else {}
|
|
244
|
+
pending = projection.get("status") == "pending"
|
|
245
|
+
failed = projection.get("status") == "failed"
|
|
246
|
+
if not facts and not avoid and not pending and not failed:
|
|
247
|
+
return []
|
|
248
|
+
scope = profile.get("scope")
|
|
249
|
+
scope = (
|
|
250
|
+
scope
|
|
251
|
+
if isinstance(scope, Mapping)
|
|
252
|
+
else {"end_user_id": profile.get("end_user_id")}
|
|
253
|
+
)
|
|
254
|
+
details = [f"{key} {value}" for key, value in scope.items() if value]
|
|
255
|
+
if _day(profile.get("as_of")):
|
|
256
|
+
details.append(f"as of {_day(profile.get('as_of'))}")
|
|
257
|
+
if projection.get("status"):
|
|
258
|
+
details.append(f"projection {projection['status']}")
|
|
259
|
+
header = "Standing profile of this user (applies to every reply"
|
|
260
|
+
lines = [header + ("; " + "; ".join(details) if details else "") + "):"]
|
|
261
|
+
for fact in facts:
|
|
262
|
+
name = " / ".join(str(fact[k]) for k in ("category", "key") if fact.get(k))
|
|
263
|
+
meta = []
|
|
264
|
+
if isinstance(fact.get("confidence"), (int, float)):
|
|
265
|
+
meta.append(f"confidence {float(fact['confidence']):.2f}")
|
|
266
|
+
if _day(fact.get("updated_at")):
|
|
267
|
+
meta.append(f"updated {_day(fact.get('updated_at'))}")
|
|
268
|
+
text = f"{name}: {fact['value']}" if name else str(fact["value"])
|
|
269
|
+
lines.append(f"- {text}" + (f" ({', '.join(meta)})" if meta else ""))
|
|
270
|
+
if avoid:
|
|
271
|
+
lines.append("- avoid topics: " + ", ".join(avoid))
|
|
272
|
+
if pending:
|
|
273
|
+
count = projection.get("pending_writes")
|
|
274
|
+
writes = (
|
|
275
|
+
f"{'at least ' if projection.get('capped') else ''}{count} recent writes"
|
|
276
|
+
if isinstance(count, int) and count > 0
|
|
277
|
+
else "recent writes"
|
|
278
|
+
)
|
|
279
|
+
lines.append(
|
|
280
|
+
f"- still being updated: {writes} not yet reflected; a fact here may be "
|
|
281
|
+
"missing or about to change."
|
|
282
|
+
)
|
|
283
|
+
elif failed:
|
|
284
|
+
count = projection.get("failed_writes")
|
|
285
|
+
writes = (
|
|
286
|
+
f"{count} recent writes"
|
|
287
|
+
if isinstance(count, int) and count > 0
|
|
288
|
+
else "recent writes"
|
|
289
|
+
)
|
|
290
|
+
lines.append(
|
|
291
|
+
f"- incomplete: {writes} could not be reflected; a fact from them may be "
|
|
292
|
+
"missing."
|
|
293
|
+
)
|
|
294
|
+
return lines
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _memory_details(row: Mapping[str, Any]) -> List[str]:
|
|
298
|
+
metadata = row.get("metadata") if isinstance(row.get("metadata"), Mapping) else {}
|
|
299
|
+
details = []
|
|
300
|
+
memory_type = metadata.get("memory_type") or row.get("memory_type")
|
|
301
|
+
if memory_type:
|
|
302
|
+
details.append(str(memory_type))
|
|
303
|
+
if _day(row.get("stated_at")):
|
|
304
|
+
details.append(f"stated {_day(row.get('stated_at'))}")
|
|
305
|
+
elif _day(row.get("created_at")):
|
|
306
|
+
details.append(f"saved {_day(row.get('created_at'))}")
|
|
307
|
+
if _day(row.get("valid_until")):
|
|
308
|
+
details.append(f"valid until {_day(row.get('valid_until'))}")
|
|
309
|
+
if row.get("subject"):
|
|
310
|
+
details.append(f"about {row['subject']}")
|
|
311
|
+
applies_to = row.get("applies_to")
|
|
312
|
+
names = (
|
|
313
|
+
[n for n in applies_to if isinstance(n, str) and n]
|
|
314
|
+
if isinstance(applies_to, list)
|
|
315
|
+
else []
|
|
316
|
+
)
|
|
317
|
+
if names:
|
|
318
|
+
details.append("names " + ", ".join(names))
|
|
319
|
+
if row.get("revision_status"):
|
|
320
|
+
details.append(str(row["revision_status"]))
|
|
321
|
+
grounding = row.get("grounding")
|
|
322
|
+
if not isinstance(grounding, Mapping):
|
|
323
|
+
grounding = metadata.get("grounding")
|
|
324
|
+
if isinstance(grounding, Mapping):
|
|
325
|
+
support = grounding.get("support_basis") or grounding.get("status")
|
|
326
|
+
if support:
|
|
327
|
+
details.append(f"support {support}")
|
|
328
|
+
outcomes = metadata.get("outcome_evidence")
|
|
329
|
+
if isinstance(outcomes, Mapping) and (
|
|
330
|
+
outcomes.get("successes") or outcomes.get("failures")
|
|
331
|
+
):
|
|
332
|
+
details.append(
|
|
333
|
+
f"outcomes {_count(outcomes.get('successes'))} worked, "
|
|
334
|
+
f"{_count(outcomes.get('failures'))} failed"
|
|
335
|
+
)
|
|
336
|
+
return details
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def answer_context(
|
|
340
|
+
response: Optional[Mapping[str, Any]],
|
|
341
|
+
decision: Optional[AnswerDecision] = None,
|
|
342
|
+
*,
|
|
343
|
+
history: bool = False,
|
|
344
|
+
require_ready: bool = False,
|
|
345
|
+
) -> str:
|
|
346
|
+
"""The text to give your own model with the user's message: the end user's
|
|
347
|
+
standing profile and the memories ``should_answer`` lets you answer from.
|
|
348
|
+
|
|
349
|
+
Pass a ``search_with_proof(..., include_profile=True)`` or ``reason()``
|
|
350
|
+
response, and the decision you already made on it (computed here when
|
|
351
|
+
omitted). The profile section lists each standing fact with its category,
|
|
352
|
+
confidence and date, the topics to avoid, the profile's scope, and whether
|
|
353
|
+
it is still being projected from recent writes; an unavailable profile is
|
|
354
|
+
said to be unavailable, never left out as if empty. The memories section
|
|
355
|
+
lists only ``decision.memories``, numbered for citation, each with its
|
|
356
|
+
memory type, date, whom it is about, the names it states, its revision
|
|
357
|
+
status and its support. When the decision is not to answer, only the
|
|
358
|
+
profile is returned: standing preferences still shape a reply such as
|
|
359
|
+
"I don't know that yet". For a Reason suggestion or plan (``context_only``)
|
|
360
|
+
the memories that should shape it are listed as context, marked as neither
|
|
361
|
+
established facts nor permission to act. Returns "" when there is nothing to
|
|
362
|
+
add.
|
|
363
|
+
"""
|
|
364
|
+
|
|
365
|
+
if decision is None:
|
|
366
|
+
decision = should_answer(
|
|
367
|
+
response, history=history, require_ready=require_ready
|
|
368
|
+
)
|
|
369
|
+
sections = []
|
|
370
|
+
profile = _profile_lines(
|
|
371
|
+
response.get("profile") if isinstance(response, Mapping) else None
|
|
372
|
+
)
|
|
373
|
+
if profile:
|
|
374
|
+
sections.append("\n".join(profile))
|
|
375
|
+
if decision.answer and decision.memories:
|
|
376
|
+
heading = (
|
|
377
|
+
"Memories to answer from (earlier versions are labelled):"
|
|
378
|
+
if decision.reason == "history"
|
|
379
|
+
else "Memories to answer from (current, supported for this message):"
|
|
380
|
+
)
|
|
381
|
+
lines = [heading]
|
|
382
|
+
for index, row in enumerate(decision.memories, start=1):
|
|
383
|
+
details = _memory_details(row)
|
|
384
|
+
lines.append(f"[{index}]" + (f" ({'; '.join(details)})" if details else ""))
|
|
385
|
+
lines.append(str(row.get("content") or ""))
|
|
386
|
+
sections.append("\n".join(lines))
|
|
387
|
+
elif decision.reason == CONTEXT_ONLY and decision.context:
|
|
388
|
+
lines = [
|
|
389
|
+
"Memories that should shape the suggestion (context: not established "
|
|
390
|
+
"facts, and never permission to act):"
|
|
391
|
+
]
|
|
392
|
+
for index, row in enumerate(decision.context, start=1):
|
|
393
|
+
details = _memory_details(row)
|
|
394
|
+
lines.append(f"[{index}]" + (f" ({'; '.join(details)})" if details else ""))
|
|
395
|
+
lines.append(str(row.get("content") or ""))
|
|
396
|
+
sections.append("\n".join(lines))
|
|
397
|
+
return "\n\n".join(sections)
|