Skip to main content

A universal agent framework for building self-driven AI agents and multi-agent teams

Project description

KohakuTerrarium

Define what an agent is. Build any kind. Compose them into teams.

Python 3.10+ License Version


What KohakuTerrarium is

KohakuTerrarium is a framework for building real agents, not just LLM wrappers.

Its core abstraction is the creature: a standalone agent with its own controller, tools, sub-agents, triggers, memory, and I/O. Creatures can run by themselves, or they can be composed into a terrarium, which is a pure multi-agent wiring layer.

The goal is simple: make agent systems modular enough to model serious products, while still staying configurable, composable, and hackable.

Where it fits

AI tooling usually lives at different layers:

Product Framework Utility / Wrapper
LLM App ChatGPT, Claude.ai LangChain, LangGraph, Dify DSPy
Agent Claude Code, Codex, OpenCode smolagents (thin), KohakuTerrarium -
Multi-Agent - KohakuTerrarium CrewAI, AutoGen

Most frameworks either operate below the agent layer, or they jump straight to multi-agent orchestration with a very thin idea of what an agent is.

KohakuTerrarium starts with the agent itself.

A creature is made of:

  • Controller: the reasoning loop
  • Input: how events enter the agent
  • Output: how results leave the agent
  • Tools: what actions it can take
  • Triggers: what wakes it up
  • Sub-agents: internal delegation for specialized tasks

Then a terrarium composes multiple creatures horizontally through channels, lifecycle management, and observability.

Why the split matters

A lot of systems blur internal agent logic and external multi-agent wiring into one abstraction. KohakuTerrarium keeps them separate on purpose.

Inside a creature
One controller delegates to tools and sub-agents.
This is the agent-level abstraction.
Between creatures
Independent creatures communicate through channels.
This is the multi-agent wiring layer.

That separation lets you:

  • build a creature once and run it solo or in a team
  • change tools, prompts, triggers, or outputs without redesigning the whole system
  • reason about single-agent behavior separately from team topology
  • keep the multi-agent layer simple instead of turning it into another hidden controller

Architecture at a glance

Terrarium view

  +---------+       +---------------------------+
  |  User   |<----->|        Root Agent         |
  +---------+       |  (terrarium tools, TUI)   |
                    +---------------------------+
                          |               ^
            sends tasks   |               |  observes results
                          v               |
                    +---------------------------+
                    |     Terrarium Layer       |
                    |   (pure wiring, no LLM)   |
                    ├-------┬----------┬--------┤
                    |  swe  | reviewer |  ....  |
                    +-------┴----------┴--------+

Creature view

    List, Create, Delete  +------------------+
                    +-----|   Tools System   |
      +---------+   |     +------------------+
      |  Input  |   |          ^        |
      +---------+   V          |        v
        |   +---------+   +------------------+   +------------+
        +-->| Trigger |-->|    Controller    |-->| Sub Agents |
User input  | System  |   |    (Main LLM)    |<--| with tools |
            +---------+   +------------------+   +------------+
                ^             |          |
                |             v          v
                |         +--------+  +------+
                +---------|Channels|  |Output|
                 Receive  +--------+  +------+
                             |  ^
                             v  |
                          +------------------+
                          | Other Creatures  |
                          +------------------+

Quick start

# Install from PyPI
pip install kohakuterrarium

# Or install from source (for development)
git clone https://github.com/Kohaku-Lab/KohakuTerrarium.git
cd KohakuTerrarium
pip install -e ".[dev]"

# Build the web frontend for `kt web` / `kt app`
npm install --prefix src/kohakuterrarium-frontend
npm run build --prefix src/kohakuterrarium-frontend

# Install the default creatures, terrariums, and plugins
kt install https://github.com/Kohaku-Lab/kt-defaults.git

# Set up LLM access (pick one)
kt login codex          # Codex OAuth (no API key needed)
kt model default gpt-5.4  # or configure any OpenAI-compatible API

# Run a single creature
kt run @kt-defaults/creatures/swe

# Run a multi-agent terrarium
kt terrarium run @kt-defaults/terrariums/swe_team

# Launch the web dashboard
kt serve

Supports OpenRouter, OpenAI, Anthropic, Google Gemini, and any OpenAI-compatible API.

Choose your path

I want to run something now

I want to build my own creature

I want to build a terrarium

I want to embed it in Python

I want to work on the framework itself

Core mental model

Creature

A creature is a standalone agent with its own runtime, tools, sub-agents, prompts, and state.

You can run it directly:

kt run path/to/creature

Terrarium

A terrarium is a composition layer that wires creatures together through channels and manages their lifecycle.

It does not add a second reasoning loop.

Root agent

A terrarium can define a root agent that sits outside the team and operates it through terrarium management tools.

Channels

Channels are how creatures communicate:

  • Queue: one consumer receives each message
  • Broadcast: all subscribers receive each message

Modules

Everything extensible in KohakuTerrarium fits into one of five main module types:

Module What it does Example custom use
Input Receives external events Discord listener, webhook, voice input
Output Delivers agent output Discord sender, TTS, file writer
Tool Executes actions API calls, database access, RAG retrieval
Trigger Generates automatic events Timer, scheduler, channel watcher
Sub-agent Delegated task execution Planning, code review, research

Session and environment

  • Environment: shared terrarium state such as shared channels
  • Session: private creature state such as scratchpad and sub-agent state

That keeps team communication shared while creature internals stay isolated.

Practical capabilities

KohakuTerrarium already includes a broad runtime surface:

  • built-in file, shell, web, JSON, channel, trigger, and introspection tools, including single-edit and multi-edit file mutation primitives
  • built-in sub-agents for exploration, planning, implementation, review, summarization, and research
  • background tool execution and non-blocking agent flow
  • session persistence with resumable operational state, not just chat history
  • package installation for creatures and terrariums
  • Python embedding through Agent, TerrariumRuntime, and KohakuManager
  • HTTP and WebSocket serving
  • web dashboard and native desktop app
  • custom module and plugin systems

Programmatic usage

Use agents and terrariums as libraries — your code is the orchestrator:

import asyncio
from kohakuterrarium.core.agent import Agent
from kohakuterrarium.core.channel import ChannelMessage
from kohakuterrarium.terrarium.config import load_terrarium_config
from kohakuterrarium.terrarium.runtime import TerrariumRuntime

async def main():
    # ── Single agent ──────────────────────────────────────────────
    agent = Agent.from_path("@kt-defaults/creatures/swe")
    agent.set_output_handler(lambda text: print(text, end=""), replace_default=True)
    await agent.start()
    await agent.inject_input("Explain what this codebase does.")
    await agent.stop()

    # ── Multi-agent terrarium ─────────────────────────────────────
    runtime = TerrariumRuntime(load_terrarium_config("@kt-defaults/terrariums/swe_team"))
    await runtime.start()
    tasks = runtime.environment.shared_channels.get("tasks")
    await tasks.send(ChannelMessage(sender="user", content="Fix the auth bug."))
    await runtime.run()
    await runtime.stop()

asyncio.run(main())

Composition algebra

Compose agents with Python operators — >> (sequence), & (parallel), | (fallback), * (retry), async for (loop):

import asyncio
from kohakuterrarium.compose import agent, factory
from kohakuterrarium.core.config import load_agent_config

def make_agent(name, prompt):
    config = load_agent_config("@kt-defaults/creatures/general")
    config.name, config.system_prompt, config.tools, config.subagents = name, prompt, [], []
    return config

async def main():
    # Persistent agents (accumulate conversation context)
    async with await agent(make_agent("writer", "You are a writer.")) as writer, \
               await agent(make_agent("reviewer", "You are a strict reviewer. Say APPROVED if good.")) as reviewer:

        # Pipeline: writer >> bridge >> reviewer
        pipeline = writer >> (lambda text: f"Review this:\n{text}") >> reviewer

        # Loop until approved (native Python control flow)
        async for feedback in pipeline.iterate("Write a haiku about coding"):
            print(f"Reviewer: {feedback[:100]}")
            if "APPROVED" in feedback:
                break

    # Parallel ensemble with fallback
    fast = factory(make_agent("fast", "Answer concisely."))
    deep = factory(make_agent("deep", "Answer thoroughly."))
    safe = (fast & deep) >> (lambda results: max(results, key=len))  # pick best
    safe_with_retry = (safe * 2) | fast  # retry twice, then fallback
    print(await safe_with_retry("What is recursion?"))

asyncio.run(main())

For more, see Programmatic Usage, Python API, and examples/code/.

Runtime surfaces

CLI and TUI

KohakuTerrarium supports multiple interactive modes:

  • cli: rich inline terminal experience
  • tui: full-screen Textual application
  • plain: simple stdout and stdin mode for piping and CI

See CLI Reference for command details.

Web dashboard

The project includes a Vue-based dashboard and FastAPI server.

python -m kohakuterrarium.api.main
# For frontend development:
npm run dev --prefix src/kohakuterrarium-frontend

See HTTP API and Frontend Architecture.

Desktop app

kt app launches the same web UI inside a native desktop window.

Sessions and persistence

Sessions are automatically saved to ~/.kohakuterrarium/sessions/ unless disabled.

Resume anytime:

kt resume
kt resume --last
kt resume swe_team

Session files use the .kohakutr format and store operational state such as:

  • conversation history
  • tool call metadata
  • event logs
  • scratchpad state
  • sub-agent state
  • channel messages
  • jobs
  • resumable triggers
  • config and topology metadata

See Sessions.

Packages, defaults, and examples

Install creature and terrarium packages from Git or local paths:

kt install https://github.com/someone/cool-creatures.git
kt install ./my-creatures -e
kt list

Run installed configs with package references:

kt run @cool-creatures/creatures/my-agent
kt terrarium run @cool-creatures/terrariums/my-team

Included resources:

  • kt-defaults/ contains installable default creatures and terrariums
  • examples/agent-apps/ contains config-driven examples
  • examples/code/ contains Python usage examples
  • examples/terrariums/ contains multi-agent examples
  • examples/plugins/ contains plugin examples

See examples/README.md and kt-defaults/README.md.

Codebase map

src/kohakuterrarium/
  core/           # Agent runtime, controller, executor, events, environment
  bootstrap/      # Agent initialization factories for LLM, tools, I/O, triggers
  cli/            # CLI command handlers
  terrarium/      # Multi-agent runtime, config loading, topology wiring, hot-plug
  builtins/       # Built-in tools, sub-agents, I/O modules, TUI, user commands
  builtin_skills/ # Markdown skill manifests for on-demand tool and sub-agent docs
  session/        # Session persistence, memory search, embeddings
  serving/        # Transport-agnostic service manager and event streaming
  api/            # FastAPI HTTP and WebSocket server
  modules/        # Base protocols for tools, inputs, outputs, triggers, sub-agents
  llm/            # LLM providers, profiles, API key management
  parsing/        # Tool-call parsing and stream handling
  prompt/         # Prompt assembly, aggregation, plugins, skill loading
  testing/        # Test infrastructure

src/kohakuterrarium-frontend/  # Vue web frontend
kt-defaults/                   # Installable defaults package
examples/                      # Example agents, terrariums, code samples, plugins
docs/                          # Guides, concepts, API reference, contributor docs

Several source packages also include local README.md files that explain internal responsibilities and dependency flow. Those are worth reading if you are contributing to the framework.

Documentation map

Full documentation lives in docs/.

Guides

Concepts

API reference

Contributing

License

KohakuTerrarium License 1.0: based on Apache-2.0 with naming and attribution requirements.

  • Derivative works must include Kohaku or Terrarium in their name
  • Derivative works must provide visible attribution with a link to this project

Copyright 2024-2026 Shih-Ying Yeh (KohakuBlueLeaf) and contributors

Project details


Download files

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

Source Distribution

kohakuterrarium-1.0.0rc3.tar.gz (7.0 MB view details)

Uploaded Source

Built Distribution

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

kohakuterrarium-1.0.0rc3-py3-none-any.whl (7.2 MB view details)

Uploaded Python 3

File details

Details for the file kohakuterrarium-1.0.0rc3.tar.gz.

File metadata

  • Download URL: kohakuterrarium-1.0.0rc3.tar.gz
  • Upload date:
  • Size: 7.0 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for kohakuterrarium-1.0.0rc3.tar.gz
Algorithm Hash digest
SHA256 49f29f2ac34477ac63677040b5f4df0a64356b5d876e30d53f12a596cc2baf98
MD5 053d9abf13bb72de8780e564a9500ff3
BLAKE2b-256 ed80159b693d1318e1c30ac786db5645c413bfdacb394843b690afbdffa0a872

See more details on using hashes here.

Provenance

The following attestation bundles were made for kohakuterrarium-1.0.0rc3.tar.gz:

Publisher: release.yml on Kohaku-Lab/KohakuTerrarium

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file kohakuterrarium-1.0.0rc3-py3-none-any.whl.

File metadata

File hashes

Hashes for kohakuterrarium-1.0.0rc3-py3-none-any.whl
Algorithm Hash digest
SHA256 f2f5d46901438ce8926660efc45b5f30d0c02cb859ff6819077a2dd779d1fd48
MD5 9fa55439adb8ea1ad2791de0fb63be8f
BLAKE2b-256 7c2fd97e39beb0980c80e91082553bff2adb58a6556fc1ca6692f1da833b1725

See more details on using hashes here.

Provenance

The following attestation bundles were made for kohakuterrarium-1.0.0rc3-py3-none-any.whl:

Publisher: release.yml on Kohaku-Lab/KohakuTerrarium

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

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