API Overview
Top-level SDK API map and import surface.
#SDK Reference
The supported public SDK surface, grouped by import path and linked to the detailed reference pages.
This page is the hub. If you are building your first agent, start with the Getting Started guide and the Agent reference. Come back here when you need to find an exact name or see how the pieces fit together. This page documents the behavioral surface (how to build an agent and stream from it). For the shapes that behavior produces and consumes (InvokeResponse, its token_usage dictionary, and privacy and billing models), see Shared Data Models.
#What this is
maivn is a Python SDK for building agentic systems. You describe what your agent can do (its tools, its dependencies, its configuration) as plain Python objects, and the SDK runs each request through an orchestrator that decides what to call and when. Everything you need lives behind a single import:
from maivn import Agent
from maivn.messages import HumanMessage
agent = Agent(name='assistant', api_key='your-api-key')
response = agent.invoke([HumanMessage(content='Hello!')])
print(response.response)The whole programming surface is the SDK. You construct Agent and Swarm objects, register tools with decorators, tune behavior with typed config models, and read results off an InvokeResponse. Tool code runs locally in your environment and is never sent: for each tool the SDK sends its name, description and parameter types for planning. The data a run needs (your messages and files, and tool-call arguments and results) does go to the platform and to the model provider that serves the run. Values you mark as private are replaced with placeholders before a model sees them.
Noteinvoke()returns anInvokeResponse. Useresponse.responsefor the final assistant text andresponse.resultfor structured or final-tool output.
#The public import surface
Everything below is exported from maivn, 202 names in all. They match maivn.__all__. Event normalization and frontend-bridge APIs live in maivn.events, message types live in maivn.messages, and file helpers live in maivn.files and maivn.artifact_images.
from maivn import (
# Version
__version__,
# Core classes
Agent,
Swarm,
Client,
ClientBuilder,
ClientConfig,
BaseScope,
RunOptions,
InvokeResponse,
StreamEvent,
# MCP
MCPServer,
MCPAutoSetup,
# Decorators
tool_output,
toolify,
toolset,
toolify_options,
toolset_options,
compose_argument_policy,
depends_on_tool,
depends_on_agent,
depends_on_private_data,
depends_on_interrupt,
depends_on_await_for,
depends_on_reevaluate,
depends_on_decision,
requires_producer_reference,
# Permissions
PERMISSION_FLAG_NAMES,
PermissionFlag,
PermissionSet,
require_permissions,
# Provider metadata
AuthMode,
ProviderCapability,
ProviderMetadata,
# SDK configuration
ConfigurationBuilder,
MaivnConfiguration,
get_configuration,
# Session config models
MemoryConfig,
MemoryGraphExtractionConfig,
MemoryInsightExtractionConfig,
MemoryLevel,
MemoryPersistenceMode,
MemoryRetrievalConfig,
MemorySharingScope,
MemorySkillExtractionConfig,
SystemToolsConfig,
# Model selection
ModelChoice,
ModelConfig,
ModelConfigPart,
ModelTier,
PlanningChoice,
PlanningTier,
# Memory resources
MemoryDeleteResponse,
MemoryEnrichmentReceipt,
MemoryInsight,
MemoryInsightCreate,
MemoryInsightOrigin,
MemoryInsightType,
MemoryInsightUpdate,
MemoryPersistenceCeiling,
MemoryResource,
MemoryResourceBindingType,
MemoryResourceDetail,
MemoryResourceStatus,
MemoryScope,
MemoryScopeRequest,
MemorySkill,
MemorySkillCreate,
MemorySkillOrigin,
MemorySkillStatus,
MemorySkillStep,
MemorySkillUpdate,
MemoryUnboundResourceCandidate,
OrganizationMemoryPolicy,
OrganizationMemoryPurgeResult,
ProjectMemoryResources,
# Resources and skills
ResourceDeleteResponse,
ResourcePatch,
ResourceRecord,
ResourceScopeRequest,
ResourceUploadOptions,
Skill,
SkillScopeRequest,
SkillSet,
SkillStep,
parse_skill_markdown,
# PII and private data
CoverRegion,
HIPAA_SAFE_HARBOR_CATEGORIES,
PIIWhitelist,
PIIWhitelistEntry,
PrivateData,
RedactedMessage,
RedactionPreviewRequest,
RedactionPreviewResponse,
EncryptedFilePrivateDataStore,
InMemoryPrivateDataStore,
LocalVaultConfig,
PrivateDataStore,
# Billing and usage
BillingCurrentUsage,
BillingPlan,
BillingUsage,
BillingUsageApiKey,
BillingUsageBreakdown,
BillingUsageProject,
BillingUsageTotals,
ProviderModelUsage,
ProviderUsage,
TokenCategoryUsage,
TokenUsageByCategory,
TokenUsageCategory,
# Threads
ApprovalDecision,
BoundThread,
ThreadAccepted,
ThreadCheckpoint,
ThreadState,
# Artifacts
ArtifactDownload,
ArtifactListPage,
ArtifactMetadata,
ArtifactPreview,
ArtifactRef,
OrdinaryArtifactRef,
PrivateArtifactRef,
PrivateArtifactsClient,
TransientVaultClientProof,
# Hosted jobs
HostedJobOptions,
HostedJobStatus,
# Exceptions
AsyncContextError,
ConfigurationError,
DurableBoundaryRefusedError,
MaivnHTTPError,
MaivnSDKError,
PlanLimitExceededError,
ResourceRegistrationError,
VaultSetupError,
PrivateArtifactError,
PrivateArtifactAuthorizationDeniedError,
PrivateArtifactEffectFailedError,
PrivateArtifactGrantExpiredError,
PrivateArtifactTimeoutError,
SkillMarkdownError,
SkillChildNotFoundError,
SkillCycleError,
SkillFrontmatterError,
# Logging
configure_logging,
get_logger,
# Scheduling
AtSchedule,
CronInvocationBuilder,
CronSchedule,
IntervalSchedule,
JitterDistribution,
JitterSpec,
MisfirePolicy,
OverlapPolicy,
Retry,
RetryBackoff,
RunRecord,
RunStatus,
Schedule,
ScheduledJob,
list_jobs,
stop_all_jobs,
# Durable triggers
Trigger,
TriggerFireReceipt,
TriggerInvocationBuilder,
TriggerOptions,
TriggerSource,
RetryPolicy,
stable_trigger_ids,
ChainedEventSource,
EmailToInvokeSource,
ExternalConnectionEventSource,
FireTriggerToolSource,
ManualSource,
MemoryEventSource,
ReplyConversationSource,
ScheduleSource,
SLATimerSource,
StorageEventSource,
WebhookSource,
# Serving
ServingEvent,
ServingListener,
ServingSession,
# Interrupts and terminal reporting
AgentGenerated,
BackpressurePolicy,
FollowupInputHandler,
FollowupOption,
FollowupQuestion,
FollowupQuestionsConfig,
default_terminal_followup,
default_terminal_interrupt,
)Event, message and file APIs live in dedicated public submodules:
from maivn.events import AppEvent, EventBridge, RawSSEEvent, normalize_streamfrom maivn.messages import HumanMessage, AIMessage, SystemMessage, RedactedMessagefrom maivn.files import GeneratedFile, GeneratedFiles, editable_source_archive, generated_file
from maivn.artifact_images import ArtifactImageUnavailableError, ResolvedArtifactImage, resolve_artifact_imageMetadata-only run telemetry lives in its own versioned submodule:
from maivn.telemetry import RunTelemetryEvent, register_listener
from maivn.telemetry.opentelemetry import OpenTelemetryAdapterTip You rarely import all of this at once. Most applications need onlyAgent(orSwarm), one or two decorators, and the message types. Everything else is opt-in.
#Core classes
The objects you instantiate and call. Agent and Swarm are the two entry points. They share tool registration, events(), batch / abatch, thread methods and scheduling. BaseScope supplies the scheduling and trigger helpers. The .structured_output(Model) builder, MCP registration and session_usage() are Agent-only. Swarms use final tools for typed output.
#How an agent runs
When you call invoke() or stream(), the SDK compiles your tools and config into a request and hands it to the orchestrator. The orchestrator plans which tools to call (it receives each tool's name, description and parameter types, never your code), executes them locally in your process, and synthesizes a response. Your messages and files and the arguments and results of tool calls go to the platform and to the model provider that serves the run, and values you mark as private are replaced with placeholders before a model sees them; see the Private Data Guide. You read the result from InvokeResponse, or consume incremental StreamEvent values.
The async methods (ainvoke / astream) mirror the synchronous ones for native asyncio code, and batch / abatch run independent requests concurrently while preserving input order.
#Decorators
Decorators define tools and declare how a tool relates to other tools, agents, secret data, and the user. @toolify turns a function or Pydantic model into a tool. @toolset marks a class whose methods become tools. Dependency decorators are applied beneath @agent.toolify(...) (or beneath @swarm.member), or chained off the builder returned by toolify(...). See the Dependencies guide for the full data-flow model.
Artifact production uses generator toolsets from maivn-tools. These tools run in the user's tool environment and return GeneratedFile values through the normal artifact intake. Stored Office files (DOCX, XLSX, PPTX) are downloadable but have no inline preview. PDF and image files (PNG, JPEG) do. See Artifacts.
from maivn import depends_on_tool
@agent.toolify(description='Fetch raw sensor data')
def fetch_sensor_data(sensor_id: str) -> dict:
return {'sensor_id': sensor_id, 'readings': [72, 73, 71]}
@agent.toolify(description='Analyze sensor readings')
@depends_on_tool(fetch_sensor_data, arg_name='sensor_data')
def analyze_readings(sensor_data: dict) -> dict:
readings = sensor_data['readings']
return {'average': sum(readings) / len(readings)}#Configuration
Two kinds of configuration exist. SDK configuration describes the environment (credentials, timeouts, defaults) and is usually built once from the environment. Session config models are typed objects that carry per-scope or per-call runtime controls. Pass them to Agent(...) / Swarm(...) as defaults, or to invoke() / stream() as overrides.
#SDK configuration
#Session config models
Memory has a dedicated family of resource and policy models (MemoryInsight, MemoryResource, MemorySkill, OrganizationMemoryPolicy, and related enums). See the Memory and Recall guide for how they fit together.
#Privacy and private data
These models declare and govern sensitive values so the SDK can keep them out of model-visible context. The model plans against a schema of key names and types. Real values are injected at tool-execution time, and tool results are scanned and redacted before returning to the model. See the Private Data guide.
Redaction aids, not compliance. phi_mode and HIPAA_SAFE_HARBOR_CATEGORIES are redaction aids. Using them does not make a deployment compliant with health-privacy law, and the hosted Service does not accept protected health information without a separate signed agreement; see the Acceptable Use Policy. mAIvn holds no SOC 2, HIPAA, ISO 27001, or FedRAMP certification, and cannot guarantee that every private value is detected. These controls do not replace required audits and organizational safeguards.
#Threads
A thread is a durable conversation. client.thread(), agent.thread() and swarm.thread() return a BoundThread, whose time_travel(checkpoint_id, message, ...) rewinds the thread and waits for the new path's InvokeResponse. The explicit methods on Client (start_thread, post_thread_message, get_thread, thread_events, time_travel_thread, submit_approval) return or consume ThreadAccepted, ThreadState, ThreadCheckpoint and ApprovalDecision. See Client.
#Artifacts
Files that tools generate come back as ArtifactRef values on response.artifacts. client.artifacts retrieves ordinary files and client.private_artifacts retrieves private ones. See Artifacts for the reference models, both clients, maivn.files and maivn.artifact_images.
#Errors
MaivnSDKError is the base of the SDK's exceptions. MaivnHTTPError and PlanLimitExceededError carry the API error envelope, DurableBoundaryRefusedError reports a privacy-boundary refusal, and private artifact calls raise PrivateArtifactError and its subclasses. See Errors and exceptions.
#Messages
Import message types from maivn.messages. These are the inputs you pass to invoke() / stream() and the assistant turns the SDK returns.
#Logging
#Events
The events surface lets you stream execution state (tool calls, phase indicators, the final response) into your own backend and frontend. The canonical normalize_stream() helper converts a raw stream into a stable, versioned AppEvent contract, payload builders construct individual event payloads, and EventBridge mounts an SSE endpoint. See the Events reference and the Frontend Events guide for the browser client example.
Task-list updates reach an events(on_event=...) callback as a dict with category == 'task_list_updated' and the items in event['payload']['items'], but reach normalized consumers as an AppEvent with event_name == 'task_list_updated' and the items in event.task_list.items. The two shapes differ; see Task-list events.
Note Enrichment events are fixed-label phase indicators (for example, "Evaluating request", "Planning actions", "Synthesizing response") streamed between tool calls so consumers can show what the system is doing. Status messages are a separate event family that may appear on the same stream.
#Decisions
The prepared maivn.decisions feature set provides categorical requests, locally authorized platform calls, fallback diagnostics, native batching, before/after invocation plans, typed arguments, function/local-tool dependencies and optional matching. Use the ordinary mAIvn key and platform address. No provider credential or model selector is exposed. See the Decisions API, guide and examples.
#Run telemetry
maivn.telemetry publishes the customer-visible run lifecycle as a closed, versioned metadata schema. The optional maivn[otel] adapter maps runs to traces and tool calls to spans without exporting messages, prompts, arguments, results, or resolved private values. See Run Telemetry.
#Scheduling
Any Agent or Swarm can run on a schedule. cron(...), interval(...), and at(...) return a chainable builder. A remote terminal call returns a durable Trigger. An explicit mode="local" call returns a process-owned ScheduledJob. See the Scheduling reference and the Scheduled Invocation guide.
#Other exports
These exports have guides but no dedicated reference page. Their signatures are in the SDK source.
#Token usage and billing
Responses expose runtime-reported token usage as an extensible dictionary, and Agent.session_usage() and Client.session_usage() return provider-reported counts as ProviderUsage. The public billing models validate aggregated plan and quota payloads, but the current public Client does not fetch those payloads. See the Billing reference and the Billing and Usage guide.
#Quick navigation by goal
- Build your first agent — Agent + Getting Started guide
- Define and wire tools — Decorators + Tools guide + Dependencies guide
- Request typed output —
structured_output()on Agent + Structured Output guide - Coordinate multiple agents — Swarm + Multi-Agent guide
- Connect external tools — MCP
- Stream events to a frontend — Frontend Events guide (one-line FastAPI mount + a browser client example); Events for the API reference and trust-boundary controls
- Export runs to an observability stack — Run Telemetry for metadata hooks and OpenTelemetry spans
- Run agents on a schedule — Scheduling + Scheduled Invocation guide
- Make categorical decisions — Decisions API + guide
- Handle secrets and PII — Private Data guide
- Tune memory and recall — Session Config Models + Memory and Recall guide
- Configure the SDK environment — Configuration
- Track tokens and usage — Usage and Cost + Billing + Billing and Usage guide
- Work with generated files — Artifacts
- Resume a durable conversation — Client threads + Sessions and Streaming guide
- Handle failures — Errors and exceptions
- Debug — Logging + Troubleshooting
#Next steps
- Getting Started — your first agent, end to end
- Agent reference — the full
AgentandBaseScopesurface - Shared Data Models — the typed shapes you read off responses and pass in
- Examples — a runnable tour organized by what you want to build
- Best Practices — production patterns
#Version
from maivn import __version__
print(__version__)