opal-agent-sdk (Python)
Async Python SDK for invoking Opal agents programmatically, with a Personal Access Token (PAT) or by signing in with your browser.
Install
pip install opal-agent-sdk # core
pip install "opal-agent-sdk[cli]" # adds the `opal` CLI
Python 3.10+. Async-only.
Quickstart
import asyncio, os
from opal_agent_sdk import OpalClient, PATAuth
async def main() -> None:
async with OpalClient(auth=PATAuth(os.environ["OPAL_PAT"])) as client:
result = await client.agents.specialized.run(
agent_id="your-agent-uuid",
parameters={"query": "Where is order #1234?"},
)
print(result.output_text)
asyncio.run(main())
See examples/ for more (streaming, multi-turn chat, workflow agents, canvas access).
Configuration
| Parameter | Env var | Default | Description |
|---|---|---|---|
base_url |
OPAL_BASE_URL |
https://opal.optimizely.com |
API Gateway URL |
instance_id |
OPAL_INSTANCE_ID |
(auto-discovered from PAT) | Opal instance ID |
timeout_s |
— | 30.0 |
Per-request timeout in seconds. A run's event stream waits up to max(timeout_s, 330) seconds between bytes |
retry_max_attempts |
— | 3 |
Max retry attempts for idempotent 5xx |
ws_connect_timeout_s |
— | 10.0 |
How long one socket.io handshake may take |
verify_ssl |
— | True |
SSL certificate verification. Set to False for localdev only — do not disable in production |
With PAT auth, the SDK extracts instance_id, customer_id, and product_instances from the JWT claims. Env vars are only used with OpalConfig.from_env() for non-PAT flows.
You can also use OpalConfig.from_pat() for explicit PAT-based config construction, or OpalConfig.from_env() to load from environment variables.
Sign in with your browser
A person at a machine with a browser can skip the PAT. AuthorizationCodeAuth
signs them in with Opti ID (OAuth 2.1 authorization code grant with PKCE),
keeps the session in a private file, and refreshes it while it is used at
least once every 30 days, for up to 90 days after sign-in:
from opal_agent_sdk import AuthorizationCodeAuth, OpalClient
async with AuthorizationCodeAuth.from_env() as auth: # reads OPAL_BASE_URL
await auth.login() # opens the browser only when needed
async with OpalClient(auth=auth) as client: # instance and customer come from the token
result = await client.agents.specialized.run("agent-id", parameters={"query": "Hi"})
login()opens the browser only when there is no usable session;login(force=True)always does (for example, to pick another instance).resume()never opens a browser: it loads and refreshes the stored session, or raisesOpalLoginRequiredError. Use it in scripts.logout()revokes the session on the server and deletes it locally.- An auth stays with the identity (issuer, user, instance) it started with. If
another sign-in stores a session for someone or somewhere else under the same
profile (
login(force=True)picking another instance, say), this auth raisesOpalSessionIdentityErroron its next token call rather than switching under a live client. Create a newAuthorizationCodeAuthandOpalClientfor that session. Use oneprofileper instance or user to hold several at once:AuthorizationCodeAuth.from_env(profile="commerce"). - Web apps use
authorization_url()andexchange_code()with a pre-registeredclient_id; seeregister_public_client()inopal_agent_sdk.oauth, and Web apps below. - The session file is
credentials.jsoninOPAL_CONFIG_DIR, else your per-user config directory (~/.config/opal-agent-sdkon Linux). It is shared with the other Opal SDKs on the machine. Passsession_store=(andclient_store=) to keep it elsewhere; see below.
Web apps
One web server signs in many people, so each person needs their own session.
Give every user their own profile (or their own session_store):
auth = AuthorizationCodeAuth(
base_url="https://opal.optimizely.com",
client_id=CLIENT_ID, # from register_public_client()
profile=f"user-{user.id}", # one session per user
)
request = await auth.authorization_url("https://app.example.com/opal/callback")
# keep request.to_dict() in the user's server-side session, redirect to request.url;
# then, on the callback:
await auth.exchange_code(AuthorizationRequest.from_dict(saved), callback_url)
# later requests for that user: the same profile, then resume()
With the default store and the default profile, every user's sign-in would go
to the one shared session, the last one would win, and a later resume() for
one user could act as another. So authorization_url() and exchange_code()
raise ValueError in that configuration. A web app that genuinely has a single
user can pass allow_shared_store=True. login() and resume() (the
browser-on-this-machine flow) are not affected.
Custom credential store
A sign-in keeps two things, and each has its own store:
- the registered client (
client|<issuer>|loopback), which is no secret: aClientRegistrationStore; - the session (
session|<issuer>|<profile>), which holds the tokens: aSessionStore, optionally with a lock (LockingSessionStore).
FileTokenStore (the default) and MemoryTokenStore are both kinds, and so is
anything else with the same three methods. Which store gets what:
- Neither given: one
FileTokenStoreholds both, in one file. - Only
session_store=: it holds the registration too. - Only
client_store=: the session goes to the default file. - Both: each goes only to its own store.
This keeps the tokens in the OS keychain and the registration in the shared file:
from contextlib import asynccontextmanager
import asyncio
import keyring # any backend works; keyring is only an example
import keyring.errors
from opal_agent_sdk import AuthorizationCodeAuth
from opal_agent_sdk.oauth import FileTokenStore
class KeyringSessionStore:
"""A SessionStore: three async methods over opaque strings."""
async def load(self, key: str) -> str | None:
return await asyncio.to_thread(keyring.get_password, "opal-agent-sdk", key)
async def save(self, key: str, value: str) -> None:
await asyncio.to_thread(keyring.set_password, "opal-agent-sdk", key, value)
async def delete(self, key: str) -> None:
try:
await asyncio.to_thread(keyring.delete_password, "opal-agent-sdk", key)
except keyring.errors.PasswordDeleteError:
pass # already gone
# Optional: makes it a LockingSessionStore (see below).
@asynccontextmanager
async def lock(self, key: str):
yield
auth = AuthorizationCodeAuth.from_env(
session_store=KeyringSessionStore(),
client_store=FileTokenStore(),
)
The contract, for both kinds:
- Values are opaque strings. The SDK owns their format (JSON). A store only keeps them. A session's value holds tokens, so a session store must protect it at rest.
load()returnsNonefor a missing key, anddelete()of a missing key is not an error.- The methods are async. Do blocking I/O in a thread (
asyncio.to_thread) so the event loop keeps running. - Locking is optional, only on the session store, and serialises refreshes
across processes. Every refresh spends the refresh token and the server
revokes the old one, so two processes must not refresh the same session at
once. A session store with an
asynccontext managerlock(key)gets every read-refresh-write, and every write (the registration's too), run inside it. The SDK never nests it and never holds it while a browser sign-in waits. It must exclude every process that shares the store;FileTokenStoreuses a lock file. Without a lock, the SDK still runs one refresh at a time per process, and before it gives up on a session it re-reads the store in case another process rotated it first. A client store is never asked for a lock.
Use a PAT instead for anything that runs without a person: servers, CI, scheduled jobs, daemons. A browser sign-in needs someone at a browser, and it ends after 30 days without use, or 90 days after sign-in however often it is used.
See examples/b7_oauth_login.py and
examples/b8_oauth_run_agent.py, and the spec,
docs/tech-spec/agent-framework/agent-sdk/auth-code-grant.md.
Token exchange (product backends)
An Optimizely product backend (CMS, CMP, Experimentation, Configured Commerce,
Campaign, Analytics) already holds the signed-in user's Opti ID access token.
TokenExchangeAuth trades it for an Agent SDK token for that user and the one
Opal instance the product instances belong to:
from opal_agent_sdk import OpalClient, TokenExchangeAuth
auth = (
TokenExchangeAuth.builder()
.client_name("Optimizely CMS") # required: your product, as authz-server's audit log shows it
.optiid_token(user_access_token) # the user's Opti ID access token (or a provider, below)
.cms_instance_id(cms_instance_id) # one or more instance ids
.build()
)
identity = await auth.exchange() # identity.instance_id is the Opal instance
async with OpalClient(auth=auth) as client: # the instance comes from the token
result = await client.agents.specialized.run("agent-id", parameters={"query": "Hi"})
await auth.aclose()
- The instance methods are
cms_instance_id,cmp_instance_id,exp_instance_id,configured_commerce_instance_id,campaign_instance_id,analytics_instance_idandopal_instance_id. Each product instance is connected to exactly one Opal instance, so name product instances from one Opal instance.opal_instance_idnames (or narrows to) that Opal instance, which the user must hold a role on; it cannot choose between Opal instances. client_nameis required: it names the registered client, which is how authz-server's audit log attributes each exchange to a product (for example"Optimizely CMS"). Each name gets its own client, so two products on one host never share one.build()raisesValueErrorwithout a client name, without an Opti ID token or provider (or with both), without any instance id, or when an id is blank.base_url,issuer,client_store,verify_sslandhttp_clientare optional and mean what they do forAuthorizationCodeAuth.- The first exchange registers a confidential client and keeps it in the client
store (
client|<issuer>|token-exchange|<client_name>; by default the shared credentials file). The client holds a secret, so treat the store as secret storage. On a server, pass aclient_store(aMemoryTokenStore, or your own backed by a secret manager); a default store that cannot be written (read-only filesystem, no writable home directory) is tolerated with a warning, and the client is kept in memory and reused for the life of the process. The Agent SDK token stays in memory. It has no refresh token: the SDK exchanges the Opti ID token again shortly before it expires, and after a 401. When that early exchange fails (a 5xx, a network error, a refusal), requests keep using the held token while it is valid, and the SDK tries again after 5 seconds; only once the token has expired does a failed exchange raise. - Using the auth before
exchange()(itsbearer_token, orOpalClient(auth=auth)without a config) raisesOpalLoginRequiredError. - A refusal raises
OpalOAuthErrorwithcode="token_error"and the server'soauth_error:invalid_grant(the Opti ID token is invalid or expired),access_denied(the user has no Opal instance for those ids, or an id was named under the wrong product), orinvalid_request(the ids belong to different Opal instances: name product instances from one Opal instance). A 5xx raisesOpalServerError.
The server never issues a token that outlives the Opti ID token it was
exchanged with. For an auth that lives as long as the user's session, pass
optiid_token_provider instead of optiid_token: a function, sync or async,
returning the user's current Opti ID token (your backend refreshes it). The SDK
calls it whenever it needs to exchange again, never on every request:
auth = (
TokenExchangeAuth.builder()
.client_name("Optimizely CMS")
.optiid_token_provider(lambda: session.optiid_access_token) # or an async def
.cms_instance_id(cms_instance_id)
.build()
)
With a static optiid_token, the auth works until that Opti ID token expires
(typically about an hour), then raises OpalOAuthError with
code="token_error" and oauth_error="invalid_grant": build a new auth with a
fresh token. A refused Opti ID token is remembered, so while the provider still
returns it, the next exchange raises the same error at once, with no request.
Keep one auth, and one OpalClient, per user and instance set rather than
exchanging on every request.
See examples/b9_token_exchange.py.
PAT Scoping
PATs are scoped to a specific Opal instance at creation time. Optionally, they can also be scoped to specific product connections (CMP, EXP, CMS, etc.).
The SDK reads the instance scope directly from the PAT's JWT claims — no separate
OPAL_INSTANCE_ID configuration is needed:
# Instance auto-discovered from PAT — no config required
async with OpalClient(auth=PATAuth(os.environ["OPAL_PAT"])) as client:
...
# Explicit config (overrides PAT claims)
from opal_agent_sdk import OpalConfig
async with OpalClient(
auth=PATAuth(os.environ["OPAL_PAT"]),
config=OpalConfig.from_pat(
os.environ["OPAL_PAT"], base_url="https://opal-localdev.optimizely.com"
),
) as client:
...
Create PATs in Settings > Developer > Personal Access Tokens in the Opal UI.
Streaming
async with OpalClient(auth=PATAuth(pat)) as client:
async for event in client.agents.specialized.stream(
agent_id="your-agent-uuid",
parameters={"query": "Summarize this article"},
):
if event.event_type == "response_chunk":
print(event.payload.get("content", ""), end="", flush=True)
Event payloads are passed through exactly as the server sends them: text is
under content, a tool_call carries name and input_params, and its
execution_id is the tool call's id, which the matching tool_result shares.
When an execution fails, run(), chat().start() and chat().send() raise
OpalServerError, with the server's error_type as code and the event
payload as payload.
A run that fails after it has started ends with an execution_complete whose
status is not COMPLETED, so streaming callers check status there:
if event.event_type == "execution_complete" and event.payload["status"] != "COMPLETED":
print(f"failed: {event.payload.get('error')}")
Run-time overrides
An agent can let a run override its Model Provider, Inference Level, default
tools and auto tool selection. Build a RunOverrides with one method per
setting and pass it to run(), stream() or run_stream():
from opal_agent_sdk import OpalRuntimeOverrideNotAllowedError, RunOverrides
overrides = (
RunOverrides.builder()
.llm_provider("anthropic")
.inference_type("complex")
.enabled_tools(["web_search"]) # replaces the agent's tools; [] means none
.enable_auto_tool_prediction(False)
.build()
)
try:
result = await client.agents.specialized.run(
"your-agent-uuid", parameters={"query": "Summarize this article"}, overrides=overrides
)
except OpalRuntimeOverrideNotAllowedError as exc:
print(f"the agent doesn't allow overriding: {exc.fields}")
Only the settings you set are sent. The agent must allow each one in its
settings; if it doesn't, the run is refused before it starts with
OpalRuntimeOverrideNotAllowedError, a subclass of OpalUnsupportedError,
whose fields lists the refused settings. chat() doesn't take overrides.
To run on one of the instance's custom inference providers, use
llm_provider("custom"), and custom_llm_provider_guid("<guid>") to pick one;
without a guid the run uses the provider the instance has selected. The
instance must have custom providers enabled.
Automatic tool prediction takes one of three states: enable_auto_tool_prediction(False) (off),
enable_auto_tool_prediction(True) (fully on), or enable_auto_tool_prediction(True) with read_only_tool_search(True) (on, finding read-only
tools only).
Multi-turn Chat
A chat needs an agent with conversation_mode on. Its first turn carries the
agent's declared inputs, as a run() does; every send() after that is a user
message. How the chat starts depends on the agent:
- With a prompt template (a "seeded" agent),
start()runs turn 1 from the parameters and returns the agent's reply. Call it beforesend(). - With an empty template (an "open chat"), turn 1 only opens the
conversation, with no model call.
start()returns a turn with empty text, and a firstsend()withoutstart()opens it for you.
chat = client.agents.specialized.chat("your-agent-uuid", parameters={"search_query": "lighthouses"})
first = await chat.start() # a seeded agent's reply; "" for an open chat
print(first.output_text)
turn = await chat.send("Summarize that in one sentence.")
print(turn.output_text) # chat.memory_id and chat.etag are managed automatically
# Streaming: start() still returns turn 1 aggregated; send() yields events.
async with client.agents.specialized.chat_stream("open-chat-agent-uuid") as chat:
async for event in chat.send("Hello"): # opens the conversation first
...
A single-turn agent has no chat: start() and send() raise
OpalUnsupportedError; use run(). parameters apply to a new chat only; to
continue a saved one, pass memory_id (and etag) and call send().
A start() that fails after the server created the conversation leaves the
chat holding its memory_id, so start() again raises OpalUnsupportedError
("chat already started"). To try again, call reset(), then start().
Catalog: list / export / import / retire Agents and Skills
Agents
# List + iterate. Each row carries its creator: `created_by` is the raw
# Turnstile id, `creator` the resolved name + email (one POST /users/lookup
# per page). Pass resolve_users=False to skip that call.
page = await client.agents.list(type="specialized")
for agent in page:
print(
agent.agent_id,
agent.name,
agent.creator.display_name if agent.creator else agent.created_by,
)
async for agent in client.agents.iter(type="all"):
print(agent.agent_id)
# Export — single agent (returns dict, optionally writes file)
doc = await client.agents.export("agent-id", type="specialized")
await client.agents.export("agent-id", type="specialized", output_file=Path("/tmp/a.json"))
# Export — recursive workflow tree (returns AgentExportTree)
tree = await client.agents.export("wf-id", type="workflow", recursive=True)
await client.agents.export(
"wf-id",
type="workflow",
recursive=True,
output_file=Path("/tmp/agents/"),
)
# Import — single agent, or recursive tree (topological sort + cycle detection)
result = await client.agents.import_(doc, type="specialized")
results = await client.agents.import_tree(Path("/tmp/agents/"))
# Shares
grants = await client.agents.list_shares("agent-id", type="specialized")
# Rename — a partial update, so this touches nothing but the name
await client.agents.update("agent-id", type="specialized", name="ARCHIVE-Weekly Digest")
# Retire, reversibly. There is no delete: deactivation is what a retention
# policy needs, and the irreversible step stays a human action in the UI.
await client.agents.deactivate("agent-id", type="specialized")
await client.agents.activate("agent-id", type="specialized")
Skills
# List
page = await client.skills.list(scope="org")
for skill in page:
print(skill.skill_guid, skill.title)
# Export — JSON envelope, SKILL.md, or whole plugin bundle
doc = await client.skills.export("skill-guid", scope="org")
await client.skills.export(
"skill-guid",
scope="org",
format="skill_md",
output_file=Path("/tmp/skills/"), # directory; SKILL.md is a directory artifact
)
result = await client.skills.export_as_plugin(
["g1", "g2"],
scope="org",
plugin_name="my-plugin",
plugin_description="...",
output_dir=Path("/tmp/plugin/"),
)
# Import — JSON, SKILL.md, or whole plugin bundle
r = await client.skills.import_(doc, scope="org")
rs = await client.skills.import_plugin(Path("/tmp/plugin/"))
# Retitle and retire. A skill's title is its name; the body and trigger keep
# round-tripping through export / import. No delete here either.
await client.skills.update("skill-guid", scope="org", title="ARCHIVE-Brand Voice")
await client.skills.deactivate("skill-guid", scope="org")
await client.skills.activate("skill-guid", scope="org")
Putting those together — the retention sweep this surface was built for.
Collect the whole catalog first, then mutate; do not mutate inside the
iter() loop:
cutoff = datetime.now(timezone.utc) - timedelta(days=60)
# Step 1 — read. Snapshot the catalog before changing anything.
stale = [
agent
async for agent in client.agents.iter(type="all")
if agent.created_at and agent.created_at < cutoff and is_stale(agent)
]
# Step 2 — write, against the snapshot.
for agent in stale:
owner = agent.creator.email if agent.creator else agent.created_by
await client.agents.update(agent.agent_id, type=agent.type, name=f"ARCHIVE-{agent.name}")
await client.agents.deactivate(agent.agent_id, type=agent.type)
notify(owner, agent)
The two-step shape is not stylistic. iter() pages with an offset, and both
mutations move the ground under it: deactivate drops the row out of the
default (active-only) query, and update bumps updated_at, which the listing
sorts on descending. Mutating mid-iteration shifts later rows into windows that
have already been read, so the sweep silently skips agents — the same class of
quiet truncation as reading the wrong pagination field.
For the wire shapes and round-trip semantics, see
docs/tech-spec/agent-framework/agent-sdk/skills-agents-export-import.md.
Agent Directory — browse and install published agents
client.agents is your instance's own catalog. client.directory is the
Agent Directory: the published, cross-region catalog you browse and install
from. Seven verbs, no publish — authoring happens in the source region and
the UI.
# Discover. Tag names feed straight back into the filter.
tags = await client.directory.tags(limit=10)
page = await client.directory.browse(tags=["reporting"], search="digest", page_size=20)
for agent in page:
# browse populates install state for YOUR instance, so one listing answers
# both "what exists" and "what do I already have".
print(agent.agent_id, agent.name, agent.is_installed, agent.installed_version)
# Full detail, including the dependencies an install would pull in.
detail = await client.directory.get("weekly-digest")
print(detail.release_notes, [d.agent_id for d in detail.dependencies])
# Add `include_agent_data=True` for the complete export JSON (the same envelope
# `agents.export()` returns). Off by default — it is the whole agent.
raw = (await client.directory.get("weekly-digest", include_agent_data=True)).agent_data
# Install, with dependencies, in topological order.
result = await client.directory.install("weekly-digest")
print(result.status, result.dependencies_installed)
# What this instance has, and what has moved on since.
for row in await client.directory.installations():
print(row.agent_id, row.directory_version, row.is_active)
for update in await client.directory.check_updates():
print(f"{update.agent_name}: v{update.current_version} -> v{update.latest_version}")
await client.directory.install(update.agent_id) # applying one is just an install
install does not overwrite by default. It matches the server (a missing
force_update reads as false) and the UI, which defaults false and confirms
before overwriting an installed agent. Installing over an existing installation
fails with HTTP 409 unless you opt in.
Pass force_update=True for idempotent provisioning. Two things follow: local
edits to an installed agent are overwritten with no undo, and since no pinned
version means latest, a downgrade only happens if you deliberately pin an
older one.
Pass user_id when you have it. Without it the server records
installed_by as null and creates the imported agent as the literal user
"system", so an audit of who installed what is empty for SDK-driven
installs.
The target instance is never a parameter. It comes from your config, which is what the server accepts anyway — it 403s unless the id matches the caller's own instance.
featured() returns a different type on purpose. The server builds featured
rows without ever looking up install state, so is_installed and friends would
arrive as schema defaults — False even for an agent that is installed.
DirectoryFeaturedAgent has no such attributes, which turns a silently wrong
answer into an AttributeError. Use browse(featured=True) when you need
featured agents with trustworthy install state.
installations() includes orphans. A row whose local agent has since been
deleted reports is_active=False rather than vanishing — filter on it when you
want live agents only.
Personal files — export and import your own /context/
client.personal_files copies the signed-in user's own personal files (Mark's
/context/ folder), using the same token as the rest of the SDK:
from pathlib import Path
# `client` is your signed-in OpalClient. The destination must be absent or empty.
directory = Path("./my-context")
exported = await client.personal_files.export_to(directory, prefix="whats-happening")
print(f"Exported {len(exported.files)} files to {exported.directory}")
if exported.changed_during_export:
print("WARNING: the folder changed during export; review before importing.")
else:
imported = await client.personal_files.import_from(directory, prefix="whats-happening/")
print(f"{len(imported.saved)} saved, {len(imported.unchanged)} unchanged")
Omit prefix for everything. a and a/ both select files under a/, not
a.md; exported paths keep that prefix so they round-trip to the same place.
Downloads verify sha256 and size and report before/after folder generations.
Import walks regular files, skips symlinks and identical hashes, and stops on
its first failed save with the path and count already saved. Import overwrites;
versions are kept on the server, and nothing is deleted, even server-only files.
opal personal-files export ./my-context --prefix whats-happening
opal personal-files import ./my-context --prefix whats-happening
Each CLI command prints a summary line; export warns about concurrent changes.
See examples/c3_personal_files.py for a
round-trip and the cross-language contract.
Remote development machines — client.rde
client.rde runs work on a remote development machine: create one from a
template, wait for it, run commands, move files, terminate it. A machine is
created from a template (which carries its image and size), and its name is
unique in the tenant forever, so a name doubles as an idempotency key.
import sys
from pathlib import Path
from opal_agent_sdk.rde import RdeCommand, RdeStatus
rde = client.rde
template = next(t for t in await rde.list_templates() if t.name == "agent-sdk-e2e")
m = await rde.create_machine(template.id, "my-build-1")
try:
await rde.wait_for_machine(m.id, RdeStatus.RUNNING, timeout_s=2400)
await rde.wait_for_command(m.id, "true", timeout_s=300) # the guest answers
await rde.upload_archive(m.id, Path("setup/"), "/home/ubuntu/mark/ci")
cmd = (
RdeCommand.builder("bash /home/ubuntu/mark/ci/run.sh")
.env("TOKEN", token) # secrets go in env, never in the command
.build()
)
session = await rde.start_command(m.id, cmd)
async for chunk in session.output(timeout_s=5400):
sys.stdout.write(chunk.text)
print("exit code", session.result.exit_code) # None when state is "unknown"
await rde.download_file(m.id, "/home/ubuntu/out/report.tar.gz", Path("report.tar.gz"))
finally:
await rde.terminate_machine(m.id)
wait_for_machinetreatsidleas running, raisesOpalRdePlacementErrorwhen no host could be found (trywake_machineand wait again) andOpalRdeMachineErrorfor any other failure, and rides out short 5xx bursts.- A non-zero exit code is a result, not an error.
run_commandreturns the output's tail and cancels the command at its deadline;session.output()leaves a command running at its deadline. upload_archivewrites under the shared tree (/home/ubuntu/mark/...or/context/...) and works on a sleeping machine;upload_fileanddownload_filework anywhere theubuntuuser can write or read, on a running machine.- There is no template or image authoring, export, network editing, terminal or agent binding here, by design.
opal rde list --name-prefix my-build-
opal rde exec <machine_id> -- df -h / # the command's exit code; 125 when it has none
opal rde terminate <machine_id> --wait
See examples/d1_rde_machine.py and
the spec.
Meeting transcripts — client.transcripts
client.transcripts uploads a meeting transcript (WebVTT or plain text), lists
and reads the transcripts you can read in Mark, shares and unshares one, and
deletes it.
from pathlib import Path
ts = client.transcripts
t = await ts.upload(
Path("standup.vtt"), # or the transcript text itself
title="DiPer Standup",
idempotency_key="standup-2026-11-13", # a retry with the same key returns t
)
async for segment in ts.segments(t.id):
print(f"[{segment.start_ms // 1000}s] {segment.speaker_name}: {segment.text}")
await ts.share(t.id, user_id="<mark user id>") # or conversation_id=...
async for row in ts.list(query="standup", source="upload"):
print(row.id, row.title, row.started_at)
- An upload is a standalone transcript: no meeting is created, and you own
it and are its only reader until you share it (
meeting_idisNone). A meeting transcript is readable by the meeting's members;can_managesays whether you may share and delete it. uploadrefuses content over 8 MiB, and requiresidempotency_key, before sending anything. The server's limits are tighter: more than 1,000,000 UTF-16 units of spoken text in all, or a segment over 20,000 characters, answers 413transcript_too_large. Pass apathlib.Pathto upload a file; astrorbytesis always the transcript itself, never read as a path.- A repeat with the same
idempotency_keyreturns the first upload's transcript. Once that transcript is deleted, the key can't make a new one: a repeat raisesOpalConflictError(409) with codetranscript_key_reused. Use a new key. listandsegmentspage lazily as you iterate;limitis the page size.- While a transcript's content isn't available yet,
content_availableis false, andsegmentsraisesOpalConflictErrorwith codetranscript_content_pending. - Sharing, unsharing or deleting a transcript you can read but don't manage
raises
OpalNotPermittedError(403, codetranscript_forbidden). It is not anOpalAuthError: your token is fine. - A transcript has at most 100 shares, users and conversations together.
Sharing it with one more raises
OpalError(400) with codetranscript_share_limit; unshare one first.
See the contract.
Execution logs
Fetch an agent's past executions (the history the Opal UI shows), paginated:
Mirrors the Opal UI's Logs view: list/iter return lightweight summaries, and
get returns the full detail for one execution (so you don't pull large
inputs/outputs for every row).
# Lightweight rows (OpalExecutionSummary) — newest first
page = await client.executions.list(agent_id="your-agent-uuid", type="specialized")
for row in page:
print(row.execution_id, row.status, row.created_at, row.duration_seconds)
if page.has_more:
nxt = await client.executions.list(agent_id="your-agent-uuid", type="specialized", page=2)
# Auto-paginate the full history (still lightweight summaries)
async for row in client.executions.iter(agent_id="your-agent-uuid", type="workflow"):
print(row.execution_id, row.status)
# Full detail for one execution (OpalExecutionLog) — inputs, output, log, steps
detail = await client.executions.get(execution_id="exec-...", type="specialized")
print(detail.parameters, detail.result, detail.log)
OpalExecutionSummary (list rows) is bounded — the Logs-table metadata plus identifiers:
execution_id, created_at, status, duration_seconds, agent_version, total_credits,
evaluation_score, user_id (triggering user), token_usage, llm_provider,
conversation_mode. OpalExecutionLog (get) is a superset that adds the potentially-large
fields: parameters (input variables), result (output), log, and (workflow)
step_executions. The agent's display name is on neither — resolve it from agent_id via
client.agents.list(...).
type is "specialized" or "workflow". Filters: status, start_date, end_date,
user_id; agent_version (specialized only) and search (workflow agent-name search only).
Live event subscription for an in-flight execution is separate — see
client.executions.subscribe(...).
Development
make install # pip install -e ".[dev,cli]"
make test # pytest
make lint # ruff check
make format # ruff format
make typecheck # mypy --strict
make check # all of the above
Demo App
A FastAPI + HTML demo app is included in demo/ — see its README for setup instructions.
Metadata
Release files for opal-agent-sdk 0.14.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 |
|---|---|---|---|---|
| opal_agent_sdk-0.14.0.tar.gz | 195.7 kB | Without provenance | Details for opal_agent_sdk-0.14.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| opal_agent_sdk-0.14.0-py3-none-any.whl | Python 3 | none | any | Details for opal_agent_sdk-0.14.0-py3-none-any.whl |
Total release size: 393.7 kB
Release files / opal_agent_sdk-0.14.0.tar.gz
| Download URL | opal_agent_sdk-0.14.0.tar.gz |
|---|---|
| Size | 195.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
04552df9454ceaa617f8e4c2b8c99b61f93d5369321df5936c6f717319c4d789
|
|
BLAKE2b-256 checksum How to use checksums |
62f2ef9d555ec56ad40705e5ffbf2f697f1bb5b1735ec934eaef38afbe474815
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / opal_agent_sdk-0.14.0-py3-none-any.whl
| Download URL | opal_agent_sdk-0.14.0-py3-none-any.whl |
|---|---|
| Size | 198.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
11c7d712add3bb8a651ba0d20d0b25a33e4a3741773bca6e184590fd893f4452
|
|
BLAKE2b-256 checksum How to use checksums |
00f54c4a149feb6c715f2213642fc3dca2bcb553a6c2746bbef7d89c15f8dd02
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for opal-agent-sdk 0.14.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.
No provenance found
None of the files in this release were uploaded with provenance metadata.
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.