littlebigbrain Python SDK
Python client for little big brain, a search
platform for AI applications such as chatbots, search tools, and agents.
Load facts, query their relationships, and keep the data version behind an answer
so you can check it later.
The package supports Python 3.10+ and provides synchronous and asynchronous
clients built on httpx. Generated Pydantic models are available in lbb.models.
Documentation ·
Quickstart ·
Issues
Install
pip install littlebigbrain
The package is installed as littlebigbrain and imported as lbb.
Load facts and run a query
Create an environment in the console and open
Connect. Copy its complete endpoint and an environment API key:
export LBB_URL="https://<your-complete-environment-host>"
export LBB_API_KEY="<your-environment-api-key>"
This example creates a graph named quickstart on its first write. It stores
three facts: a service writes to a database, and each has a label. The data uses
Resource Description Framework (RDF), where each line names a subject, a
relationship, and a value or another record. SPARQL is the query language for
those facts.
Save as quickstart.py, then run python3 quickstart.py:
import os
from lbb import LbbClient
facts = """
<https://example.org/auth-service> <https://example.org/writesTo> <https://example.org/user-db> .
<https://example.org/auth-service> <http://www.w3.org/2000/01/rdf-schema#label> "Auth Service" .
<https://example.org/user-db> <http://www.w3.org/2000/01/rdf-schema#label> "User Database" .
"""
query = """
SELECT ?service ?database WHERE {
?s <https://example.org/writesTo> ?db .
?s <http://www.w3.org/2000/01/rdf-schema#label> ?service .
?db <http://www.w3.org/2000/01/rdf-schema#label> ?database .
} ORDER BY ?service ?database LIMIT 10
"""
with LbbClient(
os.environ["LBB_URL"],
api_key=os.environ["LBB_API_KEY"],
graph="quickstart",
) as lbb:
imported = lbb.graph("quickstart").facts.import_rdf(
facts, format="ntriples", idempotency_key="sdk-quickstart-v1"
)
results = lbb.sparql(
query,
consistency="strong",
min_indexed_seq=imported["committed_commit_seq"],
)
for row in results:
print(f"{row['service']} -> {row['database']}")
On a fresh graph, this prints:
Auth Service -> User Database
The query follows the stored relationship between the service and database.
consistency="strong" makes the new facts available to this read without
waiting for a background index job. Reads default to eventual consistency, so
omit this option only when an earlier version is acceptable.
The idempotency key makes repeating the same import safe. Use a new key if you
change the data.
Async client
AsyncLbbClient provides the same methods with await. After running the
quickstart, this script reads its data:
import asyncio
import os
from lbb import AsyncLbbClient
async def main():
async with AsyncLbbClient(
os.environ["LBB_URL"],
api_key=os.environ["LBB_API_KEY"],
graph="quickstart",
) as lbb:
result = await lbb.sparql(
"ASK { ?s <https://example.org/writesTo> ?db }",
consistency="strong",
)
print(result.boolean) # True
asyncio.run(main())
Ask a question in plain words
query.ask answers a question about the graph in plain words. The server's
model runs a short loop of tool calls. It runs SPARQL queries, looks up names,
reads the graph description, finds the commit of a date, and compares two
points. Then it answers.
result = lbb.query.ask(
"Which services write to the user database?",
context="Services and databases of the platform team.",
)
print(result.answer)
print(result.citations)
for row in result.rows:
print(row)
answer holds the text. citations holds the IRIs the answer names. Each one
is in the rows the model read. steps lists the tool calls. query and rows
hold the query whose rows hold the answer. chart says how to draw rows, or
is None: kind (bar, line, scatter or table) and the columns x,
y and series. The server checked that the columns exist and that y
holds numbers for bar and line. title, x_label and y_label, when
present, are plain words for the reader, such as "Career h-index". The loop runs at most 4 rounds of
tool calls, and a question takes about 10 s. When the loop stops before it
answers, answer is None and error says why. rows then hold the best
rows it read.
mode="route" returns only the kind of question, in result.route["kind"].
The router model answers alone, so the call is fast. answer, query and
rows are then empty.
result.trace_id names the eval trace of the rows, so you can label them.
Each call uses model tokens, so the client does not retry a failed call. Pass
options={"retry": True} to retry it.
The graph can keep notes and worked examples that the model reads for every
question. Store them with query.set_rewrite_profile(notes=..., examples=..., expected_version=...) and read them with query.rewrite_profile(). A call's
context still adds notes for that call.
The server finds the names in the question ("Quelmann", "TU Dresden") in the
graph, and the loop uses the IRIs it found. result.linked lists them, so you
can show "Did you mean …?". When the user has a record open, pass its IRI in
anchor (anchor=[iri], at most 10).
A question about a date ("Which findings were open on 18 June?") reads the
last commit written by the end of that day. result.history names the commit
and how the loop found it. When your commits stand for other dates (a demo's
milestones, an import of old records), pass timeline:
timeline=[{"date": "2026-06-18", "as_of_commit_seq": 5, "label": "Addendum"}].
A question that asks what changed compares two points. Then
result.history["added"] and result.history["removed"] hold the rows that
differ, and rows is empty. When the loop pairs the rows by a variable
(key), result.history["changed"] holds the entities whose values changed.
result.history["totals"] counts each list.
Show progress
query.ask_stream sends the same request and yields an event for each step.
The last event, done, holds the same response as query.ask.
from lbb import QueryAskResult
for event in lbb.query.ask_stream("Which services write to the user database?"):
if event.event == "route":
print("route", event.data["kind"])
elif event.event == "step":
print(event.data["tool"], event.data["input"])
elif event.event == "done":
result = QueryAskResult.from_response(event.data)
The events are grounding, route, a step per tool call, answer and
done. A second route comes before answer when the loop chose another
route. mode="route" sends grounding, route and done. An error event
raises the same LbbError as query.ask. Leave the loop, or call close(),
to close the response and stop the server's work. On AsyncLbbClient, use
async for and aclose(). The client skips event names it does not know.
Tools for your own agent
When your app runs its own agent loop, four calls give it what only the
server knows. None calls a model. query.ask runs the same kind of loop on
the server.
# The IRI of a name, the person before a document with the name.
found = lbb.query.names("Summarize Mara Lindqvist's deals")
# The classes and properties a question needs: how many instances hold each
# property, and the values of small classes such as stages.
described = lbb.query.describe(question="Which deals moved stage?")
# The commit of a date.
at = lbb.query.commit_at(date="2026-06-18")
# What changed between two points, paired by entity.
diff = lbb.query.compare(
"SELECT ?deal ?stage WHERE { ?deal <https://x.test/p/stage> ?stage }",
before={"date": "2026-06-01"},
key=["deal"],
)
print(diff["totals"], diff["changed"], diff.get("next_cursor"))
compare reads up to 20,000 rows per point and pages each list: pass
next_cursor back as cursor= with the same arguments. Run your own queries
with query.sparql(..., as_of_commit_seq=...).
Model calls for your own pipeline
reason_activity, decide_activity and embed_activity call LBB's own
models: the reasoning model answers a prompt with JSON that follows a
schema, the decision model answers choice questions about a state, and the
embedding model embeds texts. The calls count against the environment's model
budget for workflows and appear in the call log under label. Pass the
same effect_id when a step repeats, and the server returns the first
answer (cached: True) at no cost.
answer = lbb.reason_activity(
'Which code does this row define? "P3 Drip tray 55x45"',
{
"type": "object",
"properties": {"code": {"type": "string"}, "description": {"type": "string"}},
"required": ["code", "description"],
},
effect_id="docs-import/define-p3",
label="define P3",
)
print(answer["value"]["code"], answer["cost_micro_usd"])
A request too large for the model raises LbbError with the code
activity_request_refused (422): split it and send each half.
Run a workflow worker
lbb.workflows runs durable workflows in Python, with the rules of the
TypeScript worker. A turn runs one message. Its named steps save their
outputs, so a turn that runs again after a crash replays them and does each
effect once.
from lbb import AsyncLbbClient
from lbb.workflows import WorkflowResult, WorkflowWorker, workflow
@workflow(name="counter", version="v1", initial_state={"count": 0})
async def counter(ctx, state, message):
amount = await ctx.step("add", lambda s: message["add"])
return WorkflowResult(state={"count": state["count"] + amount})
client = AsyncLbbClient("http://127.0.0.1:7400", api_key="lbb_sk_test_local", graph="main")
WorkflowWorker(client, [counter], worker="counter-1", concurrency=4).run()
run() serves until SIGTERM, which drains the held turns and releases the
rest. The default claim wait is 60 seconds; set claim_wait_ms to change it.
On stop, a pending claim answers before draining, so its wait and network
latency add to shutdown time. run_once() defaults to an immediate claim.
A claim carries its own request deadline, its wait plus 15 seconds, so a client
timeout shorter than the wait does not end an idle claim. A claim that does reach
its deadline is not replayed: a timeout cannot establish whether the server
awarded a turn. A proxy between the worker and the server must keep the request
open for the whole wait and pass a disconnect on, or a claim of a worker that
has gone stays open on the server and can take a turn that no worker receives.
run_async() serves inside your own event loop until stop(). A step's
effect_id stays the same on every attempt: pass it to an external service as
its idempotency key. A sync step function runs in a thread, so a blocking call
holds no other turn. lbb_activities(client) has reason, decide and
embed on the generated models, and triggered_workflow, write_owned and
requeue_failed serve the triggered workflows of a class.
client.workflows starts instances and holds the engine's blobs.
examples/values_extract is the Python port of the values-extract template.
The guide is
Run a worker in Python.
Legacy local search methods
LbbLocalClient runs lbb-testctl subprocesses against local storage. Its
semantic_search, build_embedding_index, embedding_index_inspect,
inspect_embedding_index, and embedding_search methods were retired in
Python 0.33.0. Their names/signatures remain, but they now raise
LbbLocalSearchRetiredError (code="legacy_local_search_retired") before
creating a request file or invoking a subprocess. The matching lbb-testctl
accepts legacy arguments only to return legacy_search_retired before opening
storage or reading request files. No automatic compatibility execution or
fallback is provided.
The unchanged-behavior promise in the historical 0.32.0 changelog applies to
0.32.0. Running those methods requires that SDK and a matching older
pre-retirement binary; pairing 0.32 with a new binary produces a command
retirement error. Other local methods and current HTTP clients are unchanged.
For new local integrations, run lbb-server against your local storage and
connect LbbClient or AsyncLbbClient to its HTTP endpoint. Declare searchable
classes with client.embeddings.declare(...), inspect them with
client.embeddings.get(...), and search with
client.embeddings.search("query text", ...). The
search by meaning guide
describes the supported setup. These APIs have different input and ranking
contracts: legacy fusion options, explicit record vectors and old index-build
requests have no automatic conversion or equivalent local subprocess method.
Use client.sparql(...) for RDF relationships, paths and filters.
Next steps
Every new graph stores RDF statements. commit and facts.create add facts to
it: when the graph refuses a plain commit, the client sends the same facts again
with a replace_owned that owns nothing. The commit removes no link or field
that it does not name. It replaces the other values of a field it sets, the label
of a record it names, the target of a relation that keeps one target and, with
property_merge="replace", the other fields of the records it names. A record
left with no field and no link by such a replacement loses its type and label.
History stays readable. A link with confidence or valid_time needs an
evidence entry, which stores them; without it the commit is refused before it
is sent. retract with entities needs purge_entity_properties=True there
and removes each record whole; a record left with no link and no field because
of it loses its type and label too. entity_embeddings and preconditions are
refused with the reason in the error. import_ndjson and submit_import_ndjson
need a graph that holds JSON records; import_rdf loads RDF.
Integrations for your customers
client.integrations connects each of your customers' HubSpot, Linear,
SharePoint or Google Drive to a graph of their own. Its routes are on the
integrations API, https://api.littlebigbrain.com by default
(integrations_url). They take the
same environment API key. An operator turns on developer access per environment; ask us
first. AsyncLbbClient has the same methods, with await.
graph = "c-5f1c9a0e3b7d2c4a8e6f1b0d" # one opaque graph per customer
lbb.integrations.create(
graph=graph, id="hubspot", kind="hubspot", credentials={"HUBSPOT_TOKEN": token}
)
connections = lbb.integrations.list(graph=graph)["connections"]
open_ = lbb.integrations.suggestions("hubspot", graph=graph, status="open")
lbb.integrations.accept(open_.suggestions[0].suggestion_id, graph=graph, sync=True)
lbb.integrations.erase(graph, confirm=graph)