Skip to main content

ThoughtFlow Logo

ThoughtFlow

Powerful AI systems from simple parts.

A handful of composable primitives. Event-sourced memory. Deterministic replay. Zero dependencies. Just Python.

PyPI version Python versions License: MIT Tests Downloads/month

GitHub stars Last commit Ruff

Install • Quick Start • Replay • Primitives • Foundational • Higher-Level • Patterns • Philosophy


🧠 One Idea, Carried All the Way Through

Every ThoughtFlow program — from a single prompt to an autonomous multi-agent system — is built from one pattern:

memory = primitive(memory)

A MEMORY flows through your system. Every primitive — a thought, a tool call, an agent, an entire workflow — takes the memory, does its work, records what happened, and hands the memory back. That single contract gives you things other frameworks bolt on afterward:

  • Composition is just Python. Chain primitives with a for loop. Branch with an if. No graph DSL, no YAML, no callback registry.
  • State is never hidden. The memory is an event-sourced log of every message, decision, variable change, and tool result — inspectable, serializable, and diffable at any point.
  • Any step is swappable. A THOUGHT, an AGENT, and a plain Python function are interchangeable, because they all share the same signature.

And because the entire library is pure Python with zero dependencies, the whole engine fits in your head — and in a Lambda function.


🚀 Installation

pip install thoughtflow

That's it. No transitive dependency tree, no version conflicts, no supply-chain anxiety. The core library uses only Python's standard library — pip install thoughtflow is the entire setup story.

# Upgrade to the latest version
pip install --upgrade thoughtflow

# Pin to a specific version for stability
pip install thoughtflow==0.3.0

# Check your installed version
python -c "import thoughtflow; print(thoughtflow.__version__)"

⚡ Quick Start

Here's a complete working example. Copy, paste, run:

import os
from thoughtflow import LLM, MEMORY, THOUGHT

# 1. Get your API key from environment variables
#    Set it first: export OPENAI_API_KEY="sk-..."
api_key = os.environ.get("OPENAI_API_KEY")
if not api_key:
    raise ValueError("Please set OPENAI_API_KEY environment variable")

# 2. Create an LLM instance
#    Format: "provider:model"
llm = LLM("openai:gpt-4o", key=api_key)

# 3. Create a MEMORY to store conversation state
#    MEMORY is an event-sourced container that tracks everything
memory = MEMORY()

# 4. Add a user message to memory
memory.add_msg("user", "What is the meaning of life?")

# 5. Create a THOUGHT - the atomic unit of cognition
#    A THOUGHT combines: Prompt + Context + LLM + Parsing + Validation
thought = THOUGHT(
    name="respond",
    llm=llm,
    prompt="You are a wise philosopher. Answer: {last_user_msg}",
)

# 6. Execute the thought — this is THE pattern
memory = thought(memory)

# 7. Get the result
result = memory.get_var("respond_result")
print(f"Response: {result}")
# Output: "The meaning of life is a profound philosophical question..."

# 8. View the full conversation
print(memory.render(format="conversation"))

The universal pattern is memory = thought(memory). That's not a simplification — that's the actual API. Everything flows through MEMORY.

Want it more autonomous? Swap the THOUGHT for an AGENT with tools — the contract doesn't change:

from thoughtflow import TOOL, AGENT

agent = AGENT(llm=llm, tools=[weather_tool, search_tool],
              system_prompt="You are a research assistant.")

memory = agent(memory)   # same pattern, now with autonomous tool use

🧪 Deterministic by Design: Record & Replay

The hardest part of building AI systems is testing them. Model outputs are nondeterministic, API calls cost money, and CI can't depend on a network. ThoughtFlow solves this with a capability that falls naturally out of its architecture: because MEMORY is event-sourced, the LLM boundary can be recorded as events — and any flow can be replayed deterministically.

from thoughtflow import LLM, MEMORY

# 1. RECORD — run your flow live once; every exchange is captured
llm = LLM("openai:gpt-4o", key="sk-...")
recording = MEMORY()
llm.record(recording)

memory = my_flow(MEMORY(), llm)        # hits the API, records everything
recording.to_json("session.json")      # the memory IS the recording

# 2. REPLAY — same flow, no network, no keys, byte-identical
replay_llm = LLM.replay(MEMORY.from_json("session.json"))
memory2 = my_flow(MEMORY(), replay_llm)

assert memory2.last_asst_msg() == memory.last_asst_msg()   # passes, forever
  • Offline & instant — replay runs need no API keys and cost nothing. Commit session.json to your repo and your agent tests run in CI forever.
  • Fails loudly on drift — if your flow sends a request that was never recorded, you get a ReplayMissError (or fall back to a live LLM with on_miss=), so silent staleness can't creep in.
  • Zero new concepts — there is no session object, no tracer, no plugin. Recording is just more MEMORY events; replay is just an LLM that reads them.
  • Debug production sessions on your laptop — record in production, download one JSON file, and step through the exact conversation locally.

The same seam exists for embeddings (EMBED.record() / EMBED.replay()), decision models (DM.record() / DM.replay()), and tools (TOOL.record() / tool.replay() / TOOL.replay_all()), and a thin eval harness with strict=True absorbed-error detection turns recorded flows into structured test suites. See the runnable demo: examples/scripts/13_record_replay.py.


🔥 The Manifesto

Simple parts. Powerful systems.

AI systems don't need to be complicated. The complexity lives in the problems you're solving, not in the tools you use to solve them.

ThoughtFlow is built on that belief.

  • 🎯 Your agent logic should fit in your head — A few powerful primitives, not forty classes
  • 🔍 Every state change should be visible and traceable — Event-sourced memory with full history
  • 🧪 Testing AI systems should be as easy as testing regular code — Record/replay is built into the LLM and MEMORY primitives
  • 📦 Zero dependencies means zero supply chain nightmares — Core runs on stdlib only
  • ⚡ Serverless deployment should be trivial, not heroic — Sub-second cold starts, full state in one JSON string

✅ When to Use ThoughtFlow

ThoughtFlow is the right choice when:

  • You need serverless deployment — Lambda, Cloud Functions, Edge. Zero dependencies means instant cold starts.
  • You want to understand your entire codebase in an afternoon — A handful of concepts, not forty.
  • You value explicit state over magic — Every change is visible, traceable, and replayable.
  • You need deterministic testing of AI workflows — Record sessions, replay them, assert on results.
  • You're building production agents, not prototypes — Serious error handling, retry logic, validation.
  • You prefer composition over configuration — Plain Python, not YAML or JSON configs.
  • You work across multiple LLM providers — One interface for OpenAI, Anthropic, Groq, Gemini, Ollama, and more.

🚀 Escape Velocity: What You Can Delete

Switching to ThoughtFlow? Here's what you can remove from your project:

- langchain                    # 50+ transitive dependencies
- llama-index                  # Complex retrieval abstractions  
- autogen                      # Multi-agent complexity
- crewai                       # Yet another agent framework
- semantic-kernel              # Enterprise overhead
- haystack                     # Pipeline complexity
- guidance                     # Constrained generation complexity

- your custom retry logic      # THOUGHT handles retries with repair prompts
- your custom parsing code     # valid_extract handles messy LLM output
- your state management mess   # MEMORY tracks everything
- your 47 adapter classes      # LLM provides one interface for all providers

+ thoughtflow                  # Zero dependencies. Everything you need.

Net result: Your requirements.txt gets lighter. Your code gets clearer. Your deployments get faster. Your team spends less time debugging framework internals.


📊 How ThoughtFlow Compares

Feature ThoughtFlow LangChain LlamaIndex AutoGen
Core Dependencies 0 50+ 30+ 20+
Time to Understand 5 minutes 2+ hours 1+ hour 1+ hour
Concepts to Learn ~12 core 50+ 30+ 15+
Serverless Ready Trivial Challenging Challenging Challenging
Cold Start (Lambda) Sub-second Multiple seconds Multiple seconds Multiple seconds
Full State Visibility Everything Partial Partial Partial
Deterministic Replay Built-in DIY DIY DIY
Multi-Provider LLM Built-in Via adapters Via adapters Via adapters

Each framework has its strengths. LangChain offers breadth, LlamaIndex excels at RAG, AutoGen shines at multi-agent. ThoughtFlow optimizes for simplicity, transparency, and serverless deployment.


⚡ Performance Characteristics

Metric ThoughtFlow Why It Matters
Import Time ~15ms Zero dependencies = instant module load
Memory Overhead ~2MB Minimal runtime footprint
Call Overhead <1ms Direct HTTP calls, no middleware stack
Cold Start (Lambda) Sub-second Critical for serverless economics
Event Throughput 100k+ events/sec Event-sourced architecture scales

These are architectural characteristics, not formal benchmarks. Your mileage may vary based on workload.


🧩 The Primitives

ThoughtFlow is built in layers. Four foundational primitives form the base; everything else composes on top through inheritance and delegation.

┌─────────────────────────────────────────────────────────────────────────┐
│  ORCHESTRATION        WORKFLOW ·  CHRON                                 │
│  COORDINATION         DELEGATE ·  CHAT                                  │
│  AUTONOMY             AGENT  (→ ReactAgent · ReflectAgent · PlanActAgent) │
│  CAPABILITY           TOOL · MCP                                        │
│  ─────────────────────────────────────────────────────────────────────── │
│  COGNITION            THOUGHT  (→ DECIDE · PLAN)                        │
│  OPERATION            ACTION   (→ 14 elemental subclasses)              │
│  STATE                MEMORY                                            │
│  INTELLIGENCE         LLM · EMBED · DM                                  │
│  ─────────────────────────────────────────────────────────────────────── │
│  ↑ Foundational layer            ↑ Higher-level layer                   │
└─────────────────────────────────────────────────────────────────────────┘

Foundational Primitives

Master these four and you understand the core of the framework.

Primitive What It Does The Pattern
LLM Unified interface to call any language model response = llm.call(messages)
MEMORY Event-sourced state container for everything memory.add_msg("user", "Hello!")
THOUGHT Atomic unit of cognition with retry/parsing memory = thought(memory)
ACTION External operations with consistent logging memory = action(memory, **kwargs)

Higher-Level Primitives

Built on the foundational layer for richer capabilities.

Primitive Layer Purpose
EMBED Intelligence Vector embeddings from any provider
DM Intelligence Structured System-One decision models (choice, noul, score, box)
DECIDE Cognition Constrained decisions over LLM or DM (extends THOUGHT)
PLAN Cognition Structured multi-step execution plans (extends THOUGHT)
TOOL Capability Wrap any callable as an LLM-invocable tool (needs_context, record/replay)
MCP Capability Model Context Protocol client (stdio argv/shell + http, prefix=)
AGENT Autonomy Governed write-ahead tool loop (allow, policy, budget, checkpoint, decision=)
tool_loop Autonomy One-call functional helper over native governed AGENT
ReactAgent Autonomy ReAct-style agent (extends AGENT)
ReflectAgent Autonomy Self-reflective agent with task-aware critic (extends AGENT)
PlanActAgent Autonomy Plan-then-execute agent (extends AGENT)
DELEGATE Coordination Route tasks across a team of named agents (handoff, dispatch, broadcast)
CHAT Coordination Multi-turn conversational interface
WORKFLOW Orchestration Step sequence with ok= checks, status branching, while_, and suspend/resume
CHRON Orchestration Schedule manager for recurring cron (@daily, 0 2 * * *) and interval jobs

Action Subclasses (Elemental Operations)

These are the "verbs" that agents use to interact with the world. All extend ACTION.

Category Primitives Purpose
Communication SAY, ASK, NOTIFY Output to users, get input, send notifications
Information Retrieval SEARCH, FETCH, SCRAPE, READ Multi-provider web search, HTTP requests, content scraping, file reading
Persistence WRITE, POST Write files, send data to APIs
Temporal Control SLEEP, WAIT, NOOP Pause execution, wait for conditions, no-op
Execution RUN, CALL Shell commands, function invocation

💡 Every primitive — foundational and higher-level alike — inherits serialization, execution history, and introspection from its parent class.


🔌 Supported Providers

ThoughtFlow works with any LLM provider through a unified interface:

Provider Model ID Format Example Notes
OpenAI openai:model openai:gpt-4o GPT-4, GPT-4o, GPT-3.5, etc.
Anthropic anthropic:model anthropic:claude-3-5-sonnet-20241022 Claude 3, Claude 3.5, etc.
Groq groq:model groq:llama-3.1-70b-versatile Fast inference for open models
Google Gemini gemini:model gemini:gemini-1.5-pro Gemini Pro, Flash, etc.
OpenRouter openrouter:model openrouter:anthropic/claude-3-opus Access any model via OpenRouter
Cerebras openai:model + OpenAICompatibleLLM CerebrasLLM("gpt-oss-120b", key=...) OpenAI-compatible; Cloudflare-safe defaults
Ollama ollama:model ollama:llama3.2 Local models, no API key needed

Native convenience classes (v0.2.2+) wrap production edge cases while keeping the same call() API:

Class When to use
GroqLLM Qwen models on Groq — sets reasoning_format=hidden by default
CerebrasLLM Cerebras inference — safe User-Agent, optional auth-key fallback
OpenRouterLLM OpenRouter gateway — sets HTTP-Referer and X-Title headers
OpenAICompatibleLLM Any OpenAI-compatible server (vLLM, MLX, LM Studio, Ollama /v1)

Switching providers is a one-line change:

# From OpenAI...
llm = LLM("openai:gpt-4o", key=openai_key)

# ...to Anthropic
llm = LLM("anthropic:claude-3-5-sonnet-20241022", key=anthropic_key)

# ...to local (no key needed!)
llm = LLM("ollama:llama3.2")

# Your THOUGHT and MEMORY code stays exactly the same

🔮 Foundational Primitives In Depth

LLM — The Universal Model Interface

The LLM class provides a unified interface for calling any language model. One interface, any provider, zero provider-specific code in your application.

from thoughtflow import LLM

# ═══════════════════════════════════════════════════════════════════════════
# CREATING LLM INSTANCES
# ═══════════════════════════════════════════════════════════════════════════

# OpenAI
llm = LLM("openai:gpt-4o", key="sk-...")

# Anthropic
llm = LLM("anthropic:claude-3-5-sonnet-20241022", key="sk-ant-...")

# Groq (blazing fast inference)
llm = LLM("groq:llama-3.1-70b-versatile", key="gsk_...")

# Google Gemini
llm = LLM("gemini:gemini-1.5-pro", key="...")

# OpenRouter (access to any model)
llm = LLM("openrouter:anthropic/claude-3-opus", key="sk-or-...")

# Ollama (local models - no API key needed!)
llm = LLM("ollama:llama3.2")

# ═══════════════════════════════════════════════════════════════════════════
# MAKING CALLS
# ═══════════════════════════════════════════════════════════════════════════

# Standard chat format - works with ALL providers
response = llm.call([
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "What's the capital of France?"}
])
# response: ["The capital of France is Paris."]

# With parameters
response = llm.call(
    [{"role": "user", "content": "Write a haiku about Python"}],
    params={"temperature": 0.7, "max_tokens": 100}
)

# ═══════════════════════════════════════════════════════════════════════════
# MESSAGE NORMALIZATION
# ═══════════════════════════════════════════════════════════════════════════

# LLM automatically normalizes messages - all of these work:

# Standard format
llm.call([{"role": "user", "content": "Hello"}])

# Just content (assumes role="user")
llm.call([{"content": "Hello"}])

# Plain strings (becomes user messages)
llm.call(["Hello", "How are you?"])

# ═══════════════════════════════════════════════════════════════════════════
# STRUCTURED OUTPUT — enforce a JSON Schema
# ═══════════════════════════════════════════════════════════════════════════

schema = {
    "type": "object",
    "properties": {"name": {"type": "string"}, "age": {"type": "integer"}},
    "required": ["name", "age"],
}
response = llm.call(
    [{"role": "user", "content": "Alice is 28 years old."}],
    output_schema=schema,
)
# The provider's native mechanism is used (response_format for OpenAI/Groq/
# OpenRouter, tool-use for Anthropic, format for Ollama) — with prompt
# injection as the fallback for local servers.

# ═══════════════════════════════════════════════════════════════════════════
# STREAMING — get chunks as they arrive
# ═══════════════════════════════════════════════════════════════════════════

for chunk in llm.call([{"role": "user", "content": "Tell me a story"}], stream=True):
    print(chunk, end="", flush=True)

# ═══════════════════════════════════════════════════════════════════════════
# LOCAL & SELF-HOSTED MODELS — vLLM, LM Studio, llama.cpp, MLX, Ollama
# ═══════════════════════════════════════════════════════════════════════════

# Any OpenAI-compatible server via base_url
llm = LLM("openai:my-local-model", key="dummy",
          base_url="http://localhost:8000/v1")

# Or the convenience class
from thoughtflow import OpenAICompatibleLLM
llm = OpenAICompatibleLLM(model="mlx-community/Llama-3-8B-Instruct",
                          base_url="http://127.0.0.1:8765/v1")

# Ollama is a first-class service
llm = LLM("ollama:llama3.2")   # no key needed

# ═══════════════════════════════════════════════════════════════════════════
# RECORD & REPLAY — deterministic testing at the LLM boundary
# ═══════════════════════════════════════════════════════════════════════════

recording = MEMORY()
llm.record(recording)                  # every exchange captured as events
# ... run your flow ...
recording.to_json("session.json")

replay_llm = LLM.replay(MEMORY.from_json("session.json"))
# replay_llm is a drop-in LLM: same flows, no network, identical outputs

# ═══════════════════════════════════════════════════════════════════════════
# PROMPT CACHING — stable prefixes for agentic loops (v0.2.2+)
# ═══════════════════════════════════════════════════════════════════════════

from thoughtflow import cached_system, cached_message

llm.call([
    cached_system("You are a helpful assistant. Follow these rules exactly..."),
    {"role": "user", "content": "Hello"},
])
# Anthropic: cache_control blocks on marked messages
# OpenAI-compat providers: markers stripped from bodies; opt-in wire params apply

# ═══════════════════════════════════════════════════════════════════════════
# OBSERVABILITY — last_error, last_usage, last_finish_reason, request_timeout
# ═══════════════════════════════════════════════════════════════════════════

llm = LLM("openai:gpt-4o", key="sk-...", request_timeout=30)  # default timeout is 120s
response = llm.call([{"role": "user", "content": "Hi"}])
print(llm.last_usage)          # normalized token counts + cache/cost fields
print(llm.last_finish_reason)  # "stop", "length", "tool_calls", etc.
print(llm.last_error)          # None on success, error string on provider failure

# ═══════════════════════════════════════════════════════════════════════════
# STRUCTURED CHAT (`LLM.chat`) — native tool calls, separate reasoning, abort
# ═══════════════════════════════════════════════════════════════════════════

import threading

# Returns the complete assistant message dict instead of list[str]:
msg = llm.chat(
    [{"role": "user", "content": "Read config.json"}],
    tools=[read_tool.to_schema()],
)
# msg = {
#   "role": "assistant", "content": "", "reasoning": "...",
#   "tool_calls": [{"id": "call_1", "name": "read", "arguments": {"path": "config.json"}, ...}],
#   "finish_reason": "tool_calls", "usage": {...}, "model": "gpt-4o"
# }

# Typed streaming events + immediate cross-thread socket abort:
cancel = threading.Event()
for event in llm.chat([{"role": "user", "content": "Explain"}], stream=True, cancel=cancel):
    if event["type"] == "text_delta":
        print(event["delta"], end="", flush=True)
    elif event["type"] == "done":
        final_msg = event["message"]  # finish_reason == "aborted" if cancel.set() fired

Key features:

  • Automatic message normalization — Pass dicts, strings, or mixed formats
  • Two complementary call surfaces — llm.call() returns list[str] for text thoughts; llm.chat() returns the structured assistant message dict (native tool_calls, separate reasoning, finish_reason, usage, typed stream deltas, and cancel= socket abort)
  • Zero provider-specific code — Switch providers by changing one string
  • Direct HTTP calls — No middleware, no stdout noise, 120s default timeout (None opts out)
  • Honest truncation & reasoning handling — Tracks last_finish_reason and never leaks raw chain-of-thought when content is empty (opt-in via allow_reasoning_fallback=True)
  • Structured output — JSON Schema enforcement via each provider's native mechanism
  • Streaming — SSE/NDJSON streaming with a plain generator interface
  • Record/replay — Capture both call() and chat() exchanges into MEMORY; replay them deterministically
  • Prompt caching — cached_system() / cache=True for stable agent prefixes
  • Production provider classes — GroqLLM, CerebrasLLM, OpenRouterLLM
  • Unified param pipeline — Transport keys (base_url, referer, account_id) never leak into JSON bodies

MEMORY — Event-Sourced State

MEMORY is an event-sourced container that tracks everything: messages, logs, reflections, and variables with full history. Every change is an event with a sortable ID (alphabetical = chronological).

from thoughtflow import MEMORY

memory = MEMORY()

# ═══════════════════════════════════════════════════════════════════════════
# MESSAGES — with channel tracking for omni-channel agents
# ═══════════════════════════════════════════════════════════════════════════

# Add messages with channel tracking (webapp, ios, telegram, slack, etc.)
memory.add_msg("user", "Hello from the web!", channel="webapp")
memory.add_msg("assistant", "Hi there! How can I help?", channel="webapp")
memory.add_msg("user", "Following up on Telegram", channel="telegram")
memory.add_msg("user", "Also checking on mobile", channel="ios")

# Query messages - multiple ways
all_msgs = memory.get_msgs()                              # All messages
user_msgs = memory.get_msgs(include=["user"])             # Only user messages
web_msgs = memory.get_msgs(channel="webapp")              # Only webapp channel
recent = memory.get_msgs(limit=5)                         # Last 5 messages

# Quick access to most recent (returns full event dict by default)
memory.last_user_msg()                    # Returns: {'stamp': '...', 'content': 'Also checking on mobile', ...}
memory.last_asst_msg()                    # Returns: {'stamp': '...', 'content': 'Hi there!', ...}
memory.last_sys_msg()                     # Returns: {'stamp': '...', 'content': '...', ...}

# Or get just the content string
memory.last_user_msg(content_only=True)   # Returns: "Also checking on mobile"
memory.last_asst_msg(content_only=True)   # Returns: "Hi there! How can I help?"

# ═══════════════════════════════════════════════════════════════════════════
# MESSAGE METADATA — tag events, filter views
# ═══════════════════════════════════════════════════════════════════════════

# Tag messages with metadata (e.g. RAG context the user shouldn't see)
memory.add_msg("system", "Retrieved context: ...", channel="webapp",
               metadata={"internal": True, "source": "rag"})

# UI-visible history: hide internal events
visible = memory.get_msgs(exclude_metadata={"internal": True})

# Or select only the tagged ones
rag_events = memory.get_msgs(metadata_filter={"source": "rag"})

# ═══════════════════════════════════════════════════════════════════════════
# RAG AUGMENTS — optional LLM-view merging (event log unchanged)
# ═══════════════════════════════════════════════════════════════════════════

# Store retrieved context as a tagged augment event
memory.add_augment(
    "Retrieved context:\n" + context,
    metadata={"internal": True, "source": "rag"},
)

# Default LLM view: augment is a separate message
memory.get_llm_msgs()

# Opt-in: fold augment into the preceding user turn for the model only
memory.get_llm_msgs(merge_augments=True)

# AGENT(merge_augments=True) uses the merged view automatically

# ═══════════════════════════════════════════════════════════════════════════
# LIFECYCLE EMITS — typed, JSON-safe machine-readable events
# ═══════════════════════════════════════════════════════════════════════════

memory.emit("run_started", {"run_id": "abc123", "trigger": {"source": "cron"}})
memory.emit("plan_committed", {"step_count": 3, "plan_id": "p1"})

started = memory.get_emits(kind="run_started")
all_emits = memory.get_emits()  # chronological, deep-copied payloads

# ═══════════════════════════════════════════════════════════════════════════
# LOGS & REFLECTIONS — internal agent reasoning
# ═══════════════════════════════════════════════════════════════════════════

# Logs are for debugging and audit trails
memory.add_log("User initiated conversation from webapp")
memory.add_log("Processing user request...")
memory.add_log("Response generated successfully")

# Reflections are for agent's internal reasoning
memory.add_ref("User seems interested in weather patterns")
memory.add_ref("Should ask clarifying questions about location")

# Retrieve logs and reflections (returns lists of event dicts)
memory.get_logs()                         # All log entries as list of dicts
memory.get_refs()                         # All reflections as list of dicts

# Quick access to most recent (returns full event dict by default)
memory.last_log_msg()                     # Returns: {'stamp': '...', 'content': '...', ...}
memory.last_ref()                         # Returns: {'stamp': '...', 'content': '...', ...}

# Or get just the content string
memory.last_log_msg(content_only=True)    # Returns: "Response generated successfully"
memory.last_ref(content_only=True)        # Returns: "Should ask clarifying questions..."

# ═══════════════════════════════════════════════════════════════════════════
# VARIABLES — with FULL HISTORY tracking
# ═══════════════════════════════════════════════════════════════════════════

# Set variables with optional descriptions
memory.set_var("session_id", "abc123", desc="Current session identifier")
memory.set_var("user_name", "Alice", desc="User's display name")
memory.set_var("request_count", 0)

# Update variables - this APPENDS to history, doesn't overwrite!
memory.set_var("request_count", 1)
memory.set_var("request_count", 2)
memory.set_var("request_count", 3)

# Get current value
memory.get_var("request_count")       # Returns: 3
memory.get_var("user_name")           # Returns: "Alice"
memory.get_var("nonexistent")         # Returns: None

# Get FULL HISTORY - see every change with timestamps
memory.get_var_history("request_count")
# Returns: [
#   ["stamp1...", 0],
#   ["stamp2...", 1],
#   ["stamp3...", 2],
#   ["stamp4...", 3]
# ]

# Get all current variables
memory.get_all_vars()
# Returns: {"session_id": "abc123", "user_name": "Alice", "request_count": 3}

# Get variable description
memory.get_var_desc("session_id")     # "Current session identifier"

# ═══════════════════════════════════════════════════════════════════════════
# VARIABLE DELETION — tombstone pattern preserves history
# ═══════════════════════════════════════════════════════════════════════════

# Deletion is a tombstone, not destruction
memory.del_var("session_id")

# After deletion
memory.get_var("session_id")          # Returns: None
memory.is_var_deleted("session_id")   # Returns: True

# But history is preserved!
memory.get_var_history("session_id")
# Returns: [["stamp1...", "abc123"], ["stamp2...", <DELETED>]]

# Can re-set after deletion
memory.set_var("session_id", "xyz789")
memory.get_var("session_id")          # Returns: "xyz789"

# ═══════════════════════════════════════════════════════════════════════════
# SERIALIZATION — for persistence and cloud sync
# ═══════════════════════════════════════════════════════════════════════════

# Save to file (pickle format)
memory.save("state.pkl")
memory.save("state.pkl.gz", compressed=True)  # With compression

# Load from file
memory2 = MEMORY()
memory2.load("state.pkl")

# Export to JSON (portable, human-readable)
memory.to_json("state.json")
json_string = memory.to_json()  # Returns string if no filename

# Load from JSON
memory3 = MEMORY.from_json("state.json")
memory4 = MEMORY.from_json(json_string)

# Export snapshot for cloud sync
snapshot = memory.snapshot()
# snapshot = {"id": "...", "events": {...}, "objects": {...}}

# Rehydrate from events (for distributed systems)
memory5 = MEMORY.from_events(snapshot["events"].values())

# Deep copy
memory_copy = memory.copy()

# ═══════════════════════════════════════════════════════════════════════════
# RENDERING — for debugging, logging, and LLM context
# ═══════════════════════════════════════════════════════════════════════════

# Render as conversation (great for debugging)
print(memory.render(format="conversation"))
# Output:
# User: Hello from the web!
# Assistant: Hi there! How can I help?
# User: Following up on Telegram
# ...

# Render as JSON
print(memory.render(format="json", include=("msgs", "logs")))

# Render as plain text
print(memory.render(format="plain"))

# Filter by role, channel, content
print(memory.render(
    role_filter=["user", "assistant"],
    channel_filter="webapp",
    max_total_length=2000
))

# ═══════════════════════════════════════════════════════════════════════════
# LARGE OBJECT HANDLING — automatic compression
# ═══════════════════════════════════════════════════════════════════════════

# Large values (>10KB by default) are automatically compressed
large_data = "x" * 50000  # 50KB of data
memory.set_var("big_data", large_data)

# Retrieved transparently
memory.get_var("big_data")  # Returns full 50KB string

# Or store objects explicitly
stamp = memory.set_obj(large_binary_data, name="attachment", desc="PDF file")
memory.get_var("attachment")  # Returns decompressed data

# ═══════════════════════════════════════════════════════════════════════════
# NATIVE TOOL TRANSCRIPTS — assistant tool_calls + tool results
# ═══════════════════════════════════════════════════════════════════════════

memory.add_msg(
    "assistant", "",
    tool_calls=[{"id": "call_1", "name": "read", "arguments": {"path": "a.py"}}],
)
memory.add_msg("tool", '{"lines": 42}', tool_call_id="call_1", name="read")

# Provider-valid OpenAI/OpenRouter/Groq message history (drops internal roles):
wire_msgs = memory.get_llm_msgs(format="openai")

# ═══════════════════════════════════════════════════════════════════════════
# TOKEN BUDGETS & NON-DESTRUCTIVE COMPACTION
# ═══════════════════════════════════════════════════════════════════════════

# Trim oldest unpinned turns for the LLM view only (pins system + latest user;
# never splits an assistant tool_calls message from its tool results):
window = memory.get_llm_msgs(format="openai", budget_tokens=4000)

# Or write a non-destructive summary event while keeping every original event:
memory.compact(keep=6)

# ═══════════════════════════════════════════════════════════════════════════
# ZERO-COPY SCOPED VIEWS (`memory.scope`) — multi-party & parallel isolation
# ═══════════════════════════════════════════════════════════════════════════

alpha = memory.scope(
    "alpha",
    read_rooms={"public", "alpha_board"},
    write_room="alpha_board",
    public_keys={"deal_target"},
    export_keys={"final_verdict"},
)
# alpha.set_var("bid", 80) writes under "alpha__bid" without copying events

# ═══════════════════════════════════════════════════════════════════════════
# IDEMPOTENT SUSPEND & RESUME — human approvals and durable checkpoints
# ═══════════════════════════════════════════════════════════════════════════

memory.suspend("approval_required", pending={"call_id": "call_1"})
memory.is_suspended()                        # True (survives to_json / from_json)
memory.resolve_suspension({"approve": True}) # resolves once; repeats are no-ops

Key features:

  • Event-sourced & causally ordered — Every change carries a sortable stamp and monotonic _seq for sub-millisecond from_events() branch merges
  • Full variable history — See every change with timestamps and tombstone deletions
  • Native tool transcripts — role="tool", assistant tool_calls, tool_call_id, and get_llm_msgs(format="openai")
  • Context budgets & compaction — get_llm_msgs(budget_tokens=...) and non-destructive memory.compact(keep=...)
  • Zero-copy scopes (memory.scope) — Isolate rooms/channels and {actor}__{key} scratchpads on one shared MEMORY
  • Suspend / resume — JSON-safe suspend() / resolve_suspension() with idempotent duplicate protection
  • Channel & metadata filtering — Build omni-channel agents and separate UI history from internal events
  • RAG augments & lifecycle emits — add_augment() and typed emit() / get_emits()
  • Auto-compression — Large values (>10KB) compressed automatically into memory.objects
  • Record/replay substrate — Stores 'chat', 'embed', 'decide', and 'tool' exchanges across JSON round-trips

THOUGHT — The Atomic Unit of Cognition

A THOUGHT is the discrete unit of reasoning: Prompt + Context + LLM + Parsing + Validation. It's the building block for all cognitive operations.

from thoughtflow import LLM, MEMORY, THOUGHT

llm = LLM("openai:gpt-4o", key="...")
memory = MEMORY()

# ═══════════════════════════════════════════════════════════════════════════
# BASIC THOUGHT — the simplest form
# ═══════════════════════════════════════════════════════════════════════════

thought = THOUGHT(
    name="respond",
    llm=llm,
    prompt="You are a helpful assistant. Answer: {last_user_msg}",
)

memory.add_msg("user", "What's 2 + 2?")
memory = thought(memory)  # THE UNIVERSAL PATTERN

result = memory.get_var("respond_result")
print(result)  # "2 + 2 equals 4."

# ═══════════════════════════════════════════════════════════════════════════
# WITH PARSING — extract structured data from messy LLM output
# ═══════════════════════════════════════════════════════════════════════════

thought = THOUGHT(
    name="extract_user_info",
    llm=llm,
    prompt="Extract user information from this text: {text}",
    parsing_rules={
        "kind": "python",
        "format": {
            "name": "",           # Required string
            "age": 0,             # Required int
            "email?": "",         # Optional (note the ?)
            "skills": [],         # Required list
        }
    },
)

memory.set_var("text", "My name is Alice, I'm 28, and I know Python and ML.")
memory = thought(memory)
info = memory.get_var("extract_user_info_result")
# info = {"name": "Alice", "age": 28, "skills": ["Python", "ML"]}

# ═══════════════════════════════════════════════════════════════════════════
# WITH VALIDATION — ensure output meets requirements
# ═══════════════════════════════════════════════════════════════════════════

thought = THOUGHT(
    name="generate_ideas",
    llm=llm,
    prompt="Generate exactly 5 creative ideas for: {topic}",
    parser="json",
    validation="list_min_len:5", # Must have at least 5 items
    max_retries=3,               # Retry up to 3 times if validation fails
    retry_delay=0.5,             # Wait 0.5s between retries
)

# Built-in validators (pass a string or a callable to validation=):
# - "any"                    — Accept anything
# - "has_keys:key1,key2"     — Dict must have these keys
# - "list_min_len:N"         — List must have at least N items
# - Custom callable          — Your own validation function
# (validator= is an equivalent config-style spelling of validation=)

# ═══════════════════════════════════════════════════════════════════════════
# WITH CUSTOM VALIDATION
# ═══════════════════════════════════════════════════════════════════════════

def validate_email_list(result):
    """Custom validator: all items must be valid emails."""
    if not isinstance(result, list):
        return False, "Expected a list"
    for item in result:
        if "@" not in str(item):
            return False, f"Invalid email: {item}"
    return True, ""

thought = THOUGHT(
    name="extract_emails",
    llm=llm,
    prompt="Extract all email addresses from: {text}",
    parser="list",
    validation=validate_email_list,
    max_retries=2,
)

# ═══════════════════════════════════════════════════════════════════════════
# OPERATIONS — THOUGHT isn't just for LLM calls
# ═══════════════════════════════════════════════════════════════════════════

# MEMORY QUERY — retrieve data without calling LLM
query_thought = THOUGHT(
    name="get_user_context",
    operation="memory_query",
    required_vars=["user_name", "session_id"],
    optional_vars=["preferences"],
)
memory = query_thought(memory)
context = memory.get_var("get_user_context_result")
# context = {"user_name": "Alice", "session_id": "abc123"}

# VARIABLE SET — set multiple variables at once
init_thought = THOUGHT(
    name="init_session",
    operation="variable_set",
    prompt={
        "session_active": True,
        "start_time": None,
        "message_count": 0
    }
)
memory = init_thought(memory)
# Sets all three variables in memory

# CONDITIONAL — branch logic based on memory state
branch_thought = THOUGHT(
    name="check_threshold",
    operation="conditional",
    condition=lambda m, ctx: ctx.get("score", 0) > 80,
    if_true="high_score_path",
    if_false="low_score_path"
)
memory.set_var("score", 95)
memory = branch_thought(memory)
result = memory.get_var("check_threshold_result")  # "high_score_path"

# ═══════════════════════════════════════════════════════════════════════════
# PRE/POST HOOKS — custom processing
# ═══════════════════════════════════════════════════════════════════════════

def pre_process(thought, memory, vars, **kwargs):
    """Called before execution."""
    print(f"About to execute: {thought.name}")
    # Can modify vars before execution

def post_process(thought, memory, result, error):
    """Called after execution."""
    if error:
        print(f"Error in {thought.name}: {error}")
    else:
        print(f"Success: {thought.name} -> {result}")

thought = THOUGHT(
    name="monitored_thought",
    llm=llm,
    prompt="...",
    pre_hook=pre_process,
    post_hook=post_process,
)

# ═══════════════════════════════════════════════════════════════════════════
# STREAMING — surface tokens as they arrive, keep the contract intact
# ═══════════════════════════════════════════════════════════════════════════

thought = THOUGHT(
    name="storyteller",
    llm=llm,
    prompt="Tell a short story about: {topic}",
    on_token=lambda chunk: print(chunk, end="", flush=True),
)
memory = thought(memory)
# Tokens stream through your hook in real time; the complete text still
# flows through parsing/validation and lands in memory as usual.

# ═══════════════════════════════════════════════════════════════════════════
# PROMPT RENDERING — substitute mode and history control
# ═══════════════════════════════════════════════════════════════════════════

thought = THOUGHT(
    name="extract_plan",
    llm=llm,
    prompt='Return JSON with key "steps": {task}',
    template_mode="substitute",  # exact {key} replacement (no .format() escaping issues)
    include_history=False,       # only system + rendered user prompt (no prior turns)
)
# When include_history=True (default), prior turns come from MEMORY.get_llm_msgs()
# and are forwarded without template substitution on historical content.

# ═══════════════════════════════════════════════════════════════════════════
# PRODUCTION LANE — schema dialect, retry policies, visibility, outcomes
# ═══════════════════════════════════════════════════════════════════════════

thought = THOUGHT(
    name="triage_ticket",
    llm=llm,
    prompt="Classify support ticket: {ticket}",
    template_mode="substitute",
    visibility="internal",      # store result var only; keep out of chat history
    record_prompt=True,         # save rendered prompt to triage_ticket_prompt
    parsing_rules={
        "kind": "json",
        "format": {
            "priority": {"enum": ["p1", "p2", "p3"]},
            "refund_cents": "int|null",
            "summary": "str",
        },
    },
    validation=[                # pure-JSON declarative rules (survive to_dict!)
        {"op": "non_empty", "field": "summary"},
    ],
    retry={
        "on": {"length": "double_budget", "http": "backoff"},
        "fallback_llm": backup_llm,
    },
    max_retries=2,
)
# Every run (success or failure) writes a uniform JSON-safe outcome dict:
# memory.get_var("triage_ticket_outcome") ->
# {"ok": True, "error_class": None, "finish_reason": "stop",
#  "usage": {...}, "attempts": 1, "validation_messages": []}

# ═══════════════════════════════════════════════════════════════════════════
# SERIALIZATION — save and restore thoughts
# ═══════════════════════════════════════════════════════════════════════════

# Export to dict (for storage/transmission)
thought_data = thought.to_dict()

# Reconstruct from dict (LLM must be provided separately)
thought_copy = THOUGHT.from_dict(thought_data, llm=llm)

# Copy a thought
thought_clone = thought.copy()

# ═══════════════════════════════════════════════════════════════════════════
# INTROSPECTION — examine execution history
# ═══════════════════════════════════════════════════════════════════════════

# After executing a thought multiple times
thought.execution_history
# [
#   {"stamp": "...", "duration_ms": 234.5, "success": True, ...},
#   {"stamp": "...", "duration_ms": 198.2, "success": True, ...},
# ]

thought.last_result      # Most recent result
thought.last_error       # Most recent error (if any)
thought.last_prompt      # The prompt that was sent
thought.last_response    # Raw LLM response

Key features:

  • Callable interface — memory = thought(memory) is the entire API
  • Uniform {name}_outcome telemetry — Every run records ok, error_class, finish_reason, usage, attempts, and validation_messages
  • Rich schema dialect — Type names ("str", "int"), pipe unions ("int|null"), {"enum": [...]}, oneOf branches, optional "key?", and automatic first-attempt Expected format: hints (instruct_schema=False opts out)
  • Declarative & callable validation — Pure-JSON rule lists (in, non_empty, range, regex, has_keys), built-in strings, or Python callables
  • Smart retry policies — retry={"on": {"length": "double_budget", "http": "backoff"}, "fallback_llm": ...} plus hold_msg=True by default so failed drafts never pollute chat history
  • Visibility & lazy context — visibility="internal"|"silent" skips transcript writes; unreferenced >10KB _obj_ref blobs in MEMORY are never decompressed
  • Loud template safety — Missing placeholders or required_vars fail before calling the LLM (TemplateRenderError, failure_kind="template")
  • Pure-JSON portability — json.dumps(thought.to_dict()) and THOUGHT.from_dict() work cleanly with declarative rules and schema types

ACTION — External Operations

ACTION wraps external operations (API calls, file I/O, database queries) with consistent logging and error handling:

from thoughtflow import ACTION, MEMORY

# ═══════════════════════════════════════════════════════════════════════════
# DEFINING AN ACTION
# ═══════════════════════════════════════════════════════════════════════════

def search_web(memory, query, max_results=3):
    """
    Search the web and return results.
    
    Args:
        memory: MEMORY object (always first argument)
        query: Search query string
        max_results: Maximum results to return
    
    Returns:
        dict with search results
    """
    # Your implementation here
    results = web_api.search(query, limit=max_results)
    return {"status": "success", "hits": results, "query": query}

search_action = ACTION(
    name="web_search",
    fn=search_web,
    config={"max_results": 5},  # Default config
    description="Searches the web for information"
)

# ═══════════════════════════════════════════════════════════════════════════
# EXECUTING AN ACTION
# ═══════════════════════════════════════════════════════════════════════════

memory = MEMORY()

# Execute with default config
memory = search_action(memory, query="thoughtflow python library")

# Execute with override
memory = search_action(memory, query="python agents", max_results=10)

# Results are stored automatically
result = memory.get_var("web_search_result")
# result = {"status": "success", "hits": [...], "query": "..."}

# ═══════════════════════════════════════════════════════════════════════════
# ERROR HANDLING — errors don't interrupt your workflow
# ═══════════════════════════════════════════════════════════════════════════

def risky_operation(memory, url):
    """An operation that might fail."""
    response = requests.get(url, timeout=5)
    response.raise_for_status()
    return response.json()

fetch_action = ACTION(name="fetch_data", fn=risky_operation)

# If the action fails, error info is stored (not raised)
memory = fetch_action(memory, url="https://example.com/api")

result = memory.get_var("fetch_data_result")
if "error" in result:
    print(f"Action failed: {result['error']}")
else:
    print(f"Action succeeded: {result}")

# ═══════════════════════════════════════════════════════════════════════════
# INTROSPECTION — examine execution history
# ═══════════════════════════════════════════════════════════════════════════

# After executing an action multiple times
search_action.execution_count        # How many times called
search_action.was_successful()       # Did last call succeed?
search_action.last_result            # Most recent result
search_action.last_error             # Most recent error (if any)

# Full execution history with timing
search_action.execution_history
# [
#   {"stamp": "...", "duration_ms": 145.2, "success": True, "error": None},
#   {"stamp": "...", "duration_ms": 203.1, "success": False, "error": "Timeout"},
# ]

# Get timing for last call
last_call = search_action.execution_history[-1]
print(f"Last call took {last_call['duration_ms']:.1f}ms")

# ═══════════════════════════════════════════════════════════════════════════
# RESET AND COPY
# ═══════════════════════════════════════════════════════════════════════════

# Reset stats (useful for testing)
search_action.reset_stats()

# Copy an action (shares function, copies config)
search_action_copy = search_action.copy()

# ═══════════════════════════════════════════════════════════════════════════
# SERIALIZATION
# ═══════════════════════════════════════════════════════════════════════════

# Export to dict
action_data = search_action.to_dict()

# Reconstruct (need function registry)
fn_registry = {"search_web": search_web}
action_copy = ACTION.from_dict(action_data, fn_registry)

Key features:

  • Callable interface — memory = action(memory, **kwargs)
  • Automatic result storage — Results stored in {name}_result variable
  • Error containment — Errors are logged, not raised (workflow continues)
  • Full execution history — Timing, success/failure, error details
  • Configurable defaults — Set defaults, override per-call
  • Serialization support — Save and restore actions

🔧 Higher-Level Primitives

Higher-level primitives build on the foundational layer for specialized use cases. They inherit all features from their parent class (retry logic, serialization, hooks, execution history) while adding domain-specific functionality.

DECIDE — Constrained Decision Steps

Extends: THOUGHT

DECIDE is a specialized THOUGHT that constrains LLM output to a finite set of choices. Perfect for routing, classification, and branching logic:

from thoughtflow import LLM, MEMORY, DECIDE

llm = LLM("openai:gpt-4o", key="...")
memory = MEMORY()

# ═══════════════════════════════════════════════════════════════════════════
# SIMPLE LIST OF CHOICES
# ═══════════════════════════════════════════════════════════════════════════

sentiment = DECIDE(
    name="classify_sentiment",
    llm=llm,
    choices=["positive", "negative", "neutral"],
    prompt="Classify the sentiment of: {text}",
)

memory.set_var("text", "I absolutely love this product!")
memory = sentiment(memory)
print(memory.get_var("classify_sentiment_result"))  # "positive"

# ═══════════════════════════════════════════════════════════════════════════
# DICT WITH DESCRIPTIONS (shown to LLM)
# ═══════════════════════════════════════════════════════════════════════════

router = DECIDE(
    name="route_request",
    llm=llm,
    choices={
        "approve": "Accept the request and proceed",
        "reject": "Deny the request with explanation",
        "escalate": "Send to human reviewer for decision",
    },
    prompt="Review this support ticket: {ticket}\n\nDecide how to handle it.",
    default="escalate",  # Fallback if all retries fail
)

memory.set_var("ticket", "Customer requesting refund for damaged item")
memory = router(memory)
result = memory.get_var("route_request_result")  # "approve", "reject", or "escalate"

# ═══════════════════════════════════════════════════════════════════════════
# FEATURES
# ═══════════════════════════════════════════════════════════════════════════

# DECIDE defaults to max_retries=5 (vs THOUGHT's 1)
# because classification often needs more attempts

# Smart parsing handles LLM verbosity:
# "I would choose: approve" → "approve"
# "APPROVE" → "approve" (case-insensitive by default)

# Choice-specific repair prompts:
# "(Respond with exactly one of: approve, reject, escalate. No other text.)"

Key features:

  • Works with LLM or DM — Pass a generative LLM or a System-One DM("openrouter:typesafe/jev-1.14", key=...) (model= alias supported) with zero downstream code changes
  • Four decision modes — Categorical choices, binary choices=bool (noul), ordered levels=[...] (score), and single-pass questions={...} batching
  • Calibrated uncertainty gating — min_confidence= and min_margin= route ambiguous ties to default= with full probabilities in {name}_outcome
  • Automatic state isolation — On DM calls, {var} placeholders are lifted into structured state data separate from instructions
  • Smart LLM parsing & retries — Handles exact, leading, and non-negated embedded matches with choice-specific repair prompts (max_retries=5)
  • Inherits from THOUGHT — Full JSON serialization, hooks, lifecycle emits, and execution history support

PLAN — Structured Multi-Step Planning

Extends: THOUGHT

PLAN generates structured execution plans where an LLM creates a sequence of steps with parallel task support. Each task includes a reason explaining why it was chosen:

from thoughtflow import LLM, MEMORY, PLAN

llm = LLM("openai:gpt-4o", key="...")
memory = MEMORY()

# ═══════════════════════════════════════════════════════════════════════════
# SIMPLE ACTIONS (descriptions only)
# ═══════════════════════════════════════════════════════════════════════════

planner = PLAN(
    name="research_plan",
    llm=llm,
    actions={
        "search": "Search the web for information",
        "analyze": "Analyze content for key insights",
        "summarize": "Create a concise summary",
        "notify": "Send notification to user",
    },
    prompt="Create a plan to achieve: {goal}",
)

memory.set_var("goal", "Research ThoughtFlow and summarize findings")
memory = planner(memory)
plan = memory.get_var("research_plan_result")
# [
#     [{"action": "search", "params": {"query": "ThoughtFlow"},
#       "reason": "Start by gathering information about the library."}],
#     [{"action": "analyze", "params": {"content": "{step_0_result}"},
#       "reason": "Extract key insights from search results."}],
#     [{"action": "summarize", "params": {"text": "{step_1_result}"},
#       "reason": "Condense findings into actionable summary."},
#      {"action": "notify", "params": {"message": "Research complete"},
#       "reason": "Alert user that the task is finished."}]
# ]

# ═══════════════════════════════════════════════════════════════════════════
# ACTIONS WITH PARAMETER SCHEMAS
# ═══════════════════════════════════════════════════════════════════════════

# Use "?" suffix for optional parameters (e.g., "int?" means optional int)
planner = PLAN(
    name="workflow",
    llm=llm,
    actions={
        "search": {
            "description": "Search for information",
            "params": {"query": "str", "max_results": "int?"}
        },
        "fetch": {
            "description": "Fetch a resource by URL",
            "params": {"url": "str"}
        },
        "notify": {
            "description": "Send notification",
            "params": {"message": "str", "channel": "str?"}
        }
    },
    prompt="Plan to achieve: {goal}\nContext: {context}",
    max_steps=10,      # Maximum sequential steps
    max_parallel=5,    # Maximum parallel tasks per step
)

# ═══════════════════════════════════════════════════════════════════════════
# OUTPUT STRUCTURE
# ═══════════════════════════════════════════════════════════════════════════

# Plan = List of Steps (executed sequentially)
# Step = List of Tasks (can execute in parallel)
# Task = {"action": "...", "params": {...}, "reason": "..."}

# Tasks can reference previous step results:
# {"action": "analyze", "params": {"content": "{step_0_result}"}, "reason": "..."}

Key features:

  • Structured output — List[List[Dict]] for steps with parallel tasks
  • Explainable — Each task requires a reason field (1-3 sentences)
  • Flexible actions — Simple descriptions or full parameter schemas
  • Parameter validation — Required vs optional params with ? suffix
  • Step references — Tasks can reference {step_N_result} from previous steps
  • Configurable limits — max_steps and max_parallel constraints
  • Inherits from THOUGHT — Full retry, serialization, and hook support

For an executable, offline plan-commit-reflect loop built from PLAN, MEMORY, and plain Python, see the copy-and-edit Foundation agent loop reference. The recipe demonstrates bounded execution, receipts, step-result resolution, approval gates, lifecycle emits, and isolated sub-runs without adding a framework layer.


ACTION Subclasses — Elemental Operations

Extends: ACTION

ThoughtFlow provides a suite of pre-built ACTION subclasses for common operations. These are the "verbs" that agents use to interact with the world:

Category Primitives Purpose
Communication SAY, ASK, NOTIFY Output to users, get input, send notifications
Information Retrieval SEARCH, FETCH, SCRAPE, READ Web search, HTTP requests, scraping, file reading
Persistence WRITE, POST Write files, send data to APIs
Temporal Control SLEEP, WAIT, NOOP Pause execution, wait for conditions, no-op
Execution RUN, CALL Shell commands, function invocation
from thoughtflow import MEMORY, SAY, SEARCH, FETCH, READ, WRITE, SLEEP

memory = MEMORY()

# Output a message to the user
say = SAY(message="Hello! Starting research...")
memory = say(memory)

# Search the web
search = SEARCH(query="ThoughtFlow Python library", max_results=5)
memory = search(memory)
results = memory.get_var("search_result")

# Fetch a webpage
fetch = FETCH(url="https://github.com/jrolf/thoughtflow")
memory = fetch(memory)

# Read a local file
read = READ(path="config.json", parse="json")
memory = read(memory)

# Write results to file
write = WRITE(path="output.txt", content="{search_result}")
memory = write(memory)

# Pause between operations (rate limiting)
sleep = SLEEP(duration=1.0, reason="Rate limit pause")
memory = sleep(memory)

Key features:

  • Zero dependencies — All actions use Python standard library
  • Consistent interface — memory = action(memory) pattern
  • Variable substitution — Use {variable} placeholders from memory
  • Automatic logging — All executions logged to memory
  • Inherits from ACTION — Full execution history and serialization

Extends: ACTION

SEARCH abstracts multiple search engines behind a unified interface with normalized results. Supports DuckDuckGo (free, no key), Brave Search, EXA (semantic search), and Google Custom Search.

from thoughtflow import MEMORY, SEARCH

memory = MEMORY()

# DuckDuckGo (default — no API key required)
search = SEARCH(query="ThoughtFlow Python library", max_results=5)
memory = search(memory)

# Brave Search
search = SEARCH(query="latest AI news", provider="brave", api_key="BSA...")
memory = search(memory)

# All providers return the same normalized structure:
result = memory.get_var("search_result")
# {
#   "query": "...",
#   "provider": "duckduckgo",
#   "results": [
#       {"title": "...", "url": "...", "snippet": "...", "rank": 1,
#        "source": "example.com", "date_published": "...", "extra": {}},
#       ...
#   ],
#   "total_found": 5,
#   "timestamp": "..."
# }

SCRAPE — Structured Content Extraction

Extends: ACTION

SCRAPE visits a URL and extracts content in three modes: raw HTML (default), Markdown, or a structured JSON object with metadata, headings, links, and images.

from thoughtflow import MEMORY, SCRAPE

memory = MEMORY()

# Get clean Markdown
scrape = SCRAPE(url="https://example.com", extract="markdown")
memory = scrape(memory)
markdown_text = memory.get_var("scrape_result")

# Get structured JSON with full metadata
scrape = SCRAPE(url="https://example.com", extract="structured")
memory = scrape(memory)
data = memory.get_var("scrape_result")
# {"url": "...", "title": "...", "author": "...", "content_markdown": "...",
#  "content_text": "...", "headings": [...], "links": [...], "images": [...],
#  "word_count": 42, "timestamp": "..."}

TOOL — LLM-Selectable Capabilities

TOOL wraps any callable with a JSON Schema so that an LLM can discover, reason about, and invoke it during an agentic loop. This is the bridge between your code and the LLM's function-calling protocol.

from thoughtflow import TOOL

def get_weather(city, units="celsius"):
    """Fetch current weather for a city."""
    return {"city": city, "temp": 22, "units": units}

weather_tool = TOOL(
    name="get_weather",
    description="Get the current weather for a city.",
    parameters={
        "type": "object",
        "properties": {
            "city": {"type": "string", "description": "City name"},
            "units": {"type": "string", "enum": ["celsius", "fahrenheit"]},
        },
        "required": ["city"],
    },
    fn=get_weather,
)

# Tools with needs_context=True receive context={'call_id', 'memory', 'agent'}:
audit_tool = TOOL(
    name="log_note",
    description="Save a note to memory.",
    parameters={"note": {"type": "string"}},
    fn=lambda note, context=None: context["memory"].set_var("last_note", note) or "ok",
    needs_context=True,
)

# Record live tool/MCP outputs and replay offline without external side effects:
weather_tool.record(memory)
offline_weather = weather_tool.replay(memory)           # ReplayTOOL (or on_miss="live" for splice)

MCP — Model Context Protocol Client

MCP connects to external tool servers using the open Model Context Protocol. It discovers remote tools and returns them as native TOOL instances. Supports stdio (shell string or shell=False argv list) and HTTP+SSE (with custom headers, timeout, and prefix namespacing).

from thoughtflow import MCP

# Local MCP server via safe argv list (shell=False) with tool prefixing
with MCP(["npx", "-y", "@modelcontextprotocol/server-filesystem", "/tmp"], prefix="fs__") as mcp:
    tools = mcp.list_tools()    # Returns TOOL instances (e.g. "fs__read_file")
    result = mcp.call_tool("read_file", {"path": "/tmp/notes.txt"})  # raises RuntimeError on isError=True

# Remote MCP server via HTTP with custom auth headers and timeout
with MCP("https://my-mcp-server.example.com/mcp", headers={"Authorization": "Bearer ..."}, timeout=30) as mcp:
    tools = mcp.list_tools()

AGENT & tool_loop — Governed Write-Ahead Autonomy

AGENT turns an LLM into an autonomous tool-using agent. When paired with an OpenAI-compatible LLM (openai, openrouter, groq), AGENT runs a native write-ahead tool loop over LLM.chat(): assistant tool_calls are persisted to MEMORY before any tool executes, every tool_call_id is answered (even when vetoed or over budget), and interrupted or approval-suspended runs resume directly from the transcript without re-executing completed tools. Models without chat() automatically use the text-JSON fallback loop.

from thoughtflow import LLM, MEMORY, TOOL, AGENT, tool_loop

llm = LLM("openai:gpt-4o", key="...")

agent = AGENT(
    llm=llm,
    tools=[weather_tool, refund_tool],
    system_prompt="You are a support specialist.",
    allow=["get_weather", "issue_refund"],
    policy={"issue_refund": {"mode": "approve_over", "field": "amount", "limit": 100}},
    budget={"max_model_calls": 6, "max_tool_calls": 4, "max_tokens": 8000},
    checkpoint=lambda mem: mem.to_json("checkpoint.json"),
)

memory = MEMORY()
memory.add_msg("user", "Refund $250 for order #91.")
memory = agent(memory)

# High-value refund suspends cleanly: memory.get_var("agent_status") == "suspended"
# Rehydrate later (even in another Lambda invocation) and resume with a decision:
if memory.is_suspended():
    memory = agent(memory, decision={"approve": True})

print(memory.get_var("agent_status"))   # "final" | "suspended" | "budget_exhausted" | "vetoed" | ...
print(memory.get_var("agent_outcome"))  # model_calls, tool_calls, prompt/completion tokens, vetoed

tool_loop(memory, llm, tools, policy=..., budget=..., decision=...) provides a one-call functional wrapper over the same governed loop. Subclasses implement specialized strategies:

Subclass Strategy
ReactAgent ReAct: interleaved Thought: / Action: / Observation: text loop (preserves multi-line Final Answer: and veto observations)
ReflectAgent Self-reflective: task-aware, negation-safe self-critique and revision synced into MEMORY + {name}_outcome
PlanActAgent Plan-then-execute: generates a structured plan, then executes steps sequentially

DELEGATE — Multi-Agent Coordination

DELEGATE routes tasks between a team of named agents using three coordination patterns:

from thoughtflow import AGENT, DELEGATE, MEMORY

researcher = AGENT(llm=llm, tools=[search_tool], name="researcher")
writer = AGENT(llm=llm, name="writer")

delegate = DELEGATE(agents=[researcher, writer])

memory = MEMORY()

# Dispatch: send to researcher, wait for result
memory = delegate.dispatch(memory, "researcher", "Find info on quantum computing")

# Handoff: pass to writer, fire-and-forget
delegate.handoff(memory, "writer", "Write a summary of the findings")

# Broadcast: ask all agents the same question
results = delegate.broadcast(memory, "Summarize your findings")

WORKFLOW — Step-Based Orchestration

WORKFLOW chains steps (THOUGHTs, DECIDEs, ACTIONs, AGENTs, or plain functions) into a directed sequence with ok= outcome predicates, status-based branching, bounded while_ loops, persisted {name}_log state, and durable suspend/resume (workflow(memory, decision=...)). It is "Python control flow with guardrails."

from thoughtflow import MEMORY, THOUGHT, WORKFLOW

workflow = WORKFLOW(name="research_flow", on_error="skip")

workflow.step(classify_thought, name="classify", ok="auto")  # checks classify_outcome["ok"]
workflow.branch(None, {"failed": fallback_step, "ok": search_action}, on="previous_failed")
workflow.while_(
    condition=lambda m: not m.get_var("draft_ready"),
    body_fn=refine_thought,
    max_iterations=4,
    state_key="refine_result",  # stops early as 'stopped_repeated' if unchanged
)
workflow.step(approval_agent, name="publish", ok="auto")

memory = MEMORY()
memory.add_msg("user", "Tell me about quantum computing")
memory = workflow(memory)

# If 'publish' suspended for human approval, rehydrate later and resume in place:
if memory.is_suspended():
    memory = workflow(memory, decision={"approve": True})

for entry in memory.get_var("research_flow_log"):
    print(f"{entry['step']}: {entry['status']}")

CHRON — Schedule Manager

CHRON manages recurring jobs with 5-field cron expressions, @hourly/@daily/@weekly/@monthly/@yearly aliases, or fixed intervals. It supports two execution modes: tick mode for serverless environments (Lambda, Cloud Functions) and loop mode for long-running daemons. Job state persists atomically to a JSON file.

from thoughtflow import CHRON

chron = CHRON(name="ops", state_file="jobs.json")

# Cron expression or @-alias: run daily at midnight
chron.add("nightly_cleanup", schedule="@daily", action=run_cleanup)

# Fixed interval: every 60 seconds
chron.add("heartbeat", every=60, action=lambda m: print("alive"))

# Serverless: external cron calls your handler
results = chron.tick()  # Executes any jobs that are due right now

# Daemon: blocking loop (or start() for a background thread)
chron.start(tick_interval=60)
# ... later ...
chron.stop()

CHAT — Interactive Conversation Loop

CHAT wraps any callable that follows the ThoughtFlow contract and provides a text-based input/output loop for testing agents in a terminal or Jupyter notebook.

from thoughtflow import LLM, THOUGHT, CHAT

llm = LLM("openai:gpt-4o", key="...")
responder = THOUGHT(name="respond", llm=llm, prompt="Answer: {last_user_msg}")

chat = CHAT(responder, greeting="Hello! Ask me anything.")
chat.run()  # Interactive loop — type 'q' to exit

# Or programmatic turn-by-turn:
response = chat.turn("What is the capital of France?")

EMBED — Vector Embeddings

EMBED is the embedding counterpart to LLM. It sends text to an embedding endpoint and returns a vector. Same multi-provider pattern — one class, any provider.

from thoughtflow import EMBED

embed = EMBED("openai:text-embedding-3-small", key="sk-...")

# Single text → single vector
vector = embed.call("Hello world")
print(len(vector))  # e.g., 1536

# Batch → list of vectors
vectors = embed.call(["Hello", "World"])

# Record/replay works here too — same seam as LLM
embed.record(memory)
replay_embed = EMBED.replay(memory)

# Gemini: text-embedding-004 aliases to gemini-embedding-001 automatically
embed = EMBED("gemini:text-embedding-004", key="...")
vector = embed.call("Hello world")
print(embed.last_error)  # None on success; error string on provider failure

Supported embedding providers: OpenAI, Gemini, Groq, OpenRouter, and local Ollama (ollama:all-minilm:33m, etc.).

DM — Structured Decision Models

DM is the System-One decision counterpart to LLM and EMBED. Instead of generating prose and regex-parsing labels, DM sends structured state and one or more typed questions (choice, noul, score, box) to a decision model and returns calibrated probabilities in a single forward pass — normalizing wire dialects across OpenRouter, TypeSafe (Jev), OpenAI (/v1/decisions), Liquid (d1), Cloudflare (clef), Perplexity, Inception, Upstage, local Ollama (d3, clef), and vLLM:

from thoughtflow import DM, DECIDE, MEMORY

dm = DM("openrouter:typesafe/jev-1.14", key="sk-or-...")

# Plug straight into DECIDE (1-line swap from LLM)
router = DECIDE(
    name="route",
    model=dm,
    choices={"billing": "Invoices and charges", "tech": "Crashes and bugs"},
    prompt="Route this ticket: {last_user_msg}",
    min_margin=0.60,
    default="escalate",
)

# Or evaluate multiple typed questions over shared state in one pass
res = dm.call(
    state={"ticket": "Charged twice on invoice #901."},
    questions={
        "dept": {"type": "choice", "instructions": "Owner?", "choices": ["billing", "tech"]},
        "is_refund": {"type": "noul", "instructions": "Asking for money back?"},
        "urgency": {"type": "score", "instructions": "Urgency?", "levels": ["Low", "Med", "High"]},
    },
)

# Deterministic offline replay via MEMORY
dm.record(memory)
replay_dm = DM.replay(memory)

🔧 Utilities

valid_extract — Robust LLM Output Parsing

LLMs are messy. They add prose, code fences, markdown, and formatting you didn't ask for. valid_extract handles all of it:

Basic extraction from messy output:

from thoughtflow import valid_extract, ValidExtractError

# Messy LLM output with prose and formatting
llm_output = '''
Sure! Here is the data you asked for:
{"name": "Alice", "age": 28, "skills": ["Python", "ML"]}
Let me know if you need anything else!
'''

# Define extraction rules with schema
rules = {
    "kind": "python",
    "format": {
        "name": "",      # Required string
        "age": 0,        # Required int
        "skills": [],    # Required list
    }
}

result = valid_extract(llm_output, rules)
# result = {'name': 'Alice', 'age': 28, 'skills': ['Python', 'ML']}

Optional keys (marked with ?):

rules = {
    "kind": "python",
    "format": {
        "name": "",       # Required
        "email": "",      # Required
        "phone?": "",     # Optional (note the ?)
        "address?": "",   # Optional
    }
}

llm_output = "{'name': 'Bob', 'email': 'bob@example.com'}"
result = valid_extract(llm_output, rules)
# result = {'name': 'Bob', 'email': 'bob@example.com'}
# No error even though phone and address are missing

Nested structures:

rules = {
    "kind": "python",
    "format": {
        "user": {
            "id": 0,
            "profile": {
                "name": "",
                "settings": {}
            }
        },
        "metadata": {}
    }
}

Branch-shaped responses (oneOf dialect):

# First matching branch wins — useful for classification thoughts
rules = {
    "kind": "python",
    "format": {
        "oneOf": [
            {"verdict": "found", "matched_span": ""},
            {"verdict": "absent", "note": ""},
        ]
    },
}

List element validation:

# [schema] means every element must match schema
rules = {
    "kind": "python",
    "format": [{
        "id": 0,
        "name": "",
        "done": True
    }]
}

llm_output = """
[
    {'id': 1, 'name': 'Task A', 'done': False},
    {'id': 2, 'name': 'Task B', 'done': True},
]
"""
result = valid_extract(llm_output, rules)
# Each item validated against the schema

JSON parsing:

rules = {
    "kind": "json",  # Parse as JSON instead of Python
    "format": {"status": "", "data": []}
}

llm_output = '{"status": "ok", "data": [1, 2, 3]}'
result = valid_extract(llm_output, rules)

Error handling:

try:
    result = valid_extract("no valid data here", rules)
except ValidExtractError as e:
    print(f"Extraction failed: {e}")

Schema type mapping:

  • "" or str → string
  • 0 or int → integer
  • 0.0 or float → float
  • True or bool → boolean
  • None → NoneType
  • [] → list (any contents)
  • [schema] → list of items matching schema
  • {} → dict (any contents)
  • {"k": schema} → dict with required key "k"
  • {"k?": schema} → dict with optional key "k"
  • {"oneOf": [schema, ...]} → first matching branch wins (classification)
  • "str", "int", "float", "number", "bool", "null", "list", "dict" → type-name strings
  • "int|null", "str|number" → pipe-delimited type unions
  • {"enum": ["pos", "neg"]} → constrained literal set (inline or top-level)

EventStamp — Deterministic IDs

from thoughtflow import event_stamp, hashify, EventStamp

# Generate unique, sortable event ID
# Alphabetical order = chronological order
stamp = event_stamp()  # "A1B2C3D4E5F6G7H8"

# Generate with document hash (deterministic component)
stamp = event_stamp({"user": "alice", "action": "login"})

# Decode timestamp from stamp
unix_time = EventStamp.decode_time(stamp)

# Generate deterministic hash
hash_id = hashify("some input string")       # 32 chars by default
hash_id = hashify("some input", length=16)   # Custom length
# Same input always produces same hash

Prompt Construction

from thoughtflow import construct_prompt, construct_msgs

# ═══════════════════════════════════════════════════════════════════════════
# STRUCTURED PROMPTS WITH SECTIONS
# ═══════════════════════════════════════════════════════════════════════════

prompt = construct_prompt({
    "context": "You are analyzing customer feedback data.",
    "instructions": "Follow these steps:\n1. Identify sentiment\n2. Extract key themes",
    "output_format": "Return a JSON object with 'sentiment' and 'themes' keys."
})
# Generates a structured prompt with clear section markers

# ═══════════════════════════════════════════════════════════════════════════
# MESSAGE LIST CONSTRUCTION
# ═══════════════════════════════════════════════════════════════════════════

msgs = construct_msgs(
    usr_prompt="Analyze this feedback: {feedback}",
    vars={"feedback": customer_feedback},
    sys_prompt="You are a sentiment analysis expert.",
    msgs=[]  # Prior conversation messages
)
# Returns properly formatted message list for LLM

🎨 Real-World Patterns

Multi-Step Workflow

Chain multiple thoughts together for complex workflows:

from thoughtflow import LLM, MEMORY, THOUGHT

llm = LLM("openai:gpt-4o", key="...")
memory = MEMORY()

# Define a pipeline of thoughts
analyze = THOUGHT(
    name="analyze",
    llm=llm,
    prompt="Analyze the following text and identify key themes: {text}",
    parsing_rules={"kind": "python", "format": {"themes": [], "sentiment": ""}}
)

expand = THOUGHT(
    name="expand",
    llm=llm,
    prompt="Take these themes and expand on each one: {analyze_result}",
)

summarize = THOUGHT(
    name="summarize",
    llm=llm,
    prompt="Create an executive summary from this expanded analysis: {expand_result}",
)

critique = THOUGHT(
    name="critique",
    llm=llm,
    prompt="Identify potential weaknesses or gaps in this analysis: {summarize_result}",
)

# Execute the pipeline — it's just Python!
memory.set_var("text", document)

for thought in [analyze, expand, summarize, critique]:
    print(f"Executing: {thought.name}")
    memory = thought(memory)
    print(f"  Result stored in: {thought.name}_result")

# Get final results
summary = memory.get_var("summarize_result")
critique = memory.get_var("critique_result")

Multi-Channel Agent

Build agents that work across platforms:

from thoughtflow import LLM, MEMORY, THOUGHT

memory = MEMORY()

# Messages come from different platforms
memory.add_msg("user", "Hello from the website!", channel="webapp")
memory.add_msg("user", "Following up via Telegram", channel="telegram")
memory.add_msg("user", "Quick question from mobile", channel="ios")
memory.add_msg("user", "Also checking Slack", channel="slack")

# Process messages by channel
for channel in ["webapp", "telegram", "ios", "slack"]:
    msgs = memory.get_msgs(channel=channel)
    print(f"\n{channel.upper()} ({len(msgs)} messages):")
    for msg in msgs:
        print(f"  {msg['role']}: {msg['content'][:50]}...")

# Or process all together, maintaining context
all_msgs = memory.get_msgs(include=["user", "assistant"])

# Render for LLM context with channel info
context = memory.render(
    format="conversation",
    include_roles=("user", "assistant"),
    max_total_length=4000
)

Retry with Auto-Repair

Automatic retry with intelligent repair prompts:

from thoughtflow import LLM, MEMORY, THOUGHT

llm = LLM("openai:gpt-4o", key="...")
memory = MEMORY()

thought = THOUGHT(
    name="generate_json",
    llm=llm,
    prompt="""Generate a valid JSON object with exactly these keys:
    - "name": a string
    - "count": an integer greater than 0
    - "tags": a list of at least 3 strings
    """,
    parsing_rules={
        "kind": "json",
        "format": {"name": "", "count": 0, "tags": [""]}
    },
    validator="list_min_len:3",  # Built-in: tags must have 3+ items
    max_retries=3,
    retry_delay=0.5,
)

# If validation fails, THOUGHT automatically retries with a repair prompt
# that explains what went wrong:
# "(Please return only the requested format; your last answer failed: List too short)"

memory = thought(memory)

# Check execution history
for attempt in thought.execution_history:
    print(f"Attempt: success={attempt['success']}, duration={attempt['duration_ms']:.1f}ms")

Combining THOUGHTs and ACTIONs

Build agents that think AND act:

from thoughtflow import LLM, MEMORY, THOUGHT, ACTION

llm = LLM("openai:gpt-4o", key="...")
memory = MEMORY()

# Define an action for external API calls
def search_database(memory, query, limit=10):
    results = db.search(query, limit=limit)
    return {"results": results, "count": len(results)}

search = ACTION(name="search", fn=search_database)

# Define thoughts for reasoning
analyze_query = THOUGHT(
    name="analyze_query",
    llm=llm,
    prompt="Convert this user question into a database search query: {last_user_msg}",
)

synthesize = THOUGHT(
    name="synthesize",
    llm=llm,
    prompt="Given these search results: {search_result}\n\nAnswer the user's question: {last_user_msg}",
)

# Workflow: Think → Act → Think
memory.add_msg("user", "What products do we have under $50?")

memory = analyze_query(memory)  # Think: convert to query
query = memory.get_var("analyze_query_result")

memory = search(memory, query=query, limit=20)  # Act: search database

memory = synthesize(memory)  # Think: synthesize answer
answer = memory.get_var("synthesize_result")

Agentic Research with AGENT + TOOL

Let the LLM decide which tools to call autonomously:

from thoughtflow import LLM, MEMORY, TOOL, AGENT

llm = LLM("openai:gpt-4o", key="...")

# Define tools with schemas the LLM can reason about
search_tool = TOOL(
    name="web_search",
    description="Search the web for current information.",
    parameters={
        "type": "object",
        "properties": {"query": {"type": "string", "description": "Search query"}},
        "required": ["query"],
    },
    fn=lambda query: my_search_fn(query),
)

agent = AGENT(
    llm=llm,
    tools=[search_tool],
    system_prompt="You are a research assistant. Use tools to answer questions.",
    max_iterations=5,
)

memory = MEMORY()
memory.add_msg("user", "What are the latest developments in quantum computing?")
memory = agent(memory)

print(memory.last_asst_msg(content_only=True))

Orchestrated Workflow with Branching

Use WORKFLOW for conditional step execution:

from thoughtflow import MEMORY, THOUGHT, WORKFLOW, SEARCH

workflow = WORKFLOW(name="smart_answer", on_error="skip")

# Step 1: Classify the question
workflow.step(classify_thought, name="classify")

# Step 2: Search only if classification says we need external info
workflow.step(
    SEARCH(query="{last_user_msg}", max_results=3),
    name="search",
    condition=lambda m: m.get_var("classify_result") == "needs_research",
)

# Step 3: Always summarize
workflow.step(summarize_thought, name="summarize")

memory = MEMORY()
memory.add_msg("user", "What happened in tech news today?")
memory = workflow(memory)

Scheduled Jobs with CHRON

Run recurring tasks on a cron schedule:

from thoughtflow import CHRON, MEMORY

def daily_report(memory):
    """Generate and send a daily report."""
    # ... your logic here ...
    print(f"Report generated at {memory.get_var('chron_fired_at')}")

chron = CHRON(name="scheduler", state_file="schedule_state.json")
chron.add("daily_report", schedule="0 9 * * 1-5", action=daily_report)
chron.add("health_check", every=300, action=lambda m: print("OK"))

# In serverless (Lambda handler): chron.tick()
# In a daemon process: chron.start(tick_interval=60)

Serverless Agent (Lambda, Cloud Functions, Edge)

ThoughtFlow's signature deployment pattern. Because MEMORY serializes completely to JSON and the library has zero dependencies, a stateless chat turn is three steps:

def handle_turn(session_json, user_message, llm):
    # 1. REHYDRATE — full conversation state from a JSON string
    memory = MEMORY.from_json(session_json) if session_json else MEMORY()

    # 2. RUN — the universal contract
    memory.add_msg("user", user_message, channel="webapp")
    memory = agent(memory)
    reply = memory.last_asst_msg(content_only=True)

    # 3. PERSIST — write the complete event log back to storage
    return reply, memory.to_json(indent=None)

Store the session string anywhere — S3, DynamoDB, Redis, a database column. Your deployment artifact is your handler plus one pure-Python package, well under a megabyte. A complete AWS Lambda handler with a locally runnable demo lives in examples/serverless/.

RAG, the ThoughtFlow Way

Retrieved context enters MEMORY as tagged augment events — the user's original message is never mutated, so the event log stays a truthful audit of what the user said versus what the system added:

# Retrieve (EMBED + cosine similarity, a vector DB, or any retriever you like)
context = retrieve_relevant_chunks(memory.last_user_msg(content_only=True))

# Store as an augment — auditable, filterable, separate in the event log
memory.add_augment(
    f"Relevant context:\n{context}",
    metadata={"internal": True, "source": "rag"},
)

# Default: THOUGHT/AGENT see context as a separate system message
memory = answer_thought(memory)

# Opt-in: fold context into the user turn for the LLM payload only
agent = AGENT(llm=llm, merge_augments=True)
memory = agent(memory)

# The UI shows only what the user should see
visible_history = memory.get_msgs(exclude_metadata={"internal": True})

ThoughtFlow deliberately ships no vector store — compose with whatever retrieval you already trust. The full walkthrough is in examples/scripts/14_rag_llm_view.py and docs/concepts/rag.md.


🎯 Philosophy: The Zen of ThoughtFlow

ThoughtFlow is guided by principles documented in ZEN.md:

Principle What It Means
🎯 First Principles First Built on fundamentals, not abstractions on abstractions
🧘 Complexity is the Enemy Pythonic, intuitive, elegant. As light as possible.
👁️ Obvious Over Abstract If you have to dig deep to understand, the design failed
🔍 Transparency is Trust Never guess what's happening under the hood
📦 Minimize Dependencies Zero deps for core. Serverless-ready by default.
♻️ Backward Compatibility is Sacred Code should endure. Deprecation should be rare.
🧩 Modularity Over Monolith Composable pieces, not all-or-nothing frameworks
🚗 Vehicle, Not Destination Your logic, your rules, your journey
🐍 Python is King Pythonic first. No DSLs, no YAML configs, no magic.

"Don't try to please everyone. Greatness comes from focus, not from trying to do everything."

— ZEN.md


🔗 Sister Library: ThoughtBase

ThoughtBase is an optional companion library providing persistent storage and vector search capabilities.

from thoughtflow import MEMORY, THOUGHT
from thoughtbase import VectorStore, PersistentMemory

# Create persistent, searchable memory
store = VectorStore("my_agent_memories")
persistent_mem = PersistentMemory(store)

# Your normal ThoughtFlow workflow
thought = THOUGHT(name="respond", llm=llm, prompt="...")
memory = thought(memory)

# Save to ThoughtBase
persistent_mem.save(memory)

# Later: search across all saved memories
results = persistent_mem.search("user preferences about notifications", limit=5)

# Load a specific memory
memory = persistent_mem.load(session_id="abc123")

⚠️ ThoughtBase is entirely optional. ThoughtFlow provides complete functionality standalone. ThoughtBase adds persistence and vector search when you need them.


🔧 Supported Versions

Version Python Status Notes
0.3.x 3.9 - 3.13 🟢 Active Current development

Compatibility Policy:

  • We test against Python 3.9 through 3.13 on every push (see CI)
  • We aim to support new Python versions within 3 months of stable release
  • Breaking changes are avoided; when necessary, deprecation warnings come first

🧪 Testing & Evaluation

ThoughtFlow treats deterministic testing as a first-class capability, built from the primitives you already know — no separate testing framework to learn.

from thoughtflow import LLM, MEMORY
from thoughtflow.eval import Harness, TestCase

# ═══════════════════════════════════════════════════════════════════════════
# RECORD AND REPLAY — deterministic flows, offline
# ═══════════════════════════════════════════════════════════════════════════

# Record: every LLM exchange is captured as MEMORY events
llm = LLM("openai:gpt-4o", key="sk-...")
recording = MEMORY()
llm.record(recording)

memory = my_flow(MEMORY(), llm)         # runs live, records everything
recording.to_json("session.json")       # commit this file to your repo

# Replay: a drop-in LLM that serves the recorded responses
replay_llm = LLM.replay(MEMORY.from_json("session.json"))
memory = my_flow(MEMORY(), replay_llm)  # no network, no keys, identical output

# Drift fails loudly — unrecorded requests raise ReplayMissError,
# or fall back to a live model: LLM.replay(recorded, on_miss=live_llm)

# ═══════════════════════════════════════════════════════════════════════════
# EVALUATION HARNESS — structured test cases over any flow
# ═══════════════════════════════════════════════════════════════════════════

# A test case is a name, a setup, and a check over the result MEMORY
harness = Harness([
    TestCase(
        name="capital_question",
        setup=lambda m: m.add_msg("user", "Capital of France?"),
        check=lambda m: "paris" in (m.last_asst_msg(content_only=True) or "").lower(),
    ),
    TestCase(
        name="arithmetic",
        messages=[{"role": "user", "content": "What's 2+2?"}],
        expected=lambda response: "4" in response,
    ),
])

# A flow is any `memory -> memory` callable: a THOUGHT, AGENT, WORKFLOW,
# or plain function. Pass strict=True to fail cases whose MEMORY absorbed
# any THOUGHT/DECIDE/ReplayMissError failure even if a downstream fallback ran.
results = harness.run(my_flow_with(replay_llm), strict=True)

print(results.summary())
# {"total": 2, "passed": 2, "failed": 0, "pass_rate": 1.0,
#  "failures": [], "cases_with_absorbed_errors": []}

for failure in results.failures:
    print(failure.test_case.name, failure.reason, failure.absorbed_errors, failure.memory)

Pair the harness with ReplayLLM, ReplayDM, ReplayEMBED, and ReplayTOOL and your entire agent test suite is 100% deterministic: no API keys in CI, no external tool side effects, no flaky outputs, and zero spend. The complete lifecycle is demonstrated in examples/scripts/13_record_replay.py.

Integration smoke tests (optional, real API calls) live under tests/integration/. Enable with THOUGHTFLOW_INTEGRATION_TESTS=1 and provider API keys in your environment:

THOUGHTFLOW_INTEGRATION_TESTS=1 pytest tests/integration/test_llm_providers.py \
  tests/integration/test_embed_providers.py \
  tests/integration/test_dm_providers.py -v

These cover base LLM routing, native provider classes (GroqLLM, CerebrasLLM, OpenRouterLLM), Ollama, prompt caching, record/replay, EMBED providers, and OpenRouter DM decision models (typesafe/jev-1.14, liquid/d1.2). Tests skip automatically when a key or account lacks access to a provider.


📁 Project Structure

thoughtflow/
├── src/thoughtflow/
│   ├── README.md        # Architectural guide to the package internals
│   ├── __init__.py      # Public API exports
│   ├── llm.py           # LLM — multi-provider model interface + ReplayLLM
│   ├── llm_chat.py      # LLM.chat — structured native tool calls, stream events, abort
│   ├── llm_params.py    # Unified model-param pipeline (transport vs wire)
│   ├── llm_cache.py     # Prompt caching helpers (cached_system, etc.)
│   ├── providers/       # GroqLLM, CerebrasLLM, OpenRouterLLM (+ README.md)
│   ├── embed.py         # EMBED — multi-provider embeddings + ReplayEMBED
│   ├── dm.py            # DM — multi-provider structured decision models + ReplayDM
│   ├── memory.py        # MEMORY — event-sourced state, scopes, budgets, suspend/resume
│   ├── message.py       # Message dataclass & normalization helpers
│   ├── thought.py       # THOUGHT — atomic cognitive unit + outcomes & retry policies
│   ├── action.py        # ACTION — external operations base class
│   ├── tool.py          # TOOL — LLM-selectable capabilities + ReplayTOOL
│   ├── mcp.py           # MCP — Model Context Protocol client (stdio & HTTP+SSE)
│   ├── agent.py         # AGENT & tool_loop — governed write-ahead tool loop
│   ├── delegate.py      # DELEGATE — multi-agent coordination
│   ├── workflow.py      # WORKFLOW — step orchestration, while_, & suspend/resume
│   ├── chron.py         # CHRON — schedule manager (cron/aliases/interval)
│   ├── chat.py          # CHAT — interactive conversation loop
│   ├── _cron_expr.py    # Internal cron expression parser
│   ├── _util.py         # Utilities (event_stamp, valid_extract, schema dialect, etc.)
│   ├── thoughts/        # THOUGHT subclasses: DECIDE, PLAN (+ README.md)
│   ├── actions/         # ACTION subclasses: 14 elemental operations (+ README.md)
│   ├── agents/          # AGENT subclasses: ReactAgent, ReflectAgent, PlanActAgent (+ README.md)
│   └── eval/            # Evaluation harness: Harness, TestCase (+ README.md)
├── primitives/          # Per-primitive documentation (32 Markdown specs + README.md)
├── examples/            # Working, runnable examples (+ README.md)
│   ├── scripts/         # Numbered walkthroughs (01_hello_world ... 15_thought_integration_test)
│   ├── notebooks1/      # Interactive Jupyter notebooks (01_foundations ... 05_persona_example)
│   ├── reference/       # Copy-and-edit agent loop recipes with focused tests
│   └── serverless/      # Deployable AWS Lambda chat handler
├── tests/               # Comprehensive test suite (+ README.md)
│   ├── unit/            # ~980 fast, zero-network unit tests
│   └── integration/     # Opt-in live provider smoke suites
├── docs/                # MkDocs documentation site source
├── developer/           # Contributor & maintainer guides (01 ... 21)
├── assets/              # Logo and media
└── ZEN.md               # Philosophy document

🛠️ Development

# Clone the repository
git clone https://github.com/jrolf/thoughtflow.git
cd thoughtflow

# Install in development mode with dev tooling (pytest, ruff)
pip install -e ".[dev]"

# Run the unit test suite
pytest tests/unit -q

# Run with coverage
pytest --cov=src/thoughtflow

# Lint the code (Pyflakes bug-catching only, no style enforcement)
ruff check src/ tests/

See developer/ for comprehensive development documentation.


📈 Project Status

Aspect Status Notes
Foundational Primitives ✅ Stable LLM (call + chat), EMBED, DM, MEMORY, THOUGHT, ACTION
Cognitive / Planning ✅ Stable DECIDE (LLM + DM, noul, score, multi), PLAN
Capability ✅ Stable TOOL (needs_context, ReplayTOOL), MCP (prefix=, shell=False)
Autonomy ✅ Stable Governed write-ahead AGENT, tool_loop, ReactAgent, ReflectAgent, PlanActAgent
Coordination ✅ Stable DELEGATE, CHAT
Orchestration ✅ Stable WORKFLOW (ok=, while_, suspend/resume), CHRON (@daily aliases)
Action Subclasses ✅ Stable 14 elemental operations (SEARCH, SCRAPE, FETCH, etc.)
Hermetic Record/Replay ✅ Shipped LLM, EMBED, DM, and TOOL recording + strict eval Harness
Memory Scopes & Compaction ✅ Shipped memory.scope(), budget_tokens=, compact(), suspend()/resolve_suspension()
Provider convenience classes ✅ Shipped GroqLLM, CerebrasLLM, OpenRouterLLM, OpenAICompatibleLLM, prompt caching
API Stability 🟡 Alpha May evolve based on feedback
Documentation ✅ Multi-level Root, subpackage READMEs, primitives/ specs, docs/, and developer/
Test Coverage ✅ ~984 unit tests Plus optional live integration smoke tests (API keys)
Serverless Ready ✅ Yes Zero deps, deployable example in examples/serverless/

See CHANGELOG.md for version history.


🔒 Security

Found a vulnerability? Please don't open a public issue.

See SECURITY.md for our responsible disclosure policy. We take security seriously and will respond within 48 hours.


🤝 Contributing

We welcome contributions! ThoughtFlow values:

Principle What It Means
Simplicity Over feature bloat
Clarity Over cleverness
Explicit Over implicit
Tested Everything has tests

See CONTRIBUTING.md for guidelines.


💬 Getting Help

Need Where to Go
Question about usage GitHub Discussions
Bug report GitHub Issues
Feature request GitHub Issues
Security issue See SECURITY.md

📖 Resources

Resource Description
📚 Documentation Full documentation site
🧘 ZEN.md Philosophy and design principles
🧩 primitives/ Per-primitive documentation (one Markdown file per class)
💡 examples/ Working, runnable examples
🛠️ developer/ Developer guides and docs
📝 CHANGELOG.md Version history
🤝 CONTRIBUTING.md Contribution guidelines

📄 License

MIT © James A. Rolfsen


ThoughtFlow

ThoughtFlow
Powerful AI systems from simple parts.

Built for developers who believe AI tools should empower, not mystify.

Install • Quick Start • Foundational • Higher-Level • Contribute

⭐ Star us on GitHub — it helps!

Metadata

Release files for thoughtflow 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for thoughtflow 0.3.0
File Size Uploaded Provenance Actions
thoughtflow-0.3.0.tar.gz 414.0 kB Without provenance Details for thoughtflow-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for thoughtflow 0.3.0
File Interpreter ABI Platform Actions
thoughtflow-0.3.0-py3-none-any.whl Python 3 none any Details for thoughtflow-0.3.0-py3-none-any.whl

Total release size: 699.6 kB

Release files / thoughtflow-0.3.0.tar.gz

Download URL thoughtflow-0.3.0.tar.gz
Size 414.0 kB
Tags Source
SHA-256 checksum
How to use checksums
a24c6acd95015c49837fd5f26749cf2261318b0b775044ab97bb1a3a2b5c40ff
BLAKE2b-256 checksum
How to use checksums
1086ad2dfa8b37ad20241d52e21fe43874aa8d78f831d780a945b1ea0030accc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / thoughtflow-0.3.0-py3-none-any.whl

Download URL thoughtflow-0.3.0-py3-none-any.whl
Size 285.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
70ff613bc6b21dd5f20b4a2140eefb0ada19cd0b7a9ee34cee437fba7b4368d2
BLAKE2b-256 checksum
How to use checksums
08d00a339b8f23616b83d32d95bdfea099d967a2de7fac66fe18ae80b5ad5b89
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for thoughtflow 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page