Skip to main content

A lightweight framework for building LLM-powered agents and hierarchical state machines with pluggable backends.

Project description

FlatAgents Python SDK

Python SDK for FlatAgents—YAML-configured AI agents and state machine orchestration.

LLM/machine readers: use MACHINES.md as a primary reference, it is more comprehensive and token efficient.

Install

pip install flatagents[litellm]

Quick Start

Single Agent

summarizer.yml

spec: flatagent
spec_version: "0.6.0"

data:
  name: summarizer
  model:
    provider: openai
    name: gpt-4o-mini
  system: You summarize text concisely.
  user: "Summarize: {{ input.text }}"
  output:
    summary:
      type: str
      description: A concise summary
from flatagents import FlatAgent, setup_logging, get_logger

# Optional: Enable internal logging to see agent progress
setup_logging(level="INFO")
logger = get_logger(__name__)

agent = FlatAgent(config_file="summarizer.yml")
result = await agent.execute(input={"text": "Long article..."})

logger.info(f"Summary: {result['summary']}")

State Machine

machine.yml

spec: flatmachine
spec_version: "0.1.0"

data:
  name: writer-critic
  context:
    product: "{{ input.product }}"
    score: 0
  agents:
    writer: ./writer.yml
    critic: ./critic.yml
  states:
    start:
      type: initial
      transitions:
        - to: write
    write:
      agent: writer
      output_to_context:
        tagline: "{{ output.tagline }}"
      transitions:
        - to: review
    review:
      agent: critic
      output_to_context:
        score: "{{ output.score }}"
      transitions:
        - condition: "context.score >= 8"
          to: done
        - to: write
    done:
      type: final
      output:
        tagline: "{{ context.tagline }}"
from flatagents import FlatMachine, setup_logging, get_logger

setup_logging(level="INFO")
logger = get_logger(__name__)

machine = FlatMachine(config_file="machine.yml")
result = await machine.execute(input={"product": "AI coding assistant"})

logger.info(f"Tagline: {result['tagline']}")

Configuration

Both YAML and JSON configs are supported. Pass config_file for file-based configs or config_dict for inline configs.

LLM Backends

from flatagents import LiteLLMBackend, AISuiteBackend

# LiteLLM (default)
agent = FlatAgent(config_file="agent.yml")

# AISuite
backend = AISuiteBackend(model="openai:gpt-4o")
agent = FlatAgent(config_file="agent.yml", backend=backend)

Hooks

Extend machine behavior with Python hooks:

from flatagents import FlatMachine, MachineHooks

class CustomHooks(MachineHooks):
    def on_state_enter(self, state: str, context: dict) -> dict:
        context["entered_at"] = time.time()
        return context

    def on_action(self, action: str, context: dict) -> dict:
        if action == "fetch_data":
            context["data"] = fetch_from_api()
        return context

machine = FlatMachine(config_file="machine.yml", hooks=CustomHooks())

Available hooks: on_machine_start, on_machine_end, on_state_enter, on_state_exit, on_transition, on_error, on_action

Built-in hooks: LoggingHooks, MetricsHooks, CompositeHooks

Execution Types

Configure how agents are executed in machine states:

execution:
  type: retry              # retry | parallel | mdap_voting
  backoffs: [2, 8, 16, 35] # Seconds between retries
  jitter: 0.1              # ±10% random variation
Type Use Case
default Single call
retry Rate limit handling with backoff
parallel Multiple samples (n_samples)
mdap_voting Consensus voting (k_margin, max_candidates)

Schema Validation

from flatagents import validate_flatagent_config, validate_flatmachine_config

# Returns list of warnings/errors
warnings = validate_flatagent_config(config)
warnings = validate_flatmachine_config(config)

Examples

Logging & Metrics

FlatAgents provides built-in standardized logging and OpenTelemetry-based metrics.

Logging

from flatagents import setup_logging, get_logger

# Configure once (respects FLATAGENTS_LOG_LEVEL env var)
setup_logging(level="INFO")
logger = get_logger(__name__)

logger.info("Agent starting...")

Environment Variables:

  • FLATAGENTS_LOG_LEVEL: DEBUG, INFO, WARNING, ERROR
  • FLATAGENTS_LOG_FORMAT: standard, json, simple

Metrics (OpenTelemetry)

Track performance, token usage, and costs. Metrics are opt-in.

pip install flatagents[metrics]
export FLATAGENTS_METRICS_ENABLED=true
from flatagents import AgentMonitor

with AgentMonitor("my-agent") as monitor:
    result = await agent.execute(input)
    # Automatically tracks duration, status, and can record custom metrics
    monitor.metrics["tokens"] = 1200

Supported backends via OTLP: Datadog, Honeycomb, StatsD (via collector), etc.

Specs

See flatagent.d.ts and flatmachine.d.ts for full specifications.

See MACHINES.md for state machine patterns and reference.

License

MIT — see LICENSE

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

flatagents-0.3.2.tar.gz (7.7 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

flatagents-0.3.2-py3-none-any.whl (53.5 kB view details)

Uploaded Python 3

File details

Details for the file flatagents-0.3.2.tar.gz.

File metadata

  • Download URL: flatagents-0.3.2.tar.gz
  • Upload date:
  • Size: 7.7 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.9

File hashes

Hashes for flatagents-0.3.2.tar.gz
Algorithm Hash digest
SHA256 29196f5e71626b7e90ac538260dd914de4aa91d65ea5cef607f7c4744e9184b6
MD5 46281687fdea79c98c3d458a1f6e0a82
BLAKE2b-256 68d7e6ea914c5e91485eabc1f087b89fd446f8deaee32c849a9a0505ec1ea3ec

See more details on using hashes here.

File details

Details for the file flatagents-0.3.2-py3-none-any.whl.

File metadata

  • Download URL: flatagents-0.3.2-py3-none-any.whl
  • Upload date:
  • Size: 53.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.9

File hashes

Hashes for flatagents-0.3.2-py3-none-any.whl
Algorithm Hash digest
SHA256 4f81a4db0f20ab24bf15dfc60b410dd65c1be2cfb3cde940c10b750c5958fd62
MD5 9a00be686b40775662bc5fbd33701c08
BLAKE2b-256 6115a0c666ab1ccefd7ca23602b492392eb863535b5ee3da361edc6e8c6d547b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page