REST API

HTTP endpoints for executing agents and managing distributed memory

REST API

HTTP endpoints for executing agents and managing distributed memory

HTTP endpoints for executing agents and managing distributed memory. Automatically generated from @app.reasoner and @app.skill decorators—no manual route definition needed.

Execution Patterns: Sync vs Async

Choose the execution pattern based on task duration and application requirements:

FactorSync (/execute/)Async (/execute/async/)
Response TimeBlocks until completeReturns immediately (HTTP 202)
Max Duration90 secondsUnlimited (background workers)
Result DeliveryIn HTTP responseWebhook or polling
Use CaseQuick operations, sequential workflowsLLM reasoning, batch jobs, long tasks
Best ForTranslations, validations, fast ML inferenceDocument analysis, research, content generation

Quick decision: If it involves LLM calls or takes > 10 seconds, use async.

See Make Your Agent Async for pattern comparison and examples.

Execution

Synchronous Execution

Execute a reasoner or skill and wait for the result. Agentfield persists the execution before dispatch, enabling automatic DAG construction and distributed tracing.

Pattern: Multi-Agent Workflow Orchestration

Agentfield's execution API enables autonomous software where AI agents coordinate complex workflows. Instead of manually orchestrating microservices, agents make intelligent routing decisions:

# Agent A: Sentiment analysis determines next step
sentiment_result = await app.call(
    "support-agent.analyze_sentiment",
    input={"message": customer_message, "history": conversation}
)

# Agent B: Automatically invoked based on AI decision
if sentiment_result["decision"] == "escalate":
    # AI routes to human agent with full context
    await app.call(
        "escalation-agent.create_ticket",
        input={
            "customer_id": customer_id,
            "sentiment": sentiment_result,
            "priority": "high"
        }
    )

The workflow headers (X-Workflow-ID, X-Session-ID) automatically propagate through the call chain, enabling Agentfield to construct a complete execution DAG without manual instrumentation.


Asynchronous Execution

Queue long-running tasks and receive immediate confirmation. Optionally register a webhook for completion notifications.

Webhook Callback Format

When the execution reaches a terminal state Agentfield POSTs this payload to the registered webhook URL:

Webhook Payload
{"event": "execution.completed","execution_id": "exec_abc123","workflow_id": "wf_xyz789","status": "completed","target": "research-agent.deep_analysis","type": "reasoner","duration_ms": 45230,"result": {  "summary": "Comprehensive analysis of 47 sources...",  "key_findings": [...],  "confidence": 0.94},"timestamp": "2024-01-15T10:31:30Z"}

Webhook Headers:

  • X-Agentfield-Signature - HMAC-SHA256 signature of the request body (sha256=<hex>)
  • Custom headers defined in webhook.headers

Pattern: Long-Running AI Tasks

Async execution is ideal for AI tasks that require significant processing time—research, analysis, content generation:

# Queue a multi-step research workflow
response = await app.call_async(
    "research-agent.comprehensive_analysis",
    input={
        "query": "competitive landscape analysis",
        "include_sentiment": True,
        "generate_report": True
    },
    webhook={
        "url": "https://app.com/research/complete",
        "secret": os.getenv("WEBHOOK_SECRET")
    }
)

# Immediately return to user
return {
    "status": "processing",
    "execution_id": response["execution_id"],
    "estimated_completion": "5-10 minutes"
}

# Webhook receives result when AI completes all steps

Check Execution Status

Poll for execution status and retrieve results. Useful when webhooks aren't available or as a fallback.

Status Values:

  • pending - Queued, not yet started
  • running - Currently executing
  • succeeded - Completed successfully
  • failed - Execution failed (see error field)
  • cancelled - Execution was cancelled
  • timeout - Execution exceeded time limit

Batch Status Check

Query status for multiple executions in a single request. Efficient for monitoring multiple concurrent AI tasks.


Memory

Agentfield's memory API provides hierarchical, scoped storage for cross-agent coordination. Memory automatically resolves across workflow → session → actor → global scopes.

Set Memory

Store data in distributed memory with automatic scoping based on workflow headers.

Pattern: Cross-Agent Learning

Memory enables agents to learn and share context across distributed systems:

# Agent A: Customer support learns user preference
await app.memory.set("communication_style", "concise")
await app.memory.set("preferred_channel", "email")

# Agent B: Marketing agent (different server) adapts automatically
style = await app.memory.get("communication_style")  # Returns "concise"

# AI adjusts behavior based on learned preferences
if style == "concise":
    response = await app.ai(
        "Generate a brief, bullet-point summary",
        context={"user_preference": "concise"}
    )

Memory scoping is automatic—no manual key prefixing or namespace management needed.


Get Memory

Retrieve memory with automatic hierarchical resolution across scopes.


Delete Memory

Remove a value from distributed memory.


List Memory

List all memory keys in a specific scope.


Distributed Tracing Headers

Agentfield automatically propagates workflow context through HTTP headers, enabling distributed tracing and automatic DAG construction across multi-agent systems.

Workflow Context Headers

HeaderDescriptionAuto-Generated
X-Workflow-IDGroups related executions into a workflow
X-Workflow-Run-IDIdentifies a specific workflow execution instance
X-Session-IDUser session identifier for memory scopingManual
X-Actor-IDActor (user/system/agent) for attributionManual
X-Execution-IDUnique execution identifier
X-Parent-Execution-IDParent execution in call chain
X-Root-Workflow-IDRoot workflow in nested workflows
X-Agentfield-Request-IDRequest tracking across system

How It Works:

When Agent A calls Agent B using app.call(), Agentfield automatically:

  1. Propagates all workflow headers to Agent B
  2. Sets X-Parent-Execution-ID to Agent A's execution ID
  3. Generates new X-Execution-ID for Agent B
  4. Maintains X-Root-Workflow-ID for the entire call chain

This enables automatic construction of execution DAGs without manual instrumentation.

Example: Multi-Agent Trace

# Agent A (entry point)
# Headers: X-Workflow-ID=wf_123, X-Execution-ID=exec_a

result_b = await app.call("agent-b.process", input=data)
# Agent B receives: X-Parent-Execution-ID=exec_a, X-Execution-ID=exec_b

result_c = await app.call("agent-c.analyze", input=result_b)
# Agent C receives: X-Parent-Execution-ID=exec_b, X-Execution-ID=exec_c
# All share: X-Workflow-ID=wf_123, X-Root-Workflow-ID=wf_123

Agentfield's UI automatically visualizes this as a DAG: A → B → C

For deep integration with observability tools, see Observability.


Metrics

Agentfield exposes Prometheus-compatible metrics for monitoring agent performance, execution latency, and system health.

Key Metrics:

  • agentfield_executions_total - Execution counts by node, type, and status
  • agentfield_execution_duration_seconds - Latency histograms
  • agentfield_memory_operations_total - Memory operation counts
  • agentfield_workflow_dag_depth - Workflow complexity metrics
  • agentfield_queue_depth - Execution queue backlog

For Prometheus integration, Grafana dashboards, and alerting setup, see Observability.