Skip to main content Switch to mobile version thoughtflow 0.3.0 Powerful AI systems from simple parts. Composable cognitive primitives, event-sourced memory, and autonomous agents in pure Python with zero dependencies.
pip install thoughtflow==0.3.0 Copy PIP instructions
Powerful AI systems from simple parts.
A handful of composable primitives. Event-sourced memory. Deterministic replay. Zero dependencies. Just Python.
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.
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.
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
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
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
These are architectural characteristics, not formal benchmarks. Your mileage may vary based on workload.
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.
Built on the foundational layer for richer capabilities.
Action Subclasses (Elemental Operations)
These are the "verbs" that agents use to interact with the world. All extend ACTION.
💡 Every primitive — foundational and higher-level alike — inherits serialization, execution history, and introspection from its parent class.
ThoughtFlow works with any LLM provider through a unified interface:
Native convenience classes (v0.2.2+) wrap production edge cases while keeping the same call() API:
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...", ]] # 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.
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 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
DECIDE is a specialized THOUGHT that constrains LLM output to a finite set of choices. Perfect for routing, classification, and branching logic:
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
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:
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.
ThoughtFlow provides a suite of pre-built ACTION subclasses for common operations. These are the "verbs" that agents use to interact with the world:
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
SEARCH — Multi-Provider Web Search
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
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.
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:
[schema] → list of items matching schema
{"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
Chain multiple thoughts together for complex workflows:
Build agents that work across platforms:
Automatic retry with intelligent repair prompts:
Build agents that think AND act:
Let the LLM decide which tools to call autonomously:
Use WORKFLOW for conditional step execution:
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/.
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:
"Don't try to please everyone. Greatness comes from focus, not from trying to do everything."
🔗 Sister Library: ThoughtBase
ThoughtBase is an optional companion library providing persistent storage and vector search capabilities.
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
ThoughtFlow treats deterministic testing as a first-class capability, built from the primitives you already know — no separate testing framework to learn.
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.
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.
See CHANGELOG.md for version history.
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.
We welcome contributions! ThoughtFlow values:
See CONTRIBUTING.md for guidelines.
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!
Author/Maintainer: James A. Rolfsen
agents ai anthropic langchain-alternative llm machine-learning openai orchestration
Development Status 3 - Alpha
Intended Audience Developers
License OSI Approved :: MIT License
Operating System OS Independent
Programming Language Python :: 3
Topic Scientific/Engineering :: Artificial Intelligence
Software Development :: Libraries :: Python Modules
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)
Built distribution (wheel)
Total release size: 699.6 kB
Release files / thoughtflow-0.3.0.tar.gz
Release files / thoughtflow-0.3.0-py3-none-any.whl
Security for thoughtflow 0.3.0
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.
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.
Release history Release notifications | RSS feed
Nov 19, 2026 2 release files No provenance
Jul 18, 2026 2 release files No provenance
Jul 11, 2026 2 release files No provenance
Jun 10, 2026 2 release files No provenance
Apr 1, 2026 2 release files No provenance
Mar 18, 2026 2 release files No provenance
Mar 13, 2026 2 release files No provenance
Feb 25, 2026 2 release files No provenance
Feb 23, 2026 2 release files No provenance
Feb 6, 2026 2 release files No provenance
Feb 5, 2026 2 release files No provenance
Feb 4, 2026 2 release files No provenance
Sep 30, 2024 2 release files No provenance
"PyPI", "Python Package Index", and the blocks logos are registered trademarks of the Python Software Foundation.
© 2026 Python Software Foundation




