API Reference
Complete reference for the Health Universe A2A SDK for Python.
Core Classes
Agent (AsyncAgent)
The primary agent class for Health Universe. Use this for all Health Universe agents.
from health_universe_a2a import Agent, AgentContext # Agent is alias for AsyncAgent
class MyAgent(Agent):
def get_agent_name(self) -> str:
return "My Agent"
def get_agent_description(self) -> str:
return "Processes medical data"
async def process_message(self, message: str, context: AgentContext) -> str:
return f"Processed: {message}"Required Methods
get_agent_name() -> strReturns the agent's display name
Example:
"Clinical Data Analyzer"
get_agent_description() -> strReturns what the agent does
Example:
"Analyzes clinical datasets and generates insights"
async process_message(message: str, context: AgentContext) -> strProcesses messages and returns results
Called in background after validation passes
All updates sent via POST to backend
Optional Methods
async validate_message(message: str, metadata: dict[str, Any]) -> ValidationResultValidates incoming messages before processing
Returns
ValidationAcceptedorValidationRejectedDefault: accepts all messages
get_max_duration_seconds() -> intOverride max task duration (default: 1 hour)
Returns maximum duration in seconds
async on_task_start(message: str, context: AgentContext) -> NoneCalled before
process_messagestarts in backgroundUse for logging, metrics, setup
async on_task_complete(message: str, result: str, context: AgentContext) -> NoneCalled after
process_messagecompletes successfullyUse for logging, metrics, cleanup
async on_task_error(message: str, error: Exception, context: AgentContext) -> str | NoneCalled when
process_messageraises an exceptionReturn custom error message or
Nonefor default
Server Methods
serve(host: str | None = None, port: int | None = None, reload: bool | None = None, log_level: str = "info") -> NoneStart HTTP server for this agent
Environment variables:
HOST,PORT/AGENT_PORT,RELOAD
Inter-Agent Communication
async call_agent(agent_name_or_url: str, message: str | dict | list | Any, context: BaseContext | None = None, timeout: float = 30.0) -> AnyUnified method to call another A2A agent
Supports agent names, URLs, or local paths
Automatically propagates JWT tokens
AgentContext (BackgroundContext)
Context for Agent execution. Provides document operations, progress updates, and inter-agent communication.
Properties
document_client: DocumentClientBase- Document operations in this threaduser_id: str | None- User ID from request (optional)thread_id: str | None- Thread/conversation ID (optional)file_access_token: str | None- Access token for file operationsauth_token: str | None- JWT token from original requestjob_id: str | None- Background job IDmetadata: dict[str, Any]- Raw metadata from A2A requestextensions: list[str] | None- List of extension URIs from request messagerun_storage: RunStorage | None- S3-based run storage for routine execution I/O
Methods
async update_progress(message: str, progress: float | None = None, status: str = "working", importance: UpdateImportance = UpdateImportance.NOTICE) -> NoneSend progress update (streamed via SSE or POSTed to backend)
Updates stored in database and displayed to users
progress: 0.0 to 1.0,importance: controls UI visibility
async add_artifact(name: str, content: str, data_type: str = "text/plain", description: str = "", metadata: dict[str, Any] | None = None) -> NoneAdd artifact (streamed via SSE or POSTed to backend)
Artifacts appear in UI and can be downloaded
For persistent storage, use
context.document_client.write()instead
create_inter_agent_client(agent_identifier: str, local_base_url: str | None = None, timeout: float = 30.0, max_retries: int = 3) -> InterAgentClientCreate InterAgentClient with automatic JWT propagation
Recommended way to call other agents
is_cancelled() -> boolCheck if task was cancelled (currently always returns
False)Cancellation feature not fully implemented
Sync Methods (ThreadPoolExecutor)
update_progress_sync(message: str, progress: float | None = None, status: str = "working", importance: UpdateImportance = UpdateImportance.NOTICE) -> Noneadd_artifact_sync(name: str, content: str, data_type: str = "text/plain", description: str = "", metadata: dict[str, Any] | None = None) -> None
SubAgent
Agent for internal/inter-agent use. Returns results directly (no background job).
Required Methods
Same as Agent:
get_agent_name(),get_agent_description(),process_message()
Key Differences from Agent
No background jobs or SSE streaming
Returns results directly in HTTP response
Uses
SubAgentContext(lightweight, no progress updates)Processing should complete in < 30 seconds
SubAgentContext
Lightweight context for SubAgent. Provides document operations and inter-agent communication without progress updates.
Properties
document_client: DocumentClientBase- Document operations in this threaduser_id: str | None- User ID from requestthread_id: str | None- Thread/conversation IDfile_access_token: str | None- Access token for file operationsauth_token: str | None- JWT token for inter-agent callsmetadata: dict[str, Any]- Raw metadata from A2A requestextensions: list[str] | None- List of extension URIs from request message
Methods
create_inter_agent_client(agent_identifier: str, local_base_url: str | None = None, timeout: float = 30.0, max_retries: int = 3) -> InterAgentClientis_cancelled() -> bool
Document Operations
DocumentClient
Client for document operations in a Health Universe thread. Provides listing, reading, writing, and searching documents.
Document Listing
async list_documents(include_hidden: bool = False, role: Literal["source", "artifact", "all"] | None = None, flatten_attachments: bool = True) -> list[Document]List documents in thread
role: Filter by document type ("source"for uploads,"artifact"for outputs)flatten_attachments: Replace wrapper docs with child attachments
async filter_by_name(query: str) -> list[Document]Filter documents by name/filename (case-insensitive substring match)
async get_document(document_id: str) -> DocumentGet document metadata by ID
Document Reading
async download(document_id: str) -> bytesDownload document content as bytes
async download_text(document_id: str, encoding: str = "utf-8") -> strDownload raw document content as text
Only use for text-based files (CSV, JSON, TXT, MD)
async download_extracted(document_id: str) -> strDownload platform-extracted markdown text
For PDFs, DOCX converted to markdown by platform
Document Writing
async write(name: str, content: str | bytes, filename: str | None = None, document_type: str = "agent_output", user_visible: bool = True, comment: str | None = None) -> DocumentWrite content to new document
Handles 3-step upload process automatically
filename: Auto-generated if not provided
async update(document_id: str, content: str | bytes, comment: str | None = None, base_version_id: str | None = None) -> DocumentUpdate existing document with new content (creates new version)
Document Search
async search(query: str, limit: int = 3, patient_id: str | None = None) -> list[SearchResult]Full-text search across documents
Case-insensitive text search over extracted chunks
Use for keyword-based lookups
async semantic_search(query: str, document_id: str | None = None, max_results: int = 5, similarity_threshold: float = 0.4, patient_id: str | None = None) -> list[SemanticSearchResult]Semantic search using vector embeddings
Finds semantically similar content
Powered by pgvector embeddings
Processing Status
async get_processing_status(document_id: str) -> DocumentProcessingStatusGet extraction/processing status of document
async wait_for_ready(document_ids: list[str] | None = None, poll_interval: float = 2.0, timeout: float = 300.0, patient_id: str | None = None, organization_id: str | None = None) -> list[DocumentProcessingStatus]Poll until documents are ready (extraction complete)
If
document_idsis None, waits for all source documents
async close() -> NoneClose HTTP client
Document Data Models
Document
SearchResult
SemanticSearchResult
DocumentProcessingStatus
Inter-Agent Communication
InterAgentClient
Client for calling other A2A-compliant agents with JWT propagation and retry logic.
Constructor
__init__(agent_identifier: str, auth_token: str | None = None, local_base_url: str | None = None, timeout: float = 30.0, max_retries: int = 3)agent_identifier: Target agent (/path,http://url, or name)auth_token: JWT token to propagatelocal_base_url: Base URL for local agents (default: from env)timeout: Request timeout in secondsmax_retries: Max retry attempts for transient errors
Factory Methods
@classmethod from_registry(agent_name: str, auth_token: str | None = None, timeout: float = 30.0, max_retries: int = 3) -> InterAgentClientCreate client from registry lookup
Resolves agent name using global registry
Communication Methods
async call(message: str, timeout: float | None = None) -> AgentResponseCall agent with text message
Returns parsed response
async call_with_data(data: Any, timeout: float | None = None) -> AgentResponseCall agent with structured data (dict, list, etc.)
async close() -> NoneClose client (cleanup)
AgentResponse
Response from inter-agent call with convenient parsed data access.
Properties
text: str- Concatenated text from all text partsdata: Any- First data part from response (structured data)parts: list[dict]- All parts from responseraw_response: dict- Full A2A response
Methods
__str__() -> str- Returns text content__repr__() -> str- Detailed representation
Observability
The SDK provides built-in observability via Langfuse integration. When properly configured, all agent executions and LLM calls are automatically traced.
Core Functions
Setup and Status
setup_observability() -> boolInitialize observability (lazy, idempotent, thread-safe)
Safe to call multiple times — only first call does work
Returns
Trueif observability is active,Falseotherwise
is_enabled() -> boolCheck if observability is active
Fast path: reads module-level bool
get_langfuse() -> Any | NoneReturn the Langfuse client instance, or
Noneif disabled
flush_traces() -> NoneBest-effort flush of all pending traces
Sync — safe to call from executor
Custom Tracing
@observe Decorator
@observe DecoratorParameters
capture_input: bool = False- Capture function input (default: False for performance)capture_output: bool = False- Capture function output (default: False for performance)name: str = None- Optional span name override**kwargs- Additional kwargs forwarded tolangfuse.decorators.observe
traced_span Context Manager
traced_span Context ManagerParameters
name: str- Span name (e.g., "validation", "document.download")as_type: str = "span"- Langfuse observation type ("span", "agent", "generation")input: Any = None- Optional input data to attach to spanmetadata: dict[str, Any] = None- Optional metadata dict
Environment Variables
Configure observability using environment variables:
LANGFUSE_ENABLED- Master switch ("true"/"false", default: "false")LANGFUSE_PUBLIC_KEY- Langfuse public key (required when enabled)LANGFUSE_SECRET_KEY- Langfuse secret key (required when enabled)LANGFUSE_BASE_URLorLANGFUSE_HOST- Langfuse host URL (optional)HU_OBSERVABILITY_CAPTURE_IO- Capture prompts/completions ("true"/"false", default: "false")
Automatic Tracing
When observability is enabled, the SDK automatically traces:
Agent execution - Every
process_message()call with duration, metadata, input/outputLLM calls - Model name, token usage, latency (via OpenTelemetry instrumentation)
Document operations - List, download, write operations as child spans
Inter-agent communication - Calls to other agents via
call_agent()
No code changes required — just set the environment variables.
Example Setup
Validation
ValidationResult Types
ValidationAccepted
ValidationRejected
Extensions and Types
UpdateImportance
Controls how updates are propagated to Navigator UI.
Values
ERROR- Something went wrong (pushed to Navigator)NOTICE- Standard progress update (default, pushed to Navigator)INFO- Verbose logging (stored but not pushed)DEBUG- Diagnostic information (stored but not pushed)
NavigatorTaskStatus
Task status values for Navigator UI.
Local Development
LocalDocumentClient
Filesystem-backed document client for local testing.
Constructor
__init__(data_dir: str, output_dir: str | None = None)data_dir: Root directory withsource/andartifact/subdirectoriesoutput_dir: Output directory (defaults todata_dir/artifact/)
Methods
Same interface as
DocumentClientsearch()andsemantic_search()raiseNotImplementedError
create_local_context()
Factory function for local testing context.
Parameters
data_dir: str- Root directory for test dataoutput_dir: str | None = None- Output directory (defaults todata_dir/artifact/)
Returns
AgentContext- Configured for local filesystem operations
Run Storage
RunStorage
S3-based run storage via presigned URLs for routine agent execution.
Properties
input_files: list[RunStorageFile]- All input files available for this stephas_inputs: bool- Whether any input files are available
Methods
async download_input(filename: str) -> bytes- Download a single input file by filenameasync download_all_inputs(target_dir: Path) -> list[Path]- Download all input files to a directoryasync upload_output(filename: str, content: bytes | str, content_type: str = "application/octet-stream", description: str = "") -> None- Upload an output fileasync finalize() -> None- Write the output manifest (call after all uploads)
RunStorageFile
Server Utilities
create_app()
Create Starlette ASGI application for an A2A agent.
Parameters
agent: A2AAgentBase- Agent instance to servetask_store: Any | None = None- Optional task store (defaults to InMemoryTaskStore)
Returns
Any- Starlette application with A2A endpoints
serve()
Start HTTP server for an agent (convenience wrapper).
Parameters
agent: A2AAgentBase- Agent to servehost: str | None = None- Server host (default: fromHOSTenv var or "0.0.0.0")port: int | None = None- Server port (default: fromPORT/AGENT_PORTenv var or 8000)reload: bool | None = None- Auto-reload (default: fromRELOADenv var or False)log_level: str = "info"- Uvicorn log level
Multi-Agent Server
Functions for hosting multiple agents at different paths.
create_multi_agent_app()
serve_multi_agents()
Observability
observe() Decorator
Add custom traces to your agent methods.
Parameters
capture_input: bool = False- Capture function inputcapture_output: bool = False- Capture function outputname: str | None = None- Optional span name override
traced_span() Context Manager
For inline spans within a method:
Environment Variables
Server Configuration
HOST- Server host (default: "0.0.0.0")PORTorAGENT_PORT- Server port (default: 8000, multi-agent: 8501)RELOAD- Enable auto-reload ("true"/"false", default: "false")
Service URLs
HU_NESTJS_URL- NestJS API base URL (default: "https://apps.healthuniverse.com/api/v1")LOCAL_AGENT_BASE_URL- Base URL for local agents (default: "http://localhost:8501")
Agent Registry
AGENT_REGISTRY- JSON string mapping agent names to URLsAGENT_REGISTRY_PATH- Path to agent registry JSON file
Observability
LANGFUSE_ENABLED- Enable Langfuse observability ("true"/"false")LANGFUSE_PUBLIC_KEY- Langfuse public key (pk-...)LANGFUSE_SECRET_KEY- Langfuse secret key (sk-...)LANGFUSE_BASE_URL- Langfuse host URL (optional)HU_OBSERVABILITY_CAPTURE_IO- Capture full prompts/completions ("true"/"false")
Debugging
DEBUG_HTTP_REQUESTS- Enable HTTP request logging ("true"/"false")
Error Handling
Common Exceptions
ValueError- Invalid parameters, missing documents, unresolved agentshttpx.HTTPError- Network errors, API failuresTimeoutError- Task timeout, waiting for documentsNotImplementedError- Local mode limitations (search functions)
Best Practices
Validation: Use
validate_message()to check inputs before processingError Handling: Implement try/except in
process_message()andon_task_error()Cancellation: Check
context.is_cancelled()in long-running loopsTimeouts: Use appropriate timeouts for inter-agent calls
Resource Cleanup: Always call
client.close()anddocument_client.close()
Examples
Basic Agent
Inter-Agent Communication
Local Development
Observability Integration
Last updated
Was this helpful?