Skip to main content

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. 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 Waschtisch 55x45"',
    {
        "type": "object",
        "properties": {"code": {"type": "string"}, "description": {"type": "string"}},
        "required": ["code", "description"],
    },
    effect_id="tender-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. 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

The RDF and JSON guides use different write workflows. Choose one when creating a graph; a graph first written through RDF import does not accept facts.create or JSON record imports.

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)

Google Drive connects through your own Google app. lbb.google_drive builds the consent URL and turns the callback's code into the connection's credentials (exchange_code_async for async code):

from lbb import google_drive

url = google_drive.authorize_url(client_id=client_id, redirect_uri=redirect_uri, state=state)
# On the callback, after `state` matches:
grant = google_drive.exchange_code(
    client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri, code=code
)
lbb.integrations.create(
    graph=graph, id="google-drive", kind="google_drive", credentials=grant.credentials
)

See Integrations for your customers.

Errors and retries

Failed HTTP requests raise LbbError, with a status, error code, message, and request ID. Use raw_request() when you also need response headers or timing.

Safe reads and writes with an idempotency key retry rate limits, retryable server errors, and network failures. Retries respect Retry-After and use a 60-second budget by default. See the client reference for timeout and retry options.

Development

From a clone of this repository:

python3 -m venv .venv
.venv/bin/pip install -e ".[dev]"
.venv/bin/python -m ruff check lbb tests
.venv/bin/python -m mypy lbb
.venv/bin/python -m pytest tests

lbb/models.py is generated from the API contract. See CONTRIBUTING.md for changes to generated models.

License

Apache-2.0.

Environment scope

An environment API key already selects its environment. For an account-scoped session token, pass environment="production" to the client. This uses the existing stack query parameter and does not change the endpoint or grant access.

Optional application catalog and reference reads

Start with a graph and an environment API key. Your backend chooses the graph for an authorized user; the environment key can access every graph in its environment. Catalog ownership and short-lived delegated read tokens are optional. They require separately enabled application_catalog_v1 and scoped_graph_reads_v1 support. The reference_dataset_reads_v1 capability adds explicit SELECT/ASK reads over one primary graph and up to four authorized reference graphs in the same environment. Capabilities describe support, not whether a deployment enabled the feature.

Use client.catalog to create namespaces, adopt an existing graph at its exact expected_graph_epoch, page membership, and inspect or repair pending operations. Use client.access.create_read_token and revoke_token to manage delegated reads. client.sparql_dataset takes the primary epoch and explicit references; its sources vector identifies the independently pinned versions. Keep epochs as decimal strings. Async clients expose the same helpers with await. Catalog pages can be empty with a non-null next_cursor; continue until that cursor is null.

These helpers do not move graph ownership, grant writes, or create an atomic cross-graph snapshot. See How to model your app.

Optional owner usage reports

On deployments with reporting activated, an environment administrator can read one bounded owner page. Keep that key on the backend; scoped query tokens cannot read reports. Replace the example owner and timestamp with your catalog identity and selected period.

owner = client.catalog.resolve("acme")
page = client.catalog.usage(
    owner_id=owner["identity"]["id"],
    owner_incarnation=owner["identity"]["incarnation"],
    period_start_micros=1800000000000000,  # a UTC-hour boundary
    profile="registered-request-resource-v1",
    limit=16,
)
page_cpu_nanos = int(page["page_totals"]["cpu_nanos"])
# Repeat with cursor=page["next_cursor"] until that value is None.

Async clients use await client.catalog.usage(...). CatalogUsageProfile is exported; generated response models live in lbb.models, while this thin helper returns the ordinary dictionary response.

Every result contains page totals. Preserve decimal resource quantities as exact integers and follow all continuations, including empty pages. The default registered-request-resource-v1 profile selects an admission-time hour; a complete result certifies only that registered profile and selected hour. Missing/crashed outcomes, partial activation and unattributed work remain gaps. For raw history, choose raw-resource-receipts-v1 and a UTC-day boundary; it always remains partial with no completeness watermark. These domains overlap: never add their totals together. Erased reports are unavailable, not zero. This is resource reporting, not a new billing charge. See How to model your app.

An opted-in request can finish its execution but fail to confirm the durable reporting handoff. The server then returns HTTP 503 application_usage_handoff_unconfirmed with retryable: false and no Retry-After. The original measured execution is retained once; this response does not mean that no work ran. The SDK surfaces it without automatic replay. Check operation state before explicitly retrying, because a new request can execute and be measured again. A pre-execution application_usage_unavailable response remains retryable.

Optional workflow execution reads

On a server with workflow execution and batch admission enabled, claim an ordinary workflow turn with include_execution_credential=True. Bind its returned task to the same control client:

# task is the task from an authenticated claim with include_execution_credential.
reader = client.workflow_turn_reader(task)
try:
    answer = reader.sparql(
        "SELECT ?s WHERE { ?s a <urn:Document> } LIMIT 20", timeout=10.0
    )
    # Acknowledge a small materialized result through the workflow checkpoint API.
finally:
    reader.close()

AsyncLbbClient provides the same helper with await reader.sparql(...). Heartbeat, checkpoint and complete through the original control API; the reader does not maintain the lease. Close it on lease loss. Reads refresh before first use and whenever remaining lifetime is at most the next read's timeout (capped at 30 seconds) plus one second. Monotonic elapsed time from refresh request start accounts for transport delay without comparing server time to the worker clock. A shorter lease still caps the query timeout.

The server must return issued_at_ms and expires_at_ms. Missing lifetime raises RuntimeError with an upgrade message; elapsed lifetime raises TimeoutError. These are transient/compatibility failures, not WorkflowExecutionError argument or identity refusals. No query is sent in either case and no query automatically replays on 401/403 or uses the control bearer. Acknowledged materialized checkpoints supply stable retry inputs; this helper does not pin a snapshot or add file reads.

Versioned records commits

client.records.commit and client.graph("main").records.commit send explicit records/1 on the existing commit resource. Both synchronous and asynchronous clients check records_commit_v1 before sending a mutation; an older or unknown server raises LbbCapabilityError. The marker means strict protocol recognition, not graph activation, conversion, graph creation or mixed first-write support. An unqualified graph returns its original typed server refusal. The helper has no activation option.

On an existing support-enabled graph, use full IRIs and explicit RDF values:

result = client.records.commit(
    {
        "version": "records/1",
        "entities": [{
            "id": "https://example.org/service/auth",
            "set": {"https://example.org/title": {
                "@value": "Auth Service",
                "@type": "http://www.w3.org/2001/XMLSchema#string",
            }},
        }],
    },
    idempotency_key="auth-title:v1",
)
print(result["receipt"]["commit_seq"], result["receipt"]["projection"])

commit_model validates the same result as models.RecordCommitResult. Async clients support both methods with await. Generated request models and plain mappings are accepted; optional model controls are omitted rather than sent as null. Explicit lexical envelopes retain language/datatype, large integer, decimal and temporal values. Friendly schema keys/scalars require the explicit matching schema_revision. Plain integers keep integer JSON tokens, including unsafe53bit integers so the server can refuse them without silent rounding; use a lexical envelope when an exact large integer is intended.

An explicit key is required. Body bytes, key and options are captured before capability I/O, then reused unchanged across transport retries. Keep the original body and key for a later retry after an unknown outcome; a new key can accept a second operation. An exhausted POST transport failure or a legacy/malformed success raises LbbRecordCommitOutcomeError with the original idempotency_key; it does not establish that no write occurred. There is no legacy fallback. expected_graph_epoch adds an incarnation guard; receipt epoch is an exact decimal string.

The receipt retains original resolved IDs, schema, no-op and visible RDF statement counts on replay, while idempotent_replay describes this call. Independent support may change with zero visible statement additions/removals. Acceptance, publication and class embedding readiness are separate observations. Existing commit and facts.create retain their legacy contract.

Caller task cancellation keeps Python's CancelledError semantics. Cancellation after POST may still leave an accepted operation: recover with the original body and idempotency key rather than assuming a rollback.

Metadata

Release files for littlebigbrain 0.33.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for littlebigbrain 0.33.0
File Size Uploaded Provenance Actions
littlebigbrain-0.33.0.tar.gz 506.8 kB With provenance Details for littlebigbrain-0.33.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for littlebigbrain 0.33.0
File Interpreter ABI Platform Actions
littlebigbrain-0.33.0-py3-none-any.whl Python 3 none any Details for littlebigbrain-0.33.0-py3-none-any.whl

Total release size: 876.4 kB

Release files / littlebigbrain-0.33.0.tar.gz

Download URL littlebigbrain-0.33.0.tar.gz
Size 506.8 kB
Tags Source
SHA-256 checksum
How to use checksums
52ca8623ef649ec573d20feadd95d8e63ed934f63a00a87a66397b177c3c27b0
BLAKE2b-256 checksum
How to use checksums
9e55235bce6125e53816e3fa9a992c25724aadbf0af1620849c44fb55a906de4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 30, 2026.

Transparency log

Release files / littlebigbrain-0.33.0-py3-none-any.whl

Download URL littlebigbrain-0.33.0-py3-none-any.whl
Size 369.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0386b6f78b6990d3be7b7bad60ea1d41e430c02eab4246d536e04fdc1f9de8af
BLAKE2b-256 checksum
How to use checksums
93cd903231d1868120186f9ae5c8eed8362318eb475bf4a17255c46b2d46b0dd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 30, 2026.

Transparency log

Security for littlebigbrain 0.33.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for littlebigbrain-0.33.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 30, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.33.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page