littlebigbrain 0.3.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.
- littlebigbrain-0.3.0/LICENSE +56 -0
- littlebigbrain-0.3.0/PKG-INFO +268 -0
- littlebigbrain-0.3.0/README.md +231 -0
- littlebigbrain-0.3.0/lbb/__init__.py +33 -0
- littlebigbrain-0.3.0/lbb/_async_client.py +371 -0
- littlebigbrain-0.3.0/lbb/_client_base.py +1778 -0
- littlebigbrain-0.3.0/lbb/_sync_client.py +383 -0
- littlebigbrain-0.3.0/lbb/client.py +19 -0
- littlebigbrain-0.3.0/lbb/local.py +174 -0
- littlebigbrain-0.3.0/lbb/models.py +7630 -0
- littlebigbrain-0.3.0/lbb/py.typed +1 -0
- littlebigbrain-0.3.0/littlebigbrain.egg-info/PKG-INFO +268 -0
- littlebigbrain-0.3.0/littlebigbrain.egg-info/SOURCES.txt +19 -0
- littlebigbrain-0.3.0/littlebigbrain.egg-info/dependency_links.txt +1 -0
- littlebigbrain-0.3.0/littlebigbrain.egg-info/requires.txt +14 -0
- littlebigbrain-0.3.0/littlebigbrain.egg-info/top_level.txt +1 -0
- littlebigbrain-0.3.0/pyproject.toml +73 -0
- littlebigbrain-0.3.0/setup.cfg +4 -0
- littlebigbrain-0.3.0/tests/test_client.py +1029 -0
- littlebigbrain-0.3.0/tests/test_contract_routes.py +91 -0
- littlebigbrain-0.3.0/tests/test_public_api.py +37 -0
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
|
|
5
|
+
http://www.apache.org/licenses/
|
|
6
|
+
|
|
7
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
8
|
+
|
|
9
|
+
1. Definitions.
|
|
10
|
+
|
|
11
|
+
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
|
16
|
+
|
|
17
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
|
18
|
+
|
|
19
|
+
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
|
20
|
+
|
|
21
|
+
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
|
22
|
+
|
|
23
|
+
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
|
24
|
+
|
|
25
|
+
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
|
26
|
+
|
|
27
|
+
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
|
28
|
+
|
|
29
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
|
30
|
+
|
|
31
|
+
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
|
32
|
+
|
|
33
|
+
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
|
34
|
+
|
|
35
|
+
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
|
36
|
+
|
|
37
|
+
You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
|
38
|
+
|
|
39
|
+
You must cause any modified files to carry prominent notices stating that You changed the files; and
|
|
40
|
+
|
|
41
|
+
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
|
42
|
+
|
|
43
|
+
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
|
44
|
+
|
|
45
|
+
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
|
46
|
+
|
|
47
|
+
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
|
48
|
+
|
|
49
|
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
|
50
|
+
|
|
51
|
+
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
|
52
|
+
|
|
53
|
+
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
|
54
|
+
|
|
55
|
+
END OF TERMS AND CONDITIONS
|
|
56
|
+
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: littlebigbrain
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Python client for the little big brain graph + hybrid search HTTP API
|
|
5
|
+
Author: little big brain
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Documentation, https://docs.littlebigbrain.com/sdks/python/
|
|
8
|
+
Project-URL: Issues, https://github.com/littlebigbrains/lbb-python/issues
|
|
9
|
+
Project-URL: Repository, https://github.com/littlebigbrains/lbb-python
|
|
10
|
+
Keywords: little-big-brain,graph,search,sdk
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Requires-Dist: httpx>=0.27
|
|
24
|
+
Requires-Dist: pydantic>=2
|
|
25
|
+
Provides-Extra: dev
|
|
26
|
+
Requires-Dist: build==1.5.1; extra == "dev"
|
|
27
|
+
Requires-Dist: black==26.5.1; extra == "dev"
|
|
28
|
+
Requires-Dist: datamodel-code-generator==0.63.0; extra == "dev"
|
|
29
|
+
Requires-Dist: isort==8.0.1; extra == "dev"
|
|
30
|
+
Requires-Dist: mypy>=1.15; extra == "dev"
|
|
31
|
+
Requires-Dist: packaging==26.2; extra == "dev"
|
|
32
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
33
|
+
Requires-Dist: pytest-cov>=6; extra == "dev"
|
|
34
|
+
Requires-Dist: ruff>=0.11; extra == "dev"
|
|
35
|
+
Requires-Dist: twine==6.2.0; extra == "dev"
|
|
36
|
+
Dynamic: license-file
|
|
37
|
+
|
|
38
|
+
# little big brain Python SDK
|
|
39
|
+
|
|
40
|
+
`lbb` is the Python client for a [little big brain](https://littlebigbrain.com) graph server. The
|
|
41
|
+
HTTP client (`LbbClient` / `AsyncLbbClient`) is the integration path for
|
|
42
|
+
applications; it talks to `lbb-server` with a stack API key (`lbb_sk_test_…`
|
|
43
|
+
or `lbb_sk_live_…`) or
|
|
44
|
+
single-mode token as a bearer credential — the same surface the TypeScript SDK,
|
|
45
|
+
CLI, and MCP server use.
|
|
46
|
+
|
|
47
|
+
```sh
|
|
48
|
+
pip install littlebigbrain # imports as `lbb` (httpx + pydantic)
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## HTTP client
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from lbb import LbbClient, LbbError
|
|
55
|
+
|
|
56
|
+
with LbbClient(
|
|
57
|
+
"https://db.eu.littlebigbrain.com",
|
|
58
|
+
api_key="lbb_sk_live_...",
|
|
59
|
+
graph="main",
|
|
60
|
+
) as lbb:
|
|
61
|
+
lbb.graph("main").facts.create({
|
|
62
|
+
"triplets": [{
|
|
63
|
+
"source": {"type": "SERVICE", "name": "auth-service"},
|
|
64
|
+
"relation": "WRITES_TO",
|
|
65
|
+
"target": {"type": "DATABASE", "name": "user-db"},
|
|
66
|
+
"confidence": 0.93,
|
|
67
|
+
"evidence": "auth-service writes identity records to user-db",
|
|
68
|
+
}],
|
|
69
|
+
}, idempotency_key="import-2026-06-13")
|
|
70
|
+
lbb.indexes.run(wait=True)
|
|
71
|
+
results = lbb.search.hybrid(
|
|
72
|
+
"which systems store customer identity data",
|
|
73
|
+
top_k=5,
|
|
74
|
+
source="persisted",
|
|
75
|
+
consistency="strong",
|
|
76
|
+
targets=["entities", "assertions"],
|
|
77
|
+
)
|
|
78
|
+
for assertion in results.get("assertions", []):
|
|
79
|
+
print(assertion["relation"]["name"], assertion["score"])
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Use `client.graph("name")` to scope writes. The regular methods return parsed
|
|
83
|
+
JSON dictionaries and raise `LbbError` with `status_code`, `type`, `code`,
|
|
84
|
+
`param`, `request_id`, and `doc_url` on a non-2xx response. Use
|
|
85
|
+
`raw_request(...)` when you need response metadata. An async client mirrors the
|
|
86
|
+
same methods:
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
from lbb import AsyncLbbClient
|
|
90
|
+
|
|
91
|
+
async with AsyncLbbClient("https://db.eu.littlebigbrain.com", api_key="lbb_sk_live_...") as lbb:
|
|
92
|
+
state = await lbb.current_state({"entity": {"entity_type": "SERVICE", "name": "auth-service"}})
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
The default per-attempt timeout is 120 seconds (`timeout=...` configures it).
|
|
96
|
+
Safe reads and idempotency-keyed writes retry `429`/`5xx` and transport failures
|
|
97
|
+
up to twice, honor `Retry-After` with a one-minute cap, and attach generated
|
|
98
|
+
idempotency keys to NDJSON/RDF imports unless you provide one.
|
|
99
|
+
|
|
100
|
+
## Preferred typed surface
|
|
101
|
+
|
|
102
|
+
The `context`, `ontology`, and `query` namespaces return generated Pydantic
|
|
103
|
+
models by default, while the existing flat methods keep their dict-returning
|
|
104
|
+
behavior for compatibility:
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
answer = lbb.context.ask({"question": "what stores identity data?"})
|
|
108
|
+
print(answer.answer, answer.citations)
|
|
109
|
+
|
|
110
|
+
ontology = lbb.ontology.view(counts=True)
|
|
111
|
+
rows = lbb.query.structured({"patterns": [], "select": []})
|
|
112
|
+
|
|
113
|
+
for entity in lbb.entities.iter(fields=["owner", "status"]):
|
|
114
|
+
print(entity.name, entity.attributes or {})
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
`entities.pages(...)` yields typed `ListPage` envelopes; `entities.iter(...)`
|
|
118
|
+
yields `EntityExplorerRow` objects directly. Both forms also work with
|
|
119
|
+
`AsyncLbbClient` using `async for`.
|
|
120
|
+
|
|
121
|
+
`raw_request(..., options={...})` accepts per-request `max_retries`, `timeout`,
|
|
122
|
+
and `headers`. Its response exposes `attempts`, `retry_count`, and `elapsed_ms`.
|
|
123
|
+
Typed `context`, `ontology`, and `query` reads accept the same `options=` keyword
|
|
124
|
+
and automatically classify read-only POSTs as retry-safe.
|
|
125
|
+
Pass native `httpx` `event_hooks` to the client constructor for request/response
|
|
126
|
+
instrumentation.
|
|
127
|
+
|
|
128
|
+
Primary methods: `graph("main").facts.create`; `search.hybrid`;
|
|
129
|
+
`indexes.run`; `entities.list`; `entities.filter_by_attributes`;
|
|
130
|
+
`context.ask` / `context.suggest` / `context.resolve` / `context.decode` /
|
|
131
|
+
`context.groundability`; `ontology.view` / `ontology.search` /
|
|
132
|
+
`ontology.resolve`; `query.sparql` / `query.structured` / `query.analytics` /
|
|
133
|
+
`query.shacl` / `query.infer` / `query.premises`;
|
|
134
|
+
`schema.view` / `schema.preview` /
|
|
135
|
+
`schema.publish` / `schema.audit`; plus lower-level `graph_search`,
|
|
136
|
+
`multi_search`, `full_text_search`, `embedding_search`, `traverse`,
|
|
137
|
+
`semantic_traverse`, `current_state`, `history`, `why`, `shacl`,
|
|
138
|
+
`sparql` (SPARQL text → parsed results), `sparql_select` (structured
|
|
139
|
+
SELECT/ASK/aggregate — GROUP BY entity, property, or date bucket), `analytics`,
|
|
140
|
+
`ontology_view` (pass `counts=True` for per-relation `edge_count`),
|
|
141
|
+
`ontology_search`, `ontology_resolve`, `search_feedback` (grade results 3/1/0 →
|
|
142
|
+
customer qrels for embedding fine-tuning) and `search_feedback_export`,
|
|
143
|
+
`graph_edges`, `index_build`, `index_run`, `index_delta`, `index_gc`, `compact`,
|
|
144
|
+
`status`, `metadata`, and `summary`.
|
|
145
|
+
|
|
146
|
+
## Typed responses
|
|
147
|
+
|
|
148
|
+
The dict-returning methods are stable for scripts and notebooks. For app code
|
|
149
|
+
that wants generated Pydantic models and IDE autocompletion, use the matching
|
|
150
|
+
`*_model` or `*_page` helper:
|
|
151
|
+
|
|
152
|
+
```python
|
|
153
|
+
from lbb.models import GraphSummaryResponse, SchemaBundleView
|
|
154
|
+
|
|
155
|
+
summary: GraphSummaryResponse = lbb.summary_model()
|
|
156
|
+
schema: SchemaBundleView = lbb.schema.view_model()
|
|
157
|
+
|
|
158
|
+
entities = lbb.entities.list_page(fields="*")
|
|
159
|
+
for row in entities.data:
|
|
160
|
+
print(row.name, row.attributes or {})
|
|
161
|
+
|
|
162
|
+
raw = lbb.raw_request("GET", "/v1/graph/summary")
|
|
163
|
+
typed = raw.model(GraphSummaryResponse)
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
The preferred namespaces above return models directly. Additional typed helpers
|
|
167
|
+
cover the remaining high-use surfaces: `commit_model`, `commit_dry_run_model`, `graph("main").facts.create_model`,
|
|
168
|
+
`graph("main").retract_model`, `summary_model`, `metadata_model`,
|
|
169
|
+
`list_graphs_model`, `ontology_view_model`, `ontology_conformance_model`,
|
|
170
|
+
`sparql_select_model`, `schema.view_model`, `schema.preview_model`,
|
|
171
|
+
`schema.publish_model`, `schema.audit_model`, `entities.list_page`,
|
|
172
|
+
`entities.filter_by_attributes_model`, and `graph_edges_page`.
|
|
173
|
+
|
|
174
|
+
Async clients expose the same helpers as awaitables:
|
|
175
|
+
|
|
176
|
+
```python
|
|
177
|
+
summary = await lbb.summary_model()
|
|
178
|
+
page = await lbb.entities.list_page(fields=["title", "status"])
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
## SPARQL
|
|
182
|
+
|
|
183
|
+
`client.sparql(query)` runs SPARQL 1.1 text (SELECT or ASK) through the
|
|
184
|
+
conformant engine and returns a parsed `SparqlResults` — no manual
|
|
185
|
+
`json.loads` of a results string:
|
|
186
|
+
|
|
187
|
+
```python
|
|
188
|
+
results = lbb.sparql("""
|
|
189
|
+
SELECT ?service ?db WHERE {
|
|
190
|
+
?service <https://littlebigbrain.com/r/writes_to> ?db
|
|
191
|
+
} LIMIT 10
|
|
192
|
+
""")
|
|
193
|
+
|
|
194
|
+
print(results.vars) # ['service', 'db']
|
|
195
|
+
for row in results: # iterates flat {var: value} dicts
|
|
196
|
+
print(row["service"], "->", row["db"])
|
|
197
|
+
|
|
198
|
+
answer = lbb.sparql("ASK { ?s ?p ?o }").boolean # True / False
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
`SparqlResults` exposes `.vars`, `.boolean` (for ASK), `.bindings` (the raw
|
|
202
|
+
typed term objects), `.rows()` (flattened `{var: lexical_value}` dicts, also
|
|
203
|
+
what iteration yields), and `.row_page`. Engine extensions are keyword args:
|
|
204
|
+
`reason=True` folds rule-derived edges, `entailment="none"` disables the
|
|
205
|
+
default `rdfs:subClassOf` closure, and `as_of_valid_time` / `as_of_commit_seq`
|
|
206
|
+
pin a snapshot. For the structured BGP form, `client.sparql_select(body)` posts
|
|
207
|
+
a `SparqlSelectRequest` and returns the typed `vars`/`solutions`/`groups`
|
|
208
|
+
response.
|
|
209
|
+
|
|
210
|
+
For app code that already has relation patterns but just needs typed attribute
|
|
211
|
+
predicates, `client.entities.filter_by_attributes(...)` builds the structured
|
|
212
|
+
SPARQL filter body without exposing RDF property IRIs:
|
|
213
|
+
|
|
214
|
+
```python
|
|
215
|
+
lbb.entities.filter_by_attributes(
|
|
216
|
+
patterns=[{"subject": {"var": "service"}, "predicate": "WRITES_TO", "object": {"var": "db"}}],
|
|
217
|
+
where=[{"field": "slo", "op": "ge", "value": 0.99}, {"var": "db", "field": "tier", "value": "prod"}],
|
|
218
|
+
select=["service"],
|
|
219
|
+
)
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
A standalone stack also serves the **native SPARQL 1.1 Protocol** at `/sparql`
|
|
223
|
+
(`GET ?query=`, `POST` form or `application/sparql-query` body,
|
|
224
|
+
`Accept`-negotiated JSON/XML/CSV/TSV) so off-the-shelf SPARQL clients — YASGUI,
|
|
225
|
+
Protégé, RDFLib's `SPARQLWrapper` — connect directly; `client.sparql()` returns
|
|
226
|
+
parsed JSON rows for in-process use.
|
|
227
|
+
|
|
228
|
+
Bodies may be plain `dict`s or instances of the generated Pydantic models in
|
|
229
|
+
`lbb.models` (e.g. `lbb.models.SemanticGraphSearchRequest`), which are
|
|
230
|
+
generated from the committed [`contracts/openapi.json`](https://github.com/littlebigbrains/lbb-python/blob/main/contracts/openapi.json).
|
|
231
|
+
|
|
232
|
+
## Local client (`lbb.local`)
|
|
233
|
+
|
|
234
|
+
`LbbLocalClient` shells out to `lbb-testctl` and operates directly on object
|
|
235
|
+
storage — for tests, notebooks, and local demos, not application integration.
|
|
236
|
+
It requires a full little big brain **engine** checkout (`lbb-testctl` is
|
|
237
|
+
compiled with cargo), not just this SDK repository; point `repo_root` at that
|
|
238
|
+
checkout. It is re-exported as `from lbb import LbbLocalClient`.
|
|
239
|
+
|
|
240
|
+
```python
|
|
241
|
+
from lbb import LbbLocalClient
|
|
242
|
+
|
|
243
|
+
client = LbbLocalClient(root="/private/tmp/lbb-python", tenant="acme", graph="main", branch="main",
|
|
244
|
+
repo_root="/path/to/lbb") # engine checkout, not this repo
|
|
245
|
+
client.create_graph()
|
|
246
|
+
client.commit_triplets_file("/path/to/lbb/database/examples/triplets/semantic_graph.json")
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
It also exposes `build_embedding_index`, `embedding_index_inspect`,
|
|
250
|
+
`embedding_search`, `ontology_search`, `ontology_resolve`, `semantic_search`,
|
|
251
|
+
`traverse`, `current_state`, and `relationship_history`. See
|
|
252
|
+
[`examples/embedding_search.py`](examples/embedding_search.py).
|
|
253
|
+
|
|
254
|
+
## Develop
|
|
255
|
+
|
|
256
|
+
```sh
|
|
257
|
+
python3 -m venv .venv && .venv/bin/pip install -e ".[dev]" httpx pydantic
|
|
258
|
+
ruff check lbb tests
|
|
259
|
+
mypy lbb
|
|
260
|
+
pytest tests --cov=lbb
|
|
261
|
+
python -m build && twine check dist/*
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
`lbb/models.py` is generated; the `contracts` CI job regenerates it (and the
|
|
265
|
+
OpenAPI spec and TS types) and fails if the committed output drifts. The wheel
|
|
266
|
+
ships `py.typed`; generated models and all hand-written modules pass strict
|
|
267
|
+
mypy before release. Do not edit `models.py` by hand; maintainers regenerate it
|
|
268
|
+
from the canonical private monorepo and sync the result with the OpenAPI contract.
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
# little big brain Python SDK
|
|
2
|
+
|
|
3
|
+
`lbb` is the Python client for a [little big brain](https://littlebigbrain.com) graph server. The
|
|
4
|
+
HTTP client (`LbbClient` / `AsyncLbbClient`) is the integration path for
|
|
5
|
+
applications; it talks to `lbb-server` with a stack API key (`lbb_sk_test_…`
|
|
6
|
+
or `lbb_sk_live_…`) or
|
|
7
|
+
single-mode token as a bearer credential — the same surface the TypeScript SDK,
|
|
8
|
+
CLI, and MCP server use.
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
pip install littlebigbrain # imports as `lbb` (httpx + pydantic)
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## HTTP client
|
|
15
|
+
|
|
16
|
+
```python
|
|
17
|
+
from lbb import LbbClient, LbbError
|
|
18
|
+
|
|
19
|
+
with LbbClient(
|
|
20
|
+
"https://db.eu.littlebigbrain.com",
|
|
21
|
+
api_key="lbb_sk_live_...",
|
|
22
|
+
graph="main",
|
|
23
|
+
) as lbb:
|
|
24
|
+
lbb.graph("main").facts.create({
|
|
25
|
+
"triplets": [{
|
|
26
|
+
"source": {"type": "SERVICE", "name": "auth-service"},
|
|
27
|
+
"relation": "WRITES_TO",
|
|
28
|
+
"target": {"type": "DATABASE", "name": "user-db"},
|
|
29
|
+
"confidence": 0.93,
|
|
30
|
+
"evidence": "auth-service writes identity records to user-db",
|
|
31
|
+
}],
|
|
32
|
+
}, idempotency_key="import-2026-06-13")
|
|
33
|
+
lbb.indexes.run(wait=True)
|
|
34
|
+
results = lbb.search.hybrid(
|
|
35
|
+
"which systems store customer identity data",
|
|
36
|
+
top_k=5,
|
|
37
|
+
source="persisted",
|
|
38
|
+
consistency="strong",
|
|
39
|
+
targets=["entities", "assertions"],
|
|
40
|
+
)
|
|
41
|
+
for assertion in results.get("assertions", []):
|
|
42
|
+
print(assertion["relation"]["name"], assertion["score"])
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Use `client.graph("name")` to scope writes. The regular methods return parsed
|
|
46
|
+
JSON dictionaries and raise `LbbError` with `status_code`, `type`, `code`,
|
|
47
|
+
`param`, `request_id`, and `doc_url` on a non-2xx response. Use
|
|
48
|
+
`raw_request(...)` when you need response metadata. An async client mirrors the
|
|
49
|
+
same methods:
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
from lbb import AsyncLbbClient
|
|
53
|
+
|
|
54
|
+
async with AsyncLbbClient("https://db.eu.littlebigbrain.com", api_key="lbb_sk_live_...") as lbb:
|
|
55
|
+
state = await lbb.current_state({"entity": {"entity_type": "SERVICE", "name": "auth-service"}})
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
The default per-attempt timeout is 120 seconds (`timeout=...` configures it).
|
|
59
|
+
Safe reads and idempotency-keyed writes retry `429`/`5xx` and transport failures
|
|
60
|
+
up to twice, honor `Retry-After` with a one-minute cap, and attach generated
|
|
61
|
+
idempotency keys to NDJSON/RDF imports unless you provide one.
|
|
62
|
+
|
|
63
|
+
## Preferred typed surface
|
|
64
|
+
|
|
65
|
+
The `context`, `ontology`, and `query` namespaces return generated Pydantic
|
|
66
|
+
models by default, while the existing flat methods keep their dict-returning
|
|
67
|
+
behavior for compatibility:
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
answer = lbb.context.ask({"question": "what stores identity data?"})
|
|
71
|
+
print(answer.answer, answer.citations)
|
|
72
|
+
|
|
73
|
+
ontology = lbb.ontology.view(counts=True)
|
|
74
|
+
rows = lbb.query.structured({"patterns": [], "select": []})
|
|
75
|
+
|
|
76
|
+
for entity in lbb.entities.iter(fields=["owner", "status"]):
|
|
77
|
+
print(entity.name, entity.attributes or {})
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
`entities.pages(...)` yields typed `ListPage` envelopes; `entities.iter(...)`
|
|
81
|
+
yields `EntityExplorerRow` objects directly. Both forms also work with
|
|
82
|
+
`AsyncLbbClient` using `async for`.
|
|
83
|
+
|
|
84
|
+
`raw_request(..., options={...})` accepts per-request `max_retries`, `timeout`,
|
|
85
|
+
and `headers`. Its response exposes `attempts`, `retry_count`, and `elapsed_ms`.
|
|
86
|
+
Typed `context`, `ontology`, and `query` reads accept the same `options=` keyword
|
|
87
|
+
and automatically classify read-only POSTs as retry-safe.
|
|
88
|
+
Pass native `httpx` `event_hooks` to the client constructor for request/response
|
|
89
|
+
instrumentation.
|
|
90
|
+
|
|
91
|
+
Primary methods: `graph("main").facts.create`; `search.hybrid`;
|
|
92
|
+
`indexes.run`; `entities.list`; `entities.filter_by_attributes`;
|
|
93
|
+
`context.ask` / `context.suggest` / `context.resolve` / `context.decode` /
|
|
94
|
+
`context.groundability`; `ontology.view` / `ontology.search` /
|
|
95
|
+
`ontology.resolve`; `query.sparql` / `query.structured` / `query.analytics` /
|
|
96
|
+
`query.shacl` / `query.infer` / `query.premises`;
|
|
97
|
+
`schema.view` / `schema.preview` /
|
|
98
|
+
`schema.publish` / `schema.audit`; plus lower-level `graph_search`,
|
|
99
|
+
`multi_search`, `full_text_search`, `embedding_search`, `traverse`,
|
|
100
|
+
`semantic_traverse`, `current_state`, `history`, `why`, `shacl`,
|
|
101
|
+
`sparql` (SPARQL text → parsed results), `sparql_select` (structured
|
|
102
|
+
SELECT/ASK/aggregate — GROUP BY entity, property, or date bucket), `analytics`,
|
|
103
|
+
`ontology_view` (pass `counts=True` for per-relation `edge_count`),
|
|
104
|
+
`ontology_search`, `ontology_resolve`, `search_feedback` (grade results 3/1/0 →
|
|
105
|
+
customer qrels for embedding fine-tuning) and `search_feedback_export`,
|
|
106
|
+
`graph_edges`, `index_build`, `index_run`, `index_delta`, `index_gc`, `compact`,
|
|
107
|
+
`status`, `metadata`, and `summary`.
|
|
108
|
+
|
|
109
|
+
## Typed responses
|
|
110
|
+
|
|
111
|
+
The dict-returning methods are stable for scripts and notebooks. For app code
|
|
112
|
+
that wants generated Pydantic models and IDE autocompletion, use the matching
|
|
113
|
+
`*_model` or `*_page` helper:
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
from lbb.models import GraphSummaryResponse, SchemaBundleView
|
|
117
|
+
|
|
118
|
+
summary: GraphSummaryResponse = lbb.summary_model()
|
|
119
|
+
schema: SchemaBundleView = lbb.schema.view_model()
|
|
120
|
+
|
|
121
|
+
entities = lbb.entities.list_page(fields="*")
|
|
122
|
+
for row in entities.data:
|
|
123
|
+
print(row.name, row.attributes or {})
|
|
124
|
+
|
|
125
|
+
raw = lbb.raw_request("GET", "/v1/graph/summary")
|
|
126
|
+
typed = raw.model(GraphSummaryResponse)
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
The preferred namespaces above return models directly. Additional typed helpers
|
|
130
|
+
cover the remaining high-use surfaces: `commit_model`, `commit_dry_run_model`, `graph("main").facts.create_model`,
|
|
131
|
+
`graph("main").retract_model`, `summary_model`, `metadata_model`,
|
|
132
|
+
`list_graphs_model`, `ontology_view_model`, `ontology_conformance_model`,
|
|
133
|
+
`sparql_select_model`, `schema.view_model`, `schema.preview_model`,
|
|
134
|
+
`schema.publish_model`, `schema.audit_model`, `entities.list_page`,
|
|
135
|
+
`entities.filter_by_attributes_model`, and `graph_edges_page`.
|
|
136
|
+
|
|
137
|
+
Async clients expose the same helpers as awaitables:
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
summary = await lbb.summary_model()
|
|
141
|
+
page = await lbb.entities.list_page(fields=["title", "status"])
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
## SPARQL
|
|
145
|
+
|
|
146
|
+
`client.sparql(query)` runs SPARQL 1.1 text (SELECT or ASK) through the
|
|
147
|
+
conformant engine and returns a parsed `SparqlResults` — no manual
|
|
148
|
+
`json.loads` of a results string:
|
|
149
|
+
|
|
150
|
+
```python
|
|
151
|
+
results = lbb.sparql("""
|
|
152
|
+
SELECT ?service ?db WHERE {
|
|
153
|
+
?service <https://littlebigbrain.com/r/writes_to> ?db
|
|
154
|
+
} LIMIT 10
|
|
155
|
+
""")
|
|
156
|
+
|
|
157
|
+
print(results.vars) # ['service', 'db']
|
|
158
|
+
for row in results: # iterates flat {var: value} dicts
|
|
159
|
+
print(row["service"], "->", row["db"])
|
|
160
|
+
|
|
161
|
+
answer = lbb.sparql("ASK { ?s ?p ?o }").boolean # True / False
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
`SparqlResults` exposes `.vars`, `.boolean` (for ASK), `.bindings` (the raw
|
|
165
|
+
typed term objects), `.rows()` (flattened `{var: lexical_value}` dicts, also
|
|
166
|
+
what iteration yields), and `.row_page`. Engine extensions are keyword args:
|
|
167
|
+
`reason=True` folds rule-derived edges, `entailment="none"` disables the
|
|
168
|
+
default `rdfs:subClassOf` closure, and `as_of_valid_time` / `as_of_commit_seq`
|
|
169
|
+
pin a snapshot. For the structured BGP form, `client.sparql_select(body)` posts
|
|
170
|
+
a `SparqlSelectRequest` and returns the typed `vars`/`solutions`/`groups`
|
|
171
|
+
response.
|
|
172
|
+
|
|
173
|
+
For app code that already has relation patterns but just needs typed attribute
|
|
174
|
+
predicates, `client.entities.filter_by_attributes(...)` builds the structured
|
|
175
|
+
SPARQL filter body without exposing RDF property IRIs:
|
|
176
|
+
|
|
177
|
+
```python
|
|
178
|
+
lbb.entities.filter_by_attributes(
|
|
179
|
+
patterns=[{"subject": {"var": "service"}, "predicate": "WRITES_TO", "object": {"var": "db"}}],
|
|
180
|
+
where=[{"field": "slo", "op": "ge", "value": 0.99}, {"var": "db", "field": "tier", "value": "prod"}],
|
|
181
|
+
select=["service"],
|
|
182
|
+
)
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
A standalone stack also serves the **native SPARQL 1.1 Protocol** at `/sparql`
|
|
186
|
+
(`GET ?query=`, `POST` form or `application/sparql-query` body,
|
|
187
|
+
`Accept`-negotiated JSON/XML/CSV/TSV) so off-the-shelf SPARQL clients — YASGUI,
|
|
188
|
+
Protégé, RDFLib's `SPARQLWrapper` — connect directly; `client.sparql()` returns
|
|
189
|
+
parsed JSON rows for in-process use.
|
|
190
|
+
|
|
191
|
+
Bodies may be plain `dict`s or instances of the generated Pydantic models in
|
|
192
|
+
`lbb.models` (e.g. `lbb.models.SemanticGraphSearchRequest`), which are
|
|
193
|
+
generated from the committed [`contracts/openapi.json`](https://github.com/littlebigbrains/lbb-python/blob/main/contracts/openapi.json).
|
|
194
|
+
|
|
195
|
+
## Local client (`lbb.local`)
|
|
196
|
+
|
|
197
|
+
`LbbLocalClient` shells out to `lbb-testctl` and operates directly on object
|
|
198
|
+
storage — for tests, notebooks, and local demos, not application integration.
|
|
199
|
+
It requires a full little big brain **engine** checkout (`lbb-testctl` is
|
|
200
|
+
compiled with cargo), not just this SDK repository; point `repo_root` at that
|
|
201
|
+
checkout. It is re-exported as `from lbb import LbbLocalClient`.
|
|
202
|
+
|
|
203
|
+
```python
|
|
204
|
+
from lbb import LbbLocalClient
|
|
205
|
+
|
|
206
|
+
client = LbbLocalClient(root="/private/tmp/lbb-python", tenant="acme", graph="main", branch="main",
|
|
207
|
+
repo_root="/path/to/lbb") # engine checkout, not this repo
|
|
208
|
+
client.create_graph()
|
|
209
|
+
client.commit_triplets_file("/path/to/lbb/database/examples/triplets/semantic_graph.json")
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
It also exposes `build_embedding_index`, `embedding_index_inspect`,
|
|
213
|
+
`embedding_search`, `ontology_search`, `ontology_resolve`, `semantic_search`,
|
|
214
|
+
`traverse`, `current_state`, and `relationship_history`. See
|
|
215
|
+
[`examples/embedding_search.py`](examples/embedding_search.py).
|
|
216
|
+
|
|
217
|
+
## Develop
|
|
218
|
+
|
|
219
|
+
```sh
|
|
220
|
+
python3 -m venv .venv && .venv/bin/pip install -e ".[dev]" httpx pydantic
|
|
221
|
+
ruff check lbb tests
|
|
222
|
+
mypy lbb
|
|
223
|
+
pytest tests --cov=lbb
|
|
224
|
+
python -m build && twine check dist/*
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
`lbb/models.py` is generated; the `contracts` CI job regenerates it (and the
|
|
228
|
+
OpenAPI spec and TS types) and fails if the committed output drifts. The wheel
|
|
229
|
+
ships `py.typed`; generated models and all hand-written modules pass strict
|
|
230
|
+
mypy before release. Do not edit `models.py` by hand; maintainers regenerate it
|
|
231
|
+
from the canonical private monorepo and sync the result with the OpenAPI contract.
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Python SDK for little big brain.
|
|
2
|
+
|
|
3
|
+
The HTTP client (:class:`LbbClient`, :class:`AsyncLbbClient`) is the primary
|
|
4
|
+
integration path. The legacy :class:`LbbLocalClient` shells out to
|
|
5
|
+
``lbb-testctl`` for local tests/notebooks and lives in :mod:`lbb.local`.
|
|
6
|
+
Generated request/response types are in :mod:`lbb.models`; selected client
|
|
7
|
+
methods also expose ``*_model`` and ``*_page`` helpers for validated Pydantic
|
|
8
|
+
responses.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from .client import (
|
|
12
|
+
AsyncLbbClient,
|
|
13
|
+
LbbClient,
|
|
14
|
+
LbbError,
|
|
15
|
+
ListPage,
|
|
16
|
+
RawLbbResponse,
|
|
17
|
+
RequestOptions,
|
|
18
|
+
SparqlResults,
|
|
19
|
+
)
|
|
20
|
+
from .local import LbbCommandError, LbbLocalClient
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"LbbClient",
|
|
24
|
+
"AsyncLbbClient",
|
|
25
|
+
"LbbError",
|
|
26
|
+
"ListPage",
|
|
27
|
+
"RawLbbResponse",
|
|
28
|
+
"RequestOptions",
|
|
29
|
+
"SparqlResults",
|
|
30
|
+
"LbbLocalClient",
|
|
31
|
+
"LbbCommandError",
|
|
32
|
+
]
|
|
33
|
+
__version__ = "0.1.0"
|