Quick Start Tutorial

LeafMesh Quick Start

Build your first agent mesh in 5 minutes.

Step 1: Install LeafMesh

pip install leafmesh

Or use the scaffolding tool for a complete project:

pip install create-leafmesh create-leafmesh my-project cd my-project

Step 2: Set Up .env

Your project holds only its custom code and its .env. The agency's configuration lives in its store (Redis or Postgres), not in a project file: every save is a new version, and every pod runs the latest.

# .env LEAFMESH_ENV_TOKEN=your-environment-token # Studio › Keys, shown when you create the agency LEAFMESH_AGENCY_NAME=my-first-mesh OPENAI_API_KEY=your-openai-key # Never made by the mesh (2.4.507); create-leafmesh writes both for you LEAFMESH_VAULT_KEY=... # 32 random bytes, URL-safe base64 LEAFMESH_WEBHOOK_SECRET=... # same format; signed webhooks answer 503 without it # The store (set only here, never in the YAML) LEAFMESH_STORE=redis REDIS_HOST=localhost REDIS_PORT=6379

Tip: You can use any supported provider. Change agent models to claude-sonnet-4-6 (Anthropic), gemini-2.5-flash (Google), bedrock/claude-sonnet-4-6 (AWS Bedrock), vertex/gemini-2.5-flash (Google Vertex AI), or foundry/gpt-4o (Microsoft Foundry). See LLM Providers for setup. A model key in .env wins; a key saved on Infrastructure → Models in Studio fills any gap.

Step 3: Define Your Agents

An empty store starts a blank agency, which you build in Studio. Open Studio's YAML view and paste this configuration (YAML is the format Studio's YAML view shows). If you have it as a file, leafmesh config import --if-empty <file> loads it into an empty store and never overwrites what is already there.

name: "my-first-mesh" architecture: "managed_mesh" manager: enabled: true model: "gpt-4o-mini" entry_points: - name: "ask" target: "greeter" agents: greeter: name: "greeter" model: "gpt-4o-mini" prompt: "You are a friendly assistant. Greet the user and help with their request." temperature: 0.7 max_tokens: 500 yields: greeting: "string" summary: "string" can_call: - agent: "researcher" condition: "true" researcher: name: "researcher" model: "gpt-4o" prompt: "You research topics thoroughly and provide detailed answers." temperature: 0.3 max_tokens: 1500 tools: ["web_request", "chain_of_thought"] yields: findings: "string" confidence: "number"

Saving in Studio creates a new version of the configuration, and it applies without a restart.

Step 4: Add Python Intelligence (Optional)

Create agency/greeter.py:

from leafmesh import pre_compose @pre_compose(context_processor=lambda ctx: {"tone": "professional"}) async def greeter(llm_response, input_data, context): """Enhance the greeter with custom logic""" return { "greeting": llm_response.get("greeting", "Hello!"), "summary": llm_response.get("summary", str(input_data)), }

The @pre_compose decorator shapes input before the LLM call. The agent function runs after the LLM responds, adding deterministic validation.

Step 5: Create the Entry Point

Create main.py:

import asyncio from leafmesh import LeafMesh async def main(): leafmesh = LeafMesh.from_store() # agency named by LEAFMESH_AGENCY_NAME, store from .env await leafmesh.start() print(f"LeafMesh running!") print(f"API docs: http://127.0.0.1:18820/docs") print("Press Ctrl+C to stop") try: await asyncio.Event().wait() except KeyboardInterrupt: pass finally: await leafmesh.stop() if __name__ == "__main__": asyncio.run(main())

Step 6: Start Redis and Run

# Start Redis (if not already running) redis-server & # Run your mesh python main.py

Step 7: Test It

Open http://127.0.0.1:18820/docs for the interactive API explorer, or use curl:

curl -X POST http://127.0.0.1:18820/api/mesh/request \ -H "Content-Type: application/json" \ -d '{ "entry_point": "ask", "data": {"message": "Hello! Tell me about machine learning."}, "session_id": "my-first-session" }'

What Just Happened?

  1. The agency's configuration (stored and versioned in your store) defined two agents with structured yields schemas
  2. Entry point ask routes requests to greeter
  3. can_call routing automatically chains greeter → researcher
  4. Built-in coordination provides oversight and automatic intervention
  5. Session management persists conversation across requests
  6. API server exposes everything at :18820 with OpenAPI docs
  7. Observability on when your plan includes it

Key Concepts

Entry Points

Entry points are the external-facing API for your mesh. Define them in YAML, call them via POST /api/mesh/request.

Agent Routing (can_call)

Agents declare which agents they can call and under what conditions:

can_call: - agent: "next_agent" condition: "confidence > 0.8" # AST-safe condition on yields

Fan-In (Wait For)

When multiple agents need to contribute before a final agent runs:

agents: final_agent: name: "final_agent" wait_for: "agent_a AND (agent_b OR agent_c)" wait_for_timeout: 60

Python Intelligence

Add deterministic logic on top of LLM responses. The function name must match the agent name in YAML:

async def agent_name(llm_response, input_data, context): # LLM handles interpretation, Python handles logic return {"validated_result": compute(llm_response)}

API Endpoints

Your LeafMesh API server runs at http://127.0.0.1:18820 with these key endpoints:

MethodEndpointDescription
POST/api/mesh/requestSubmit a request via entry point
POST/api/mesh/streamSSE stream of LLM response via entry point
GET/api/mesh/entry_pointsList available entry points
POST/webhook/{entry_point}Webhook — new task or human response (see below)
POST/callback/{agent_name}External-system callback for connectors with after_handoff: wait or move_on (2.4.508; was mode: callback)
POST/callback/calls/{framework}A phone-call platform's "call finished" webhook (2.4.508)
GET/healthHealth check

Webhook Endpoint

POST /webhook/{entry_point} is a single unified endpoint for external integrations (Slack, Zapier, n8n, etc.). The {entry_point} is the name from your entry_points config (e.g. greet_user, research).

Smart routing based on your payload:

PayloadBehavior
No session_id in bodyNew task — routes to the agent mapped to this entry point
session_id matching a paused workflowResume — delivers the human response to the waiting agent
# New task — Slack sends a message curl -X POST http://localhost:18820/webhook/greet_user \ -H "Content-Type: application/json" \ -d '{"message": "Hello, I need help"}' # Human response — resume a paused workflow curl -X POST http://localhost:18820/webhook/greet_user \ -H "Content-Type: application/json" \ -d '{"session_id": "sess_abc123", "decision": "approved"}'

Enable Production Features

Observability (Auto-Enabled)

Observability is on when your plan includes it, carried by the mesh's own sign-in; no setting is needed. Traces, metrics, and logs are collected automatically.

Self-Healing

self_healing: enabled: true # watch agent health and notify (default) actions_enabled: false # set true to let the mesh restart or back up a failing agent

Webhook Signing

Outbound webhook payloads are signed with X-LeafMesh-Signature. The secret is LEAFMESH_WEBHOOK_SECRET in .env; use it to verify the signature on the receiving side. From 2.4.507 the mesh never derives one: without it, the mesh starts with a warning and signed webhooks answer 503.

Next Steps


LeafMesh — YAML-native multi-agent orchestration platform

Last updated: 11/21/2026