SSyncropel Docs

Python SDK

Use Syncropel from Python: add records, query threads, and keep your app running through network errors.

Install

pip install syncropel

Requires Python 3.10 or later. One runtime dependency (httpx).

Hello, Syncropel

Start a workspace locally (spl serve), then:

import asyncio
from syncropel import Client, Identity, Ref

async def main():
    async with Client(
        endpoint="http://localhost:9100",
        identity=Identity.static("did:example:my-app"),
    ) as client:
        result = await client.emit(
            act="PUT",
            kind="music.catalog.track",
            body={"title": "Glow", "artists": ["Zonke"]},
            refs=[Ref.music_track(isrc="USJI19810404")],
            thread="music.library",
        )
        print(result.success, result.record_id)

asyncio.run(main())

One call validates the body.kind grammar, builds the record, retries on temporary server and network errors, and returns a result instead of raising on network failures, so a flaky network never crashes your handler.

What you get

  • Async client: emit, query, query_thread, intend, fulfill, plus reserved-kind helpers
  • Sync helper: emit_sync() for scripts and CLIs without an event loop
  • Kind checking: body.kind is validated before any network call
  • Shared references: built-in constructors that let records from different apps point at the same thing (music tracks, code files, incidents, calendar events, and more)
  • No crashes on network errors: every emit returns a result; network errors never raise
  • Identity-aware: records carry the configured DID
  • Test helper: MockKernel in syncropel.testing lets you write tests without running a workspace

Core API

Client

MethodPurpose
emit(act, kind, body, thread, refs=, parents=, data_type=, clock=)Primary emit. Validates, builds the record, retries. Returns EmitResult. Never raises on transport failures.
emit_sync(...)Synchronous variant. Reuses one httpx.Client connection across calls, so bulk emits are faster.
intend(goal, thread=, ...)Open a thread with an INTEND record. Generates a random thread ID if none supplied.
fulfill(thread, summary, fulfills=, ...)Close a thread with a KNOW record. fulfills accepts one record ID or a list.
query_thread(thread, limit=100, since=None)All records in a thread. Returns [] on a network error.
query(kind=, actor=, thread=, since=, limit=100, where=None)Filtered records. At least one of kind/actor/thread is required.
health()Checks the server's health. Returns {} on failure.
close()Release the underlying HTTP client.

Constructor kwargs: endpoint (required), identity (required), timeout=30.0, max_retries=2, backoff_ms=250.0, on_emit=None, api_key=None (bearer token for workspaces that require sign-in), transport=None (custom httpx transport for tests).

Identity

Identity.static("did:example:my-app")     # Supported
Identity.key(path_or_bytes)                # Not supported
Identity.federated(...)                    # Not supported

Reserved-kind helpers

For records that correct, erase or rename earlier ones:

await client.emit_correction(
    corrects=[record_id],
    revised_fields={"title": "Glow (Remastered)"},
    reason="updated metadata",
    thread="music.library",
)

await client.emit_erasure(
    erases=[record_id],
    reason="GDPR request",
    thread="music.library",
)

await client.emit_alias(
    old_kind="music.song",
    new_kind="music.catalog.track",
    reason="grammar migration",
    thread="music.library",
)

Each helper uses a reserved core.* kind and checks that the body has the right shape.

Canonical references (Ref)

References let records about the same real-world thing match up across apps:

Ref.music_track(isrc="USJI19810404")            # → @music.track
Ref.code_file(repo="acme/myproject",
              path="src/main.rs")               # → @code.file
Ref.ops_incident(pagerduty="ABC123")            # → @ops.incident
Ref.cal_event(uid="abc@google.com")             # → @cal.event
Ref.social_person(email="alice@example.com")   # → @social.person

There are eleven categories. See the full list with help(Ref).

Authenticating to a remote workspace

When the workspace requires sign-in, pass the token via api_key:

import os

async with Client(
    endpoint="https://your-host.example.com:9100",
    identity=Identity.static("did:example:my-app"),
    api_key=os.environ["SPL_TOKEN"],
) as client:
    ...

The client sends Authorization: Bearer <token> on every outbound request. See Authentication & Service Accounts for how to mint the token.

Synchronous usage

For scripts and CLI tools without an event loop:

from syncropel import Client, Identity

client = Client(
    endpoint="http://localhost:9100",
    identity=Identity.static("did:example:cli-tool"),
)

result = client.emit_sync(
    act="KNOW",
    kind="ops.deploy.completed",
    body={"version": "1.2.3", "duration_s": 42},
    thread="ops.deploys",
)
print(result.success, result.record_id)

client.close()

emit_sync() reuses one connection across calls, so bulk emits are faster.

Inference: client.infer()

client.infer() sends an inference request and, by default, waits for the answer. The full query anatomy lives in the Inference guide; this section covers the SDK.

from syncropel import Client

client = Client(endpoint="http://localhost:9100")

result = await client.infer({
    "input": {"goal": "Summarise this paper in one paragraph"},
    "responders": [
        {"kind": "llm", "model": "~sonnet"},
        {"kind": "llm", "model": "~gpt-4o"},
    ],
    "fold": {"function": "consensus", "min_quorum": 2},
    "answer_shape": {"kind": "core.summary.v1"},
    "side_effects": {"max_cost_usd": 0.30, "max_latency_secs": 60},
})

print(result.answer)
print(f"Trust: {result.trust_summary['mean']:.2f}")
print(f"Cost: ${result.cost_actual_usd:.4f}")

The request dict has the same fields as the query. fold sets how the answers from several responders are combined into one. See Query Anatomy for every field.

Fire-and-forget

Pass InferOptions(wait=False) to send the request and return immediately:

from syncropel import InferOptions

pending = await client.infer(request, InferOptions(wait=False))
print(pending.correlation_id, pending.thread_id)

You get back InferPending with pending=True, correlation_id, and thread_id. Check the thread yourself, or subscribe, to get the answer.

Options

await client.infer(request, InferOptions(
    wait=True,                # default
    poll_interval_ms=500,     # default
    poll_timeout_ms=300_000,  # default: 5 minutes
    thread="th_abc123...",    # optional explicit thread
))

Result shape

@dataclass
class InferResult:
    answer: Any
    provenance: list[ProvenanceEntry]
    trust_summary: dict  # mean, min, max, n_contributors
    cost_actual_usd: float
    fold_function: str
    chosen_response_id: str | None
    know_record_id: str
    thread_id: str

Error handling

Unlike client.emit(), which never raises on network errors, client.infer() raises on failure:

  • Invalid request shape raises ValueError / TypeError before any HTTP call.
  • A network or workspace error when sending the request raises RuntimeError.
  • Poll timeout raises TimeoutError.

Catch timeouts explicitly if you want to keep the thread ID and check it yourself.

Testing without a workspace

Use MockKernel to write unit tests without running spl serve:

from syncropel import Client, Identity
from syncropel.testing import MockKernel

def test_my_adapter():
    kernel = MockKernel()

    client = Client(
        endpoint="mock://",
        identity=Identity.static("did:example:test"),
        transport=kernel.transport(),
    )

    # Call your code-under-test
    my_adapter_function(client)

    # Assert against what was emitted
    records = kernel.records_for_thread("my-thread")
    assert len(records) == 1
    assert records[0].body["kind"] == "music.catalog.track"

What's next

On this page