Client
HTTP client lifecycle and connection reuse behavior.
#Client
Client is the low-level HTTP and thread API used by Agent and Swarm. Most applications should start with those higher-level objects.
#Construction
from maivn import Client
client = Client(
api_key="...",
client_timezone="America/Chicago",
timeout_seconds=30,
)Client accepts an API key, a base URL, ClientConfig, an optional HTTPX transport, timeout controls, an initial thread ID, a default customer ID (default_user_id, or MAIVN_DEFAULT_USER_ID), and an optional private-data store. timeout is the older spelling of timeout_seconds. Pass both only if they match. default_user_id is for trusted backends that act for one customer. An explicit RunOptions.user_id on a call always wins.
tool_execution_timeout (seconds, default 600) is sent as the timeout of each SDK tool. See Tool timeout and the RunOptions table.
Omitting private_data_store selects automatic encrypted local storage for caller-declared private values. The required private-data-vault dependency opens lazily. Supported desktops use the OS credential store. Servers supply MAIVN_VAULT_DIRECTORY and MAIVN_VAULT_KEY, or pass local_vault=LocalVaultConfig(directory=..., key_provider=...). Import LocalVaultConfig from maivn.
Explicit private_data_store=None disables local persistence. A custom PrivateDataStore replaces the automatic store. InMemoryPrivateDataStore retains values only for the lifetime of that store instance. Do not combine a custom store with local_vault configuration.
Use client.forget_private_data(thread_id) or await client.aforget_private_data(thread_id) to delete that thread's saved caller values locally. These methods do not delete server records or uploaded files. See Values that outlive one call for setup and recovery requirements.
restore_private_values defaults to True, which restores private values in the output you get back. Pass restore_private_values=False to keep the final message and structured result masked: they carry placeholders instead of the real values. Arguments for your local tools are still resolved, so those tools still receive real values. See Keep private values masked in output.
env_file= and api_key_file= accept a string or Path naming a selected dotenv or single-line key file. Direct credentials win over the terminal environment, which wins over file values. MAIVN_API_KEY_FILE selects a key file when no higher-priority key value exists. Files are never searched for automatically, and an explicit config= remains authoritative. See credential sources and precedence.
When an explicit value is omitted the environment supplies it: MAIVN_API_KEY for the key, and MAIVN_BASE_URL for base_url (default https://api.maivn.io). There is one public address. The SDK does not accept or read a separate address for any other request grouping. See Choosing which mAIvn endpoint to call.
#One-shot execution
invoke() returns an InvokeResponse, and stream() yields StreamEvent values. Async equivalents are ainvoke() and astream().
from maivn import Client
client = Client(api_key="...")
response = client.invoke("Summarize this incident")
print(response.final_message or response.response)
for event in client.stream("Explain the remediation"):
print(event.name, event.payload)Execution methods accept options, tool metadata, private data, force_final_tool, and swarm-member descriptors. They do not accept the removed status_messages, force_model, or per-call memory/swarm configuration arguments. astream() also takes cancel_on_close=False. Set it to True to cancel the runtime session when you close the stream early.
client.cancel(session_id) (async acancel) cancels a runtime session.
#RunOptions
RunOptions carries per-call settings for invoke, stream and the thread methods. It is frozen, rejects unknown fields, and every field is optional. Agent and Swarm build one for you from their own arguments.
tool_execution_timeout (seconds, greater than 0) is sent as the timeout of each SDK tool. A tool that runs longer ends with a timeout, and the value also bounds how long a human-approval tool can wait. A value on RunOptions wins over the client's value. The default is 600 seconds, and values above 600 are sent as 600.
max_cycles (1 to 1000) caps the run's model-loop cycles. The platform never runs more than 20 cycles, so it uses the smaller of your value and 20. The cap is exact: a run that reaches it raises MaivnSDKError with error_code='max_iterations_exceeded'. A per-call value beats RunOptions.max_cycles, which beats the scope's value. It requires a platform release that supports it. Against an older platform, setting it makes the request fail with a validation error, and leaving it unset works everywhere. For a run time limit, use hosted jobs and max_duration_seconds.
#Usage and redaction preview
client.session_usage(session_id) (async asession_usage) returns a ProviderUsage for a session and the work it started. See Usage and cost.
client.preview_redaction(prompt, *, attachments=None, resources=None, pii_whitelist=None, known_pii_values=None, cover_regions=None, timeout_seconds=300.0) (async apreview_redaction) returns a RedactionPreviewResponse that shows what a run would send to the model provider, before you run it. See Preview redaction.
#Resources, skills and memory
The client exposes resources, skills, and memory facades. Resource operations include upload, binding, metadata updates, soft deletion, and restoration. client.skills.delete(skill_id) deletes a first-class skill by its Skill.memory_id. client.memory.skills and client.memory.insights support CRUD. Insights also support promotion. Read post-run persistence receipts through client.memory.enrichments.list(session_id). The jobs facade starts and cancels hosted jobs, reads their status, and waits for them with wait / async_wait. See Hosted jobs.
See SDK Resource Configuration for method names, request models, async counterparts, and the distinction between constructor declarations and stored-asset operations.
#Generated message attachments
Successful generated files are returned in response.artifacts and on the assistant message as immutable ArtifactRef values. Two facades retrieve the bytes: client.artifacts for ordinary files and client.private_artifacts for private ones. Both verify what they download and replace the destination only after verification succeeds.
from pathlib import Path
from mimetypes import guess_extension
# response is the completed result from your file-producing Agent or Client.
destination = Path("downloads")
destination.mkdir(exist_ok=True)
for index, ref in enumerate(response.artifacts or ()):
extension = guess_extension(ref.mime_type) or ".bin"
path = destination / f"file-{index}{extension}"
if ref.custody == "vault_private":
client.private_artifacts.download_to(
ref, path,
session_id=response.session_id,
)
else:
client.artifacts.download_to(ref, path)Choose the destination filename and extension in your application. A private reference contains a safe label, not the original private filename or file contents.
The Artifacts reference covers listing, previews, editing a revision, private deletion and redacted export, the models, and the helpers a custom toolset uses to return files.
#Durable threads and interrupts
A thread is a durable conversation. The thread methods start one, continue it, read its state, replay its events, branch from an earlier checkpoint, and answer approvals and questions.
#Bound threads
client.thread(thread_id=None, *, options=None) returns a BoundThread. Construction is local. Omitting the ID selects a fresh one. The same factory exists on Agent and Swarm and preserves their execution defaults and tools.
conversation = client.thread()
response = conversation.send(["Remember the project is Atlas.", "Summarize it."])
response = conversation.send("What is the project called?")send and stream take options and the usual invocation arguments. A handle allows one active send or stream at a time. Starting a second raises RuntimeError. Make a fresh handle after another client changes the thread's active session. See thread handles and cleanup.
#Explicit thread methods
Each method has an async twin with an a prefix.
The dispatch methods (start_thread, post_thread_message, time_travel_thread) accept options, tools, private_data, force_final_tool and swarm_members. Their return value is an acceptance receipt, not a result. Raw thread_events consumption does not run local Python tools. Use normal invocation or a bound handle for that lifecycle.
#Thread models
All four are frozen and reject unknown fields. Pass a checkpoint_id from ThreadState.checkpoints to time travel.
#Approvals and questions
from maivn import ApprovalDecision, Client
client = Client(api_key="...")
accepted = client.start_thread("Prepare the release")
client.submit_approval(
accepted.thread_id,
"interrupt-123",
decision=ApprovalDecision(
approved=True,
decided_by="operator@example.com",
),
)
client.submit_interrupt_response(
accepted.thread_id,
"interrupt-456",
answer="Use the staged rollout",
responded_by="operator@example.com",
)#Deliberately absent operations
The current public client has no get_usage() method. The billing classes are exported read models, not callable SDK operations.