dyadic
The official Python SDK for the Dyadic API: use Iris from Python with streaming, function calling, images and typed errors. Requests use your Dyadic credits.
pip install dyadic
from dyadic import Dyadic
client = Dyadic() # reads DYADIC_API_KEY
print(client.ask("Hello!", model="iris"))
API Surfaces and Configuration
The client defaults to https://api.dyadic.app/openai/v1. Configure the OpenAI-compatible base,
not the platform /v1 root: the client derives the platform, Anthropic and gateway URLs from it.
Anthropic's own SDK instead takes https://api.dyadic.app/anthropic and appends /v1 itself.
| Resource | Surface |
|---|---|
| Chat, Responses, Decisions, web retrieval, files, containers, skills and vector stores | OpenAI-compatible |
| Runs, Plans and Black Box | Platform |
anthropic |
Anthropic-compatible |
openrouter |
OpenRouter gateway, requiring platform-granted key access |
Owner-session Store, Current Work, Patch, paired machines and independent Agent Tasks are Workspace workflows, not additional SDK resources. API keys do not grant administrator documentation access. Contract versions and SDK versions are independent. Use the Registry and Platform Integration for the current interface boundaries.
Keep your key on the server
A Dyadic API key is a long-lived secret that spends your credits. Use it only in server-side code; never put it in a mobile app, a desktop app you ship, or anything that runs in someone else's browser. Front-end code should call your own server, which calls Dyadic.
request() only ever sends the key to the API you configured: a relative path
joins base_url, and an absolute URL on any other host, port or scheme (or with
credentials in it) raises DyadicError instead of being sent. Redirects are not
followed. Plain http:// is accepted only for a local or private-network API
(localhost, a private IP, or a single-label name such as dyadic-api).
Streaming and Cancellation
Consume the documented terminal event. A premature EOF or malformed frame raises DyadicError;
partial text is not a completed answer. Closing or aborting a local stream releases the connection.
It does not prove that provider work stopped, a background resource was cancelled or no charge occurred.
Inspect the resource and use its documented cancellation method where available, such as Responses,
batches or plans. Do not resubmit an uncertain operation just because its stream was interrupted.
Retain request/resource IDs and reported usage. Missing usage stays unknown; estimates, holds and
settled charges are distinct. An Idempotency-Key header does not guarantee universal deduplication.
Black Box chain integrity, observed execution, persisted output, delivery and semantic correctness
are separate claims. Documentation MCP reads interface descriptions without running them; authenticated
Black Box MCP records and investigates execution. See MCP Integration.
Retries
GET, HEAD, DELETE and OPTIONS are retried on busy or failing servers. Anything
else (a completion, an upload, a run) may already have run, and been billed,
when it fails, so it is retried only if it provably never started: the
connection was never made, or Dyadic refused it with rate_limit_exceeded or
concurrency_limit. Every attempt of one call carries the same
Idempotency-Key; pass idempotency_key= to choose it, or idempotent=True to
request() for a call that is safe to send twice.
Shared Web Search and Reading
The key's Agent Tools capability controls these bounded public-source operations. They use the shared search and page-extraction pipeline, without a paid search-engine or inference escalation. Retrieved content remains untrusted data, and a cached page is not proof of its current live contents.
results = client.web.search("Dyadic API", max_results=3)
page = client.web.read("https://dyadic.app/developers/", max_chars=4000, max_age_seconds=900)
print(results, page)
The same methods on AsyncDyadic are awaited. Use a context manager to close the client's connections.
Runs: your own agent, Dyadic's tools, your functions
An application brings its own agent (name and instructions), lets it use
Dyadic's built-in tools, and gives it functions it runs itself. runs.run
calls your functions whenever the agent asks and returns the finished run.
def lookup_order(order_id):
"""Look up an order by id."""
return {"order_id": order_id, "status": "shipped"}
lookup_order.schema = {"type": "object", "properties": {"order_id": {"type": "string"}}, "required": ["order_id"]}
run = client.runs.run(
agent={"id": "helpdesk", "name": "Helpdesk", "instructions": "You answer customers of a small shop."},
messages=[{"role": "user", "content": "Where is order 1042? Also, what's the weather in Lisbon today?"}],
builtin_tools=["data.web_search", "data.web_fetch"],
functions={"lookup_order": lookup_order},
end_user="customer-17", # your own id for who asked, kept with the run's usage
conversation_id="ticket-88",
)
print(run.output_text, run.credits)
runs.create(..., stream=True) streams events (run.started, status,
tool.started, tool.completed, plan.updated, sources, image.generated,
delta, requires_action, run.completed).
Use approval_mode="autonomous" explicitly for supported routine and delegated
work without discretionary interruptions, including unattended work. The account
must opt into broader modes. Connection approvals, key/tool scope, execution and
financial limits remain enforced; outcomes report the actual effective mode and
immutable snapshot identity. Bypass preserves authorized work after outside content.
Runs accept approval_mode="custom" and an owned permission_profile_id, or
use the account's saved selection when the ID is omitted. The server freezes the
profile revision chain for that run and rechecks policy changes and revocation.
run.permissions reports the requested/effective mode and snapshot identity.
An unavailable profile fails closed; a noninteractive Ask does not execute the
tool. The key's existing tools, spending limits and private-file restrictions
still apply. Bypass retains the account's Safety setting. Profiles govern
Dyadic's built-ins; functions passed to runs.run execute in your process under
your own authorization. Configure profiles through the authenticated
Workspace(token).permission_profiles API using its separate native token.
Workspace(token).permission_profiles.snapshot(snapshot_id) reads the frozen
run policy, original profile names/revisions and current revocation evidence.
It grants no execution; native admission still validates the current run context.
Compatible chat, text completions, Responses and Anthropic Messages accept
dyadic={"approval_mode": "custom", "permission_profile_id": profile_id}.
These controls govern server tools through the same policy owner. Application
functions retain their own authorization. Custom and automatic modes report
the actual selection in dyadic.permissions, including streamed final output.
Batch admission pins the selected profile identity; execution rechecks its policy.
Images accept the same dyadic selection on images.generate, images.edit and
images.create_variation. The SDK encodes it as a JSON text field for multipart
edits/variations. Results retain dyadic.permissions and dyadic.storage:
saved includes the library file ID; not_saved includes a reason code;
external_url means the provider returned a link. The generated bytes remain
available when optional library storage is refused. Saving or quota cleanup
never repeats the image request. An Ask before generation returns HTTP 409;
this endpoint cannot wait for an approval card.
Deterministic client.web.search(..., dyadic=selection) and
client.web.read(..., dyadic=selection) accept the same mode/profile selection,
with outcome and snapshot identity in result.dyadic.permissions. They retain
the key's Agent Tools restriction and cannot access private Workspace files.
A profile Ask returns HTTP 409 permission_approval_required; Deny returns
403 permission_denied; unavailable policy returns 400
permission_policy_unavailable. These calls do not wait for approval cards.
Plans: propose, approve, carry out
With the key's Plans switch on, a run can plan before it acts. plan_mode=True
investigates read-only and proposes a plan of Steps; nothing that changes
anything runs. Your user reviews it (edit it with plans.update), you approve
the revision they saw, and a run with plan_id carries it out step by step.
The service checks the approval: a plan that isn't approved at its current
revision doesn't run (plan_not_runnable). A run that ends with steps left
pauses the plan; another run with the same plan_id resumes it.
proposal = client.runs.create(agent="iris", messages=[{"role": "user", "content": "Move our blog to a static site."}],
plan_mode=True, conversation_id="ticket-88")
plan = client.plans.retrieve(proposal.plans[0].id)
plan = client.plans.approve(plan.id, revision=plan.revision)
client.runs.create(agent="iris", messages=[{"role": "user", "content": "Go ahead."}], plan_id=plan.id,
conversation_id="ticket-88")
for event in client.plans.stream(plan.id): # live; resumes after the last event and ends once the plan is finished
print(event.event, event.data.get("step"), event.data.get("status"))
client.plans also has list(conversation=, status=, limit=, after=),
create(title=, steps=, mode="plan" | "live"), update(id, revision=, ...),
cancel(id), move_step(id, key, status=, note=, verified_by=) and
events(id, after=). A key sees only its own plans.
POG (Predictive Operation Graphs): intents, $future DAGs and safe speculation
Compile and run a POG from a high-level intent or explicit multi-step DAG through /v1/pog with client.pog (or pass pog= on client.runs.create / client.runs.run). Both Dyadic and AsyncDyadic expose the same .pog methods (await them on AsyncDyadic):
from dyadic import Dyadic, DyadicError
client = Dyadic() # reads DYADIC_API_KEY
# 1. Compile and run a DAG with a $future dependency and safe read-only speculation
pog = client.pog.create(
intent="Search docs and read the top matching reference",
nodes=[
{"id": "find", "tool": "data.web_search", "args": {"query": "dyadic pog"}},
{
"id": "read",
"tool": "data.web_fetch",
"depends_on": ["find"],
"args": {"url": {"$future": "find.data.results[0].url"}},
},
],
config={"max_concurrency": 4}, # explicit nodes run as given; speculation applies to intent-only graphs
budget={"max_nodes": 16, "max_cost_usd": 0.25},
idempotency_key="pog-docs-001",
)
# 2. Inspect the graph (nodes and edges) and consolidated EvidencePackage
graph = client.pog.graph(pog.id)
evidence = client.pog.evidence(pog.id)
print(pog.status, graph["graph"]["edges"], evidence.metrics, evidence.conflicts)
# 3. Follow live SSE events (reconnects automatically with Last-Event-ID until "end")
for event in client.pog.stream(pog.id):
print(event.event, event.data)
- Dry-run planning, inline SSE streaming & live mutation: pass
dry_run=Trueto compile the graph without executing nodes,stream=Trueto receive the liveEventStream/AsyncEventStreamdirectly frompog.create(...), orbackground=True(aliasasync_exec=True) to launch asynchronously and follow.stream(pog.id). While active, callclient.pog.modify(pog.id, add_nodes=[...], cancel_nodes=[...], reprioritize={...})orclient.pog.cancel(pog.id).WorkspaceandAsyncWorkspaceexpose the same.pogresource over/pog. - Safe speculation boundary: speculative execution only permits
RiskLevel.READoperations outside protected scopes; mutations, shell commands, and approval-gated calls execute only through authorized dispatch. - Agent runs with POG: pass
pog={"enabled": True, "mode": "hybrid", "speculative": True}toclient.runs.create(...)orclient.runs.run(...). - Error handling: catch
DyadicError(error.status,error.code,error.message,error.request_id) — for example409on cyclic or invalid state transitions and422when speculative bounds or schemas are rejected.
Also available: pog.list(status=, run_id=, limit=), pog.retrieve(pog_id), and pog.events(pog_id, after=, limit=). See the runnable scripts in examples/ and the POG guide.
Decisions: typed answers, fast and cheap
Ask one or more questions about some text (or text and images) and get typed answers
back: a probability (predicate), one of your values (choice) or a rubric level
(score). Latency and cost depend on the selected model, input and current provider configuration; inspect the returned usage.
answer = client.decisions.create(
input="I can't log in after resetting my password.",
questions=[
{"type": "predicate", "name": "urgent", "instructions": "The customer is blocked from using the product."},
{"type": "choice", "name": "team", "instructions": "Which team should handle this.",
"choices": [{"value": "account", "description": "Sign-in and account access"},
{"value": "billing", "description": "Payments and invoices"},
{"value": "other", "description": "Anything else"}]},
],
)
answers = {a["name"]: a for a in answer["answers"]} # urgent: probability; team: choice
Connected apps: saving into a person's Workspace
With the person's approval, an application can save into their Dyadic Workspace, naming them by the Discord account linked to their Dyadic account.
from dyadic import DyadicError
status = client.connections.discord(discord_id)
if not status.authorized:
print("Allow this app:", status.authorize_url) # show the person this link
try:
saved = client.workspace.saves.create(discord_id=discord_id, kind="message", title="From #general",
text="Worth keeping", url="https://discord.com/channels/1/2/3")
print(saved.url)
except DyadicError as error:
if error.code == "authorization_required":
print("Allow this app:", error.body["authorize_url"])
kind is message, conversation (with messages, saved as a chat the
person can continue unless as_chat=False), image or file (with files:
base64, up to 10 of 8 MB).
Conversations, stored completions, containers, vector stores, skills
The rest of the OpenAI-compatible API, named as OpenAI's SDK names it (the same
calls on AsyncDyadic, awaited):
conversation = client.conversations.create(metadata={"ticket": "88"})
client.responses.create(model="iris", input="Hello", conversation=conversation.id)
items = client.conversations.items.list(conversation.id, order="asc")
client.responses.input_tokens.count(model="iris", input="How long is this?") # free: an estimate
compacted = client.responses.compact(model="iris", previous_response_id="resp_...") # send compacted.output next
stored = client.chat.completions.list(metadata={"team": "support"}) # completions made with store=True
client.chat.completions.messages.list(stored.data[0].id)
container = client.containers.create(name="scratch") # the key's code interpreter switch
client.containers.files.create(container.id, file="data.csv")
store = client.vector_stores.create(name="docs", file_ids=[file.id]) # file search switch; no credits
hits = client.vector_stores.search(store.id, query="refund policy")
skill = client.skills.create(files="./csv-skill") # a folder (or one zip, or a list of files)
Also conversations.retrieve/update/delete and items.create/retrieve/delete,
chat.completions.retrieve/update/delete, containers.files.list/retrieve/delete/content.retrieve,
vector_stores.files.* and vector_stores.file_batches.*, and skills.versions.*.
The Anthropic API and OpenRouter's, on the same key
client.anthropic speaks the Anthropic API at /api/anthropic/v1
(Claude's request and answer shapes, behaving as Anthropic's do) and client.openrouter OpenRouter's API through the
AI gateway at /api/openrouter/v1, both with this client's key and beside
its base URL:
message = client.anthropic.messages.create(model="iris", max_tokens=1024, system="Be brief.",
messages=[{"role": "user", "content": "Hello"}])
print(message.text, message.stop_reason, message.usage.output_tokens) # Anthropic's answer; .text joins its text blocks
stream = client.anthropic.messages.create(model="iris", max_tokens=1024, stream=True,
messages=[{"role": "user", "content": "Tell me a story"}])
for event in stream: # Anthropic's events: message_start, content_block_delta, ...
if event.type == "content_block_delta" and event.delta.type == "text_delta":
print(event.delta.text, end="")
batch = client.anthropic.messages.batches.create(requests=[{"custom_id": "a", "params": {
"model": "iris", "max_tokens": 256, "messages": [{"role": "user", "content": "Hi"}]}}])
results = client.anthropic.messages.batches.results(batch.id) # once processing_status is "ended"
# OpenRouter's models through the AI gateway (Dyadic turns it on for an app's key on request):
reply = client.openrouter.chat.completions.create(model="anthropic/claude-haiku-5.5",
messages=[{"role": "user", "content": "Hello"}])
print(client.openrouter.key().data.limit_remaining) # this key's limits, answered by Dyadic
Also anthropic.messages.count_tokens (free), anthropic.messages.batches.list/retrieve/cancel/delete,
anthropic.models.list/retrieve, anthropic.files.create/list/retrieve/content/delete, and
openrouter.completions, openrouter.embeddings, openrouter.models.list/endpoints, openrouter.generation and
openrouter.credits. The gateway is a platform decision: Dyadic turns it on for an app's key on request, the key's
owner can turn it off, and a key without it gets 403 gateway_not_allowed. Anthropic's own SDKs and Claude Code work
too, with the base URL https://api.dyadic.app/anthropic.
Agent Black Box: a flight recorder for your own agent
Record what your agent does into Dyadic's tamper-evident Black Box: every event is chained by hash and signed, so you (or anyone you give the evidence to) can check later that the record wasn't changed. Switch Black Box: send telemetry (and read, to read runs back) on for the key first; both are off by default.
from dyadic.blackbox import Recorder
recorder = Recorder() # or client.blackbox.recorder()
with recorder.run("Book a room", agent="planner") as run:
run.declare(allowed_tools=["search_rooms", "book_room"], allowed_hosts=["rooms.example.com"])
with run.model_call("gpt-4.1") as call:
call.responded(usage={"input_tokens": 812, "output_tokens": 40}, tool_calls=[{"id": "call_1", "name": "book_room"}])
with run.tool_call("book_room", effect=True, hosts=["rooms.example.com"], call_id="call_1") as tool:
tool.result(book_room("Orion"))
run.verified("booking", "confirmation ORN-1042 read back from the booking API")
- Recording never blocks your agent: a bounded queue, a background thread, batches
with an
Idempotency-Key. Every event carries your process's own sequence number, so lost events show up as gaps. - Only metadata leaves your process unless you pass
capture_content=True(then secrets are redacted first, and the account's own settings decide what's kept). - Subagents in other services: send
run.traceparent()and start theirs withrecorder.run(..., traceparent=header). - Already on OpenTelemetry?
BlackBoxSpanExporter()sends your spans (GenAI semantic conventions or OpenInference). Like the Recorder, it keeps content attributes (gen_ai.input.messages, tool arguments and results,input.value, ...) in your process unlesscapture_content=True, and passes every value throughredact_secretsfirst (credential-named attributes are withheld;redact=Noneturns this off). MCP:instrument_mcp(session, run, server="notes"). - The Recorder sends from a background thread, so it takes the synchronous
Dyadicclient (AsyncDyadic().blackbox.recorder()raisesTypeError); its runs and spans work under asyncio all the same. - Read back and check:
client.blackbox.runs.list(),.graph(id),.verify(id),.export(id, format="zip")(the bundle includes a dependency-freeverify.py), andpython -m dyadic.blackbox verify bundle.json --key KEY_ID=PUBLIC_KEY. An anchored bundle's RFC 3161 timestamp is checked too (verify_bundle(..., tsa_roots=[der])). client.blackbox.runs.simulate(id, mode="simulate" | "counterfactual" | "reconstruct"): nothing ever runs in a simulation; it is not historical evidence.
Reading, triaging and managing
With the key's read switch: client.blackbox.overview(), .settings(),
runs.list/retrieve/events(types=[...])/graph/verify/checkpoints/otlp/export,
diff(a, b), findings.list(status=, severity=, rule=) (calling findings(...)
still works), rules.list() and rules.preview(rules) (what detection would raise
with other settings; nothing is saved). Write: bookmarks.create(run_id, seq=, note=),
findings.update(id, status="dismissed"). Content: runs.content(id). Manage:
runs.erase(id), runs.delete(id) and the sinks below. A run of the key's that was
deleted raises dyadic.RunDeletedError (HTTP 410). OTLP protobuf goes as it is:
client.blackbox.send_otlp(raw_bytes).
Live
with client.blackbox.runs.stream(run_id) as events:
for event in events:
if event.event == "event":
print(event.id, event.data.type) # id: the event's sequence number
elif event.event == "end":
print(event.data.status, event.data.outcome) # the stream stops after end (or deleted)
for event in client.blackbox.watch(): # this key's runs as they start, change and grow
if event.event == "run":
print(event.data.id, event.data.status)
Both reconnect by themselves when the service asks or the connection drops (a run's
stream resumes after its last event); on AsyncDyadic they are async iterators
(async for). Break out of the loop or close() to end them.
Webhooks and collectors
client.blackbox.sinks.create(kind="webhook", url=..., events=["finding.created", "run.failed"], min_severity="high")
sends signed JSON as findings are raised and runs end (keep its secret: it is shown
once; sinks.rotate(id) makes a new one); kind="otlp" exports each finished run to an
OpenTelemetry collector (protocol="http/protobuf", headers=). Check every webhook
before trusting it, with the body exactly as it arrived:
from dyadic.blackbox import verify_webhook, WebhookVerificationError
try:
message = verify_webhook(request.body, request.headers, secret) # whsec_...
except WebhookVerificationError:
... # answer 400
(Standard Webhooks: HMAC-SHA256, several signatures during a rotation, a timestamp
within 5 minutes by default; skip repeats by the webhook-id header.)
Tests
pytest runs the SDK's own tests against a mocked transport: nothing reaches a server and nothing is spent. The
live checks in live_tests/ call a real API and run only when DYADIC_LIVE_API_KEY is set (DYADIC_LIVE_BASE_URL for
another deployment): free listings and token counts, and two messages of at most 16 tokens. Use a short-lived key with
a small credit cap.
See https://dyadic.app/developers/ for the full guide.
MCP Recording In 1.9
The MCP wrapper also records resource reads, prompt retrieval and tools/resources/prompts discovery when the
client exposes those methods. It returns the original result and preserves errors and cancellation.
tool.result now contains the complete MCP response, including content, structuredContent, pagination
and failure bodies, instead of choosing just one content field. Update code that consumed the old projection.
Content capture remains opt-in and redacted; recordings do not grant execution or verify a server
claim. This instruments your MCP client; Workspace connections still use Workspace authentication.
Sharing Account Controls In 1.12
Version 1.12 includes account.sharing in both Workspace and
AsyncWorkspace. These controls require the matching sharing server release. Discovery
and retrieval use workspace:read, content create/edit/status uses
workspace:write, and recipient/grant/review management uses
workspace:sharing. Existing native sessions are never silently widened.
shared = account.sharing.list("library", limit=50)
resource = account.sharing.retrieve("library", library_id)
person = account.sharing.recipient("library", library_id, "member@example.test")
review = account.sharing.create_review(
"library", library_id, person.recipient.id,
level="editor", expected_revision=0,
idempotency_key="sharing-review-001",
)
print(review.verification_uri) # The owner reviews this in their browser.
# After explicit browser/passkey approval, inspect review.state, then apply:
account.sharing.update(
"library", library_id, person.recipient.id,
level="editor", expected_revision=0, review_id=review.id,
idempotency_key="sharing-apply-001",
)
grants supplies explicit recipient revisions. review inspects approval state;
the SDK never approves, polls into an automatic mutation, or treats review
creation as completion. Use level none to revoke (no passkey review); use
restore_inherited=True instead of a level to remove an override, with a new
explicit review. Preserve each mutation key and inspect its receipt after an
uncertain result. Recipient emails stay in JSON bodies, not URLs.
create_organization(kind, organization_id, **fields) creates with the actual
organization owner. edit(..., expected_updated_at=..., **changes) edits only
supported content/appearance fields; status(..., "deleted"|"archived"|"active", expected_updated_at=...) retains management checks. Editors cannot create,
delete, move, change ownership or change execution bindings. Shared metadata
excludes the owner's private drafts/read state. AI execution is a separate
integration, not granted by metadata retrieval or message publication.
Version 1.12 also exposes account.shared_chats and
account.library_groups. Published chat history requires current read access;
posting requires Participant or Editor access plus native workspace:write.
Posting text does not invoke Iris or transfer the owner's tools or credentials.
Version 1.12 provides explicit shared AI through the same platform agent
loop. This requires native workspace:run; inspection and events require
workspace:read. Personal shared chats use the initiating account's AI credits;
organization chats use organization credits. Content and storage retain their
actual owner. Private extensions, memory, credentials and computers are not
inherited. These methods require the matching sharing server release.
import uuid
ai_key = str(uuid.uuid4()) # Retain before submitting this exact question.
accepted = account.shared_chats.ask(chat_id, "Summarize our discussion.", request_key=ai_key)
run = accepted.run
for event in account.shared_chats.ai_events(chat_id, run.id):
print(event)
# Recover a lost submission response using GET, without starting AI again:
recorded = account.shared_chats.ai_submission(chat_id, ai_key)
requests = account.shared_chats.ai_runs(chat_id, limit=20)
current = account.shared_chats.ai_run(chat_id, run.id)
# Initiator or content manager only; already dispatched calls may incur cost:
account.shared_chats.cancel_ai(chat_id, run.id)
Retain the latest recorded event sequence and pass after when reconnecting.
Unavailable replay and an unknown execution outcome require inspecting the
recorded request and published messages; they are not permission to submit a
new AI call. Cancellation is not a claim that prior provider work was free.
Shared attachment methods are included in 1.12. Uploads use the conversation owner's storage (organization storage for organization chats), with unrelated-file eviction disabled. Uploading does not publish a message. A file must be explicitly attached; source metadata does not make other files visible. Each shared upload is limited to 6 MiB and a message can attach up to eight files.
file_key = str(uuid.uuid4()) # Keep for this exact file and destination.
uploaded = account.shared_chats.upload(
chat_id, b"A document for this conversation", name="brief.txt", request_key=file_key,
)
# After an uncertain response, resolve by GET before selecting a new upload:
recorded_upload = account.shared_chats.upload_submission(chat_id, file_key)
if recorded_upload.file is None:
raise RuntimeError("The uploaded file was removed.")
file_id = recorded_upload.file.id
account.shared_chats.post(
chat_id, "Read the brief.", request_key=str(uuid.uuid4()), attachments=[file_id],
)
metadata = account.shared_chats.file(chat_id, file_id)
downloaded = account.shared_chats.file_content(chat_id, file_id)
with open("brief-copy.txt", "xb") as output:
output.write(downloaded.content)
ask accepts the same attachments keyword. Only admitted published attachments
enter model input; the inference payer stays separate. save_state accepts
draft_attachments with expected_draft_revision, sharing the text draft's CAS.
Detaching a file from a draft does not delete an owner file or published history.
Retried upload keys do not recreate removed files. All reads recheck current
conversation and file authority; private owner files cannot be guessed through
a shared chat.
import uuid
page = account.shared_chats.messages(chat_id, limit=50)
request_key = str(uuid.uuid4()) # Keep this UUID for retries of this exact message.
posted = account.shared_chats.post(
chat_id, "Here is the updated brief.", request_key=request_key,
idempotency_key=request_key,
)
receipt = account.shared_chats.submission(chat_id, request_key)
draft = account.shared_chats.state(chat_id)
account.shared_chats.save_state(
chat_id, draft="My private unsent text",
expected_draft_revision=draft.draft_revision,
idempotency_key="shared-draft-001",
)
Use before or after with returned numeric message IDs to page published
history. History omits private metadata and execution records. The actor-bound
message key prevents duplicate publication across concurrent requests, new
transport receipts and reconnects. Deleted messages cannot be resurrected using
their old key. Drafts and read markers belong to the caller; saving a draft never
edits another participant's draft. Resolve a 409 against its returned current
state before saving again. Both sync and async account clients use this contract.
Both account clients default to https://api.dyadic.app; use base_url only
for your explicitly configured API root. The public app host is not the API.
library = account.sharing.retrieve("library", library_id).resource
with open("library.png", "rb") as source:
updated = account.sharing.set_icon(
library_id, source.read(), expected_updated_at=library.updated_at,
idempotency_key="library-icon-001",
)
icon = account.sharing.icon(library_id) # Binary: bytes, content type, headers.
account.sharing.remove_icon(
library_id, expected_updated_at=updated.resource.updated_at,
idempotency_key="library-icon-remove-001",
)
Icons require current library read/edit access and owner storage allowance.
Use a still PNG, JPEG, WebP or GIF up to 1 MiB and 2048px per side. The server
publishes a sanitized 256px PNG. Replaced images remain owner-accounted Files
history until removed; a stale revision or refused upload preserves the old
image. changes can atomically include supported library metadata. Async
clients expose the same methods with await.
Knowledge Uploads, Organization Storage And Content History
Upload as a current library/project manager, then explicitly publish the file by saving a Knowledge entry. Keep the upload UUID for exact retries and recovery; uploading alone does not share bytes with readers.
import uuid
upload_key = str(uuid.uuid4()) # Retain this with the exact file and destination.
uploaded = account.sharing.upload_knowledge(
"library", library_id, b"Reviewed reference", name="reference.txt",
request_key=upload_key,
)
recovered = account.sharing.knowledge_upload_submission("library", library_id, upload_key)
entry = account.sharing.create_knowledge(
"library", library_id, kind="note", title="Reference", body="Shared reference",
attachments=[uploaded.file.id],
)
files = account.sharing.organization_files(organization_id, status="active", limit=25)
history = account.sharing.content_history(organization_id=organization_id, limit=25)
activity = account.sharing.activity("library", library_id, limit=25)
print(activity["items"], activity.next_before) # Keep bigint cursors as strings.
Files use the actual content owner's quota; org storage management and org-wide
history require current Owner/Admin authority. organization_file reads
metadata or, with content=True, bytes. organization_file_status uses the
reviewed expected_status and sha256 for Delete/Archive/Unarchive/Restore/Purge;
it does not transfer ownership. History's before cursor and optional
kind/resource_id filters keep the same owner. Exact shared activity needs
current resource access, omits private bodies and hides recipient records from
nonmanagers. Read scopes do not confer write, AI or key-management permission.
Matrix Account Controls In 1.10
Workspace and AsyncWorkspace call the existing account-scoped Workspace API,
including Matrix, profiles, chats, run observation and preferences.
Pass an explicitly approved native access token. Developer API keys and native
refresh tokens are rejected by these constructors. The SDK does not read the
Terminal vault, sign in, refresh credentials or register third-party OAuth clients.
The existing native-session approval flow and server scopes remain authoritative.
account.chats.create/retrieve/update/list/send, account.runs.list/events/reconcile/cancel,
account.preferences.retrieve/update, account.permission_profiles and
account.capabilities() use that same account transport. For another admitted
operation, use a relative route; the native allowlist still decides access:
with Workspace(os.environ["DYADIC_WORKSPACE_ACCESS_TOKEN"]) as account:
capabilities = account.capabilities()
library = account.request("POST", "/libraries", {"name": "Research"},
idempotency_key="create-research-library-001")
chat = account.chats.create(title="Notes", library_id=library.id)
accepted = account.chats.send(chat.id, "Summarize the supplied notes.",
approval_mode="ask",
idempotency_key="notes-submission-001")
for event in account.runs.events(accepted.run_id, after=-1):
print(event)
evidence = account.runs.reconcile(accepted.run_id)
Persist the mutation key before submission and reuse it only for the same operation and payload. All account mutations, including DELETE, carry a receipt key. Event observation does not submit work again; after a lost connection use the last recorded cursor or reconcile the accepted identity. AsyncWorkspace returns awaitables and asynchronous streams for the same resources. Generic requests accept the existing transport's query, stream, binary and file options. The default renderer is conservative text/structured data; the capability descriptor grants no execution rights. Account opt-in, exact approvals, ownership, scopes, budgets and configuration version checks still apply.
import os
from dyadic import Workspace
source = 'matrix "sdk-demo" { print "hello" }'
with Workspace(os.environ["DYADIC_WORKSPACE_ACCESS_TOKEN"]) as account:
syntax = account.matrices.source(source) # Inert, syntax-only compilation.
review = account.matrices.preview(source)
# Inspect review.graph, review.bindings and review.effects before accepting.
definition = account.matrices.create(
source, review_sha256=review.review_sha256,
idempotency_key="sdk-demo-install",
)
run = account.matrices.run(
definition.id, request_key="sdk-demo-invocation",
idempotency_key="sdk-demo-submit",
)
record = account.matrices.runs.retrieve(run.id)
print(record.run.state)
Use async with AsyncWorkspace(...) and await the same methods for async code.
matrices also exposes list, retrieve, preview_generated and event.
matrices.runs exposes list, retrieve(after=...), pause, resume, cancel,
reconcile, approve and replay. Read responses preserve the server's bounded
lists, cursor events, inputs, full outputs, unknown states, approval subjects,
Black Box identity and retry history. Some retained database JSON fields arrive
as strings; decode them before inspecting their structure.
The default base is https://api.dyadic.app; an explicit private/local base
can be supplied. Transport retains origin checks, redirect refusal and safe retry
rules. Read/preview needs workspace:read; installation/approval/replay needs
workspace:approve; invocation, controls and events need workspace:run.
Enabling automatic runs also requires run authority. Scopes, account ownership,
expiry and revocation are checked by the server on every relevant call.
Keep a transport idempotency_key for mutations. If a response is lost, use
account.receipts.retrieve(key) before deciding what happened. Missing or unknown
receipts do not authorize repeating an effect. The separate Matrix request_key
names one intended invocation; new intended work gets a new invocation key.
Approval never automatically resumes. Reconciliation reads original receipts;
replay first returns a new review and never accepts its own review. Cancellation
requests and actual process exit remain distinct.
Language, limits and exact review: https://dyadic.app/developers/matrix/
Library groups
account.library_groups.list() reads your navigation document.
account.library_groups.save(groups, expected_revision=current["revision"], idempotency_key="organize-libraries-001") saves its ordered groups. Each group
contains id (UUID), name, library_ids and collapsed (boolean). A library
appears in at most one group. These preferences organize your own navigation;
they never share, move or delete content. Current read access is required for
every referenced library. A stale revision returns 409; reload before editing.
Shared library/project Knowledge uses workspace.sharing.knowledge(kind, id)
and knowledge_entry(kind, id, entry, history=True). History is paged ten
versions at a time; pass before_version=result.next_version for older pages.
create_knowledge, edit_knowledge(..., base_version=...) and
delete_knowledge(..., base_version=...) retain current container authority.
Editors update existing text; managers create/delete and change attachments.
knowledge_file(..., content=True) returns binary bytes only while the file
remains attached to a readable entry. Raw private provenance is not returned.
Metadata
Release files for dyadic 2.0.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| dyadic-2.0.0.tar.gz | 150.8 kB | With provenance | Details for dyadic-2.0.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| dyadic-2.0.0-py3-none-any.whl | Python 3 | none | any | Details for dyadic-2.0.0-py3-none-any.whl |
Total release size: 243.8 kB
Release files / dyadic-2.0.0.tar.gz
| Download URL | dyadic-2.0.0.tar.gz |
|---|---|
| Size | 150.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
723209a1e59164d2a96bb54ecf16534453028914f78c0ea5d039275fd48a4081
|
|
BLAKE2b-256 checksum How to use checksums |
7bd558283d2c8b605ad1778a20e9daed991a67ec6b1d3e0098bcb71ee89ea4a5
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.18
|
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 GitLab CI/CD, verified by PyPI on Nov 27, 2026.
Transparency logRelease files / dyadic-2.0.0-py3-none-any.whl
| Download URL | dyadic-2.0.0-py3-none-any.whl |
|---|---|
| Size | 93.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
dcc1d92003b21463822ae091d764b8fa0e5e6d6bd5d53394daa235c9ff339a93
|
|
BLAKE2b-256 checksum How to use checksums |
e6b00766ae7bd9dfa240a20d42765e3da6300a8b5cd957e85dfd3df6c042ed89
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.18
|
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 GitLab CI/CD, verified by PyPI on Nov 27, 2026.
Transparency logSecurity for dyadic 2.0.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.
Attestation for dyadic-2.0.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitLab CI/CD, verified by PyPI on Nov 27, 2026.
Transparency logA 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.