Skip to main content

Phoson

phoson-engine-minimal

Minimal Python runtime for the Phoson autonomous-agent platform

Python uv ruff pytest License Stars Build

๐Ÿ”ฅ Open Source โ€” Built for developers who want full control over their AI agents.


๐Ÿ“‹ Table of Contents


๐Ÿค” What this project is

phoson-engine-minimal is the core runtime behind the Phoson autonomous-agent platform. It's a lightweight, framework-free Python implementation that gives you complete control over your AI agents without the bloat of heavy frameworks.

Unlike other agent frameworks (LangChain, LangGraph, etc.), Phoson is built from scratch using provider SDKs directly, with a custom ReAct loop designed for:

  • ๐Ÿ”„ Streaming behavior โ€” Token-by-token events for real-time UIs
  • ๐Ÿ”ง Tool-call orchestration โ€” Full control over tool execution
  • ๐Ÿ’ฐ Cost accounting โ€” Track spend per run with built-in pricing
  • ๐Ÿ‘๏ธ Observability โ€” RunStep events and typed event streams
  • ๐ŸŒณ Session trees โ€” Branchable conversation history (not linear!)
  • โŒจ๏ธ Interactive REPL โ€” Debug and iterate on agents interactively

๐ŸŽฏ Why Phoson?

Traditional Frameworks Phoson
Heavy dependencies Zero external agent frameworks
Linear conversations Branchable conversation trees
Black-box streaming Full event visibility
Fixed patterns Custom ReAct loop
Enterprise pricing MIT licensed

โœจ Features

Feature Description
Framework-free Pure Python + provider SDKs; no LangChain/LangGraph
Multi-provider 20+ providers behind a single BaseLLMChat contract
Typed events Normalized LLMEvent stream for all providers
Tool execution @tool decorator with JSON Schema definitions
Middleware hooks Pre/post processing for LLM calls and tool execution
Branching sessions ConversationTree for non-linear conversation history
Interactive REPL CLI with streaming, session persistence, and model switching
Cost tracking Built-in pricing module for USD usage calculation
Thinking support Native reasoning/thinking token handling (Anthropic & OpenAI o1)

๐Ÿ—๏ธ High-level architecture

flowchart LR
    U[App / CLI / API] --> AE[AgentEngine\nphoson_agent]
    AE --> MW[Middleware Hooks]
    AE --> T[Registered Tools]
    AE --> S[ConversationTree + Storage]
    AE --> C[BaseLLMChat Contract]
    C --> OA[OpenAIChat]
    C --> AN[AnthropicChat]
    OA --> P1[OpenAI / OpenRouter / Ollama]
    AN --> P2[Anthropic]
    OA --> E[Typed LLM Events]
    AN --> E
    E --> AE
    AE --> R[Agent Events + RunResult]

Runtime loop (tool call cycle)

sequenceDiagram
    participant Client
    participant Engine as AgentEngine
    participant LLM as LLM Adapter
    participant Tool as Tool Handler

    Client->>Engine: run(messages, config)
    Engine->>LLM: stream(history, config, tools)
    LLM-->>Engine: TokenEvent / ReasoningTokenEvent
    LLM-->>Engine: ToolCallEvent
    Engine->>Tool: execute(args)
    Tool-->>Engine: result/error
    Engine->>LLM: continue with ToolResultBlock
    LLM-->>Engine: UsageEvent + LLMDoneEvent
    Engine-->>Client: AgentRunResult

๐Ÿ—บ๏ธ Repository map

phoson-engine-minimal/
โ”œโ”€โ”€ phoson_llm/           # LLM normalization layer (adapters + schemas + pricing)
โ”œโ”€โ”€ phoson_agent/         # ReAct agent loop, tools, middleware, sessions
โ”œโ”€โ”€ phoson_cli/           # Interactive CLI (REPL) for agent sessions
โ”œโ”€โ”€ phoson_plugin_*/      # Official plugins (checkpoint, mcp, memory)
โ”œโ”€โ”€ tests/                # Unit/integration tests for all layers
โ”œโ”€โ”€ docs/api/             # Per-package API documentation
โ”œโ”€โ”€ .github/workflows/    # CI and security automation
โ”œโ”€โ”€ ROADMAP.md            # Project roadmap
โ””โ”€โ”€ pyproject.toml        # Project metadata, dependencies, tooling config

๐Ÿ“ฆ Core modules

phoson_llm โ€” LLM normalization layer

Provider adapters return a single typed event stream (LLMEvent subclasses):

Event Description
LLMStartEvent Call start (model, message count)
TokenEvent Text fragment token-by-token
ReasoningStartEvent Model started reasoning (Anthropic thinking / OpenAI o1)
ReasoningTokenEvent Reasoning fragment
ReasoningDoneEvent Complete reasoning block
ToolCallDeltaEvent Partial tool args chunk (for real-time UI)
ToolCallEvent Complete tool call with parsed args
UsageEvent Tokens + cost in USD
LLMDoneEvent Full assembled text (always last)
ErrorEvent Error with code, message, retryable flag

Supported providers:

Category Providers
Native adapters OpenAI (tool use, reasoning effort), Anthropic (thinking, tool use, prompt caching), Google Gemini, Mistral, Azure OpenAI, AWS Bedrock
OpenAI-compatible endpoints OpenRouter, Ollama, LM Studio, vLLM, DeepSeek, Groq, xAI (Grok), Together, Perplexity, NVIDIA, Fireworks, Cohere, GitHub Models

All of them are available via the build_chat() factory, e.g. build_chat("openrouter"), and expose the same stream() event contract.

Pricing module (phoson_llm.pricing) provides calculate_cost() for provider-level USD usage.

phoson_agent โ€” Agent orchestration

Stateless-by-run orchestration over message history with tool execution:

  • AgentEngine โ€” Main entry point for running agents (async and sync)
  • @tool decorator โ€” Transform Python functions into AgentTool definitions with JSON Schema
  • AgentMiddleware โ€” Hooks for pre/post processing (LLM calls, tool execution)
  • AgentContext โ€” Shared state across middleware and tools

phoson_agent.sessions โ€” Conversation persistence

  • ConversationTree โ€” Branchable conversation structure (not linear)
  • ConversationNode โ€” Individual node with messages, children, label
  • JsonlStorage โ€” JSONL-backed session storage (local file)
  • SessionMeta โ€” Session metadata (id, message_count, created_at, updated_at)

phoson_cli โ€” Interactive REPL

Command-line interface for interactive agent sessions:

  • PhosonRepl โ€” Interactive read-eval-print loop
  • Commands: /exit, /quit, /clear, /new, /model, /tree, /sessions, /label, /help
  • Real-time streaming responses
  • Session persistence and labeling
  • Multiple model switching

๐Ÿš€ Quick Start

from phoson_agent import AgentEngine
from phoson_llm.chats.openai import OpenAIChat
from phoson_llm.schemas import Message, ModelConfig

engine = AgentEngine(
    chat=OpenAIChat(),
    tools=[],
    phoson_weight=1.2,
)

result = engine.run_sync(
    messages=[Message(role="user", content="Summarize this project in one line")],
    config=ModelConfig(model="openai/gpt-4o-mini", max_tokens=128),
)

print(result.final_content)
print(result.total_cost_usd, result.total_credits)

Or run the interactive CLI:

uv run phoson-cli

Run the setup wizard to configure provider credentials and defaults:

uv run phoson-cli --setup

๐Ÿ“ฅ Installation

# Clone the repository
git clone https://github.com/phoson-lat/phoson-engine-minimal.git
cd phoson-engine-minimal

# Install dependencies
uv sync --dev --locked

# Install git hooks
uv run pre-commit install --install-hooks
uv run pre-commit install --hook-type commit-msg
uv run pre-commit install --hook-type pre-push

๐Ÿ› ๏ธ Development setup

Install dependencies

uv sync --dev --locked

Install git hooks

uv run pre-commit install --install-hooks
uv run pre-commit install --hook-type commit-msg
uv run pre-commit install --hook-type pre-push

โœ… Run checks locally

uv sync --dev --all-extras   # --all-extras is needed for pyright (provider SDK stubs)
uv run ruff format --check .
uv run ruff check .
uv run pyright
uv run python -m compileall phoson_llm phoson_agent phoson_cli
uv run pytest -q

๐Ÿ” Environment variables

Set the variables for the providers you use (the adapter reads the default when no api_key is passed):

# Cloud providers
OPENAI_API_KEY=
ANTHROPIC_API_KEY=
OPENROUTER_API_KEY=
GEMINI_API_KEY=
MISTRAL_API_KEY=
GROQ_API_KEY=
XAI_API_KEY=
DEEPSEEK_API_KEY=
TOGETHER_API_KEY=
PERPLEXITY_API_KEY=
NVIDIA_API_KEY=
FIREWORKS_API_KEY=
COHERE_API_KEY=
GITHUB_TOKEN=

# Azure OpenAI
AZURE_OPENAI_ENDPOINT=
AZURE_OPENAI_API_KEY=
AZURE_OPENAI_DEPLOYMENT=

# AWS Bedrock (plus standard AWS credentials: AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY)
AWS_DEFAULT_REGION=us-east-1

Local servers (Ollama, LM Studio, vLLM) need no API key โ€” just the right base_url.


๐Ÿ’ป Usage examples

Minimal agent usage

from phoson_agent import AgentEngine
from phoson_llm.chats.openai import OpenAIChat
from phoson_llm.schemas import Message, ModelConfig

engine = AgentEngine(
    chat=OpenAIChat(),
    tools=[],
    phoson_weight=1.2,
)

result = engine.run_sync(
    messages=[Message(role="user", content="Summarize this project in one line")],
    config=ModelConfig(model="openai/gpt-4o-mini", max_tokens=128),
)

print(result.final_content)
print(result.total_cost_usd, result.total_credits)

Define a tool

import ast
import operator

from phoson_agent import tool


@tool
def calculate(expression: str) -> str:
    """Safely evaluate a basic arithmetic expression like "2 + 2 * 10"."""

    def _eval(node: ast.AST):
        match node:
            case ast.Expression(body=value):
                return _eval(value)
            case ast.Constant():
                return node.value
            case ast.BinOp(left=left, op=op, right=right):
                ops = {
                    ast.Add: operator.add,
                    ast.Sub: operator.sub,
                    ast.Mult: operator.mul,
                    ast.Div: operator.truediv,
                }
                if type(op) not in ops:
                    raise ValueError(f"Unsupported operator: {type(op).__name__}")
                return ops[type(op)](_eval(left), _eval(right))
            case ast.UnaryOp(op=op, operand=value) if isinstance(op, ast.USub):
                return -_eval(value)
        raise ValueError(f"Unsupported expression: {expression!r}")

    return str(_eval(ast.parse(expression, mode="eval")))

โš ๏ธ Never use eval()/exec() on model-generated input โ€” treat LLM output as untrusted and validate or sandbox every tool argument.

Interactive CLI

uv run phoson-cli

One-shot mode (no REPL, no session โ€” for scripts and CI):

phoson-cli "fix the failing tests"     # positional task
phoson-cli -p "summarize this repo"    # --print flag
echo "explain the CI failure" | phoson-cli   # piped stdin

The final answer is printed to stdout; the exit code is 0 on success and 1 on agent error.

Available commands:

  • /new โ€” Start a new session
  • /model <name> โ€” Switch model
  • /tree โ€” Show conversation tree
  • /sessions โ€” List saved sessions
  • /label <text> โ€” Label current node
  • /undo โ€” Undo the last turn (branch from before your last message)
  • /update โ€” Check for and install CLI updates
  • /help โ€” Show all commands

Self-update: phoson-cli --self-update performs the same check/upgrade flow from outside the REPL (e.g. from a script).

Appearance: PHOSON_THEME=light|ansi|no-color (or theme = "..." in ~/.phoson/config.toml) switches the color tier; NO_COLOR / CLICOLOR=0 always produce plain output (scripts, CI).

Reasoning: press Ctrl+T to toggle the live "thinking" view while a run is streaming, or to expand the full reasoning of the last turn after it finishes (persisted with the session, so it survives resume).

Models file: ~/.phoson/models.json (optional) holds model overrides (context window, labels โ€” user-defined models appear in /model), non-sensitive provider settings (default_model, base_url for self-hosted/proxied endpoints) and an automatic 24 h model-list cache that makes /model instant and works offline. API keys never live there; see docs/api/phoson_cli.md.

UI: the interactive REPL (Rich + prompt_toolkit) is the only front end. One-shot mode (phoson-cli "task") is always stdout-only. A full-screen prompt_toolkit front end (persistent scrollable chat pane, header/footer, /model//provider//sessions pickers and bash confirmation as overlay floats) is planned to replace the classic REPL.

๐Ÿ”’ CI and security workflows

  • .github/workflows/ci.yml: Format check, lint, smoke compile, and tests on PRs and pushes to main.
  • .github/workflows/security.yml: Dependency audit and secret scan on PRs, pushes to main, and weekly schedule.

๐Ÿ“ Commit message format

Conventional Commits are enforced through a commit-msg hook.

Examples:

feat: add streaming chat abstraction
fix: handle unknown model pricing fallback
chore: update pre-commit hook versions

Common types: feat, fix, docs, refactor, test, chore, ci


๐Ÿ—“๏ธ Roadmap

For the project roadmap see ROADMAP.md, and per-package API documentation under docs/api/.


๐Ÿค Contributing

Contributions are welcome! Here's how you can help:

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Commit your changes: git commit -m 'feat: add amazing feature'
  4. Push to the branch: git push origin feature/amazing-feature
  5. Open a Pull Request

๐ŸŒ Language policy: everything in this repository must be in English โ€” documentation, docstrings, code comments, commit messages, issue titles and bodies, and PR descriptions. This keeps the project accessible to contributors worldwide. If you're more comfortable writing in another language, draft your changes in a branch and maintainers will help polish the English before merge.

Please read CONTRIBUTING.md for details on our code of conduct and development process.

Ideas for contributions

  • ๐Ÿ†• Add new LLM providers (20+ already supported โ€” see the table above)
  • ๐Ÿ”ง Improve tool execution (batching, retries, caching)
  • ๐Ÿ“Š Add observability integrations (OpenTelemetry, Langfuse)
  • ๐Ÿ–ฅ๏ธ Build a web-based REPL or playground
  • ๐Ÿ“š Improve documentation and examples

๐Ÿ“„ License

This project is licensed under the MIT License โ€” see the LICENSE file for details.

MIT License

Copyright (c) 2024 Phoson

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

๐Ÿ’ฌ Support


โญ Show your support

Give us a โญ๏ธ if this project helped you build better AI agents!


Built with ๐Ÿ”ฅ by phoson.lat

Download files

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

Source Distribution

phoson_engine_minimal-0.7.1.tar.gz (442.3 kB view details)

Uploaded Source

Built Distribution

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

phoson_engine_minimal-0.7.1-py3-none-any.whl (231.8 kB view details)

Uploaded Python 3

File details

Details for the file phoson_engine_minimal-0.7.1.tar.gz.

File metadata

  • Download URL: phoson_engine_minimal-0.7.1.tar.gz
  • Upload date:
  • Size: 442.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for phoson_engine_minimal-0.7.1.tar.gz
Algorithm Hash digest
SHA256 fce59c8bd34bef099de965ee188a006288f923f073aabf9cda536961f4d56d92
MD5 ef4ea63a5083edc4affec0c72ff7333c
BLAKE2b-256 e5700a598e21539215d833361dde757aee7bd39690ba27187e1a9de75843b54e

See more details on using hashes here.

Provenance

The following attestation bundles were made for phoson_engine_minimal-0.7.1.tar.gz:

Publisher: publish.yml on phoson-lat/phoson-engine-minimal

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

File details

Details for the file phoson_engine_minimal-0.7.1-py3-none-any.whl.

File metadata

File hashes

Hashes for phoson_engine_minimal-0.7.1-py3-none-any.whl
Algorithm Hash digest
SHA256 6cfd9c4d59d16326795a9458248f808be84343fb4d776d558adc99f1bded1a80
MD5 63292bfea19fdf206dca11bb4f82e82a
BLAKE2b-256 5f47c6ef45631d4f15f39e9b2cdc9592e4a3998fe2f34ae96b0fc2485f9d89aa

See more details on using hashes here.

Provenance

The following attestation bundles were made for phoson_engine_minimal-0.7.1-py3-none-any.whl:

Publisher: publish.yml on phoson-lat/phoson-engine-minimal

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

Release history Release notifications | RSS feed

0.8.0

2 files

0.7.3

2 files

0.7.2

2 files

This release

0.7.1 This release

2 files

0.7.0

2 files

0.6.0

2 files

0.5.0

2 files

0.4.0

2 files

0.3.0

2 files

Supported by

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