niadra 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.
Files changed (51) hide show
  1. niadra-0.1.0/.gitignore +9 -0
  2. niadra-0.1.0/CHANGELOG.md +44 -0
  3. niadra-0.1.0/LICENSE +202 -0
  4. niadra-0.1.0/PKG-INFO +398 -0
  5. niadra-0.1.0/README.md +373 -0
  6. niadra-0.1.0/pyproject.toml +78 -0
  7. niadra-0.1.0/src/niadra/__init__.py +136 -0
  8. niadra-0.1.0/src/niadra/_async_client.py +582 -0
  9. niadra-0.1.0/src/niadra/_base.py +585 -0
  10. niadra-0.1.0/src/niadra/_cache.py +206 -0
  11. niadra-0.1.0/src/niadra/_client.py +691 -0
  12. niadra-0.1.0/src/niadra/_ids.py +39 -0
  13. niadra-0.1.0/src/niadra/_queue.py +357 -0
  14. niadra-0.1.0/src/niadra/_transport.py +317 -0
  15. niadra-0.1.0/src/niadra/_version.py +1 -0
  16. niadra-0.1.0/src/niadra/conversation.py +416 -0
  17. niadra-0.1.0/src/niadra/errors.py +105 -0
  18. niadra-0.1.0/src/niadra/handles.py +77 -0
  19. niadra-0.1.0/src/niadra/integrations/__init__.py +5 -0
  20. niadra-0.1.0/src/niadra/integrations/openai.py +359 -0
  21. niadra-0.1.0/src/niadra/keys.py +45 -0
  22. niadra-0.1.0/src/niadra/models/__init__.py +101 -0
  23. niadra-0.1.0/src/niadra/models/_base.py +20 -0
  24. niadra-0.1.0/src/niadra/models/common.py +69 -0
  25. niadra-0.1.0/src/niadra/models/context.py +217 -0
  26. niadra-0.1.0/src/niadra/models/events.py +272 -0
  27. niadra-0.1.0/src/niadra/models/objects.py +20 -0
  28. niadra-0.1.0/src/niadra/models/results.py +118 -0
  29. niadra-0.1.0/src/niadra/models/tokens.py +34 -0
  30. niadra-0.1.0/src/niadra/options.py +55 -0
  31. niadra-0.1.0/src/niadra/py.typed +0 -0
  32. niadra-0.1.0/src/niadra/tools.py +297 -0
  33. niadra-0.1.0/src/niadra/vocabulary.py +101 -0
  34. niadra-0.1.0/src/niadra_mock/__init__.py +24 -0
  35. niadra-0.1.0/src/niadra_mock/__main__.py +47 -0
  36. niadra-0.1.0/src/niadra_mock/app.py +297 -0
  37. niadra-0.1.0/src/niadra_mock/cell.py +688 -0
  38. niadra-0.1.0/tests/__init__.py +0 -0
  39. niadra-0.1.0/tests/conftest.py +125 -0
  40. niadra-0.1.0/tests/test_async.py +122 -0
  41. niadra-0.1.0/tests/test_context.py +374 -0
  42. niadra-0.1.0/tests/test_fail_open.py +109 -0
  43. niadra-0.1.0/tests/test_handles.py +74 -0
  44. niadra-0.1.0/tests/test_keys.py +104 -0
  45. niadra-0.1.0/tests/test_methods.py +410 -0
  46. niadra-0.1.0/tests/test_mock.py +294 -0
  47. niadra-0.1.0/tests/test_objects_feedback_media.py +214 -0
  48. niadra-0.1.0/tests/test_openai_wrap.py +350 -0
  49. niadra-0.1.0/tests/test_track.py +238 -0
  50. niadra-0.1.0/tests/test_transport.py +158 -0
  51. niadra-0.1.0/uv.lock +738 -0
@@ -0,0 +1,9 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ .pytest_cache/
5
+ .mypy_cache/
6
+ .ruff_cache/
7
+ dist/
8
+ build/
9
+ *.egg-info/
@@ -0,0 +1,44 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project adheres to
5
+ [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [0.1.0] - 2026-09-23
8
+
9
+ First public release, against the `/v1` API and the v0 open specs.
10
+
11
+ ### Added
12
+
13
+ - `Niadra` and `AsyncNiadra`, twin clients over one transport core.
14
+ - `context()` with per-conversation caching: fresh for 10 s, stale-while-revalidate for 10
15
+ minutes more with one background refresh per key, ETag revalidation, the last good pack on
16
+ errors up to 30 minutes old, at most 1,000 packs, and purge on 401 and 403 (`CacheOptions`).
17
+ Plain and delta reads of a conversation share one entry, and each delta is handed out once.
18
+ - History navigation: `search()`, `timeline()` and `open()`.
19
+ - `track()` with a bounded local queue, batching by count and time, three attempts with backoff,
20
+ and per-source heartbeats. `action()` and `handoff()` build on it.
21
+ - `identify()` and `verify()`, sent at once so the next `context()` reflects them.
22
+ - `conversation()` and `task()` context managers that read the pack the server pins, ask for
23
+ deltas after the first read and keep them until the pack changes, capture turns, and emit
24
+ `conversation.ended` or `task.ended`. `verify()` on a session raises its level for later reads.
25
+ A task centers its pack on its object and defaults to the `brief` view. `tools()` on a session
26
+ gives the history kit bound to it, following its verification level.
27
+ - `mark_injected()` and `context_stamp`: the agent's turns and actions carry the etag of the pack
28
+ its prompt held and when it went in, as the event's `context_stamp`.
29
+ - `object_state()` and `object_timeline()` for business objects.
30
+ - `feedback()` to retract or correct a fact, resolve an open item or record a conversation's outcome.
31
+ - `upload_media()`: reserves an upload, sends the bytes to the signed URL with exactly the headers it names (HTTPS
32
+ only, never the key) and returns `media_ref` and `media_sha256`; optionally bound to a `subject`.
33
+ - `tools()`: the history kit as function-calling tools bound to one customer, in OpenAI and
34
+ Anthropic shapes.
35
+ - `subject_token()` and `mcp_url` for MCP connections bound to one customer.
36
+ - `wrap()` for the OpenAI Python client, sync and async: `chat.completions.create` and `parse`
37
+ (also under `beta`), streams, and `with_raw_response`. It stamps the injection, records the
38
+ answer (the first choice), and never lets a capture failure reach the caller.
39
+ - `object_refs` in events accept the `type:namespace:id` shorthand.
40
+ - Handle helpers: `phone`, `email`, `whatsapp`, `whatsapp_bsuid`, `system_id`, `app_user`, `anonymous`.
41
+ - Fail-open behavior: a no-op client without a key, no exceptions from public methods unless
42
+ `strict=True`, and per-method time budgets.
43
+ - `niadra-mock`, an in-memory emulator of the API with ASGI and WSGI entry points and a
44
+ `niadra-mock` command, including object reads, feedback and media uploads.
niadra-0.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
niadra-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,398 @@
1
+ Metadata-Version: 2.5
2
+ Name: niadra
3
+ Version: 0.1.0
4
+ Summary: Python SDK for Niadra, the shared customer memory for every AI agent in a company: context before the model call, history, tools and MCP.
5
+ Project-URL: Homepage, https://niadra.com
6
+ Project-URL: Documentation, https://niadra.com/en/docs
7
+ Project-URL: Source, https://github.com/ainiadra/niadra-sdk-python
8
+ Author: Niadra
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: agent-memory,ai-agents,context-engineering,customer-context,customer-support,function-calling,gdpr,lgpd,llm,mcp,niadra,voice-ai,whatsapp
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.10
22
+ Requires-Dist: httpx<1,>=0.27
23
+ Requires-Dist: pydantic<3,>=2.6
24
+ Description-Content-Type: text/markdown
25
+
26
+ # Niadra Python SDK
27
+
28
+ [![PyPI](https://img.shields.io/pypi/v/niadra)](https://pypi.org/project/niadra/)
29
+ [![Python](https://img.shields.io/pypi/pyversions/niadra)](https://pypi.org/project/niadra/)
30
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue)](LICENSE)
31
+
32
+ **Niadra is the shared customer memory for every AI agent in a company.** The WhatsApp agent, the
33
+ voice agent, the billing agent and the human team read the same memory before they act and write
34
+ back what they said and did. This package connects a Python agent to it.
35
+
36
+ [Website](https://niadra.com/en) · [Documentation](https://niadra.com/en/docs) ·
37
+ [Talk to us](https://niadra.com/en/enterprise) · [TypeScript SDK](https://github.com/ainiadra/niadra-sdk-ts)
38
+
39
+ ```
40
+ pip install niadra
41
+ ```
42
+
43
+ ## The problem it solves
44
+
45
+ A customer tells your WhatsApp agent that order 4471 arrived with a broken lid and that she needs a
46
+ replacement by Friday. An hour later she calls. Without shared memory, the voice agent asks her to
47
+ explain everything again, and nobody remembers the Friday promise. With Niadra, the voice agent
48
+ starts the call knowing about the open replacement and its deadline, and when the billing agent
49
+ credits her invoice, the other agents see it within seconds.
50
+
51
+ Niadra does the remembering for you:
52
+
53
+ - it turns conversations and system events into facts, open items and promises, each with the
54
+ turns that prove it;
55
+ - it ties them to the right person across phone numbers, e-mails, WhatsApp ids and CRM ids, and to
56
+ the companies and partners that person acts for;
57
+ - it compiles a short context for each agent, holding back what the customer's verification level
58
+ does not allow, and records a receipt of every read.
59
+
60
+ Your agents keep their own models, prompts and vendors. Niadra is the memory layer they share.
61
+
62
+ ## Quickstart
63
+
64
+ ```python
65
+ from niadra import Niadra, phone
66
+
67
+ niadra = Niadra(channel="whatsapp") # reads NIADRA_API_KEY
68
+ customer = phone("+5511912345678")
69
+
70
+ with niadra.conversation("thread-81", subject=customer) as conversation:
71
+ conversation.customer(incoming_text) # what the customer wrote
72
+ context = conversation.context() # what this agent needs to know now
73
+ prompt = instructions + "\n\n" + context.system_block + "\n\n" + context.turn_block
74
+ conversation.mark_injected(context)
75
+ reply = your_model(prompt)
76
+ conversation.agent(reply) # what the agent answered
77
+ ```
78
+
79
+ Three moments cover most agents: read the context before the model call, record the turns after
80
+ it, and record an `action()` when the agent does something in a system (a refund, a new delivery
81
+ date). `wrap()` does the reading and recording for you around an OpenAI-compatible client.
82
+
83
+ Requires Python 3.10+. Depends on `httpx` and `pydantic` only.
84
+
85
+ ## What your agent gets
86
+
87
+ | Call | What it returns |
88
+ |---|---|
89
+ | `context()` | a few lines about this customer, compiled from every channel and agent, pinned for the conversation |
90
+ | `search()`, `timeline()`, `open()` | the full history on demand, with how often a problem happened before |
91
+ | `tools()` | the same history as function-calling tools bound to one customer, for any model provider |
92
+ | `subject_token()` | a token that binds an MCP connection to one customer |
93
+ | `track()`, `action()` | messages, system events and actions, sent in the background, never blocking the agent |
94
+ | `identify()`, `verify()` | which ids belong to the same person, and what the conversation proved about who is there |
95
+ | `object_state()`, `object_timeline()` | a business object (an order, an invoice, a ticket) as the systems of record reported it |
96
+ | `feedback()` | a correction of what Niadra derived, audited like any other event |
97
+
98
+ ## Questions people ask
99
+
100
+ **How do I give my AI agent memory of past conversations on other channels?** Record the turns
101
+ with `track()` or `conversation()` in every agent, and read `context()` before each model call.
102
+ Niadra ties the turns to the person, whichever id each channel uses.
103
+
104
+ **How is this different from keeping chat history in my database or in a vector store?** Stored
105
+ history is raw text for one channel. Niadra keeps derived facts and open items with evidence,
106
+ resolves identity across channels and systems, closes items when a system of record confirms an
107
+ action, and filters what each agent may read by the verification level of the conversation.
108
+
109
+ **What happens if Niadra is slow or down?** The agent keeps answering without the memory. Every
110
+ call has its own time budget (150 ms for voice context, 300 ms otherwise) and returns an empty
111
+ value instead of raising, unless you ask for `strict=True`.
112
+
113
+ **What about privacy and LGPD or GDPR?** Items carry a verification level and a purpose, and the
114
+ policy decides what each agent sees. Every read leaves a receipt, and a person can be erased or
115
+ exported on request. The SDK never logs handles or message text.
116
+
117
+ **Which models and frameworks does it work with?** Any. The context is text you place in your
118
+ prompt, the tools follow the common function-calling format (and the Anthropic one), and
119
+ `wrap()` covers OpenAI-compatible clients.
120
+
121
+ ## The client
122
+
123
+ `Niadra` is synchronous and thread-safe; `AsyncNiadra` has the same methods, awaited. One instance
124
+ per process is enough. The key names its region and space, and the SDK derives the address from it:
125
+ `nia_sk_live_br1_acme_...` talks to `https://acme.br1.api.niadra.com`. Pass `base_url=` (or set
126
+ `NIADRA_BASE_URL`) to point it elsewhere, such as the local emulator.
127
+
128
+ ## Context
129
+
130
+ `context()` returns the context pack for a person, an organization or a business object: the few
131
+ lines that matter now, compiled by Niadra from every channel and every agent.
132
+
133
+ ```python
134
+ context = niadra.context(
135
+ phone("+5511912345678"),
136
+ view="voice", # chat, voice, brief, full, account, partner, task:<name>
137
+ verification="V1", # what you have proven about who is on the line
138
+ conversation_id=call_id,
139
+ target="openai/gpt-4.1", # lets Niadra aim the pack at the model's prompt-cache floor
140
+ )
141
+ context.system_block # the pinned pack: place it after your own instructions
142
+ context.turn_block # live turns from other channels and the delta: place it at the end
143
+ context.withheld # items the policy held back at this verification level
144
+ ```
145
+
146
+ Pass `object="invoice:erp:0823"` instead of a subject to center the pack on a business object, and
147
+ `about=` to add what the organization the person acts for has that matters here.
148
+
149
+ With a `conversation_id` (or `task_id`) the server pins the pack to the same bytes on every
150
+ turn. `delta=True` asks for what changed since this agent last read the subject; the server sends
151
+ each change once, and `conversation()` keeps them for you (below).
152
+
153
+ ### The context cache
154
+
155
+ Inside a conversation or task, packs are cached in memory:
156
+
157
+ - younger than 10 s: returned without a request;
158
+ - up to 10 minutes older: returned at once while one background request refreshes it;
159
+ - when a request fails: the last good pack, if it is less than 30 minutes old;
160
+ - at most 1,000 packs, the least recently used evicted first.
161
+
162
+ Refreshes send the cached ETag, so an unchanged pack costs a `not_modified` answer instead of the
163
+ full text, and only one background refresh per pack runs at a time. A 401 or 403 is not an
164
+ outage: the cached packs go (all of them on 401, the one requested on 403), so cutting a vendor's
165
+ access also cuts what it had cached. A plain read and a `delta` read of one conversation share one
166
+ entry, and each delta is handed out once.
167
+
168
+ Configure it with `CacheOptions(ttl, stale_while_revalidate, max_stale, max_entries)`, in
169
+ seconds, or turn it off with `CacheOptions(enabled=False)`.
170
+
171
+ ## Search, timeline and open
172
+
173
+ For what does not fit in the pack, the whole history is one call away.
174
+
175
+ ```python
176
+ found = niadra.search(customer, "technician visit", conversation_id=call_id)
177
+ found.recurrence # occurrences=3, window_days=90: "this happened before"
178
+ page = niadra.timeline(customer, limit=20) # most recent first; pass page.next_cursor to go on
179
+ item = niadra.open(found.items[0].id) # what was asked, promised and by whom, the outcome
180
+ ```
181
+
182
+ ## Track
183
+
184
+ `track()` records a message, a system event or an action. It never blocks: items go to a bounded
185
+ local queue and a background thread (a task, with `AsyncNiadra`) sends them in batches of 15 or
186
+ every second, whichever comes first, with three attempts and backoff.
187
+
188
+ ```python
189
+ niadra.track(
190
+ {
191
+ "conversation_id": thread_id,
192
+ "handles": [phone("+5511912345678")],
193
+ "speaker": {"role": "customer"},
194
+ "content": {"text": "I was charged twice"},
195
+ }
196
+ )
197
+ ```
198
+
199
+ Items take their `idempotency_key` from you (use the provider's message id when there is one) or
200
+ from a UUIDv7 minted by the SDK, so a retried batch never duplicates anything. Call `flush()` to send
201
+ what is queued now; `close()` and the exit hook flush for you.
202
+
203
+ ## Identity and verification
204
+
205
+ ```python
206
+ niadra.identify([phone("+5511912345678"), email("marina@example.com")])
207
+ niadra.verify("otp_whatsapp", "V2", handle=phone("+5511912345678"), conversation_id=thread_id)
208
+ ```
209
+
210
+ `identify()` states that handles belong to the same person. `verify()` raises the verification
211
+ level of one conversation after you proved it; Niadra never infers it. Both are sent at once rather
212
+ than queued, so the next `context()` sees them, and `verify()` drops the cached pack of that
213
+ conversation.
214
+
215
+ ## Actions
216
+
217
+ ```python
218
+ niadra.action(
219
+ "credit",
220
+ subject=customer,
221
+ object="invoice:erp:0823",
222
+ result="R$ 40",
223
+ closes={"object": "invoice:erp:0823", "operation": "credit"},
224
+ )
225
+ ```
226
+
227
+ An action is what an agent did in a system of record. `closes` names the open item or promise it
228
+ fulfils. It shows in every other agent's pack as declared until the system of record confirms it.
229
+
230
+ ## Conversations and tasks
231
+
232
+ ```python
233
+ with niadra.conversation(thread_id, subject=customer, view="chat") as conversation:
234
+ conversation.customer(incoming_text)
235
+ context = conversation.context() # pinned, cached, with every delta since the pin
236
+ conversation.mark_injected(context) # when the pack went into the prompt
237
+ conversation.agent(reply_text) # carries the context stamp
238
+ conversation.verify("otp_whatsapp", "V2")
239
+ conversation.handoff("human", reason="asked for a person")
240
+ # conversation.ended is emitted on exit, even if the block raised
241
+ ```
242
+
243
+ The first `context()` of a conversation gets the pack the server pins for it. Later reads also
244
+ ask for the delta, and the conversation keeps every delta it receives, in order, in
245
+ `context.delta`, so `turn_block` carries all the changes since the pin, followed by the live
246
+ turns. When the server pins a new pack, after `verify()` for instance, the kept deltas are
247
+ dropped: the new pack already has them. A read with `query=` is a one-off and leaves them alone.
248
+
249
+ Call `mark_injected()` each time you put the pack in a prompt. The agent's turns and actions that
250
+ follow carry it as `context_stamp`, with the pack's etag, which is how Niadra tells a context
251
+ that arrived after the agent spoke from one the agent had and did not use.
252
+ `context_injected_at` and `first_agent_turn_at` keep the first of each, for your own checks.
253
+
254
+ `task()` is the same for internal agents (billing, orders, tickets): it takes an `object` and a task
255
+ view such as `task:billing` (the default is `brief`), centers the pack on the object, and emits
256
+ `task.ended`.
257
+
258
+ ### Wrapping the OpenAI client
259
+
260
+ ```python
261
+ from openai import OpenAI
262
+ from niadra import wrap
263
+
264
+ openai = wrap(OpenAI())
265
+ with niadra.conversation(thread_id, subject=customer):
266
+ openai.chat.completions.create(model="gpt-4.1", messages=messages)
267
+ ```
268
+
269
+ Inside a conversation block, `chat.completions.create` and `chat.completions.parse`, sync or
270
+ async, streaming or not, get the pack after your leading system messages and the turn block at
271
+ the end. The injection is stamped, and the model's answer is recorded as the agent's turn: when
272
+ a stream ends or is closed, and, through `with_raw_response`, when you call `parse()`. Outside a
273
+ block, calls pass through untouched. Nothing the wrapper does can fail your call: a context it
274
+ cannot fetch is left out, and a failure to record the answer is logged, without content.
275
+
276
+ ## Business objects
277
+
278
+ ```python
279
+ invoice = niadra.object_state("invoice:erp:0823") # state, as_of, open items
280
+ page = niadra.object_timeline("invoice:erp:0823", limit=20)
281
+ ```
282
+
283
+ The state comes only from what the systems of record reported; an agent's action counts once a
284
+ system confirms it. The timeline lists system events and agent actions, newest first, never what
285
+ anyone said. Object ids are record ids, not personal data, so they go in the URL; an id with a
286
+ slash cannot be addressed that way.
287
+
288
+ ## Feedback
289
+
290
+ ```python
291
+ niadra.feedback("correct_fact", customer, fact_id=fact.id, value="prefers e-mail")
292
+ niadra.feedback("resolve_open_item", customer, open_item_id=item.id)
293
+ niadra.feedback("conversation_outcome", customer, conversation_id=thread_id, value="resolved")
294
+ ```
295
+
296
+ A correction of what Niadra derived. It is sent at once and recorded as an event, so it is
297
+ audited like any other; `retract_fact` takes the fact out of every pack.
298
+
299
+ ## Media
300
+
301
+ ```python
302
+ upload = niadra.upload_media(recording, "audio/wav", subject=customer)
303
+ if upload:
304
+ niadra.track(
305
+ {
306
+ "conversation_id": call_id,
307
+ "handles": [customer],
308
+ "speaker": {"role": "customer"},
309
+ "content": {
310
+ "type": "audio",
311
+ "media_ref": upload.media_ref,
312
+ "media_sha256": upload.media_sha256,
313
+ "transcript": transcript,
314
+ },
315
+ }
316
+ )
317
+ ```
318
+
319
+ Media never travels inside an event. `upload_media()` reserves an upload, sends the bytes
320
+ straight to storage over a signed URL (HTTPS only, with exactly the headers the signature
321
+ covers and nothing else, so never your key), and returns the reference and digest for the event.
322
+ Storage checks the body against the declared size and digest. With `subject`, the file is stored under that person, so
323
+ erasing them erases it even if no event ever references it.
324
+
325
+ ## Tools and MCP
326
+
327
+ `tools()` gives any model the history kit as function-calling tools, bound to one customer. The
328
+ customer is not a parameter the model can see or change, which is what stops a prompt injection
329
+ from switching customers.
330
+
331
+ ```python
332
+ kit = niadra.tools(customer, conversation_id=thread_id)
333
+ response = openai.chat.completions.create(model="gpt-4.1", messages=messages, tools=kit.definitions)
334
+ for call in response.choices[0].message.tool_calls or []:
335
+ result = kit.call(call.function.name, call.function.arguments) # always a string for the model
336
+ ```
337
+
338
+ Inside a conversation or task, `conversation.tools()` gives the same kit bound to it, at the
339
+ session's current verification level, including a level raised by `verify()` after the kit was
340
+ made. `kit.anthropic_definitions()` returns the same tools in the Anthropic shape. For agents that speak
341
+ MCP, mint a subject token from your backend and open the connection with it:
342
+
343
+ ```python
344
+ token = niadra.subject_token(customer, conversation_id=thread_id, verification="V1")
345
+ # connect to niadra.mcp_url with the source key as Bearer and token.headers
346
+ ```
347
+
348
+ ## Failure behavior
349
+
350
+ Niadra must never take your agent down.
351
+
352
+ - **No key:** the client is a no-op and warns once.
353
+ - **Every public method** catches and logs its own failures and returns a safe value: an empty
354
+ `Context` (check `context.error`), an empty result, `False` or `None`.
355
+ - **Own time budgets:** `context()` gives up after 150 ms for voice views and 300 ms otherwise;
356
+ search, timeline, open and the object reads after 300 ms (voice) or 600 ms; writes sent at
357
+ once after 5 s per attempt, and each attempt of a media transfer after 60 s. Adjust them with
358
+ `Timeouts`.
359
+ - **Retries:** 5xx, 429 and network errors are retried with backoff; 421 (the space is moving
360
+ between cells) is retried at once on a fresh connection; other 4xx are final.
361
+ - **Logs** carry method names, status codes, error codes and request ids, never handles or text.
362
+
363
+ Pass `strict=True` to raise instead, which is what you want in tests.
364
+
365
+ ## Testing without the cloud
366
+
367
+ `niadra-mock` is a local, in-memory emulator of the same API. In tests, run the SDK against it
368
+ in-process:
369
+
370
+ ```python
371
+ import httpx
372
+ from niadra import Niadra
373
+ from niadra_mock import MOCK_KEY, MockApp
374
+
375
+ mock = MockApp()
376
+ http = httpx.Client(
377
+ transport=httpx.WSGITransport(app=mock.wsgi)
378
+ ) # ASGITransport(app=mock.asgi) for AsyncNiadra
379
+ niadra = Niadra(MOCK_KEY, base_url="http://mock", http_client=http, strict=True)
380
+ ```
381
+
382
+ Recent turns become a small pack, deltas are sent once per change, search matches keywords,
383
+ verification only rises through `verify()`, objects take their state from system events, feedback
384
+ becomes a `feedback.*` event, and media uploads land in `mock.cell.media`. `mock.cell` also lets
385
+ you inspect events or inject failures (`fail_next`, `revoke`, `cut`, `put_in_holdout`). From a shell, `niadra-mock --port 8765` serves it over HTTP.
386
+
387
+ ## Em português
388
+
389
+ A Niadra é a memória de clientes compartilhada por todos os agentes de IA de uma empresa: o agente
390
+ do WhatsApp, o de voz, o de cobrança e o time humano leem a mesma memória antes de agir e registram
391
+ o que disseram e fizeram. Este pacote conecta um agente em Python a essa memória: `context()` antes
392
+ de chamar o modelo, `track()` depois, e `action()` quando o agente faz algo num sistema.
393
+ Documentação em [niadra.com/docs](https://niadra.com/docs) e contato em
394
+ [niadra.com/enterprise](https://niadra.com/enterprise).
395
+
396
+ ## License
397
+
398
+ Apache 2.0. See [LICENSE](LICENSE).