# Technical Documentation: MervinPraison/PraisonAI

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/MervinPraison/PraisonAI)

### Overview (README.md)

<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset=".github/images/logo_dark.png" />
    <source media="(prefers-color-scheme: light)" srcset=".github/images/logo_light.png" />
    <img alt="PraisonAI Logo" src=".github/images/logo_light.png" width="250" />
  </picture>
</p>



<p align="center">
<a href="https://github.com/MervinPraison/PraisonAI"><img src="https://static.pepy.tech/badge/PraisonAI" alt="Total Downloads" /></a>
<a href="https://github.com/MervinPraison/PraisonAI"><img src="https://img.shields.io/github/v/release/MervinPraison/PraisonAI" alt="Latest Stable Version" /></a>
<a href="https://github.com/MervinPraison/PraisonAI"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License" /></a>
</p>

# PraisonAI

**AI agents that run on your own computers, even fully offline.**

[2M+ downloads](https://pepy.tech/projects/praisonai) · [9.3K stars](https://github.com/MervinPraison/PraisonAI) · [600+ releases in the last year](https://github.com/MervinPraison/PraisonAI/releases) · [80+ contributors](https://github.com/MervinPraison/PraisonAI/graphs/contributors) · MIT

<table>
<tr>
<td colspan="3">
<b>Private AI</b> <i>(early access)</i><br />
Private AI that earns trust one task at a time. Each task moves to your own AI only after it passes a test. If quality slips, it moves back automatically, and every step is recorded for regulators. For banks, insurers and hospitals.<br />
<a href="https://praison.ai/enterprise/"><img src=".github/images/readme/talk-to-us.svg" alt="Talk to us" width="168" height="40" align="right" /></a>
<a href="#how-the-handover-works-early-access">How the handover works</a> · <a href="#whats-new">What's new</a>
</td>
</tr>
<tr>
<td width="33%" valign="top">
<a href="src/praisonai-agents"><b>Agents</b></a><br />
<sub>Python agent framework: teams, workflows, memory, tools.</sub><br />
<code>pip install praisonaiagents</code><br />
<a href="#quick-start">Your first agent</a>
</td>
<td width="33%" valign="top">
<a href="src/praisonai-bot"><b>Bot</b></a><br />
<sub>Your agent on Telegram, Discord, Slack and WhatsApp, 24/7.</sub><br />
<code>pip install "praisonai-bot[gateway,bot]"</code><br />
<code>praisonai-bot onboard</code>
</td>
<td width="33%" valign="top">
<a href="src/praisonai-code"><b>Code</b></a><br />
<sub>An agent in your terminal that reads and edits your code.</sub><br />
<code>pip install praisonai-code</code><br />
<code>praisonai-code code</code>
</td>
</tr>
<tr>
<td valign="top">
<a href="src/praisonai-mcp"><b>MCP</b></a><br />
<sub>Your agents and tools inside Cursor, Claude Desktop and other MCP clients.</sub><br />
<code>pip install praisonai-mcp</code><br />
<code>praisonai-mcp connect cursor</code>
</td>
<td valign="top">
<a href="src/praisonai-train"><b>Train</b></a><br />
<sub>Fine-tune an open model on your own GPUs, and train agents on past runs.</sub><br />
<code>pip install "praisonai-train[llm]"</code><br />
<code>praisonai-train --help</code>
</td>
<td valign="top">
<b>All of it</b><br />
<sub>CLI, bots, dashboard and integrations in one install.</sub><br />
<code>pip install "praisonai[dashboard]"</code><br />
<code>praisonai setup</code>
</td>
</tr>
</table>

<p align="center">
  <img src=".github/images/readme/offline-ollama.gif" alt="A terminal: offline.py creates an Agent with model ollama/llama3.2, the API key is shown as none, and the agent answers why the sky is blue in under three seconds" width="800" />
  <br />
  <sub>A real run with <code>pip install praisonai</code>: a local Llama 3.2 model through Ollama, with no API key set.</sub>
</p>

## How it fits together

<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset=".github/images/readme/architecture-dark.svg" />
    <img src=".github/images/readme/architecture-light.svg" alt="Chat apps and your tools on the left connect to PraisonAI in the middle: the Agents core with Bot, Code, MCP and Train. On the right, cloud models or your own models running fully offline. Underneath, Private AI for regulated teams: Watch, Test, Hand over, Roll back, Record." width="880" />
  </picture>
</p>

## Quick start

Set a key for any supported provider (OpenAI shown here), or skip the key and use a local model as in the next section.

```bash
pip install praisonai
export OPENAI_API_KEY="your-api-key"
```

```python
from praisonai import Agent

agent = Agent(instructions="You are a helpful assistant.")
print(agent.start("In two sentences, why do some companies keep their data on their own computers?"))
```

Only want the lightweight core? `pip install praisonaiagents` and write `from praisonaiagents import Agent`; the rest of the code is the same.

## Run fully offline

Run the same agent on a model on your own computer with [Ollama](https://ollama.com). You need no API key, and your prompts and answers stay on the machine.

Install the package and pull the model while you still have internet; after that, the agent runs with no network at all. `pip install praisonai` includes local-model support; with only the core library, use `pip install "praisonaiagents[llm]"`.

```bash
# Start Ollama first (the app, or "ollama serve" in another terminal)
ollama pull llama3.2
export DO_NOT_TRACK=true   # keeps telemetry off (PraisonAI sends none unless you turn it on)
```

```python
from praisonai import Agent

agent = Agent(instructions="You are a helpful assistant.", model="ollama/llama3.2")
print(agent.start("Why is the sky blue?"))
```

If Ollama runs on another computer on your network, pass `base_url` (or set `OLLAMA_API_BASE`):

```python
agent = Agent(instructions="...", model="ollama/llama3.2", base_url="http://192.168.1.10:11434")
```

vLLM and LM Studio work the same way: use `hosted_vllm/` (vLLM) or `lm_studio/` with your server's `base_url`. More in the [Ollama guide](https://praison.ai/docs/models/ollama) and [Models docs](https://praison.ai/docs/models).

## What you can build

<table>
<tr>
<td width="33%" valign="top">
<a href="https://praison.ai/docs/cli/bot"><picture><source media="(prefers-color-scheme: dark)" srcset=".github/images/ui/bot-desktop-dark.webp" /><img src=".github/images/ui/bot-desktop-light.webp" alt="PraisonAI Bot reporting that Telegram and Slack are connected" /></picture></a><br />
<b>Bots</b><br /><sub>Telegram, Discord, Slack and WhatsApp, with memory. <a href="https://praison.ai/docs/features/bot-gateway">Gateway</a></sub>
</td>
<td width="33%" valign="top">
<a href="https://praison.ai/docs/concepts/claw"><picture><source media="(prefers-color-scheme: dark)" srcset=".github/images/ui/claw-desktop-dark.webp" /><img src=".github/images/ui/claw-desktop-light.webp" alt="The PraisonAI dashboard with a chat on the left and a canvas on the right" /></picture></a><br />
<b>Dashboard</b><br /><sub>Chat, agents, memory, knowledge and channels in one app.</sub>
</td>
<td width="33%" valign="top">
<a href="https://praison.ai/docs/cli/mcp"><img src=".github/images/readme/mcp-connect.gif" alt="A terminal: praisonai-mcp connect cursor writes the Cursor MCP config and reports 85 tools ready from praisonai" /></a><br />
<b>Your agents in Cursor</b><br /><sub><code>praisonai-mcp connect cursor</code>: 85 tools, one command. A real run.</sub>
</td>
</tr>
<tr>
<td valign="top"><b><a href="https://praison.ai/docs/concepts/agentflow">Multi-agent teams</a></b><br /><sub>Handoffs, route, parallel, loop and repeat.</sub></td>
<td valign="top"><b><a href="https://praison.ai/docs/concepts/memory">Memory and RAG</a></b><br /><sub>Memory, knowledge and sessions, with zero extra deps to start.</sub></td>
<td valign="top"><b><a href="https://praison.ai/docs/tools/tools">Tools and MCP</a></b><br /><sub>Your own <code>@tool</code> or any MCP server.</sub></td>
</tr>
<tr>
<td valign="top"><b><a href="https://praison.ai/docs/cli/code">Coding agent</a></b><br /><sub><code>praisonai code</code>, <code>run</code> and <code>chat</code> in your terminal.</sub></td>
<td valign="top"><b><a href="https://praison.ai/docs/features/browser-agent">Browser automation</a></b><br /><sub>An agent that uses websites for you.</sub></td>
<td valign="top"><b><a href="https://praison.ai/docs/features/sandbox">Sandboxes</a></b><br /><sub>Run tools in Docker, E2B, Modal and more.</sub></td>
</tr>
<tr>
<td valign="top"><b><a href="https://praison.ai/docs/train">Fine-tuning</a></b><br /><sub>Train an open model on your own past work.</sub></td>
<td valign="top"><b><a href="#using-yaml-no-code">YAML, no code</a></b><br /><sub>Agents and workflows from one file.</sub></td>
<td valign="top"><b><a href="https://praison.ai/docs/deploy">Deploy</a></b><br /><sub>Ship agents as APIs or to the cloud.</sub></td>
</tr>
</table>

> **Open Products** — Built directly on PraisonAI with zero duplicated code:
> **[PraisonAI Ship](products/openship/)** *(OpenShip)* — open-source PR shipping, self-review, PR Steward, and declarative `.praisonai/approvals.yml` on any LLM or local Ollama (draft PRs only; never merges). Browse all [`products/`](products/).

## The Five-Layer Agent Stack

Most frameworks hand you one or two layers and leave the rest as homework. PraisonAI covers **all five** — plus the outer layer that decides *where* your agent actually runs.

Each layer wraps the one inside it. When an agent misbehaves, the layer tells you where to look.

<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset=".github/images/readme/stack-dark.svg" />
    <img src=".github/images/readme/stack-light.svg" alt="Five nested layers: Prompt inside Context inside Harness inside Loop inside Graph, all inside Managed Agents" width="880" />
  </picture>
</p>

| Layer | The question it answers | PraisonAI |
|:--|:--|:--|
| **1 · Prompt** | Did I say it clearly? | `instructions=`, `role`/`goal`/`backstory`, `output=`, `templates=` |
| **2 · Context** | Is the right thing in the window? | `memory=`, `knowledge=`, `context=`, handoff `ContextPolicy` |
| **3 · Harness** | Can it act, and be checked? | `tools=`, `MCP()`, `guardrails=`, `approval=`, `hooks=`, `sandbox=` |
| **4 · Loop** | When do we stop? | `execution=ExecutionConfig(...)`, `reflection=`, `autonomy=`, doom-loop detection |
| **5 · Graph** | Who runs when, and who checks whom? | `AgentFlow`, `route()`, `parallel()`, `loop()`, `repeat()` |
| **⬡ Managed** | *Where does it actually run?* | `tools_run_on="docker"` — one shared sandbox for the tools, or `run_on="anthropic"` for the whole agent |

<details>
<summary><strong>Show an example for each layer, and Managed Agents</strong></summary>

### Layer 1 · Prompt — *Did I say it clearly?*

Role, instructions, examples, output format.

```python
from praisonai import Agent

agent = Agent(
    role="Senior Data Analyst",
    goal="Turn raw numbers into decisions",
    output="verbose",              # markdown-formatted output
)
agent.start("Summarise Q3 revenue trends")
```

### Layer 2 · Context — *Is the right thing in the window?*

Write, select, compress, isolate — the four context operations, one parameter each.

```python
from praisonai import Agent

agent = Agent(
    instructions="You are a support engineer.",
    memory={"user_id": "u-42"},    # write    — persists across runs (needs a user_id)
    knowledge=["docs/"],           # select   — retrieves only what's relevant
    context="summarize",           # compress — auto-compacts before the limit
)
```

> **Isolate** is `handoffs=[specialist]` — a sub-agent inherits the last few messages and the intersection of your tools, not your whole transcript. [📖 Handoffs](https://praison.ai/docs/concepts/handoffs)

### Layer 3 · Harness — *Can it act, and be checked?*

*Agent = Model + Harness.* Tool dispatch, plus the guides that steer before acting and the sensors that observe after.

```python
from praisonai import Agent, MCP, tool

@tool
def deploy(env: str) -> str:
    """Deploy the current build to an environment."""
    return f"Deployed to {env}"

agent = Agent(
    name="ReleaseEngineer",
    instructions="You are a release engineer.",
    tools=[deploy, MCP("npx -y @modelcontextprotocol/server-filesystem /tmp")],
    approval=True,                 # guide — human gate before risky tools run
)
agent.start("Deploy to staging, then list the files you can read")
```

### Layer 4 · Loop — *When do we stop?*

Hard iteration caps, budget ceilings, no-progress detection and completion checks — every brake is explicit.

```python
from praisonai import Agent, ExecutionConfig

agent = Agent(
    instructions="Fix the failing tests.",
    execution=ExecutionConfig(max_iter=30, max_budget=0.50, on_budget_exceeded="stop"),
    autonomy=True,                 # required to drive the loop with run_autonomous()
)
result = agent.run_autonomous("Refactor the auth module", max_iterations=5)

print(result.completion_reason)
# goal | no_tool_calls | max_iterations | timeout | doom_loop | needs_help | error
# (with on_budget_exceeded="stop", hitting the cap raises BudgetExceededError,
#  surfaced here as completion_reason="error")
```

> **Doom-loop detection is on by default.** Repeated identical tool calls and A→B→A→B oscillation get caught — while a poller whose output keeps changing does not. [📖 Doom Loop Detection](https://praison.ai/docs/features/doom-loop-detection)

### Layer 5 · Graph — *Who runs when, and who checks whom?*

Topology as a versionable artifact: prompt chaining, routing, parallelisation, orchestrator-worker.

```python
from praisonai import AgentFlow
from praisonai import route, parallel, repeat

flow = AgentFlow(steps=[
    classifier,
    route({"bug": [bug_agent], "feature": [feature_agent], "default": [triage]}),
    parallel([reviewer, tester]),                      # fan out, join automatically
    repeat(editor, until=lambda ctx: "approved" in ctx.previous_result.lower(),
           max_iterations=3),                          # evaluator–optimizer
])
flow.run("Ticket #123: login fails on Safari")
```

> The same graph is expressible in YAML with no Python at all. [📖 AgentFlow](https://praison.ai/docs/concepts/agentflow)

### ⬡ Outside the stack: Managed Agents — *Where does it actually run?*

The harness is commoditising; **where** the agent executes is the next multiplier. Rather than burning your laptop's CPU, hand an agent a short-lived cloud sandbox — repo, tools and tests run there.

```bash
pip install praisonai
```

The simplest way in is `tools_run_on=` — one whole team or workflow shares **one** sandbox, so a file written by step 1 is there for step 2. Thinking stays on your machine:

```python
from praisonai import Agent, AgentFlow

writer = Agent(name="Writer", instructions="You write files.")
reader = Agent(name="Reader", instructions="You read files.")

flow = AgentFlow(tools_run_on="docker", steps=[writer, reader])  # or e2b | modal | daytona | flyio
flow.run("Write 'hello' to /workspace/note.txt, then read it back")
```

Same thing with no Python at all:

```yaml
name: remote-demo
tools_run_on: docker      # every step shares one sandbox
agents:
  writer: {role: Writer, goal: Write files}
  reader: {role: Reader, goal: Read files}
steps:
  - agent: writer
    action: "Write 'hello' to /workspace/note.txt"
  - agent: reader
    action: "Read /workspace/note.txt"
```

For a single agent, two words cover it — and they answer different questions:

```python
from praisonai import Agent

# A. Only the TOOLS move. Thinking stays on your machine.
agent = Agent(name="builder", instructions="You build things.",
              tools_run_on="docker")   # docker | e2b | modal | daytona | flyio
                                       # tenki | sandlock | ssh | novita | subprocess

# B. The WHOLE agent moves — model calls, loop and tools
agent = Agent(name="teacher", instructions="You teach.", run_on="anthropic")  # hosted
agent = Agent(name="builder", instructions="You build.", run_on="docker")     # self-hosted
agent.start("Write a Python script that prints the first 10 primes, then run it")
```

Ask any object where it runs, and it will tell you:

```python
>>> Agent(name="builder", instructions="x", tools_run_on="docker")
Agent(name='builder', thinks_on='this machine', tools_run_on='a Docker container')

>>> agent.where_does_it_run()
Thinking (the AI model calls) happens on this machine.
Tools run on a Docker container.
Your own tools (check_db) still run on this machine -- only shell, file and
code tools move. They read and write this machine's files.
```

Naming a place that cannot do the job is a typo, not a preference, so it says so:

```python
>>> Agent(name="x", instructions="i", run_on="e2b")
TypeError: Agent(run_on='e2b') is not valid: run_on= places the whole agent
-- model calls, loop and tools -- on a managed runtime, and 'e2b' runs
commands but cannot host an agent loop.
  To run only the tools there:  Agent(tools_run_on='e2b')
```

To run one block of code somewhere else, name the place on that call:

```python
agent.execute_code_sync("print(6 * 7)", run_in="sandlock")   # kernel-enforced
```

See what is running and reclaim strays:

```bash
praisonai managed ps          # list running sandboxes
praisonai managed stop --all  # reclaim them
```

Sandboxes shut themselves down when idle (`auto_shutdown`, `idle_timeout_s`), and a post-setup snapshot is reused so the next run skips the image pull and dependency install. Commit a `.praisonai/environment.yaml` and the environment travels with the repo.

> 📖 [20 runnable examples](examples/python/managed-agents/) · manage sessions with `praisonai managed sessions list <agent-id>` or `praisonai managed sessions resume <session-id> "<prompt>"`

<sub>Stack framing adapted from [The Five-Layer Agent Stack](https://mer.vin/2026/07/five-layer-agent-stack-match-bug-to-right-layer/) and [Agent Harnesses vs Orbs](https://mer.vin/2026/08/agent-harnesses-vs-orbs-why-remote-sandboxes-beat-local-agent-loops/).</sub>

</details>

## How the main features work

**Multi-agent patterns.** One `AgentFlow`, seven ways to run its steps. [Docs](https://praison.ai/docs/concepts/agentflow)

<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset=".github/images/readme/multi-agent-patterns-dark.svg" />
    <img src=".github/images/readme/multi-agent-patterns-light.svg" alt="An AgentFlow runs steps in order, and seven patterns change how: route picks one branch, parallel runs steps at once, loop runs once per item, repeat runs until a condition holds, when or If branches on a check, include reuses another flow, and handoffs pass work to another agent." width="880" />
  </picture>
</p>

**Agent teams.** One `AgentTeam`, three ways to run the same tasks: in order, under a manager agent, or as a workflow. [Docs](https://praison.ai/docs/concepts/process)

<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset=".github/images/readme/agent-team-dark.svg" />
    <img src=".github/images/readme/agent-team-light.svg" alt="AgentTeam runs the same tasks three ways. Sequential: Research, Write and Review run in list order. Hierarchical: a manager agent tells each agent to execute or stop and reads their status back. Workflow: a start task, a decision that routes to Publish or Revise, and Revise routes back to the start." width="880" />
  </picture>
</p>

**PraisonAI Ship (OpenShip).** From feature branch to reviewed, CI-green draft PR on any LLM or local Ollama, while you keep the merge. [Quickstart](products/openship/) · [Docs](https://praison.ai/docs/features/openship)

<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset=".github/images/readme/praisonai-ship-dark.svg" />
    <img src=".github/images/readme/praisonai-ship-light.svg" alt="PraisonAI Ship (OpenShip) four-step flow on any LLM or local Ollama: 01 Ship PR with secret guard and AI PR text, 02 Self-Review on lockfile-filtered diff with typed findings, 03 PR Steward fixing CI, conflicts and threads up to a 3-try cap, and 04 Approvals and Merge using .praisonai/approvals.yml where a human always merges, with a changes requested loop back to PR Steward." width="880" />
  </picture>
</p>

**One agent turn.** What happens between your prompt and the answer, and what stops it. [Docs](https://praison.ai/docs/features/doom-loop-detection)

<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset=".github/images/readme/agent-turn-dark.svg" />
    <img src=".github/images/readme/agent-turn-light.svg" alt="One agent turn as a loop: build the prompt, call the model, approve risky tools, run the tool locally or in a sandbox, check it with guardrails and the loop guard, then answer or go round again, up to max_steps." width="880" />
  </picture>
</p>

**Bot gateway.** Ten channels in, one agent, team or flow behind them. [Docs](https://praison.ai/docs/features/bot-gateway)

<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset=".github/images/readme/bot-gateway-dark.svg" />
    <img src=".github/images/readme/bot-gateway-light.svg" alt="Ten channels on the left (Telegram, Discord, Slack, WhatsApp, Signal, Email, AgentMail, Linear, Webhook, Local) feed the praisonai-bot gateway. Incoming messages get pairing, rate limits and one session per chat; replies get streaming, voice and an outbox with retries. Approvals, media and rooms are built in. The gateway runs an Agent, AgentTeam or AgentFlow." width="880" />
  </picture>
</p>

**MCP both ways.** Your agents use MCP servers, and your editor uses your agents. [Docs](https://praison.ai/docs/mcp/transports)

<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset=".github/images/readme/mcp-both-ways-dark.svg" />
    <img src=".github/images/readme/mcp-both-ways-light.svg" alt="MCP both ways. Left: agents use any MCP server over stdio, SSE, Streamable HTTP or WebSocket, with OAuth sign-in and trust checks. Right: praisonai-mcp serves 85 tools to 22 clients such as Cursor, Claude Desktop, Claude Code, VS Code and Codex." width="880" />
  </picture>
</p>

## How the handover works (early access)

<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset=".github/images/readme/handover-dark.svg" />
    <img src=".github/images/readme/handover-light.svg" alt="Watch, Test, Hand over, Roll back, Record: a task moves to your own AI only after it passes a test, and moves back if quality drops" width="880" />
  </picture>
</p>

1. **Watch:** records how each task is done today.
2. **Test:** your own AI takes an exam made from real past work it never studied.
3. **Hand over:** a task moves to your own AI only when it passes.
4. **Roll back:** if quality drops, the task moves back automatically.
5. **Record:** every handover leaves a record your regulator can check.

<p align="center">
  <img src=".github/images/readme/handover-film.gif" alt="A hand-drawn machine tests three example tasks. Claim triage passes at 99% and Invoice check at 98%, so both move to your own AI. Discharge note scores 71%, so a person keeps it." width="800" />
  <br />
  <sub>An illustration with example tasks, not customer data.</sub>
</p>

**What is "your own AI"?** An open model, such as Llama, Qwen or Gemma, running on your own computers. Use it as it is, or train it on your own past work with [PraisonAI Train](https://praison.ai/docs/train) on your own GPU servers. Your team decides when to train; nothing trains automatically. Either way, a task moves to it only after it passes that exam.

**Why now.** Highly regulated teams, such as banks, insurers and hospitals, want AI but can't send customer data to outside models. The largest banks built private AI in-house; most mid-size banks and insurers can't fund a team to do that. From 6 January 2027, OpenAI also takes no new self-serve fine-tuning jobs ([notice](https://developers.openai.com/api/docs/deprecations)), so teams that customise models need models they own.

The handover is built on parts of this framework that are live today: tracing, evaluation, fine-tuning, model routing and local models. It is in early access, and we are taking on our first design partners. The framework stays free and MIT-licensed. Design partners, investors and press: enterprise@praison.ai or [praison.ai/enterprise](https://praison.ai/enterprise/).

## JavaScript and TypeScript

```bash
npm install praisonai
```

The TypeScript and JavaScript SDK has its own guide at [praison.ai/docs/js](https://praison.ai/docs/js).

```javascript
const { Agent } = require('praisonai');
const agent = new Agent({ instructions: 'You are a helpful AI assistant' });
agent.start('Write a movie script about a robot in Mars');
```

## Install

### Desktop app

<div align="center">
  <a href="https://github.com/MervinPraison/PraisonAI/releases/latest">
    <img src="https://img.shields.io/badge/Download_for_macOS-000000?style=for-the-badge&logo=apple&logoColor=white" alt="Download for macOS" />
  </a>
  &nbsp;&nbsp;
  <a href="https://github.com/MervinPraison/PraisonAI/releases/latest">
    <img src="https://img.shields.io/badge/Download_for_Windows-0078D6?style=for-the-badge&logo=windows&logoColor=white" alt="Download for Windows" />
  </a>
  &nbsp;&nbsp;
  <a href="https://github.com/MervinPraison/PraisonAI/releases/latest">
    <img src="https://img.shields.io/badge/Download_for_Linux-FCC624?style=for-the-badge&logo=linux&logoColor=black" alt="Download for Linux" />
  </a>
</div>

### Other ways to install

One-line installer:

```bash
curl -fsSL https://praison.ai/install.sh | bash
```

The full `praisonai` package, with the CLI and integrations. Add the `[dashboard]` extra for bots and the dashboard (`pip install "praisonai[dashboard]"`):

```
 ██████╗ ██████╗  █████╗ ██╗███████╗ ██████╗ ███╗   ██╗     █████╗ ██╗
 ██╔══██╗██╔══██╗██╔══██╗██║██╔════╝██╔═══██╗████╗  ██║    ██╔══██╗██║
 ██████╔╝██████╔╝███████║██║███████╗██║   ██║██╔██╗ ██║    ███████║██║
 ██╔═══╝ ██╔══██╗██╔══██║██║╚════██║██║   ██║██║╚██╗██║    ██╔══██║██║
 ██║     ██║  ██║██║  ██║██║███████║╚██████╔╝██║ ╚████║    ██║  ██║██║
 ╚═╝     ╚═╝  ╚═╝╚═╝  ╚═╝╚═╝╚══════╝ ╚═════╝ ╚═╝  ╚═══╝    ╚═╝  ╚═╝╚═╝

 pip install praisonai
```

<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset=".github/images/ui/claw-desktop-dark.webp" />
    <img src=".github/images/ui/claw-desktop-light.webp" alt="PraisonAI Claw dashboard in the Chat + Canvas layout: the chat on the left with a comparison table and a Python script the agent wrote, and the canvas on the right showing the table above the script" width="800" />
  </picture>
</p>

<div align="center">

<a href="https://trendshift.io/repositories/9130" target="_blank"><img src="https://trendshift.io/api/badge/repositories/9130" alt="MervinPraison%2FPraisonAI | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>

</div>

## Docs, community and licence

- **Documentation:** [praison.ai/docs](https://praison.ai/docs)
- **Questions and bugs:** [Discussions](https://github.com/MervinPraison/PraisonAI/discussions) · [Issues](https://github.com/MervinPraison/PraisonAI/issues)
- **Contributing:** [Contributing guide](https://github.com/MervinPraison/PraisonAI/blob/main/CONTRIBUTING.md)
- **Videos and news:** [YouTube](https://youtube.com/@MervinPraison) · [X](https://x.com/MervinPraison) · [LinkedIn](https://linkedin.com/in/mervinpraison)
- **Highlighted by Elon Musk:** [his post quoting our Grok 3 customer-support tutorial](https://x.com/elonmusk/status/1893870468249141688)
- **Desktop app:** macOS, Windows and Linux builds are on the [latest release](https://github.com/MervinPraison/PraisonAI/releases/latest)
- **Licence:** [MIT](https://github.com/MervinPraison/PraisonAI/blob/main/LICENSE)

---

## The PraisonAI Ecosystem

Start simple with the core SDK, or expand to full visual builders and dashboards when you're ready.

*   **Core SDK (`praisonaiagents`)**: For pure Python development. `pip install praisonaiagents`
*   💻 **PraisonAI CLI (`praisonai`)**: For terminal-based developers. `pip install praisonai`
*   🦅 **PraisonAI Dashboard**: Chat, agents, memory and knowledge, and connect agents to Telegram, Slack, or Discord. `pip install "praisonai[dashboard]"`
*   🔗 **Flow Visual Builder**: Drag-and-drop workflow creation. `pip install "praisonai[flow]"`
*   🤖 **PraisonAI UI**: Chat with a canvas for the tables and code your agents write. `pip install "praisonai[ui]"`

### JavaScript SDK

```bash
npm install praisonai
```

## Supported Providers & Features

Powered by 100+ LLMs (OpenAI, Anthropic, Gemini & local models).

<p align="center">
<img src="https://img.shields.io/badge/OpenAI-412991?style=flat&logo=openai&logoColor=white" alt="OpenAI" />
<img src="https://img.shields.io/badge/Anthropic-191919?style=flat&logo=anthropic&logoColor=white" alt="Anthropic" />
<img src="https://img.shields.io/badge/Google_Gemini-4285F4?style=flat&logo=google&logoColor=white" alt="Google Gemini" />
<img src="https://img.shields.io/badge/DeepSeek-566AB2?style=flat" alt="DeepSeek" />
<img src="https://img.shields.io/badge/Azure-0078D4?style=flat&logo=microsoftazure&logoColor=white" alt="Azure" />
<img src="https://img.shields.io/badge/Ollama-000000?style=flat" alt="Ollama" />
<img src="https://img.shields.io/badge/Groq-F05237?style=flat" alt="Groq" />
<img src="https://img.shields.io/badge/Mistral-FF7000?style=flat" alt="Mistral" />
<img src="https://img.shields.io/badge/Cerebras-F05A28?style=flat" alt="Cerebras" />
<img src="https://img.shields.io/badge/Cohere-39594D?style=flat" alt="Cohere" />
<img src="https://img.shields.io/badge/OpenRouter-6467F2?style=flat" alt="OpenRouter" />
<img src="https://img.shields.io/badge/Perplexity-20808D?style=flat" alt="Perplexity" />
<img src="https://img.shields.io/badge/Fireworks-FF6B35?style=flat" alt="Fireworks" />
<img src="https://img.shields.io/badge/AWS_Bedrock-FF9900?style=flat&logo=amazonaws&logoColor=white" alt="AWS Bedrock" />
<img src="https://img.shields.io/badge/xAI_Grok-000000?style=flat" alt="xAI Grok" />
<img src="https://img.shields.io/badge/Vertex_AI-4285F4?style=flat&logo=googlecloud&logoColor=white" alt="Vertex AI" />
<img src="https://img.shields.io/badge/HuggingFace-FFD21E?style=flat&logo=huggingface&logoColor=black" alt="HuggingFace" />
<img src="https://img.shields.io/badge/Together_AI-000000?style=flat" alt="Together AI" />
<img src="https://img.shields.io/badge/Databricks-FF3621?style=flat&logo=databricks&logoColor=white" alt="Databricks" />
<img src="https://img.shields.io/badge/Replicate-262626?style=flat" alt="Replicate" />
<img src="https://img.shields.io/badge/Cloudflare-F38020?style=flat&logo=cloudflare&logoColor=white" alt="Cloudflare" />
</p>

<details>
<summary><strong>View all 24 providers with examples</strong></summary>

| Provider | Example |
|----------|:-------:|
| OpenAI | [Example](examples/python/providers/openai/openai_gpt4_example.py) |
| Anthropic | [Example](examples/python/providers/anthropic/anthropic_claude_example.py) |
| Google Gemini | [Example](examples/python/providers/google/google_gemini_example.py) |
| Ollama | [Example](examples/python/providers/ollama/ollama-agents.py) |
| Groq | [Example](examples/python/providers/groq/kimi_with_groq_example.py) |
| DeepSeek | [Example](examples/python/providers/deepseek/deepseek_example.py) |
| xAI Grok | [Example](examples/python/providers/xai/xai_grok_example.py) |
| Mistral | [Example](examples/python/providers/mistral/mistral_example.py) |
| Cohere | [Example](examples/python/providers/cohere/cohere_example.py) |
| Perplexity | [Example](examples/python/providers/perplexity/perplexity_example.py) |
| Fireworks | [Example](examples/python/providers/fireworks/fireworks_example.py) |
| Together AI | [Example](examples/python/providers/together/together_ai_example.py) |
| OpenRouter | [Example](examples/python/providers/openrouter/openrouter_example.py) |
| HuggingFace | [Example](examples/python/providers/huggingface/huggingface_example.py) |
| Azure OpenAI | [Example](examples/python/providers/azure/azure_openai_example.py) |
| AWS Bedrock | [Example](examples/python/providers/aws/aws_bedrock_example.py) |
| Google Vertex | [Example](examples/python/providers/vertex/vertex_example.py) |
| Databricks | [Example](examples/python/providers/databricks/databricks_example.py) |
| Cloudflare | [Example](examples/python/providers/cloudflare/cloudflare_example.py) |
| AI21 | [Example](examples/python/providers/ai21/ai21_example.py) |
| Replicate | [Example](examples/python/providers/replicate/replicate_example.py) |
| SageMaker | [Example](examples/python/providers/sagemaker/sagemaker_example.py) |
| Moonshot | [Example](examples/python/providers/moonshot/moonshot_example.py) |
| vLLM | [Example](examples/python/providers/vllm/vllm_example.py) |

</details>

---

## Why PraisonAI?

| | Feature | How |
|--|---------|-----|
| 🔌 | **MCP Protocol** — stdio, HTTP, WebSocket, SSE | `tools=MCP("npx ...")` |
| 🧠 | **Planning Mode** — plan → execute → reason | `planning=True` |
| 🔍 | **Deep Research** — multi-step autonomous research | [Docs](https://praison.ai/docs/agents/deep-research) |
| 🤖 | **External Agents** — orchestrate Claude Code, Gemini CLI, Codex | [Docs](https://praison.ai/docs/code/external-agents) |
| 🔄 | **Agent Handoffs** — seamless conversation passing | `handoffs=[other_agent]` |
| 🛡️ | **Guardrails** — input/output validation | [Docs](https://praison.ai/docs/concepts/guardrails) |
|  | **Web Search + Fetch** — native browsing | `web=True` |
| 🪞 | **Self Reflection** — agent reviews its own output | [Docs](https://praison.ai/docs/concepts/reflection) |
| 🔀 | **Workflow Patterns** — route, parallel, loop, repeat | [Docs](https://praison.ai/docs/concepts/agentflow) |
| 🧠 | **Memory (zero deps)** — works out of the box | `memory=True` |

<details>
<summary><strong>View all 25 features</strong></summary>

| | Feature | How |
|--|---------|-----|
| 💡 | **Prompt Caching** — reduce latency + cost | `caching=True` |
| 💾 | **Sessions + Auto-Save** — persistent state across restarts | `auto_save="my-project"` |
| 💭 | **Thinking Budgets** — control reasoning depth | `agent.thinking_budget = 1024` |
| 📚 | **RAG + Quality-Based RAG** — auto quality scoring retrieval | [Docs](https://praison.ai/docs/concepts/rag) |
| 📊 | **Model Router** — auto-routes to cheapest capable model | [Docs](https://praison.ai/docs/features/model-router) |
| 🧊 | **Shadow Git Checkpoints** — auto-rollback on failure | [Docs](https://praison.ai/docs/features/checkpoints) |
| 📡 | **A2A Protocol** — agent-to-agent interop | [Docs](https://praison.ai/docs/features/a2a) |
| 📏 | **Context Compaction** — never hit token limits | [Docs](https://praison.ai/docs/features/context-compaction) |
| 📡 | **Telemetry** — OpenTelemetry traces, spans, metrics | [Docs](https://praison.ai/docs/features/telemetry) |
| 📜 | **Policy Engine** — declarative agent behavior control | [Docs](https://praison.ai/docs/features/policy-engine) |
| 🔄 | **Background Tasks** — fire-and-forget agents | [Docs](https://praison.ai/docs/features/background-tasks) |
| 🔁 | **Doom Loop Detection** — auto-recovery from stuck agents | [Docs](https://praison.ai/docs/features/doom-loop-detection) |
| 🕸️ | **Graph Memory** — Neo4j-style relationship tracking | [Docs](https://praison.ai/docs/features/graph-memory) |
| 🏖️ | **Sandbox Execution** — isolated code execution | [Docs](https://praison.ai/docs/features/sandbox) |
| 🖥️ | **Bot Gateway** — multi-agent routing across channels | [Docs](https://praison.ai/docs/features/bot-gateway) |

</details>

---

## Using Python Code

<details>
<summary><strong>Show Python examples: single agent, multi-agent, MCP, tools, databases, Claw, Langflow, UI</strong></summary>

> Unsure whether a result is a bug or model randomness? Check the [SDK Behavior Matrix](https://github.com/MervinPraison/PraisonAI/blob/main/src/praisonai-agents/docs/sdk-behavior-matrix.md) for `stream`, memory prefetch, structured output, teams and AG-UI.

### 1. Single Agent

```python
from praisonai import Agent
agent = Agent(instructions="You are a helpful AI assistant")
agent.start("Write a movie script about a robot in Mars")
```

### 2. Multi Agents

```python
from praisonai import Agent, Agents

research_agent = Agent(instructions="Research about AI")
summarise_agent = Agent(instructions="Summarise research agent's findings")
agents = Agents(agents=[research_agent, summarise_agent])
agents.start()
```

### 3. MCP (Model Context Protocol)

```python
from praisonai import Agent, MCP

# stdio - Local NPX/Python servers
agent = Agent(tools=MCP("npx @modelcontextprotocol/server-memory"))

# Streamable HTTP - Production servers
agent = Agent(tools=MCP("https://api.example.com/mcp"))

# WebSocket - Real-time bidirectional
agent = Agent(tools=MCP("wss://api.example.com/mcp", auth_token="token"))

# With environment variables
agent = Agent(
    tools=MCP(
        command="npx",
        args=["-y", "@modelcontextprotocol/server-brave-search"],
        env={"BRAVE_API_KEY": "your-key"}
    )
)
```

> 📖 [Full MCP docs](https://praison.ai/docs/mcp/transports) — stdio, HTTP, WebSocket, SSE transports

### 4. Custom Tools

```python
from praisonai import Agent, tool

@tool
def search(query: str) -> str:
    """Search the web for information."""
    return f"Results for: {query}"

@tool
def calculate(expression: str) -> float:
    """Safely evaluate a numeric arithmetic expression."""
    import ast
    import operator
    
    # Define allowed operations
    _OPS = {
        ast.Add: operator.add,
        ast.Sub: operator.sub,
        ast.Mult: operator.mul,
        ast.Div: operator.truediv,
        ast.Pow: operator.pow,
        ast.USub: operator.neg,
        ast.UAdd: operator.pos,
    }
    
    def _safe_eval(node):
        if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
            return node.value
        elif isinstance(node, ast.BinOp) and type(node.op) in _OPS:
            return _OPS[type(node.op)](_safe_eval(node.left), _safe_eval(node.right))
        elif isinstance(node, ast.UnaryOp) and type(node.op) in _OPS:
            return _OPS[type(node.op)](_safe_eval(node.operand))
        else:
            raise ValueError("Unsupported expression")
    
    try:
        return _safe_eval(ast.parse(expression, mode="eval").body)
    except (ValueError, SyntaxError, TypeError, ZeroDivisionError, OverflowError):
        raise ValueError("Invalid arithmetic expression")

agent = Agent(
    instructions="You are a helpful assistant",
    tools=[search, calculate]
)
agent.start("Search for AI news and calculate 15*4")
```

> ⚠️ **Security Note:** Never use `eval()`, `exec()`, or `subprocess` in tool functions that process LLM-generated or user-supplied input. Always validate and sanitize inputs to prevent code injection attacks.
> 📖 [Full tools docs](https://praison.ai/docs/tools/tools) — BaseTool, tool packages, 100+ built-in tools

### 5. Persistence (Databases)

```python
from praisonai import Agent, db

agent = Agent(
    name="Assistant",
    memory={
        "db": db(database_url="postgresql://localhost/mydb"),
        "session_id": "my-session",
    },
)
agent.chat("Hello!")  # Auto-persists messages, runs, traces
```

> 📖 [Full persistence docs](https://praison.ai/docs/databases/overview) — PostgreSQL, MySQL, SQLite, MongoDB, Redis, and 20+ more

### 6. PraisonAI Dashboard

Connect your AI agents to **Telegram, Discord, Slack, WhatsApp** and more — all from a single command.

```bash
pip install "praisonai[dashboard]"   # or: "praisonai[claw]" (the same extra)
praisonai dashboard                 # or: praisonai claw (the same app)
```

#### Required Environment Variables

Copy `.env.example` to `.env` and configure the following variables:

| Variable | Required | Description |
|----------|----------|-------------|
| `OPENAI_API_KEY` | Yes | OpenAI API key for all LLM calls |
| `TAVILY_API_KEY` | Yes (Dashboard) | Tavily key for the built-in web-search tool. Get one free at https://app.tavily.com |

Open **http://localhost:8082** — the dashboard opens in **Chat + Canvas**: the chat on the left, and the tables, code and files your agents write on a canvas beside it (sort, copy, download, compare versions). Every other page (Agents, Memory, Knowledge, Channels, Guardrails, Cron, and more) is in the sidebar or the command palette (⌘K). Add messaging channels directly from the UI.

> 📖 [Full Dashboard docs](https://praison.ai/docs/concepts/claw) — platform tokens, CLI options, Docker, and YAML agent mode

### 7. Langflow Integration (Visual Flow Builder)

Build multi-agent workflows visually with **drag-and-drop** components in Langflow.

```bash
pip install "praisonai[flow]"
praisonai flow
```

Open **http://localhost:7861** — use the **Agent** and **Agent Team** components to create sequential or parallel workflows. Connect Chat Input → Agent Team → Chat Output for instant multi-agent pipelines.

> 📖 [Full Flow docs](https://praison.ai/docs/concepts/agentflow) — visual agent building, component reference, and deployment

### 8. PraisonAI UI (Chat + Canvas)

Chat with your AI agents; the tables and code they write open on a canvas beside the chat.

```bash
pip install "praisonai[ui]"
praisonai ui            # chat           → http://localhost:8081
praisonai ui agents     # YAML agents
praisonai ui bot        # bot interface
praisonai ui realtime   # realtime voice
```

<p align="center">
  <img src=".github/images/ui/ui-welcome-desktop-light.webp" alt="praisonai ui opening a new chat: the PraisonAI Chat title, the app's welcome greeting under it, four starter prompts and the message box" width="400" />
  <img src=".github/images/ui/ui-desktop-dark.webp" alt="praisonai ui in dark mode: the chat on the left and the canvas with the comparison table and the benchmark script on the right" width="400" />
</p>

- **Welcome:** each app greets you in the new-chat hero, in every layout. Set the text with `UIPreset(welcome=...)` or your own `@aiui.welcome` handler.
- **Layout:** Chat + Canvas by default. Pick another for one run with `AIUI_LAYOUT=chat` (no canvas), `workbench`, `command`, `guided` or `mission`, or switch from the command palette (⌘K).
- **Look:** light and dark follow the toggle in the top bar; ⌘K → **Switch look: Pro** swaps the Paper look for the plain one.
- **Stop:** the Stop button cancels the agent's reply. A reply that sends nothing for 10 minutes is cancelled too (`AIUI_REPLY_IDLE_TIMEOUT`, in seconds; `0` turns it off).
- **Uploads:** request bodies are capped at 25 MiB (`AIUI_MAX_BODY_MB`; `0` turns it off).
- **Data:** chat history is saved by PraisonAI under `~/.praisonai/sessions` (set `PRAISONAI_HOME` to move it); the UI's own settings live in `~/.praisonaiui` (set `AIUI_DATA_DIR` to move them). To keep both on a mounted volume, set both variables.
- An existing `~/.praisonai/claw/app.py` from an older install keeps aiui's own default layout (Chat, no canvas) and has no welcome greeting; delete it to get the new default app, or add `layout="chat-canvas"` to its `configure_host(...)` call.

</details>

---

## Using YAML (No Code)

<details>
<summary><strong>Show YAML examples</strong></summary>

### Example 1: Two Agents Working Together

Create `agents.yaml`:

```yaml
framework: praisonai
topic: "Write a blog post about AI"

agents:
  researcher:
    role: Research Analyst
    goal: Research AI trends and gather information
    instructions: "Find accurate information about AI trends"
    
  writer:
    role: Content Writer
    goal: Write engaging blog posts
    instructions: "Write clear, engaging content based on research"
```

Run with:
```bash
praisonai agents.yaml
```

> The agents automatically work together sequentially

### Example 2: Agent with Custom Tool

Create two files in the same folder:

**agents.yaml:**
```yaml
framework: praisonai
topic: "Calculate the sum of 25 and 15"

agents:
  calculator_agent:
    role: Calculator
    goal: Perform calculations
    instructions: "Use the add_numbers tool to help with calculations"
    tools:
      - add_numbers
```

**tools.py:**
```python
def add_numbers(a: float, b: float) -> float:
    """
    Add two numbers together.
    
    Args:
        a: First number
        b: Second number
    
    Returns:
        The sum of a and b
    """
    return a + b
```

Run with:
```bash
praisonai agents.yaml
```

> 💡 **Tips:** 
> - Use the function name (e.g., `add_numbers`) in the tools list, not the file name
> - Tools in `tools.py` are automatically discovered
> - The function's docstring helps the AI understand how to use it

</details>

---

## CLI Quick Reference

| Category | Commands |
|----------|----------|
| **Execution** | `praisonai`, `--auto`, `--interactive`, `--chat` |
| **Research** | `research`, `--query-rewrite`, `--deep-research` |
| **Planning** | `--planning`, `--planning-tools`, `--planning-reasoning` |
| **Workflows** | `workflow run`, `workflow list`, `workflow auto` |
| **Memory** | `memory show`, `memory add`, `memory search`, `memory clear` |
| **Knowledge** | `knowledge add`, `knowledge query`, `knowledge list` |
| **Sessions** | `session list`, `session resume`, `session delete` |
| **Tools** | `tools list`, `tools info`, `tools search` |
| **MCP** | `mcp list`, `mcp create`, `mcp enable` |
| **Development** | `commit`, `docs`, `checkpoint`, `hooks` |
| **Scheduling** | `schedule start`, `schedule list`, `schedule stop` |

> 📖 [Full CLI reference](https://praison.ai/docs/cli/cli-reference)

---

## Key Features

<details>
<summary><strong>Show all features by category</strong></summary>

<details open>
<summary><strong>🤖 Core Agents</strong></summary>

| Feature | Code | Docs |
|---------|:----:|:----:|
| Single Agent | [Example](examples/python/agents/single-agent.py) | [📖](https://praison.ai/docs/agents/single) |
| Multi Agents | [Example](examples/python/general/mini_agents_example.py) | [📖](https://praison.ai/docs/concepts/agents) |
| Auto Agents | [Example](examples/python/general/auto_agents_example.py) | [📖](https://praison.ai/docs/features/autoagents) |
| Self Reflection AI Agents | [Example](examples/python/concepts/self-reflection-details.py) | [📖](https://praison.ai/docs/concepts/reflection) |
| Reasoning AI Agents | [Example](examples/python/concepts/reasoning-extraction.py) | [📖](https://praison.ai/docs/features/reasoning) |
| Multi Modal AI Agents | [Example](examples/python/general/multimodal.py) | [📖](https://praison.ai/docs/features/multimodal) |

</details>

<details>
<summary><strong>🔄 Workflows</strong></summary>

| Feature | Code | Docs |
|---------|:----:|:----:|
| Simple Workflow | [Example](examples/python/workflows/simple_workflow.py) | [📖](https://praison.ai/docs/concepts/agentflow) |
| Workflow with Agents | [Example](examples/python/workflows/workflow_with_agents.py) | [📖](https://praison.ai/docs/concepts/agentflow) |
| Agentic Routing (`route()`) | [Example](examples/python/workflows/workflow_routing.py) | [📖](https://praison.ai/docs/features/routing) |
| Parallel Execution (`parallel()`) | [Example](examples/python/workflows/workflow_parallel.py) | [📖](https://praison.ai/docs/features/parallelisation) |
| Loop over List/CSV (`loop()`) | [Example](examples/python/workflows/workflow_loop_csv.py) | [📖](https://praison.ai/docs/features/repetitive) |
| Evaluator-Optimizer (`repeat()`) | [Example](examples/python/workflows/workflow_repeat.py) | [📖](https://praison.ai/docs/concepts/evaluation) |
| Conditional Steps | [Example](examples/python/workflows/workflow_conditional.py) | [📖](https://praison.ai/docs/concepts/agentflow) |
| Workflow Branching | [Example](examples/python/workflows/workflow_branching.py) | [📖](https://praison.ai/docs/concepts/agentflow) |
| Workflow Early Stop | [Example](examples/python/workflows/workflow_early_stop.py) | [📖](https://praison.ai/docs/concepts/agentflow) |
| Workflow Checkpoints | [Example](examples/python/workflows/workflow_checkpoints.py) | [📖](https://praison.ai/docs/concepts/agentflow) |

</details>

<details>
<summary><strong>💻 Code & Development</strong></summary>

| Feature | Code | Docs |
|---------|:----:|:----:|
| Code Interpreter Agents | [Example](examples/python/agents/code-agent.py) | [📖](https://praison.ai/docs/features/codeagent) |
| AI Code Editing Tools | [Example](examples/python/code/code_editing_example.py) | [📖](https://praison.ai/docs/code/editing) |
| External Agents (All) | [Example](examples/python/code/external_agents_example.py) | [📖](https://praison.ai/docs/code/external-agents) |
| Claude Code CLI | [Example](examples/python/code/claude_code_example.py) | [📖](https://praison.ai/docs/code/claude-code) |
| Gemini CLI | [Example](examples/python/code/gemini_cli_example.py) | [📖](https://praison.ai/docs/code/gemini-cli) |
| Codex CLI | [Example](examples/python/code/codex_cli_example.py) | [📖](https://praison.ai/docs/code/codex-cli) |
| Cursor CLI | [Example](examples/python/code/cursor_cli_example.py) | [📖](https://praison.ai/docs/code/cursor-cli) |

</details>

<details>
<summary><strong>🧠 Memory & Knowledge</strong></summary>

| Feature | Code | Docs |
|---------|:----:|:----:|
| Memory (Short & Long Term) | [Example](examples/python/general/memory_example.py) | [📖](https://praison.ai/docs/concepts/memory) |
| File-Based Memory | [Example](examples/python/general/memory_example.py) | [📖](https://praison.ai/docs/concepts/memory) |
| Claude Memory Tool | [Example](examples/python/memory/claude_memory_example.py) | [📖](https://praison.ai/docs/features/claude-memory-tool) |
| Add Custom Knowledge | [Example](examples/python/concepts/knowledge-agents.py) | [📖](https://praison.ai/docs/concepts/knowledge) |
| RAG Agents | [Example](examples/python/concepts/rag-agents.py) | [📖](https://praison.ai/docs/concepts/rag) |
| Chat with PDF Agents | [Example](examples/python/concepts/chat-with-pdf.py) | [📖](https://praison.ai/docs/features/chat-with-pdf) |
| Data Readers (PDF, DOCX, etc.) | [CLI](https://praison.ai/docs/cli/knowledge) | [📖](https://praison.ai/docs/features/chunking-strategies) |
| Vector Store Selection | [CLI](https://praison.ai/docs/cli/knowledge) | [📖](https://praison.ai/docs/features/knowledge-backends) |
| Retrieval Strategies | [CLI](https://praison.ai/docs/cli/knowledge) | [📖](https://praison.ai/docs/features/retrieval-strategies) |
| Rerankers | [CLI](https://praison.ai/docs/cli/knowledge) | [📖](https://praison.ai/docs/features/smart-retrieval) |
| Index Types (Vector/Keyword/Hybrid) | [CLI](https://praison.ai/docs/cli/knowledge) | [📖](https://praison.ai/docs/features/incremental-indexing) |
| Query Engines (Sub-Question, etc.) | [CLI](https://praison.ai/docs/cli/knowledge) | [📖](https://praison.ai/docs/features/retrieval) |

</details>

<details>
<summary><strong>🔬 Research & Intelligence</strong></summary>

| Feature | Code | Docs |
|---------|:----:|:----:|
| Deep Research Agents | [Example](examples/python/agents/research-agent.py) | [📖](https://praison.ai/docs/agents/deep-research) |
| Query Rewriter Agent | [Example](examples/python/agents/query-rewriter-agent.py) | [📖](https://praison.ai/docs/agents/query-rewriter) |
| Native Web Search | [Example](examples/python/agents/websearch-agent.py) | [📖](https://praison.ai/docs/agents/websearch) |
| Built-in Search Tools | [Example](examples/python/agents/websearch-agent.py) | [📖](https://praison.ai/docs/tools/tavily) |
| Unified Web Search | [Example](examples/python/web_search_example.py) | [📖](https://praison.ai/docs/tools/web-search) |
| Web Fetch (Anthropic) | [Example](examples/python/agents/web-fetch-agent.py) | [📖](https://praison.ai/docs/features/model-capabilities) |

</details>

<details>
<summary><strong>📋 Planning & Execution</strong></summary>

| Feature | Code | Docs |
|---------|:----:|:----:|
| Planning Mode | [Example](examples/python/agents/planning-agent.py) | [📖](https://praison.ai/docs/concepts/planning) |
| Planning Tools | [Example](examples/python/agents/planning-agent.py) | [📖](https://praison.ai/docs/concepts/planning) |
| Planning Reasoning | [Example](examples/python/agents/planning-agent.py) | [📖](https://praison.ai/docs/concepts/planning) |
| Prompt Chaining | [Example](examples/python/general/prompt_chaining.py) | [📖](https://praison.ai/docs/features/promptchaining) |
| Evaluator Optimiser | [Example](examples/python/general/evaluator-optimiser.py) | [📖](https://praison.ai/docs/concepts/evaluation) |
| Orchestrator Workers | [Example](examples/python/general/orchestrator-workers.py) | [📖](https://praison.ai/docs/concepts/orchestration) |

</details>

<details>
<summary><strong>👥 Specialized Agents</strong></summary>

| Feature | Code | Docs |
|---------|:----:|:----:|
| Data Analyst Agent | [Example](examples/python/agents/data-analyst-agent.py) | [📖](https://praison.ai/docs/agents/data-analyst) |
| Finance Agent | [Example](examples/python/agents/finance-agent.py) | [📖](https://praison.ai/docs/agents/finance) |
| Shopping Agent | [Example](examples/python/agents/shopping-agent.py) | [📖](https://praison.ai/docs/agents/shopping) |
| Recommendation Agent | [Example](examples/python/agents/recommendation-agent.py) | [📖](https://praison.ai/docs/agents/recommendation) |
| Wikipedia Agent | [Example](examples/python/agents/wikipedia-agent.py) | [📖](https://praison.ai/docs/agents/wikipedia) |
| Programming Agent | [Example](examples/python/agents/programming-agent.py) | [📖](https://praison.ai/docs/agents/programming) |
| Math Agents | [Example](examples/python/agents/math-agent.py) | [📖](https://praison.ai/docs/features/mathagent) |
| Markdown Agent | [Example](examples/python/agents/markdown-agent.py) | [📖](https://praison.ai/docs/agents/markdown) |
| Prompt Expander Agent | [Example](examples/python/agents/prompt-expander-agent.py) | [📖](https://praison.ai/docs/agents/prompt-expander) |

</details>

<details>
<summary><strong>🎨 Media & Multimodal</strong></summary>

| Feature | Code | Docs |
|---------|:----:|:----:|
| Image Generation Agent | [Example](examples/python/image/image-agent.py) | [📖](https://praison.ai/docs/features/image-generation) |
| Image to Text Agent | [Example](examples/python/agents/image-to-text-agent.py) | [📖](https://praison.ai/docs/agents/image-to-text) |
| Video Agent | [Example](examples/python/agents/video-agent.py) | [📖](https://praison.ai/docs/agents/video) |
| Camera Integration | [Example](examples/python/camera/) | [📖](https://praison.ai/docs/features/camera-integration) |

</details>

<details>
<summary><strong>🔌 Protocols & Integration</strong></summary>

| Feature | Code | Docs |
|---------|:----:|:----:|
| MCP Transports | [Example](examples/python/mcp/mcp-transports-overview.py) | [📖](https://praison.ai/docs/mcp/transports) |
| WebSocket MCP | [Example](examples/python/mcp/websocket-mcp.py) | [📖](https://praison.ai/docs/mcp/sse-transport) |
| MCP Security | [Example](examples/python/mcp/mcp-security.py) | [📖](https://praison.ai/docs/mcp/transports) |
| MCP Resumability | [Example](examples/python/mcp/mcp-resumability.py) | [📖](https://praison.ai/docs/mcp/sse-transport) |
| MCP Config Management | [Docs](https://praison.ai/docs/cli/mcp) | [📖](https://praison.ai/docs/cli/mcp) |
| LangChain Integrated Agents | [Example](examples/python/general/langchain_example.py) | [📖](https://praison.ai/docs/features/langchain) |

</details>

<details>
<summary><strong>🛡️ Safety & Control</strong></summary>

| Feature | Code | Docs |
|---------|:----:|:----:|
| Guardrails | [Example](examples/python/guardrails/comprehensive-guardrails-example.py) | [📖](https://praison.ai/docs/concepts/guardrails) |
| Human Approval | [Example](examples/python/general/human_approval_example.py) | [📖](https://praison.ai/docs/concepts/approval) |
| Rules & Instructions | [Docs](https://praison.ai/docs/features/rules) | [📖](https://praison.ai/docs/features/rules) |

</details>

<details>
<summary><strong>⚙️ Advanced Features</strong></summary>

| Feature | Code | Docs |
|---------|:----:|:----:|
| Async & Parallel Processing | [Example](examples/python/general/async_example.py) | [📖](https://praison.ai/docs/features/async) |
| Parallelisation | [Example](examples/python/general/parallelisation.py) | [📖](https://praison.ai/docs/features/parallelisation) |
| Repetitive Agents | [Example](examples/python/concepts/repetitive-agents.py) | [📖](https://praison.ai/docs/features/repetitive) |
| Agent Handoffs | [Example](examples/python/handoff/handoff_basic.py) | [📖](https://praison.ai/docs/concepts/handoffs) |
| Stateful Agents | [Example](examples/python/stateful/workflow-state-example.py) | [📖](https://praison.ai/docs/features/stateful-agents) |
| Autonomous Workflow | [Example](examples/python/general/autonomous-agent.py) | [📖](https://praison.ai/docs/concepts/autonomy) |
| Structured Output Agents | [Example](examples/python/general/structured_agents_example.py) | [📖](https://praison.ai/docs/features/structured) |
| Model Router | [Example](examples/python/agents/router-agent-cost-optimization.py) | [📖](https://praison.ai/docs/features/model-router) |
| Prompt Caching | [Example](examples/python/agents/prompt-caching-agent.py) | [📖](https://praison.ai/docs/features/model-capabilities) |
| Fast Context | [Example](examples/context/00_agent_fast_context_basic.py) | [📖](https://praison.ai/docs/features/fast-context) |

</details>

<details>
<summary><strong>🛠️ Tools & Configuration</strong></summary>

| Feature | Code | Docs |
|---------|:----:|:----:|
| 100+ Custom Tools | [Example](examples/python/general/tools_example.py) | [📖](https://praison.ai/docs/tools/tools) |
| YAML Configuration | [Example](examples/cookbooks/yaml/secondary_market_research_agents.yaml) | [📖](https://praison.ai/docs/developers/agents-playbook) |
| 100+ LLM Support | [Example](examples/python/providers/openai/openai_gpt4_example.py) | [📖](https://praison.ai/docs/models) |
| Callback Agents | [Example](examples/python/general/advanced-callback-systems.py) | [📖](https://praison.ai/docs/concepts/hooks) |
| Hooks | [Example](examples/python/hooks/hooks_example.py) | [📖](https://praison.ai/docs/concepts/hooks) |
| Middleware System | [Example](examples/middleware/basic_middleware.py) | [📖](https://praison.ai/docs/features/middleware) |
| Configurable Model | [Example](examples/middleware/configurable_model.py) | [📖](https://praison.ai/docs/features/configurable-model) |
| Rate Limiter | [Example](examples/middleware/rate_limiter.py) | [📖](https://praison.ai/docs/features/rate-limiter) |
| Injected Tool State | [Example](examples/middleware/injected_state.py) | [📖](https://praison.ai/docs/features/injected-state) |
| Shadow Git Checkpoints | [Example](examples/checkpoints/basic_checkpoint.py) | [📖](https://praison.ai/docs/features/checkpoints) |
| Background Tasks | [Example](examples/background/basic_background.py) | [📖](https://praison.ai/docs/features/background-tasks) |
| Policy Engine | [Example](examples/policy/basic_policy.py) | [📖](https://praison.ai/docs/features/policy-engine) |
| Thinking Budgets | [Example](examples/thinking/basic_thinking.py) | [📖](https://praison.ai/docs/features/thinking-budgets) |
| Output Styles | [Example](examples/output/basic_output.py) | [📖](https://praison.ai/docs/features/output-styles) |
| Context Compaction | [Example](examples/compaction/basic_compaction.py) | [📖](https://praison.ai/docs/features/context-compaction) |

</details>

<details>
<summary><strong>📊 Monitoring & Management</strong></summary>

| Feature | Code | Docs |
|---------|:----:|:----:|
| Sessions Management | [Example](examples/python/sessions/comprehensive-session-management.py) | [📖](https://praison.ai/docs/concepts/session-management) |
| Auto-Save Sessions | [Docs](https://praison.ai/docs/cli/session) | [📖](https://praison.ai/docs/cli/session) |
| History in Context | [Docs](https://praison.ai/docs/cli/session) | [📖](https://praison.ai/docs/cli/session) |
| Telemetry | [Example](examples/python/telemetry/production-telemetry-example.py) | [📖](https://praison.ai/docs/features/telemetry) |
| Langfuse Tracing | [Docs](https://praison.ai/docs/observability/langfuse) | [📖](https://praison.ai/docs/observability/langfuse) |
| Project Docs (.praison/docs/) | [Docs](https://praison.ai/docs/cli/docs) | [📖](https://praison.ai/docs/cli/docs) |
| AI Commit Messages | [Docs](https://praison.ai/docs/cli/commit) | [📖](https://praison.ai/docs/cli/commit) |
| @Mentions in Prompts | [Docs](https://praison.ai/docs/cli/mentions) | [📖](https://praison.ai/docs/cli/mentions) |

</details>

<details>
<summary><strong>🖥️ CLI Features</strong></summary>

| Feature | Code | Docs |
|---------|:----:|:----:|
| Slash Commands | [Example](examples/python/cli/slash_commands_example.py) | [📖](https://praison.ai/docs/cli/slash-commands) |
| Autonomy Modes | [Example](examples/python/cli/autonomy_modes_example.py) | [📖](https://praison.ai/docs/cli/autonomy-modes) |
| Cost Tracking | [Example](examples/python/cli/cost_tracking_example.py) | [📖](https://praison.ai/docs/cli/cost-tracking) |
| Repository Map | [Example](examples/python/cli/repo_map_example.py) | [📖](https://praison.ai/docs/cli/repo-map) |
| Interactive TUI | [Example](examples/python/cli/interactive_tui_example.py) | [📖](https://praison.ai/docs/cli/interactive-tui) |
| Git Integration | [Example](examples/python/cli/git_integration_example.py) | [📖](https://praison.ai/docs/cli/git-integration) |
| Sandbox Execution | [Example](examples/python/cli/sandbox_execution_example.py) | [📖](https://praison.ai/docs/cli/sandbox-execution) |
| CLI Compare | [Example](examples/compare/cli_compare_basic.py) | [📖](https://praison.ai/docs/cli/compare) |
| Profile/Benchmark | [Docs](https://praison.ai/docs/cli/profile) | [📖](https://praison.ai/docs/cli/profile) |
| Auto Mode | [Docs](https://praison.ai/docs/cli/auto) | [📖](https://praison.ai/docs/cli/auto) |
| Init | [Docs](https://praison.ai/docs/cli/init) | [📖](https://praison.ai/docs/cli/init) |
| File Input | [Docs](https://praison.ai/docs/cli/file-input) | [📖](https://praison.ai/docs/cli/file-input) |
| Final Agent | [Docs](https://praison.ai/docs/cli/final-agent) | [📖](https://praison.ai/docs/cli/final-agent) |
| Max Tokens | [Docs](https://praison.ai/docs/cli/max-tokens) | [📖](https://praison.ai/docs/cli/max-tokens) |

</details>

<details>
<summary><strong>🧪 Evaluation</strong></summary>

| Feature | Code | Docs |
|---------|:----:|:----:|
| Accuracy Evaluation | [Example](examples/eval/accuracy_example.py) | [📖](https://praison.ai/docs/cli/eval) |
| Performance Evaluation | [Example](examples/eval/performance_example.py) | [📖](https://praison.ai/docs/cli/eval) |
| Reliability Evaluation | [Example](examples/eval/reliability_example.py) | [📖](https://praison.ai/docs/cli/eval) |
| Criteria Evaluation | [Example](examples/eval/criteria_example.py) | [📖](https://praison.ai/docs/cli/eval) |

</details>

<details>
<summary><strong>🎯 Agent Skills</strong></summary>

| Feature | Code | Docs |
|---------|:----:|:----:|
| Skills Management | [Example](examples/skills/basic_skill_usage.py) | [📖](https://praison.ai/docs/concepts/skills) |
| Custom Skills | [Example](examples/skills/custom_skill_example.py) | [📖](https://praison.ai/docs/concepts/skills) |

</details>

<details>
<summary><strong>⏰ 24/7 Scheduling</strong></summary>

| Feature | Code | Docs |
|---------|:----:|:----:|
| Agent Scheduler | [Example](examples/python/scheduled_agents/news_checker_live.py) | [📖](https://praison.ai/docs/cli/scheduler) |

</details>

</details>

---

## Performance

PraisonAI keeps framework overhead microsecond-class: creating an `Agent` (one tool, no LLM call) averaged **46 μs** in our 2026-10-15 run, so per-agent setup is negligible next to model latency in multi-agent workloads.

| Performance Metric | PraisonAI | Measured |
|--------------------|-----------|----------|
| Avg Agent instantiation (1 tool, 1000 iterations) | **46 μs** | 2026-10-15 · praisonaiagents 1.7.12 |

Methodology, comparisons and how to reproduce: [benchmarks/BENCHMARK_RESULTS.md](https://github.com/MervinPraison/PraisonAI/blob/main/src/praisonai-agents/benchmarks/BENCHMARK_RESULTS.md) · [docs](https://praison.ai/docs/developers/benchmarks)

---

---

## Langfuse Tracing

```bash
pip install "praisonai[langfuse]"
praisonai langfuse
```

<p align="center">
  <img src=".github/images/langfuse.png" alt="PraisonAI Langfuse Tracing" width="800" />
</p>

---

## Video Tutorials

Learn PraisonAI through our comprehensive video series:

<details>
<summary><strong>View all 22 video tutorials</strong></summary>

| Topic | Video |
|-------|--------|
| AI Agents with Self Reflection | [](https://www.youtube.com/watch?v=vLXobEN2Vc8) |
| Reasoning Data Generating Agent | [](https://www.youtube.com/watch?v=fUT332Y2zA8) |
| AI Agents with Reasoning | [](https://www.youtube.com/watch?v=KNDVWGN3TpM) |
| Multimodal AI Agents | [](https://www.youtube.com/watch?v=hjAWmUT1qqY) |
| AI Agents Workflow | [](https://www.youtube.com/watch?v=yWTH44QPl2A) |
| Async AI Agents | [](https://www.youtube.com/watch?v=VhVQfgo00LE) |
| Mini AI Agents | [](https://www.youtube.com/watch?v=OkvYp5aAGSg) |
| AI Agents with Memory | [](https://www.youtube.com/watch?v=1hVfVxvPnnQ) |
| Repetitive Agents | [](https://www.youtube.com/watch?v=dAYGxsjDOPg) |
| Introduction | [](https://www.youtube.com/watch?v=Fn1lQjC0GO0) |
| Tools Overview | [](https://www.youtube.com/watch?v=XaQRgRpV7jo) |
| Custom Tools | [](https://www.youtube.com/watch?v=JSU2Rndh06c) |
| Firecrawl Integration | [](https://www.youtube.com/watch?v=UoqUDcLcOYo) |
| User Interface | [](https://www.youtube.com/watch?v=tg-ZjNl3OCg) |
| Crawl4AI Integration | [](https://www.youtube.com/watch?v=KAvuVUh0XU8) |
| Chat Interface | [](https://www.youtube.com/watch?v=sw3uDqn2h1Y) |
| Code Interface | [](https://www.youtube.com/watch?v=_5jQayO-MQY) |
| Mem0 Integration | [](https://www.youtube.com/watch?v=KIGSgRxf1cY) |
| Training | [](https://www.youtube.com/watch?v=aLawE8kwCrI) |
| Realtime Voice Interface | [](https://www.youtube.com/watch?v=frRHfevTCSw) |
| Call Interface | [](https://www.youtube.com/watch?v=m1cwrUG2iAk) |
| Reasoning Extract Agents | [](https://www.youtube.com/watch?v=2PPamsADjJA) |

</details>

---

## Contributing

We welcome contributions! Fork the repo, create a branch, and submit a PR → [Contributing Guide](https://github.com/MervinPraison/PraisonAI/blob/main/CONTRIBUTING.md).

---

## FAQ & Troubleshooting

<details>
<summary><strong>Show FAQ and troubleshooting</strong></summary>

<details>
<summary><strong>ModuleNotFoundError: No module named 'praisonai'</strong></summary>

Install the package:
```bash
pip install praisonai
```

Using only the core library? `pip install praisonaiagents` and import from `praisonaiagents` instead.

</details>

<details>
<summary><strong>API key not found / Authentication error</strong></summary>

Ensure your API key is set:
```bash
export OPENAI_API_KEY=your_key_here
```

For other providers, see [Models docs](https://praison.ai/docs/models).

</details>

<details>
<summary><strong>How do I use a local model (Ollama)?</strong></summary>

```bash
# Start Ollama and pull a model
ollama serve
ollama pull llama3.2
```

```python
from praisonai import Agent

agent = Agent(instructions="You are a helpful assistant", llm="ollama/llama3.2")
agent.start("Why is the sky blue?")
```

The `ollama/` prefix is what selects Ollama's handling — tool-call repair,
tool-result formatting and the streaming rules small local models need. Or set
it by environment instead:

```bash
export OPENAI_MODEL_NAME=ollama/llama3.2
```

Setting only `OPENAI_BASE_URL` is not enough: with no model named, the OpenAI
default (`gpt-4o-mini`) is sent to Ollama, which answers
`404 model 'gpt-4o-mini' not found`. Always name the model.

Point at a non-default host with `base_url=` or `OLLAMA_HOST`:

```python
agent = Agent(instructions="...", llm="ollama/llama3.2", base_url="http://192.168.1.10:11434")
```

The same shape works for other local runtimes — `lm_studio/`, `vllm/` and
`hosted_vllm/` with their server's `base_url`.

See [Models docs](https://praison.ai/docs/models) for more details.

</details>

<details>
<summary><strong>How do I persist conversations to a database?</strong></summary>

Use the `db` parameter:
```python
from praisonai import Agent, db

agent = Agent(
    name="Assistant",
    memory={
        "db": db(database_url="postgresql://localhost/mydb"),
        "session_id": "my-session",
    },
)
```

See [Persistence docs](https://praison.ai/docs/databases/overview) for supported databases.

</details>

<details>
<summary><strong>How do I enable agent memory?</strong></summary>

```python
from praisonai import Agent

agent = Agent(
    name="Assistant",
    # Enables file-based memory (no extra deps!)
    memory={"user_id": "user123"},
)
```

See [Memory docs](https://praison.ai/docs/concepts/memory) for more options.

</details>

<details>
<summary><strong>How do I run multiple agents together?</strong></summary>

```python
from praisonai import Agent, Agents

agent1 = Agent(instructions="Research topics")
agent2 = Agent(instructions="Summarize findings")
agents = Agents(agents=[agent1, agent2])
agents.start()
```

See [Agents docs](https://praison.ai/docs/concepts/agents) for more examples.

</details>

<details>
<summary><strong>How do I use MCP tools?</strong></summary>

```python
from praisonai import Agent, MCP

agent = Agent(
    tools=MCP("npx @modelcontextprotocol/server-memory")
)
```

See [MCP docs](https://praison.ai/docs/mcp/transports) for all transport options.

</details>

</details>

### Getting Help

- 📚 [Full Documentation](https://praison.ai/docs)
- 🐛 [Report Issues](https://github.com/MervinPraison/PraisonAI/issues)
- 💬 [Discussions](https://github.com/MervinPraison/PraisonAI/discussions)

---

<div align="center">
  <p><strong>Made with ❤️ by the PraisonAI Team</strong></p>
  <p>
    <a href="https://praison.ai/docs">📚 Documentation</a> •
    <a href="https://github.com/MervinPraison/PraisonAI">GitHub</a> •
    <a href="https://youtube.com/@MervinPraison">▶️ YouTube</a> •
    <a href="https://x.com/MervinPraison">𝕏 X</a> •
    <a href="https://linkedin.com/in/mervinpraison">💼 LinkedIn</a>
  </p>
</div>

---

## What's new

| What's new | What it is |
|:--|:--|
| **Six products, one framework** | Bot, Code, MCP and Train now install on their own: `pip install praisonai-bot`, `praisonai-code`, `praisonai-mcp`, `praisonai-train`. `pip install praisonai` still installs everything. |
| **[`praisonai connect`](https://praison.ai/docs/cli/mcp)** | One command puts your agents and 85 tools in 22 MCP clients: Cursor, VS Code, Claude Desktop, Claude Code, Codex, Zed and more. |
| **[Replay](https://praison.ai/docs/features/replay)** | Record any agent run, then replay it step by step, rerun from a node, or export it to HTML, Mermaid or OpenTelemetry. |
| **[Dashboard](https://praison.ai/docs/concepts/claw)** | Chat + Canvas, a microphone in the composer, and a Connect page for MCP clients. `pip install "praisonai[dashboard]"` |
| **[v4.8.0](https://github.com/MervinPraison/PraisonAI/releases/tag/v4.8.0)** | A security hardening release. 608 releases in the last 12 months. |

## Star History

[](https://star-history.com/#MervinPraison/PraisonAI&Date)

---

### Src Praisonai Agents Docs Local Model Layer README (`src/praisonai-agents/docs/local-model-layer/README.md`)

# Local Model Layer — implementation ledger

**Status:** every order below has an open PR. See §4.
**Owner workstream:** local model runtimes (Ollama, LM Studio, llama.cpp, vLLM, MLX, `transformers serve`)
**Created:** 2026-09-03

---

## 0. How to use this document

This directory is a **work-order ledger**. It exists so that any agent — including one
with no memory of the conversation that produced it — can pick up exactly one unit of
work and execute it correctly, in isolation, without re-deriving the analysis.

**If you are an agent starting work here, do this in order:**

1. Read [`00-ground-truth.md`](00-ground-truth.md). It records what was measured, how, and
   when. Do not trust a claim in any work order that contradicts it; re-measure instead.
2. Read §2 (Invariants) and §3 (File ownership) of this file. §3 is what stops two agents
   corrupting each other's work.
3. Open the single work order you were assigned. Execute only that one.
4. Update the status row in §4 of this file in the same commit as your change. That row is
   the only shared file content; keep the edit to one line to avoid conflicts.

**Do not** expand scope, batch two work orders into one PR, or "fix while you're in there".
Each order is independently revertible by design and that property is worth more than
convenience.

> **Two corrections this ledger has already had to make.** Both were caught by measuring rather
> than reasoning, and both would have sent an agent down the wrong path.
>
> **The D7 root cause is not `provider_ollama`.** The audit blamed the per-file `provider_ollama`
> tag. Measurement (`04-test-gating.md` §2) shows `not network` deselects all seven tests **on its
> own**, because the plugin implies `network` from *any* provider marker and the file also matches
> `provider_openai`. **Removing `not provider_ollama` from the workflows would change nothing.**
> That is why order `04` touches no YAML at all — the fix is marker-side.
> Its first draft told an agent to "wire
> the twelve dead adapter methods". Measurement (`06-adapter-revival.md` §1) says the opposite:
> **12 of 20 items should be deleted, only 3 wired.** Six of the dead methods have no inline
> equivalent anywhere — they are speculative API, and an agent told to "wire them up" would
> invent an implementation that no test could ever have failed against. Read the decision table
> before touching `llm/adapters/`; do not act on the summary in §1 of this file.

---

## 1. Why this work exists

Every local runtime worth supporting already speaks `POST /v1/chat/completions`, and
`litellm` already handles that transport. So the problem is not calling local models — the
SDK can already do that. The problems are:

- **Discovery.** A user with a running daemon still hand-types a URL, a port and an exact
  model tag; getting any one wrong produces `OPENAI_API_KEY environment variable is required`.
- **Capability.** "Does this model support tools?" is answerable by asking the server
  (`/api/show`, `/props`, `/server_info`). The SDK asks nothing and guesses from a name prefix.
- **Quirks.** Local stacks fail silently with HTTP 200. The sharpest: sending `format` and
  `tools` together to Ollama suppresses the tool call and the model fabricates an answer.

The layer being built is therefore a **resolver, not a transport**: it returns data about
what is running and what it will get wrong. Compensating behaviour stays in
`llm/adapters/`, which already declares methods for exactly this purpose.

---

## 2. Invariants — never break these

These come from `src/praisonai-agents/AGENTS.md` §4.6 plus the structural review in
`00-ground-truth.md`. Every work order inherits them; none may waive them.

| # | Invariant | Why it binds this work specifically |
|---|-----------|--------------------------------------|
| I1 | **Backward compatible.** Public API changes need a deprecation cycle. | Several fixes change which code path a given input takes. Each order carries an explicit list of inputs whose behaviour must not change. |
| I2 | **Lazy imports.** Optional deps never imported at module level. | Discovery must not import `litellm` or any runtime SDK at import time. |
| I3 | **Safe defaults.** New features are opt-in. | Discovery must not fire unless the model spec is `"local"` or unset. Never probe the network on a fully-specified config. |
| I4 | **Deterministic tests.** No dependence on timing or external state. | Every test must pass with **no server running**. Live-server tests go behind an explicit marker and never run in the default suite. |
| I5 | **Protocol-driven core.** No heavy implementations in core. | `local/` returns dataclasses. It performs no chat calls, no retry, no request mutation. |
| I6 | **`local/` is a dependency sink.** | It may import the **standard library only** — nothing from `praisonaiagents`, and no third-party distribution (`httpx`/`requests`/`aiohttp` are forbidden; use `urllib.request`). Enforced by a test. See §5 and `07` §3. |
| I7 | **No second abstraction.** | `llm/adapters/` is the extension point. Do not add a parallel quirk/adapter registry beside it. |
| I8 | **No new public knobs without a live consumer.** | Root `AGENTS.md`: do not add params, modules or exports that merely duplicate existing behaviour. |

### I6 in detail — the import rule

An AST pass over `praisonaiagents/` (595 files, 238,936 lines) found **65 subpackages, 212
directed edges and 26 mutually-importing subpackage pairs**. `llm/` already imports upward
into `agent/`, and 15 subpackages import `llm/` back. Consequently a shared helper placed in
`llm/` **cannot** be adopted by `memory/` or `eval/` without deepening the existing cycles.

`local/` is therefore specified as a leaf. That single property is what allows the 21
modules which currently bypass the LLM layer to adopt it later. Treat any import of
`praisonaiagents.*` from inside `local/` as a build break, not a style issue.

The HTTP client is stdlib `urllib.request`, **not** `httpx`. An earlier draft of this ledger
permitted `httpx` on the grounds that it is a transitive dependency of `openai>=2.0.0`. That
was reversed in `07` §3: the edge is undeclared in `pyproject.toml`, so a future `openai`
release that drops `httpx` would silently break the sink — precisely the class of failure this
package exists to catalogue. The boundary test in §5 hard-forbids `httpx`/`requests`/`aiohttp`
so the decision cannot drift.

---

## 3. File ownership — collision avoidance

Two work orders that touch the same file **must not run concurrently**. This table is the
authority. Before starting, check that no in-flight PR owns your files.

| Work order | Owns (may edit) | Must not edit |
|---|---|---|
| `01-d1-default-model` | `agent/agent.py` (branch chain only) | `llm/llm.py`, `llm/adapters/` |
| `02-d3-provider-detection` | `llm/llm.py` (`_detect_provider`, `_is_ollama_provider` only) | `agent/agent.py`, `llm/adapters/` |
| `03-d2-base-url-routing` | `agent/agent.py` (base_url branch), root `README.md` | `llm/llm.py`, `llm/adapters/` |
| `04-test-gating` | `tests/_pytest_plugins/test_gating.py`, both `pytest.ini`, `tests/conftest.py`, `tests/integration/test_base_url_api_base_fix.py`, `tests/unit/cli/test_test_command.py` | any `praisonaiagents/` source; **`.github/workflows/**` — the `-m` expressions are not the bug** |
| `05-live-ci-job` | `.github/workflows/test-optimized.yml`, `tests/integration/test_ollama_tool_calling_live.py` | any `praisonaiagents/` source; `test_gating.py` |
| `06-adapter-revival` | `llm/adapters/__init__.py`, `llm/llm.py` (3 response paths) | `agent/agent.py` |
| `07-local-package` | `praisonaiagents/local/**` (new), `src/praisonai/tests/unit/llm/local/**` (new), `pyproject.toml` extras | everything else |
| `08-reachability` | `memory/`, `eval/`, `context/`, `lite/`, `telemetry/` | `llm/`, `agent/` |

### Enforced serialisation

- **`01` then `03`** — both edit `agent/agent.py`. Land `01` first.
- **`02` then `06`** — both edit `llm/llm.py`. Land `02` first; it is far smaller.
- **`04` then `05`** — before `04`, `-m provider_ollama` selects 32 tests across 5 files (only 7
  are Ollama tests), so `05` has no usable selector and is unbuildable.
- **`04` and `07` are independent** of orders 01/02/03/06 and may run in parallel with them.
- **`08` requires `07`** to have landed, because it consumes `local/`.

---

## 4. Status

Update your row in the same commit as your change. One line only.

Additional PRs not in the original order list, found while executing it:
D4 (local route prefixes) #4798, D5 (local embedding dimensions) #4802,
D6 (registry accepts local providers) #4800.

**Three claims in this ledger were corrected by executing it.** Each is marked
inline where it appears, but they are collected here because a reader who trusts
the summary would otherwise carry the wrong version:

1. *"Wire the twelve dead adapter methods."* Measurement said the opposite:
   **12 of 20 items should be deleted, only 3 wired** (`06` §1). Six had no
   inline equivalent at all — an agent told to wire them would have invented
   behaviour no test could fail against.
2. *"`provider_ollama` deselects the mocked base_url suite."* It does not.
   **`not network` deselects it on its own**, because the plugin implies
   `network` from any provider marker (`04` §1). Editing the workflow `-m`
   strings would have changed nothing.
3. *"Running fully locally is unachievable, not merely unconfigured."* Not so:
   litellm and the openai SDK both honour `OPENAI_BASE_URL`, so the bypass sites
   **do** reach a local server. The blocker is the hardcoded model name they then
   ask for (`00` §5, `08`).

| Order | Title | Branch | PR | Status |
|---|---|---|---|---|
| 01 | D1 — provider-prefixed default model never reaches litellm | `fix/d1-default-provider-model` | #4795 | PR open |
| 02 | D3 — provider over-detection from base_url | `fix/d3-provider-detection` | #4797 | PR open |
| 03 | D2 — README recipe + local-endpoint diagnostic | `fix/d2-base-url-routing` | #4799 | PR open |
| 04 | D7 — per-file provider marker deselects unrelated tests | `fix/d7-per-test-provider-markers` | #4801 | PR open |
| 05 | Live local-model CI job | `feat/ci-ollama-live-job` | #4803 | PR open |
| 06 | A1/A2 — make the provider adapter load-bearing (6 sub-steps) | 6 branches, stacked | #4804 #4806 #4808 #4809 #4810 #4811 | **complete — KNOWN_DEAD empty** |
| 07 | `praisonaiagents/local/` — discovery and capability resolver | `feat/local-model-resolver` | #4807 | PR open |
| 08 | A3 — auxiliary-model fallback configurable everywhere | `fix/reachability-local-endpoint` | #4812 | PR open (model half; parameter half deferred) |

---

## 5. The two tests that keep this work honest

Both are cheap, both are anti-regression, and both should land with their respective orders.

**Import boundary (`07`).** Asserts `local/` imports nothing from `praisonaiagents`. Without
it, I6 decays silently and the leaf property — the whole reason the package can be adopted
by `memory/` and `eval/` — is lost.

**Adapter reachability (`06`).** Asserts every method on `DefaultAdapter` has at least one
call site. This is the test whose absence allowed 11 of 17 adapter methods to become dead code
while `llm.py` grew 145 hand-written Ollama references. Two limits, both real: it cannot detect
an *unreachable* call site (proven by `should_skip_streaming_with_tools`, which a caller would
have satisfied while the branch stayed dead), and **one call site satisfies it — so it does not
detect the three-path divergence at all.** A floor, not a ceiling.

---

## 6. Deliberately out of scope

Named here so that deferring them is a decision rather than an oversight. Do not let a work
order quietly grow into one of these.

| Deferred | Measured size | Why not now |
|---|---|---|
| Consolidating `LLM` and `OpenAIClient` behind one protocol | 7,160 + 2,691 lines, selected by one boolean at 6 sites | Neither is a superset of the other; the merge is larger than every order in this ledger combined. |
| Decomposing `LLM.get_response` | 1,675 lines, 194 branch/loop/try nodes | Highest-risk file in the package. Order `06` must edit it surgically without reflowing it. |
| Removing the sync/async divergence | ~1,628 duplicated lines across 10 pairs; `get_response` vs `_async` only 22.3% similar | Requires the consolidation above to be worth doing. |

The one obligation this ledger accepts toward them: **do not make them worse.** No order may
add a fifth copy of any compensation, and no order may add new logic inside `get_response`
that is not a delegation to an adapter.

---

### Src Praisonai Agents Docs Env Vars (`src/praisonai-agents/docs/env-vars.md`)

# Environment variables read by praisonaiagents



149 variables, 67 of them `PRAISONAI_*`/`PRAISON_*`. "Security switch" marks a variable that loosens or tightens a safety check; "credential" marks a secret. Names built at run time are not listed.

| Variable | Kind |
|---|---|
| `AGENTMAIL_API_KEY` | credential |
| `AGENTMAIL_INBOX_ID` |  |
| `ALLOW_LOCAL_CRAWL` | security switch |
| `ANONYMIZED_TELEMETRY` |  |
| `APPDATA` |  |
| `AZURE_STORAGE_CONNECTION_STRING` | credential |
| `BRAVE_API_KEY` | credential |
| `CODEX_HOME` |  |
| `COMSPEC` |  |
| `DAKERA_AGENT_ID` |  |
| `DAKERA_API_KEY` | credential |
| `DAKERA_API_URL` |  |
| `DAKERA_URL` |  |
| `DO_NOT_TRACK` |  |
| `EMAIL_ADDRESS` |  |
| `EMAIL_IMAP_PORT` |  |
| `EMAIL_IMAP_SERVER` |  |
| `EMAIL_PASSWORD` | credential |
| `EMAIL_SMTP_PORT` |  |
| `EMAIL_SMTP_SERVER` |  |
| `EXA_API_KEY` | credential |
| `GEMINI_API_KEY` | credential |
| `GITHUB_ACTIONS` |  |
| `GITHUB_TOKEN` | credential |
| `GIT_DIR` |  |
| `GIT_WORK_TREE` |  |
| `GOOGLE_API_KEY` | credential |
| `HOME` |  |
| `JIRA_API_TOKEN` | credential |
| `JIRA_EMAIL` |  |
| `JIRA_URL` |  |
| `JIRA_USERNAME` |  |
| `LANG` |  |
| `LC_ALL` |  |
| `LITELLM_TELEMETRY` |  |
| `LOCALAPPDATA` |  |
| `LOGLEVEL` |  |
| `MCP_AUTH_TOKEN` | credential |
| `MCP_SSE_ALLOWED_ORIGINS` | security switch |
| `MCP_SSE_AUTH_TOKEN` | credential |
| `MEM0_API_KEY` | credential |
| `MODEL_NAME` |  |
| `NVIDIA_API_KEY` | credential |
| `NVIDIA_NIM_API_BASE` |  |
| `NVIDIA_NIM_API_KEY` | credential |
| `OLLAMA_API_KEY` | credential |
| `OLLAMA_DECISION_MODEL` |  |
| `OLLAMA_HOST` |  |
| `OLLAMA_SYSTEM_ONE_TIMEOUT` |  |
| `OPENAI_API_BASE` |  |
| `OPENAI_API_KEY` | credential |
| `OPENAI_BASE_URL` |  |
| `OPENAI_EMBEDDING_MODEL` |  |
| `OPENAI_MAX_RETRIES` |  |
| `OPENAI_MODEL_NAME` |  |
| `OPENAI_TIMEOUT` |  |
| `OPENROUTER_APP_TITLE` |  |
| `OPENROUTER_REFERER` |  |
| `PATH` |  |
| `PLAYWRIGHT_BROWSERS_PATH` |  |
| `PRAISONAI_ALLOW_INSECURE_WS` | security switch |
| `PRAISONAI_ALLOW_LOCAL_TOOLS` | security switch |
| `PRAISONAI_ALLOW_MODEL_REQUESTS` | security switch |
| `PRAISONAI_ALLOW_PLUGIN_DISCOVERY` | security switch |
| `PRAISONAI_ALLOW_PROJECT_PLUGINS` | security switch |
| `PRAISONAI_ALLOW_TEMPLATE_TOOLS` | security switch |
| `PRAISONAI_APPEND_SYSTEM_PROMPT` |  |
| `PRAISONAI_ATTACHMENTS_ON_MISSING` |  |
| `PRAISONAI_ATTACHMENTS_STRICT` | security switch |
| `PRAISONAI_AUTO_APPROVE` | security switch |
| `PRAISONAI_AUTO_INSTRUMENT` |  |
| `PRAISONAI_BACKGROUND_JOB_STORE` |  |
| `PRAISONAI_CONTEXT_MONITOR_FORMAT` |  |
| `PRAISONAI_CONTEXT_MONITOR_FREQUENCY` |  |
| `PRAISONAI_CONTEXT_MONITOR_PATH` |  |
| `PRAISONAI_CONTEXT_MONITOR_WRITE_MODE` |  |
| `PRAISONAI_CONTEXT_STRATEGY` |  |
| `PRAISONAI_DISABLE_TELEMETRY` |  |
| `PRAISONAI_EMBEDDING_MODEL` |  |
| `PRAISONAI_FLOW_ANALYSIS_ENABLED` |  |
| `PRAISONAI_FULL_TELEMETRY` |  |
| `PRAISONAI_GIT_ALLOW_UNSAFE_BRANCH` | security switch |
| `PRAISONAI_GIT_USER_EMAIL` |  |
| `PRAISONAI_GIT_USER_NAME` |  |
| `PRAISONAI_HOME` |  |
| `PRAISONAI_IDENTITY_PATH` |  |
| `PRAISONAI_LAUNCH_AUTH_TOKEN` | credential |
| `PRAISONAI_LOCAL_EMBED_MODEL` |  |
| `PRAISONAI_LOCAL_MODEL` |  |
| `PRAISONAI_LOCAL_NEG_TTL` |  |
| `PRAISONAI_LOCAL_TIMEOUT` |  |
| `PRAISONAI_LOCAL_TTL` |  |
| `PRAISONAI_MAX_BODY_BYTES` |  |
| `PRAISONAI_MAX_DOWNLOAD_BYTES` |  |
| `PRAISONAI_MCP_TRUST` | security switch |
| `PRAISONAI_NO_PLUGINS` |  |
| `PRAISONAI_OCR_MODEL` |  |
| `PRAISONAI_OUTPUT` |  |
| `PRAISONAI_PERFORMANCE_DISABLED` |  |
| `PRAISONAI_PERFORMANCE_ENABLED` |  |
| `PRAISONAI_PERFORMANCE_MODE` |  |
| `PRAISONAI_PLUGINS` |  |
| `PRAISONAI_PRE_COMPACTION_FLUSH` |  |
| `PRAISONAI_PRE_COMPACTION_FLUSH_TIMEOUT` |  |
| `PRAISONAI_PROFILE` |  |
| `PRAISONAI_PROJECT_ROOT` |  |
| `PRAISONAI_QWEN_BASE_URL` |  |
| `PRAISONAI_SAVE_OUTPUT` |  |
| `PRAISONAI_SCHEDULE_TIMEZONE` |  |
| `PRAISONAI_SERVER_READY_TIMEOUT` |  |
| `PRAISONAI_SESSION_ACTIVE_WINDOW` |  |
| `PRAISONAI_SESSION_LEGACY_AGENT_KEYS` |  |
| `PRAISONAI_SESSION_RETENTION` |  |
| `PRAISONAI_SHELL_ENV_ALLOWLIST` | security switch |
| `PRAISONAI_STRICT_TOOLS` | security switch |
| `PRAISONAI_STRUCTURED_LOGS` |  |
| `PRAISONAI_TELEMETRY_DISABLED` |  |
| `PRAISONAI_TELEMETRY_ENABLED` |  |
| `PRAISONAI_TELEMETRY_SHUTDOWN_TIMEOUT` |  |
| `PRAISONAI_TOOL_OUTPUT_DIR` |  |
| `PRAISONAI_TOOL_OUTPUT_RETENTION_HOURS` |  |
| `PRAISONAI_TOOL_SAFETY` | security switch |
| `PRAISONAI_TRACK_COST` |  |
| `PRAISONAI_VIDEO_MODEL` |  |
| `PRAISONAI_VISION_MODEL` |  |
| `PRAISON_HOME` |  |
| `PRAISON_MAX_FILE_CHARS` |  |
| `SEARXNG_URL` |  |
| `SEARXNG_URL_ALLOWLIST` | security switch |
| `SHELL` |  |
| `SKILL_CAPABILITY_ENFORCEMENT` | security switch |
| `SKILL_MAX_PENDING` |  |
| `SKILL_WRITE_APPROVAL` | security switch |
| `SPIDER_API_KEY` | credential |
| `SYSTEMROOT` |  |
| `SYSTEM_ONE_TIMEOUT` |  |
| `TAVILY_API_KEY` | credential |
| `TAVILY_SEARCH_DEPTH` |  |
| `TEMP` |  |
| `TMP` |  |
| `TMPDIR` |  |
| `TYPESAFE_API_KEY` | credential |
| `TYPESAFE_DEFAULT_MODEL` |  |
| `USER` |  |
| `USERNAME` |  |
| `USERPROFILE` |  |
| `WEB_SEARCH_PROVIDER` |  |
| `XDG_DATA_HOME` |  |
| `YDC_API_KEY` | credential |

---

### Src Praisonai Agents Docs Sdk Behavior Matrix (`src/praisonai-agents/docs/sdk-behavior-matrix.md`)

# SDK Behavior Matrix

Deterministic expectations for the public knobs that integrators most often mistake for
"model randomness". Each row lists a related test. Passing it is a useful check, but mocked
unit tests do not rule out SDK bugs in the paths they replace. If your app disagrees with a
row, check the sharp edges and investigate the real call path.

- **Scope:** `praisonaiagents` Python API (main branch). Paths are relative to
  `src/praisonai-agents/`.
- **Source of truth:** code + the listed tests. If a docstring disagrees with this page,
  trust the test, then fix whichever is stale.

## How to use

1. Find the knob from the report in the tables below.
2. Run the listed test: `PYTHONPATH=. python -m pytest <test> -q`.
3. **Test fails** → SDK defect; open a bug. **Test passes** but behavior differs → check the
   *Sharp edge* column, reproduce on the real call path, then open a bug or update this page.

---

## 1. Chat & streaming

Streaming is configured through `output=`, not a constructor kwarg.
`Agent(stream=True)` raises `TypeError` with the hint
*"streaming moved into output=; use output=OutputConfig(stream=True)."*
`agent.stream` is `False` unless `output="stream"` or `OutputConfig(stream=True)` is used.

| API / knob | Expected behavior | Sharp edge | Test |
| --- | --- | --- | --- |
| `chat(prompt, stream=None)` | Inherits `agent.stream`. Returns the final `str` (or model, see §3). | Never a generator. | `tests/unit/agent/test_execution_api.py` |
| `chat(stream=True)` | Tokens go to `agent.stream_emitter`; the call still returns the full `str`. If the adapter cannot stream (`"Streaming is not supported"`) or the stream attempt fails transiently, it falls back to a non-streaming call. | `None` is **not** a valid "streaming succeeded" result (#5737). `LLMError`, `ToolExecutionError`, other `ValueError`s and post-dispatch tool-turn failures are **not retried** by the fallback. Of these, only `ToolExecutionError` reaches the caller; the rest roll back history and `chat()` returns `None` (see below). | `tests/test_chat_explicit_stream_fallback.py`, `tests/test_streaming_fallback_kwargs.py` |
| `chat(stream=False)` | Single non-streaming completion; no stream events. | — | `tests/unit/test_stream_preset.py` |
| `start(prompt)` | Stream priority: explicit kwarg > `agent.stream` > TTY. When streaming, returns a **generator** of chunks; otherwise a `str`. | Because `agent.stream` is always a bool, the TTY fallback only applies if `agent.stream` is set to `None`. Output guardrails are not applied to streamed chunks. | `tests/unit/agent/test_execution_api.py` |
| `run(prompt)` | Never streams unless `stream=True` is passed; returns `str`. | Ignores TTY. | `tests/unit/agent/test_execution_api.py::TestAgentRunMethod::test_run_ignores_tty_detection` |
| `iter_stream(prompt)` | Always a generator of chunks. | — | `tests/unit/agent/test_execution_api.py::TestAgentIterStreamMethod::test_iter_stream_always_streams` |
| `achat()` / `astart()` | Same `stream` resolution as `chat()`; awaits and returns the final `str`. | Unlike `start()`, `astart()` never returns an (async) generator. | `tests/unit/agent/test_achat_unified_dispatch.py`, `tests/unit/agent/test_execution_api.py::TestAsyncMethods::test_astart_streams_in_tty` |

**When `chat()`/`achat()` return `None`:** input guardrail or `BEFORE_AGENT` hook blocked the
run, or the LLM call failed with anything other than `ToolExecutionError` (history is rolled
back and the error is displayed/logged, not raised). Check for `None` rather than relying on
`try/except` around `chat()`.
An **output** guardrail rejection returns a fixed refusal string, not `None`; see
`agent.last_guardrail_error`.

## 2. Memory prefetch & scope

| API / knob | Expected behavior | Sharp edge | Test |
| --- | --- | --- | --- |
| `MemoryConfig(prefetch=True)` — sync (`_prefetch_memory`) | Before each turn, searches long-term memory with up to 5 terms (verbatim prompt → significant words → salient single words), stopping at the first non-empty hit. Results are injected into the **system prompt** under `## Recalled memories`, capped by `prefetch_limit` (5) and `prefetch_token_budget` (512, truncated with `…`). | Off by default. Errors are swallowed (debug log) and inject nothing. | `tests/unit/memory/test_prefetch.py` |
| Same — async (`_aprefetch_memory`) | Same terms, stop rule, scope and formatting via `asearch_memory`. | Backends with only `.search()` (no `search_long_term`) are searched by the sync path but not the async path. | `tests/unit/memory/test_prefetch.py::test_async_prefetch_falls_back_to_significant_tokens` |
| `MemoryConfig(user_id=...)` | Agents sharing a `user_id` share a store and recall each other's turns. Search is scoped by `user_id` + `session_id`, not `agent_id`. | Without `user_id`, each Agent gets a random `agent-<uuid>` id (warning logged) — memory is **isolated per instance**. There is no `Agent(user_id=...)` kwarg. | `tests/test_memory_cross_session.py` |

## 3. Structured output

`output_pydantic` / `output_json` are per-call `chat()`/`achat()` kwargs (forwarded by
`start()`/`run()`) and `Task` fields — not `Agent` constructor params. There is no
`output_json_schema`. Native `response_format` is used when the model supports structured
outputs; otherwise the schema is appended to the prompt as text.

| API / knob | Expected behavior | Sharp edge | Test |
| --- | --- | --- | --- |
| `chat(..., output_pydantic=Model)` | Returns a `Model` **instance** (tries strict JSON, fenced ```json, then first `{...}` in prose). | On parse failure, logs a warning and returns the **raw string** — no exception, no retry. Check `isinstance`. | `tests/unit/agents/test_chat_output_pydantic_coercion.py` |
| `chat(..., output_json=Model)` | Returns a JSON **string**. | Never a `dict` — call `json.loads` yourself. | `tests/unit/agents/test_chat_output_pydantic_coercion.py::test_chat_output_json_stays_string` |
| `Task(output_pydantic=Model)` in a team | `TaskOutput.pydantic` holds the instance; `output_format="Pydantic"`. | Fails closed: invalid output is a failed task (`Structured output validation failed ...`), which drives the retry loop. Setting both `output_json` and `output_pydantic` raises `ValueError`. | `tests/unit/agents/test_output_pydantic_policy.py` |
| `Task(output_json=Model)` in a team | `TaskOutput.json_dict` holds the parsed `dict`; `output_format="JSON"`. | Same fail-closed rule. | `tests/unit/agents/test_output_pydantic_policy.py::test_output_json_prose_is_not_success` |
| Native vs text schema | `response_format` (strict) for capable models; prompt injection otherwise. | Provider-dependent. | `tests/test_native_structured_outputs.py` |

## 4. Teams & handoff

| API / knob | Expected behavior | Sharp edge | Test |
| --- | --- | --- | --- |
| `AgentTeam(agents, tasks=[Task, ...])` | Accepts a list/tuple of `Task`. Sequential tasks are chained. `start()` returns the last task's `.raw` string (`return_dict=True` → `{"task_status", "task_results"}`). | `tasks="..."` → `TypeError: AgentTeam.tasks must be a list of Task instances, not str. ...`; `tasks=[]` → `ValueError: If tasks are provided, at least one task must be present`; non-`Task` item → `TypeError: tasks[i] must be a Task instance, got <type>`. | `tests/unit/agents/test_agentteam_task_validation.py` |
| `AgentTeam(agents)` (no tasks) | One task auto-generated per agent. | Empty `agents` fails at `start()`, not construction. | `tests/unit/agents/test_agentteam_task_validation.py::test_tasks_none_auto_generates` |
| `Agent(handoffs=[other])` | Adds a `transfer_to_<name>` tool; the model decides whether to call it. Tool returns `"Handoff successful. <name> response: ..."`. | The model may not call the tool — that is a prompt issue, not a crash. Cycles/depth (`max_depth=10`) return an `"Error: ..."` string to the model rather than raising. Timeout (300 s) applies to async handoffs only. | `tests/test_handoff_compatibility.py`, `tests/unit/test_handoff_unified.py` |

## 5. AG-UI

| API / knob | Expected behavior | Sharp edge | Test |
| --- | --- | --- | --- |
| `AGUI(agent=...).get_router()` | Returns a FastAPI `APIRouter`; mount it with `app.include_router(...)`. `POST {prefix}/agui` → SSE (`text/event-stream`); `GET {prefix}/status` → `{"status": "available"}`. | AGUI has no built-in server or default port — you run uvicorn and own startup/shutdown. `AGUI()` with no agent raises `ValueError`. | `tests/agui/test_agui.py`, `tests/agui/test_router.py` |
| SSE events | `RUN_STARTED` → `TEXT_MESSAGE_*` / `TOOL_CALL_*` → `RUN_FINISHED`; exceptions become `RUN_ERROR`. | Multi-agent (`agents=`) sends the whole result as one text message, not token stream. Event order and `RUN_ERROR` emission over the endpoint are **not pinned** by a test; the router test only checks that a failing agent still yields HTTP 200. | `tests/agui/test_streaming.py::TestRunLifecycleEvents` (event construction), `tests/agui/test_router.py::TestAGUIEndpointErrorHandling::test_agui_endpoint_handles_agent_error` (HTTP only) |

---

## Keeping this page in sync

- A PR that changes behavior of any API listed here updates the matching row (and its test)
  in the same PR.
- Intentional behavior that looks like a bug: keep it in *Sharp edge* with the issue number.
- Renamed/moved tests: update the *Test* column.

---

### Src Praisonai Mobile Docs Gaps (`src/praisonai-mobile/docs/gaps.md`)

# Engine capability gaps

Referenced from `engines/src/praisonai-ts/engine.ts` and its conformance run.
This file records what each engine **cannot report**, so a gap is a written
fact rather than something a reader has to infer from a `false` in a struct.

## praisonai-ts

### The one root cause

Upstream `Agent.streamEvents()` emits a five-variant union:

```ts
type AgentEvent =
  | { type: 'text';        delta: string }
  | { type: 'tool_call';   callId: string; name: string; args: Record<string, unknown> }
  | { type: 'tool_result'; callId: string; name: string; ok: boolean; output: string }
  | { type: 'finish';      text: string }
  | { type: 'error';       error: Error }
```

Protocol v2 has **eleven** events. The channel now carries tool calls and
results, so this engine reports tool activity. What it still cannot carry is an
approval request, reasoning, or usage — so the `two_approvals` conformance
scenario below is declared unsupported rather than faked. (`approval` is *not*
unsupported: its case only decides an unknown id, which needs no approval
channel — see the note under the table.)

### What that means per capability

| Capability | Declared | Why |
|---|---|---|
| `streaming` | `true` | `text` deltas map straight to `delta`. |
| `cancellation` | `true` | Via `AgentStreamOptions.signal` (added upstream in #4426). |
| `reasoning` | `false` | No reasoning channel upstream. |
| `tools` | **`true`** | Since upstream gained `tool_call`/`tool_result`. Was false — see the note below. |
| `approvals` | `false` | `ApprovalManager` exists upstream but cannot reach the event channel. |
| `attachments` | `false` | `streamEvents` takes a prompt string only. |

**RESOLVED.** Upstream now emits `tool_call` and `tool_result`, so the flag is
`true` and three conformance scenarios that were declared unsupported
(`tool_ok`, `tool_failed`, `tool_unresolved`) are produced and passing. The
original note is kept below because the reasoning is what made the flag
trustworthy in the first place.

**`tools: false` did not mean tools do not run.** praisonai-ts executes tools
normally; it just never *announces* them. The flag describes what the engine can
**report**, because a UI that renders tool rows from a `true` flag would render
nothing and look broken. A tool call that silently failed would then be
indistinguishable from a normal answer — which is the exact defect protocol v2's
`tool_result.ok` field was introduced to prevent.

### Unsupported conformance scenarios

| Scenario | Reason |
|---|---|
| `two_approvals` | `ApprovalManager` gates tool execution upstream but its prompt cannot reach the event channel, so two `approval_request` events cannot be emitted |

`tool_ok`, `tool_failed` and `tool_unresolved` were listed here until upstream
gained `tool_call`/`tool_result`; they are now produced and passing. The suite
prints every remaining omission on each run, so a contract that quietly shrinks
is visible in the output rather than silently green.

`approval` was also listed here until it was confirmed dead: that case only
asserts that deciding an *unknown* id returns `false`, which this engine's
`decide()` always does — it needs no approval channel. Declaring it unsupported
skipped a case that already passed, so it now runs. `capabilities.approvals`
stays `false`: the engine still cannot *emit* an approval request, which is what
`two_approvals` needs.

### Closing the remaining gap

Approvals need a further upstream change: `AgentEvent` gaining an approval
variant, mirroring Python's `StreamEventType` (17 members). Until then the
mobile app either runs without approval prompts, or uses the `remote-http`
engine — which speaks the full vocabulary because the desktop server already
emits it.

## Node-only globals on the Agent import graph

Separately from the event vocabulary: 21 files are reachable from `Agent`, and
after PR #4433 the only remaining `process.env` read among them is in
`utils/logger.ts`, which is already guarded. Two bare Node builtin imports do
remain on that graph and will need a bundler alias or an upstream change:

- `agent/simple.ts` — `import { randomUUID } from 'crypto'`
- `ai/tool-approval.ts` — `import { EventEmitter } from 'events'`

`randomUUID` has a direct WebCrypto equivalent (`globalThis.crypto.randomUUID`)
available in every target webview, so this is a small upstream fix rather than a
polyfill. It is an **import-time** failure, which makes it more severe than a
guarded read: it takes the whole bundle down before any code runs.

---

# Design gaps found while building the UI layer

Raised by the `ui/` build against the existing `core/` and `protocol/` types.
Two were fixed immediately (below); the rest are recorded here rather than
fixed, because each needs a decision rather than an edit.

## Fixed

- **`UsageEvent.ttft` had no unit** while its sibling was `seconds`, so a
  renderer had to guess between seconds and milliseconds — a 1000x difference
  in a number the user reads. The TS field is now `ttftSeconds`; the wire key
  stays `ttft`, translated in `decode.ts`, which is where that belongs.
- **`EndEvent.versions` / `active` had no documented meaning**, so the UI
  dropped them. Both are now documented, including why `decode.ts` clamps
  `active` into `[0, versions - 1]` rather than trusting it.

## Open

### ~~1. `TurnState` loses the interleaving of text and tool calls~~ — CLOSED

`text` is one accumulated string and `tools` is a parallel array, so there is no
way to place a tool row *between* the two paragraphs it actually happened
between — which is how every chat UI renders a multi-step turn. The view model
currently emits all text, then all tool rows.

Closing it needs an ordered block list in the reducer:
`blocks: ({ kind: "text"; … } | { kind: "tool"; callId: string })[]`.

**Closed.** `TurnState` now carries `blocks: Block[]` — the turn in the order it
actually happened. A delta extends the open text block or starts a new one; a
`tool_call` appends a tool block; a result for a call never seen gets a
position too, or its row would exist in `tools` and appear nowhere on screen.

The invariant that stops the two representations drifting is asserted: every
text block concatenated reproduces `text` exactly. Verified by mutation — every
delta opening its own block fails one case, and a `tool_call` adding no block
fails three.

`buildTranscript` now walks `blocks`, so a tool row renders between the
paragraphs it ran between, and only the LAST text block streams (an earlier one
was closed by the tool call after it, and a caret on it would claim two places
are being written at once).

### ~~2. `settle()` empties `approvals`, so an ended turn cannot show what was approved~~ — CLOSED

Right for actionability — a settled approval is not pressable — but wrong as an
audit trail: after the turn ends the transcript can never say "you allowed
`rm -rf /`". A `resolved: true` flag kept on the entry would give the UI both.

### ~~3. `PendingApproval` and `ApprovalEntry` are the same four fields in two places~~ — CLOSED

`transcript.ts` and `approvals.ts` each declare them, so the view model joins by
`approvalId` at render time. Making `ApprovalEntry` literally
`PendingApproval & { state }` removes a join — and that join is exactly where a
future author reintroduces index-pairing, which is the bug the whole
`approvalId` design exists to prevent.

### ~~4. There is no user-message side, and no stable identity for a live turn~~ — CLOSED

`TurnState` is assistant-only; `StoredChat.messages` has a different shape
(`role`/`content`/`at`). `end.userIndex` is the only link and it is `null` until
the turn ends, so a live turn cannot be keyed the same way before and after
persistence.

The join now has an owner: `core/src/chat/session.ts` implements
`RunPersistence` and is where `end.userIndex` is produced by whatever really did
the write. But it is **not yet wired into the run loop**: `createPraisonTsEngine`
is the only engine that takes a `RunPersistence`, and it is constructed with one
only in its tests — `boot.ts` builds the `session` and never hands it to an
engine, and the `remote-http` engine has no persistence at all. So a completed
turn is still not written to disk in production, and the live-turn identity the
gap is about is still not stable end-to-end. Closing this needs the composition
root to pass `session` as the praisonai-ts engine's persistence, and a persist
step for `remote-http`.

### ~~5. `ShellPort` exposes `insets` synchronously but the keyboard only by callback~~ — CLOSED

First paint therefore has to assume height 0. Correct on a cold launch, wrong on
a warm resume with a hardware or floating keyboard already up: one wrong frame,
then a jump — the exact "web page in a box" tell the synchronous `insets`
snapshot was introduced to avoid.

`ShellPort` now carries a synchronous `readonly keyboardHeightPx: number`, so a
component can *read* the current height at mount instead of waiting for the first
callback. But the value is not seeded the way `insets` is: both `createWebShell`
and `createTauriShell` initialise `keyboardHeightPx = 0` and only correct it on a
later `resize`/`keyboard-height` event, whereas `insets` is seeded synchronously
from the mirrored CSS custom properties (`readInsets(source)` in the Tauri shell,
before anything can paint). So a warm resume with the keyboard already up still
reads 0 on the first frame and jumps — the exact behaviour this entry is about.
Closing it needs each adapter to seed `keyboardHeightPx` from a synchronous
source at construction, mirroring what `insets` already does.

### ~~6. `SettingsFacade` cannot enumerate or observe~~ — CLOSED

No `keys()`, no change notification, and `SettingDef[]` is not reachable from
the facade — so a settings screen must hard-code the key list that already
exists as data, and re-render blindly after every `set()`.

### ~~7. `Dropped.reason` has no user-facing text~~ — CLOSED

The diagnostic row renders raw reason strings. Honest, but not readable.


---

# Why this file gets audited, not just appended to

A re-audit of the gaps above found the first draft of this section had made the
very error it warns about: it recorded three gaps as closed when only one (Gap
6) was, and the other two had landed a mechanism without the wiring that would
actually close them. That is not a filing problem, it is the same failure this
package is built against, one level up: **a document asserting a state nobody
re-checked** — including the check that a "closed" gap is closed *end-to-end*
and not just given a type or a function nothing calls.

It has a cost. A stale P0 list for `praisonai-ts` sent two agents to verify
nine "blockers" that were every one of them already fixed — useful work, since
it turned up three real bugs nobody had listed, but not the work it was
supposed to be.

So the rule for this file: **when a gap closes, close it here in the same
commit that closes it — and a gap is closed only when it is wired end-to-end,
not when the mechanism exists.** And when reading it, verify before believing.
Every claim below is checkable in under a minute.

## What closed, and what only half-closed

The re-audit found one gap fully closed and two that landed a mechanism without
finishing the wiring — recorded here as such rather than as closed, because a
half-closed gap read as closed is exactly the stale claim this file exists to
prevent.

- **Gap 6 — CLOSED.** `defs()`, `subscribe()`, `setSecret()` and `clearSecret()`
  on the facade (`core/src/settings/store.ts`). `subscribe` fires only after an
  *accepted* write; notifying on a refused one makes a screen redraw a value the
  user did not manage to change. A settings screen can now enumerate and observe
  from the facade alone.
- **Gap 4 — mechanism landed, not wired.** `core/src/chat/session.ts` implements
  `RunPersistence` and owns the join between the assistant-only `TurnState` and
  the two-sided `StoredChat`. But no engine is constructed with it in
  production: `createPraisonTsEngine` is the only one that takes a
  `RunPersistence` and gets one only in its tests, `boot.ts` never hands the
  `session` to an engine, and `remote-http` has no persistence at all. The join
  exists; the turn is still not recorded end-to-end.
- **Gap 5 — property added, snapshot not seeded.** `ShellPort.keyboardHeightPx`
  is readable synchronously, but both shell adapters initialise it to 0 and only
  correct it on a later event, so — unlike `insets`, which is seeded from CSS
  before first paint — a warm resume with the keyboard up still paints once at 0
  and jumps.

## Genuinely still open

Gaps **2**, **3**, **4**, **5** and **7** above. None blocks shipping:

- **2** is an audit-trail nicety — a settled approval cannot be shown after the
  turn ends.
- **3** is a duplicated four-field type, and worth closing because the join it
  forces at render time is exactly where index-pairing gets reintroduced.
- **4** has its join owner in place but is unwired in the composition root, so
  turns are not yet persisted in production.
- **5** has its synchronous property in place but no synchronous seed, so the
  warm-resume keyboard jump it targets is not yet prevented.
- **7** renders raw reason enums to a user.

Also open, and larger than any of them: **route→view dispatch** (the view models
exist and nothing mounts them) and the **Tauri Rust crate**. Neither is a gap in
the sense this file records — they are unbuilt work, not defects.


## Gaps 4 and 5, actually closed this time

A reviewer amended both of these back to open after I marked them closed, and
was right to. The corrections are worth keeping, because both are the same
mistake: **a mechanism existing is not the same as a mechanism working.**

- **Gap 4 was "MECHANISM LANDED, NOT WIRED".** `createSession` was called and
  `RunPersistence.record` was called, and nothing connected them -- the two
  signatures did not even line up (`record(prompt, answer)` against
  `record(request, answer)`), which is why nobody had noticed. So no
  conversation was ever written, and the gap read as closed from either end.
  `persistenceFor()` is now the named adapter where the two vocabularies meet,
  and `AppDeps.engines` is a FACTORY taking the persistence -- so there is no
  longer a way to obtain the engine list without being handed the thing engines
  write through. Enforced by the type, not by a comment.

  SCOPE, stated so it is not read later as an oversight: only the in-process
  `praisonai-ts` engine writes through this session. `remote-http` deliberately
  does not, because the desktop server it talks to is the owner of that write
  and the only thing that can report authoritative indices for its own store
  (registry.ts). A reviewer flagged that a turn answered by the default remote
  engine therefore leaves the *local* mobile session empty; that is true and
  intended -- local mirroring of a server-owned transcript is a separate feature
  (it needs a read-back from the server on connect), not part of closing this
  wiring gap. What this gap was about -- the in-process engine's turn never
  reaching disk -- is now closed and asserted end to end.

- **Gap 5 was "PROPERTY ADDED, SNAPSHOT NOT SEEDED".** `keyboardHeightPx` was
  declared `= 0` and only ever updated by an event, so a component mounting
  while the keyboard was already up laid out at 0 for one frame and then
  jumped -- exactly the bug the synchronous property was added to prevent. It
  is seeded from `visualViewport` at construction now.

Both are verified by a positive control: reverting either makes a named test
fail.


## Gaps 2, 3 and 7, closed

The last three. None blocked shipping, which is exactly why they sat — and two
of them were one bad day away from mattering.

- **Gap 2.** `settle()` deleted the approvals, so a finished transcript could
  never say *"you were asked to allow `rm -rf /` and the turn ended first"* —
  the thing a reader most wants to see afterwards. They are kept now and marked
  `resolved`, which means *not actionable* rather than *not recorded*. The pair
  test matters here: marking everything resolved would satisfy the audit-trail
  case while making every live prompt unanswerable.

- **Gap 3.** `ApprovalEntry` is now literally `PendingApproval & { state }`
  rather than a second copy of the same four fields. The duplication forced the
  view model to join them by `approvalId` at render time, and **that join is
  where index-pairing gets reintroduced** — pairing an approval by position is
  the defect the whole `approvalId` design exists to prevent.

  **Correction.** This entry used to end "Removing the join removes the
  opportunity." The join was never removed — only the *type* duplication was.
  `view-model.ts` still calls `findApproval(table, pending.approvalId)`, and
  replacing that with `table.entries[0]` passed the entire suite, because every
  test had exactly one approval in flight. With two outstanding, the second row
  rendered the first's decision: an `rm -rf /` prompt shown as already-allowed,
  against a decision nobody made. The join is correct and is now pinned by two
  tests in both directions. The opportunity still exists; what changed is that
  taking it now fails.

- **Gap 7.** A dropped event said `wrong_msg_id` to a user, which tells them
  nothing. It now reads as a sentence *and* keeps the tag: translating the tag
  away would make the one searchable string in the message unsearchable for
  whoever they report it to. An unknown tag passes through rather than becoming
  "unknown reason", because a newer engine can invent one and the tag is still
  the only information there.

Each verified by reverting it: emptying the approvals again fails 2 tests,
returning bare tags fails 3.

**Every gap originally recorded in this file is closed.** That is a narrower
claim than the one this line used to make, and the difference is the point: a
later multi-agent validation pass found fourteen mutation survivors and three
product defects that no test could reach, none of which were "gaps" in the
sense this file was recording. A file that lists closed gaps is not evidence
that nothing is wrong.

Corrected since: this line used to say what remained was "the Tauri Rust
crate". The crate exists — `src-tauri/src/{lib,commands,main}.rs`, the shell
module and two test files — with a CI job that compiles it on Linux and macOS.
It also used to omit **route→view dispatch**, which the body of this file lists
as open and which is still open; dropping it from the closing line implied it
had landed.

## The publish gate was wired and unreachable — CLOSED

`core/src/pacing/publish-gate.ts` is a verbatim port of the desktop's
stream-pacing, with two constants tightened deliberately for mobile
(`MAX_HELD_CHARS = 96`, `UNPAINTED_REOPEN_MS = 200`). It WAS called --
`controller.ts` had `if (frames.length > 0 && gate(streamed)) publish()` -- but
in the shipped pipeline that condition was almost never true, so neither
constant affected anything.

The reason was the coalescer's flush tick, added to fix answers arriving in one
lump. The tick drains the coalescer every `maxDelayMs`, so by the time a delta
arrives `push()` usually returns `[]` and the gate was not consulted at all. The
tick's own publish was ungated, on the reasoning that its frame "exists
precisely because nothing has painted recently."

Measured by driving the real controller with a virtual clock and counting
whether the gate was consulted even once (it calls `requestFrame` on its first
invocation, so the count is exact rather than inferred):

| tokens/sec | publishes for 2000 tokens | gate consulted (before) |
|-----------:|--------------------------:|:------------------------|
|         20 |                      2004 | no                      |
|         60 |                      2004 | no                      |
|        150 |                       670 | no                      |
|        400 |                       289 | no                      |
|       1600 |                        80 | no                      |
|       3200 |                        42 | YES                     |
|       8000 |                        42 | YES                     |

The threshold was where 256 bytes land inside a single 16ms window. Real model
streaming is 20-150 tokens/sec, so the gate was unreachable in practice.

This was not a live defect: paints stayed bounded by time (20-38/sec observed).
But two things followed from it. There was no backpressure path at all -- the
gate is the mechanism that notices the renderer cannot keep up, and it never
ran. And a module with its own tuned constants that never executes reads as
load-bearing to the next person who changes pacing.

**CLOSED by wiring, not deletion.** The flush tick now publishes THROUGH the
gate: `if (gate(streamed)) publish()`. The old "ungated is correct here"
reasoning had the gate's state backwards -- `gate()` returns `true` whenever the
gate is OPEN, and it is open exactly when nothing has painted recently (it opens
on its first call and reopens on a frame callback or after `UNPAINTED_REOPEN_MS`
with no paint). So the tick after a quiet period still paints immediately; the
gate only skips a tick that fires just after a paint, which is backpressure and
the one thing this pipeline lacked. `MAX_HELD_CHARS` still forces the tail out,
so a closed gate cannot swallow the end of an answer, and the final
`finally`-publish is ungated as before. Both constants are now load-bearing.

Pinned by `controller.test.ts` ("the flush tick paints through the publish gate,
so backpressure bounds it"): 40 ticks with no frame release produce a handful of
paints, not 40. Reverting to the ungated tick makes every tick paint (measured:
45 paints for 40 ticks) and fails the bound.

One subtlety the wiring had to answer, or it would have traded a paint-rate
problem for a visibility one. A tick DRAINS the coalescer before the gate is
consulted, so a frame the gate rejects is already gone from the coalescer -- its
text is on the transcript (the run loop applies every event) but not yet
painted. If the stream then PAUSES, no later tick sees pending text and the gate
reopening does not itself publish, so that progress would sit invisible until
the next delta or the final publish -- on a phone, a provider pausing mid-answer
is ordinary, so this is a real stall, not a corner case. The controller tracks
how far the screen has actually painted (`paintedChars`) and, on a tick that
finds nothing new to drain, flushes that stranded progress once the gate has
reopened. This is the backpressure RELEASE the gate needs to be safe: skip a
paint under load, then catch up the moment the renderer can. Pinned by
`controller.test.ts` ("text drained by a rejected tick is still painted when the
stream pauses"): the reopen fires mid-pause and the full answer paints WHILE THE
RUN IS STILL LIVE, not only at `end`.

Five settings used to be declared and consumed by nothing: `model`,
`temperature`, `showReasoning`, `showDiagnostics` and `apiKey` (issue #4636).
They were written for a settings screen and engine parameterisation that do not
exist yet. That is not a neutral "not done": a declared-but-unread setting is a
control the UI promises and the app does not keep, and `showDiagnostics` was
worse still — its `false` default claimed to hide dropped events, which are
rendered unconditionally. `apiKey` was the sharp one: `setSecret` was its only
write path and nothing outside tests called it, and even a written key was never
sent, because `enginesFor` never passed a `token`.

**Removed rather than half-wired.** `registry.ts` now declares only `engineId`
and `baseUrl` — the two the shipping app reads — and `registry.test.ts` pins
`SETTING_DEFS` to `CONSUMED_SETTING_KEYS`, so declaring a setting without also
wiring the code that reads it fails. The store's secret and validation machinery
stays (it is contract-tested in `core/src/settings/store.test.ts`), so a real
setting can return the day its consumer does.

What actually remains for praisonai-mobile, all of it unbuilt rather than
broken:

- **The keyboard half of the shell, and an iOS back.** The Rust crate now
  emits three of the four events: `lifecycle` from Tauri's suspend/resume/focus
  window events, `safe-area-changed` (an empty payload, meaning "re-read the
  CSS") on resize and scale change, and `back-gesture` from Android's system
  back via the in-repo `tauri-plugin-back-gesture`, answered through
  `back_gesture_result`. `keyboard-height` is still never emitted natively --
  the TypeScript reads `visualViewport` instead, and would take a native event
  as an override -- and nothing installs an iOS edge-swipe back. Haptics and
  share have no plugin; the bridge's invokes for them reject and degrade.
- **Route→view dispatch.** `ui/src/screens.ts` and `app/src/mount.ts` are built
  and tested, and `main.ts` imports neither. Tapping "Settings" pushes onto a
  stack nothing reads.
- **Every screen except the transcript.** Settings, chat list and about have
  complete view models and no renderer.
- **Tauri-native secrets and HTTP.** Declared honestly at
  `app/src/platform.ts`. Storage is no longer on this list: the Tauri build now
  writes chats to the app's data directory through `src-tauri/src/store.rs`
  (temp file, fsync, rename, fsync the directory), because the WKWebView
  `localStorage` it used before is evictable under storage pressure -- so
  `en.crashed`'s "Your conversations are saved" was false on a device. The
  StoragePort contract gained an atomicity case and three relaunch cases, both
  with break modes, and an existing install's `localStorage` data is migrated
  once (`adapters/src/storage/migrate.ts`) so the fix cannot look like the
  disease.
- **The in-process praisonai-ts engine as a shipping option.** Its stated
  blocker — bare `crypto` and `events` imports on the Agent graph — is fixed
  upstream; the wiring here is not done.

The decode-rejection defect recorded here is now closed. remote-http was the
only production caller of `decodeEvent` and discarded every rejection, so a
malformed frame made its tool vanish and the turn rendered as a clean answer.
`core/src/run/drop-sink.ts` is the channel between the engine (built at
composition) and the controller (built per app); refusals are drained onto the
transcript per event and again in `finally`, so one arriving beside the last
frame is still shown. Eight mutations, one per hop, each fails -- including
the two that make it *wired* rather than merely present: removing the sink
from `createRunController` and dropping the registry's forward both left the
suite green until composition tests were added for each.

One correction landed with it. `apply(start)` carried `dropped` across every
new `start`, including one that followed a FINISHED turn -- so a refusal on
turn 1 painted turn 2's clean answer as damaged, a success made to look like a
defect (the same failure this channel exists against, inverted). A turn that
already ended owns its drops; only a `before_start` drop, recorded while
`idle`, belongs to the turn now opening. Fixed by clearing `dropped` on a
`start` that replaces an ended turn, pinned at both hops: reverting it fails
one reducer test and one controller test.


## Conversation memory, and the one thing it deliberately does not do

**Closed.** `engines/src/praisonai-ts/engine.ts` sent `request.prompt` and only
`request.prompt`. Nothing in `engines/src` assembled prior messages, so the app
stored a conversation, rendered it, and showed the model none of it. Measured on
an Android emulator against the real provider: "What is the capital of France?"
→ "Paris.", then "And its population?" → a request for clarification, because
the second question arrived with no subject.

The fix is `Agent.setHistory`, upstream's documented answer to exactly this
("Restore a previously saved conversation so the model regains its memory of
it"). The engine builds a **fresh agent per turn** — the model and the key come
from settings and can change between messages — so upstream's own accumulation
across `streamEvents` calls dies with each agent and the conversation has to be
restored explicitly, every turn.

**Where the layering fell out.** Conversation memory is an *engine-level*
responsibility, owned by whoever owns the store, and it is NOT on
`AgentEnginePort`. Widening `RunRequest` with a `history` field would hand the
conversation to `remote-http` as well — and that engine POSTs `chat_id` to a
server that keeps its own history for that id, so every prior turn would arrive
twice, once from the client and once from the server's store. A doubled
conversation is worse than a missing one: silent, growing, and it makes the
model contradict itself. This is the same split `RegistryDeps.persistence`
already draws for the WRITE, drawn once more for the READ: two engines, two
owners of the conversation.

### Truncation: what happens, and what a user sees

`core/src/chat/history.ts` bounds a turn's history to
`HISTORY_CHAR_BUDGET` (24,000 characters, ≈6,000 tokens) by keeping the
**recent** end, stopping at the first message that does not fit, and dropping a
leading assistant message so the history never begins with an answer to a
question the model cannot see. Characters rather than tokens because tokenizing
would pull a model-specific tokenizer into a webview bundle; the budget is
deliberately an order of magnitude under the default model's window, because it
exists to make the failure impossible rather than to use the window efficiently.

**Still open, and stated rather than implied:** truncation is *not surfaced in
the UI*. When it fires, the transcript on screen is unchanged — nothing is
deleted, scrolling back still shows every message — but the model stops being
able to refer to the oldest turns, and the user is not told. Protocol v2 has no
event for "context was trimmed" and adding one is a protocol bump, so this is
recorded here instead of being half-done. `truncateHistory` already returns
`dropped`, so the value a notice would carry exists; nothing consumes it yet.

**Also still open:** `remote-http` conversations remain server-owned end to end,
so a chat answered by the default remote engine leaves the local session empty
and has no local history to restore. That is the same scope note Gap 4 carries
and it is unchanged by this.

---

### Src Praisonai Docs Channels Gateway (`src/praisonai/docs/channels-gateway.md`)

# Channels gateway integration

Channel bots (Telegram, Discord, Slack, WhatsApp) require the **`praisonai[bot]`** optional extra:

```bash
pip install "praisonai[bot]"
```

## Architecture

- **Pattern B/C host**: `configure_host()` + `AIUIGateway` serve chat UI and REST APIs.
- **Channels feature** (`praisonaiui.features.channels`): starts platform bots via `praisonai.bots`.
- **Gateway WebSocket**: `/ws` on the same process when using Pattern C.

## Environment variables

| Platform | Variables |
|----------|-------------|
| Telegram | `TELEGRAM_BOT_TOKEN` |
| Discord | `DISCORD_BOT_TOKEN` |
| Slack | `SLACK_BOT_TOKEN`, `SLACK_APP_TOKEN` |
| WhatsApp | `WHATSAPP_ACCESS_TOKEN`, `WHATSAPP_PHONE_NUMBER_ID` |

## CLI

```bash
praisonai dashboard --unified --aiui  # Pattern B in-process host (unified launcher)
PRAISONAI_HOST_LEGACY=1 praisonai ui  # Legacy @aiui.reply callbacks only
```

See `praisonai.bots.BotOS` for multi-platform orchestration.

---

### Src Praisonai Docs Pattern D Platform (`src/praisonai/docs/pattern-d-platform.md`)

# Pattern D — Platform API integration (defer)

Pattern D connects PraisonAIUI dashboard pages to a **PraisonAI Platform** server via `PlatformClient` `/api/v1`.

> The platform is an optional, separately released service maintained at
> [MervinPraison/PraisonAI-Platform](https://github.com/MervinPraison/PraisonAI-Platform).
> Nothing in this repository depends on it, and no self-hosted install needs it.
> The agent roster lives at `/api/v1/workspaces/{workspace_id}/agents` — note
> that `/api/v1/agents` is a different, unrelated endpoint served by
> `praisonai serve agents`.

## Scope (P3)

| Item | Status |
|------|--------|
| aiui pages → PlatformClient | Documented, optional |
| Platform JWT auth | Optional `auth.platform_jwt` config |
| Issues / kanban pages | Optional `@aiui.page` via platform |
| agent_id linking | See below |

## agent_id linking

Several agent registries coexist in a full install; the three relevant to correlation here are:

1. **Platform roster** — workspace-scoped agents (`/api/v1/workspaces/{workspace_id}/agents`)
2. **Gateway registry** — WebSocket `/ws` agent ids
3. **aiui SDKAgentRegistry** — YAML CRUD + local `Agent` instances

Use explicit `agent_id` in session metadata (`source=gateway|platform|ui`) to correlate rows in the workflow-runs and sessions tables.

## Optional platform JWT

When `PRAISONAI_PLATFORM_TOKEN` is set, future aiui auth middleware may validate JWT from the platform issuer. Not required for Patterns B/C self-hosted installs.

---

### Src Praisonai Agents Docs History LLM OPTIMIZATION SUMMARY (`src/praisonai-agents/docs/history/LLM_OPTIMIZATION_SUMMARY.md`)

# LLM Class Performance Optimizations Summary

## Overview
These optimizations improve the performance of the PraisonAI LLM class, particularly when running examples like `gemini-basic.py`. All changes maintain backward compatibility and preserve all existing features.

## Implemented Optimizations

### 1. One-Time Logging Configuration
- **Change**: Logging configuration moved to class-level method `_configure_logging()`
- **Impact**: ~3.4x speedup for subsequent LLM instances
- **Implementation**: Class flag `_logging_configured` ensures single configuration

### 2. Lazy Console Loading
- **Change**: Console only created when first accessed via property
- **Impact**: Saves ~5-10ms per LLM instance when verbose=False
- **Implementation**: Changed `self.console = Console()` to lazy property

### 3. Tool Formatting Cache
- **Change**: Cache formatted tools to avoid repeated processing
- **Impact**: 1764x speedup on cache hits
- **Implementation**: Added `_formatted_tools_cache` with cache key generation

### 4. Optimized litellm Import
- **Change**: Import litellm after logging configuration
- **Impact**: Cleaner initialization flow
- **Implementation**: Moved import after class-level logging setup

### 5. Cache Size Limits
- **Change**: Added `_max_cache_size = 100` to prevent unbounded growth
- **Impact**: Prevents memory issues in long-running applications
- **Implementation**: Simple size check before adding to cache

## Performance Improvements

For the `gemini-basic.py` example:
- **First LLM initialization**: ~0.004s
- **Subsequent LLM initialization**: ~0.001s (3.4x faster)
- **Tool formatting**: 1764x faster with caching
- **Console creation**: Only when needed (lazy loading)

## Code Changes Summary

### Modified Methods:
1. `__init__`: Simplified to use class-level logging configuration
2. Added `console` property for lazy loading
3. Added `_get_tools_cache_key()` for cache key generation
4. Modified `_format_tools_for_litellm()` to use caching

### New Class Members:
1. `_logging_configured`: Class-level flag
2. `_configure_logging()`: Class method for one-time setup
3. `_formatted_tools_cache`: Instance cache for tools
4. `_max_cache_size`: Cache size limit

## Backward Compatibility

All optimizations maintain 100% backward compatibility:
- All public APIs unchanged
- All features preserved
- Lazy loading transparent to users
- Caching automatic and invisible
- No behavioral changes

## Testing

Verified with:
- `gemini-basic.py` - Works correctly with optimizations
- Multiple LLM instances - Logging configured once
- Tool formatting - Cache works correctly
- Console usage - Lazy loading works as expected

The optimizations significantly improve performance while maintaining all functionality.

---

### Src Praisonai Agents Docs History LOGGING (`src/praisonai-agents/docs/history/LOGGING.md`)

# Centralized Logging in PraisonAI Agents

This document explains the enhanced centralized logging system implemented to address inconsistent logging patterns across the codebase.

## Problem Addressed

- **53+ scattered logger instances** with no unified configuration
- **No standard log format** across modules  
- **Mixed logging approaches** (logger.debug(), print(), console.print())
- **No structured logging option** for production deployments
- **Difficult filtering** by subsystem in multi-agent runs

## Solution

Enhanced the existing `praisonaiagents/_logging.py` with:

1. **Consistent naming convention**: All loggers follow `praisonaiagents.<module>` pattern
2. **Structured logging support**: JSON output for production environments
3. **Backward compatibility**: Existing code continues to work
4. **Centralized configuration**: Single place to configure all logging
5. **Optional extra data**: Structured data for better observability

## Quick Start

### Basic Usage

```python
# New recommended approach
from praisonaiagents import get_logger

# Automatic module detection
logger = get_logger()
logger.info("This is a log message")

# Explicit module name
logger = get_logger(__name__)
logger.info("Explicit module logging")
```

### Structured Logging

```python
import os
from praisonaiagents import get_logger, configure_structured_logging

# Enable structured JSON logging
os.environ['PRAISONAI_STRUCTURED_LOGS'] = 'true'
configure_structured_logging()

# Logger with extra structured data
logger = get_logger(extra_data={"agent_id": "assistant", "session": "123"})
logger.info("Task completed", extra={"task_id": "task_001", "duration": 1.5})
```

Output:
```json
{
  "timestamp": "2026-03-30T21:35:00Z",
  "level": "INFO", 
  "logger": "praisonaiagents.agent.agent",
  "message": "Task completed",
  "module": "agent",
  "function": "start",
  "line": 42,
  "agent_id": "assistant",
  "session": "123",
  "task_id": "task_001",
  "duration": 1.5
}
```

### Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `LOGLEVEL` | `WARNING` | Global log level (DEBUG, INFO, WARNING, ERROR) |
| `PRAISONAI_STRUCTURED_LOGS` | `false` | Enable JSON structured logging |

### Per-Module Configuration

```bash
# Set specific module to DEBUG level
export LOGLEVEL=INFO
# Configure in Python:
logging.getLogger('praisonaiagents.memory').setLevel(logging.DEBUG)
```

## Migration Guide

### For New Code

Use the new logging utilities:

```python
# ✅ Recommended - new code
from praisonaiagents import get_logger
logger = get_logger()
```

### For Existing Code

**No changes required** - existing code continues to work:

```python
# ✅ Still works - existing code
import logging
logger = logging.getLogger(__name__)
```

**Optional enhancement** for better observability:

```python
# ✅ Enhanced - gradually migrate
from praisonaiagents._logging import get_logger
logger = get_logger(__name__, extra_data={"subsystem": "agent"})
```

## Naming Convention

The `get_logger()` function automatically ensures consistent naming:

| Input | Output Logger Name |
|-------|--------------------|
| `"my_module"` | `"praisonaiagents.my_module"` |
| `"praisonaiagents.existing"` | `"praisonaiagents.existing"` (unchanged) |
| `"praisonai.other"` | `"praisonaiagents.other"` |
| `"__main__"` | `"praisonaiagents.main"` |
| `None` (auto-detect) | `"praisonaiagents.<current_module>"` |

## Production Deployment

### ELK Stack / Elasticsearch

```python
import os
from praisonaiagents import configure_structured_logging

# Enable JSON logging for log shipping
os.environ['PRAISONAI_STRUCTURED_LOGS'] = 'true'
configure_structured_logging()
```

### CloudWatch / Splunk

```python
import logging
from praisonaiagents import get_logger, StructuredFormatter

# Custom handler with structured format
handler = logging.StreamHandler()
handler.setFormatter(StructuredFormatter())

logger = get_logger()
logger.addHandler(handler)
```

### Filtering by Subsystem

With structured logging enabled, you can easily filter logs:

```bash
# Filter by agent subsystem
jq 'select(.logger | startswith("praisonaiagents.agent"))' logs.json

# Filter by specific agent
jq 'select(.agent_id == "assistant")' logs.json

# Filter by session
jq 'select(.session == "session_123")' logs.json
```

## Backward Compatibility

- ✅ All existing `logging.getLogger(__name__)` calls continue to work
- ✅ No performance impact on existing code
- ✅ No breaking changes to public APIs
- ✅ Gradual migration path available

## Examples

See the updated modules for examples:
- `praisonaiagents/plugins/builtin/logging_plugin.py` - Logging plugin with extra data
- `praisonaiagents/memory/memory.py` - Memory module with subsystem tagging

## Benefits

1. **Unified format**: All PraisonAI logs follow the same format
2. **Better observability**: Structured data for monitoring and debugging  
3. **Easy filtering**: Filter by subsystem, agent, or session
4. **Production ready**: JSON output for log aggregation systems
5. **Zero breaking changes**: Existing code continues to work unchanged
6. **Performance conscious**: No import-time overhead for normal usage

---

### Src Praisonai Agents Docs History OPENAI CLIENT OPTIMIZATION SUMMARY (`src/praisonai-agents/docs/history/OPENAI_CLIENT_OPTIMIZATION_SUMMARY.md`)

# OpenAIClient Performance Optimizations Summary

## Overview
These optimizations improve the performance of the OpenAIClient class, particularly when running examples like `openai-basic.py`. All changes maintain backward compatibility and preserve all existing features.

## Implemented Optimizations

### 1. Lazy Console Loading
- **Change**: Console only created when first accessed via property
- **Impact**: Saves initialization overhead when verbose=False (common case)
- **Implementation**: Changed direct initialization to lazy property

### 2. Lazy Sync Client Initialization
- **Change**: OpenAI sync client created only when first used
- **Impact**: Significant speedup (~5ms saved) when client not immediately needed
- **Implementation**: Property-based lazy loading with `_sync_client = None` initially

### 3. Tool Formatting Cache
- **Change**: Cache formatted tools to avoid repeated processing
- **Impact**: 346x speedup on cache hits for tool formatting
- **Implementation**: Added `_formatted_tools_cache` with cache key generation

### 4. Fixed Schema Cache Structure
- **Change**: Added cache for fixed array schemas
- **Impact**: Prevents repeated schema fixing operations
- **Implementation**: `_fixed_schema_cache` with size limit

### 5. Global Client Optimization
- **Change**: Enhanced global client to check parameters before recreating
- **Impact**: Avoids unnecessary client recreation when parameters match
- **Implementation**: Added `_global_client_params` tracking

### 6. Cache Size Limits
- **Change**: Added `_max_cache_size = 100` to prevent unbounded growth
- **Impact**: Prevents memory issues in long-running applications
- **Implementation**: Simple size check before adding to caches

## Performance Improvements

For the `openai-basic.py` example:
- **OpenAIClient initialization**: Near-instant (< 0.0001s)
- **Console creation**: Only when needed (lazy loading)
- **Sync client creation**: Deferred until first API call (~5ms saved)
- **Tool formatting**: 346x faster with caching
- **Global client reuse**: Instant when parameters match

## Code Changes Summary

### Modified Methods:
1. `__init__`: Added lazy initialization flags and caches
2. Added `console` property for lazy loading
3. Added `sync_client` property for lazy loading
4. Added `_get_tools_cache_key()` for cache key generation
5. Modified `format_tools()` to use caching
6. Enhanced `get_openai_client()` for parameter checking

### New Instance Members:
1. `_console`: Lazy-loaded console instance
2. `_formatted_tools_cache`: Cache for formatted tools
3. `_fixed_schema_cache`: Cache for fixed schemas
4. `_max_cache_size`: Cache size limit

### New Global Members:
1. `_global_client_params`: Track parameters for global client

## Backward Compatibility

All optimizations maintain 100% backward compatibility:
- All public APIs unchanged
- All features preserved
- Lazy loading transparent to users
- Caching automatic and invisible
- No behavioral changes
- Existing code continues to work without modification

## Testing

Verified with:
- `openai-basic.py` - Works correctly with optimizations
- Lazy loading tests - Console and clients load on demand
- Tool formatting cache - 346x speedup observed
- Global client reuse - Properly reuses when parameters match
- All tests pass without errors

## Summary

The optimizations significantly improve OpenAIClient performance through:
1. Deferred initialization of expensive resources
2. Caching of computed values
3. Smart global client management
4. Memory-bounded caches

These changes make the OpenAIClient more efficient for common use cases while maintaining all functionality and compatibility.

---

### Src Praisonai Agents Docs History OPTIMIZATION SUMMARY (`src/praisonai-agents/docs/history/OPTIMIZATION_SUMMARY.md`)

# Agent Performance Optimizations Summary

## Overview
These optimizations significantly improve the performance of PraisonAI agents, especially for simple use cases like `agent.start("Why sky is Blue?")`. All changes maintain backward compatibility and preserve all existing features.

## Implemented Optimizations

### 1. Lazy Loading of Rich Console
- **Change**: Console is only created when first accessed via property
- **Impact**: Saves ~5-10ms per agent when `verbose=False`
- **Implementation**: Changed `self.console = Console()` to lazy property

### 2. System Prompt Caching
- **Change**: Cache generated system prompts based on role, goal, and tools
- **Impact**: ~5ms saved per chat call after first call
- **Implementation**: Added `_system_prompt_cache` dictionary with cache key generation

### 3. Tool Formatting Caching
- **Change**: Cache formatted tool definitions to avoid repeated processing
- **Impact**: ~15-20ms saved for agents with tools (5395x speedup on cache hit)
- **Implementation**: Added `_formatted_tools_cache` dictionary

### 4. Deferred Knowledge Processing
- **Change**: Knowledge sources are processed only when first accessed
- **Impact**: Saves 50-200ms during initialization for agents with knowledge
- **Implementation**: Store sources in `_knowledge_sources`, process on first use

### 5. One-Time Logging Configuration
- **Change**: Configure logging only once at class level instead of per instance
- **Impact**: ~1-2ms saved per agent after first agent
- **Implementation**: Class method `_configure_logging()` with `_logging_configured` flag

### 6. Lazy Agent ID Generation
- **Change**: Generate UUID only when `agent_id` is first accessed
- **Impact**: ~0.5ms saved if agent_id is never used
- **Implementation**: Changed to property with lazy UUID generation

## Performance Improvements

For the simple example `agent.start("Why sky is Blue?")`:
- **Initialization time**: ~50% faster
- **First response time**: ~30% faster
- **Memory usage**: ~40% lower

Cache effectiveness:
- System prompt caching: 1.6x speedup
- Tool formatting caching: 5395x speedup (near-instant on cache hit)

## Code Changes Summary

All changes are minimal and focused on lazy loading and caching:
1. Properties replace direct initialization where possible
2. Caching added for expensive computations
3. Deferred processing for optional features
4. Class-level configuration for one-time setup

## Backward Compatibility

All optimizations maintain 100% backward compatibility:
- All public APIs unchanged
- All features preserved
- Lazy loading transparent to users
- Caching automatic and invisible
- No behavioral changes

## Testing

Verified with:
- `openai-basic.py` - Simple agent works correctly
- Tool-based agents - Tool formatting cache works
- Multiple agents - Logging configured once
- Console usage - Lazy loading works correctly

The optimizations significantly improve performance while maintaining all functionality.

---

### Src Praisonai Agents Docs History TELEMETRY SUMMARY (`src/praisonai-agents/docs/history/TELEMETRY_SUMMARY.md`)

# Telemetry Implementation Summary

## What Was Fixed

1. **PostHog initialization error** - Removed invalid `events_to_ignore` parameter
2. **Missing imports** - Added `MinimalTelemetry` and `TelemetryCollector` imports to telemetry `__init__.py`
3. **Wrong method instrumentation** - Changed from `agent.execute()` to `agent.chat()`
4. **Task tracking** - Added instrumentation for `workflow.execute_task()`
5. **Automatic setup** - Added `auto_instrument_all()` in main `__init__.py`
6. **Automatic flush** - Added `atexit` handler to send data on program exit

## Current Status

✅ **Telemetry is now working automatically!**

- Enabled by default (opt-out via environment variables)
- Tracks agent executions and task completions
- Sends anonymous data to PostHog on program exit
- No manual setup required

## Metrics Example
```
Telemetry metrics collected:
- Agent executions: 4
- Task completions: 2
- Errors: 0
- Session ID: 33873e62396d8b4c
```

## To Disable
Set any of these environment variables:
- `PRAISONAI_TELEMETRY_DISABLED=true`
- `DO_NOT_TRACK=true`

---

### Src Praisonai Agents Docs History Telemetry Analysis (`src/praisonai-agents/docs/history/telemetry_analysis.md`)

# Telemetry Analysis: Why PostHog Events Aren't Being Sent by Default

## Executive Summary

The telemetry system is implemented but **not actively integrated** into the PraisonAI Agents codebase. While PostHog is properly configured and functional, telemetry data is never sent because:

1. **No automatic integration**: Agent and PraisonAIAgents classes don't use telemetry
2. **No automatic flush**: Events are collected but never sent to PostHog
3. **No lifecycle hooks**: No atexit handler or periodic flush mechanism

## Current State

### What's Working ✓
- PostHog client is properly initialized with API key and host
- Telemetry can be enabled/disabled via environment variables
- Privacy-first design with anonymous tracking
- Manual telemetry tracking and flushing works correctly

### What's Not Working ✗
- Agent class doesn't integrate telemetry
- PraisonAIAgents class doesn't integrate telemetry
- No automatic flush() calls anywhere in the codebase
- Integration module (integration.py) is not used

## Technical Analysis

### 1. PostHog Configuration (telemetry.py)
```python
# Lines 84-93: PostHog is initialized correctly
if POSTHOG_AVAILABLE:
    try:
        self._posthog = Posthog(
            project_api_key='phc_skZpl3eFLQJ4iYjsERNMbCO6jfeSJi2vyZlPahKgxZ7',
            host='https://eu.i.posthog.com'
        )
    except:
        self._posthog = None
```

### 2. Flush Implementation (telemetry.py)
```python
# Lines 208-224: flush() sends events but is never called automatically
def flush(self):
    if hasattr(self, '_posthog') and self._posthog:
        try:
            self._posthog.capture(
                distinct_id='anonymous',
                event='sdk_used',
                properties={...}
            )
            self._posthog.capture('test-id', 'test-event')
        except:
            pass
```

### 3. Missing Integration Points

#### Agent Class (agent/agent.py)
- No telemetry imports
- No telemetry initialization in __init__
- No telemetry tracking in start(), run(), or execute_tool()

#### PraisonAIAgents Class (agents/agents.py)
- No telemetry imports
- No telemetry initialization
- No telemetry tracking in start() or workflow execution

## Root Causes

1. **Incomplete Implementation**: The telemetry system was built but never integrated into the main classes
2. **No Automatic Lifecycle Management**: No atexit handler or periodic flush
3. **Integration Module Not Used**: `integration.py` has the code but it's never imported/called

## Recommendations

### Immediate Fixes

1. **Add automatic integration to Agent class**:
```python
# In agent/agent.py __init__
from ..telemetry import get_telemetry
self._telemetry = get_telemetry()

# In start() method
if self._telemetry and self._telemetry.enabled:
    self._telemetry.track_agent_execution(self.name, success=True)
```

2. **Add atexit handler in telemetry.py**:
```python
import atexit

def _flush_on_exit():
    if _telemetry_instance:
        _telemetry_instance.flush()

atexit.register(_flush_on_exit)
```

3. **Add periodic flush**:
```python
# Flush after N events or T seconds
if self._metrics["total_events"] >= 100:
    self.flush()
```

### Long-term Improvements

1. **Make telemetry opt-in by default** with clear documentation
2. **Add telemetry configuration options** (flush interval, batch size)
3. **Implement proper error handling** for network failures
4. **Add telemetry dashboard** for users to see their usage

## Testing

Created test files demonstrate:
- `test_posthog.py`: PostHog is working correctly
- `test_posthog_detailed.py`: Events are sent when flush() is called
- `test_telemetry_integration.py`: Integration is missing

## Conclusion

The telemetry infrastructure is well-designed but incomplete. The main issue is that telemetry code exists in isolation and is never called by the core Agent/PraisonAIAgents classes. Additionally, even if it were integrated, the lack of automatic flush mechanisms means data would never reach PostHog.

---

### Src Praisonai Agents Docs Local Model Layer 00 Ground Truth (`src/praisonai-agents/docs/local-model-layer/00-ground-truth.md`)

# Ground truth

Every claim here was measured, not estimated. Each carries **how** it was obtained so it can
be re-checked cheaply. Measured 2026-09-03 against `origin/main` at `2591aa405`, with a live
Ollama 0.33.2 (`b79067b0`) on `127.0.0.1:11434`.

If a work order contradicts something here, re-measure before acting. Numbers drift.

> **Capabilities are per-model, not per-server.** An early draft of this file attributed the
> 9B model's capability list to `qwen3:0.6b`. Re-verified 2026-09-03: `qwen3:0.6b` is
> `["completion","tools","thinking"]` — **no vision**. Always name the model when quoting a
> capability set.

---

## 1. Runtime facts, verified live

| Fact | Value | How to re-verify |
|---|---|---|
| Ollama liveness probe | `GET /` returns `200` with body `Ollama is running` | `curl -sI 127.0.0.1:11434/` |
| Ollama version probe | `{"version":"0.33.2"}` | `curl -s 127.0.0.1:11434/api/version` |
| Capability probe works | `qwen3:0.6b` → `["completion","tools","thinking"]` (the 9B tamil model, separately, → `[...,"vision"]`) | `curl -s :11434/api/show -d '{"model":"qwen3:0.6b"}' \| jq .capabilities` |
| Unknown `options` keys are silently dropped | `{"totally_bogus_key":123}` → HTTP 200, no warning | send it to `/api/chat`; response is a normal completion |
| Tool-param schema keywords are stripped | `minLength`, `format`, `default`, `additionalProperties` all absent from the rendered prompt | `/api/chat` with `_debug_render_only: true` and those keys set |
| `parameters.type` must be a bare string | `"type": ["object","null"]` → **HTTP 400** `cannot unmarshal array into Go struct field ToolFunctionParameters...type of type string` | send that tool definition to `/api/chat` |
| **`format` + `tools` are mutually destructive** | Tool call silently suppressed; model fabricates. Same request without `format` calls the tool correctly. | see §2 below |

### Installed on this machine

`ollama` (0.33.2), `llama-server` (b7620, Homebrew), `mlx_lm.server`, `hf` CLI.
**Not** installed: `lms` (LM Studio), `vllm`.
Ports open at time of measurement: `11434` only.

---

## 2. The reproduction that matters most

`format` (JSON schema) plus `tools`, sent to Ollama, produces a **confident fabrication** with
an HTTP 200 and no warning. The JSON grammar makes the tool-call tag unemittable, so the
model cannot call the tool and answers from nothing instead.

```
POST /api/chat   model=qwen3:0.6b   think=false
prompt: "What is the weather in Paris? Use the tool."
tools:  [get_weather(city: string)]

WITH format + tools                     -> HTTP 200
  message.tool_calls : null
  message.content    : {"answer": "The weather in Paris is sunny with a temperature of 15C."}

TOOLS ONLY (format removed)             -> HTTP 200
  message.tool_calls : [{"function": {"name": "get_weather",
                                      "arguments": {"city": "Paris"}}}]
  message.content    : ""
```

Consequence for design: this combination must **raise**, not be silently repaired. A
fabricated answer that looks correct is worse than an error.

---

## 3. Codebase measurements

All obtained by script over `praisonaiagents/` at `2591aa405`.

### Scale

| Metric | Value |
|---|---|
| Python files / lines | 595 / 238,936 |
| Files over 2,000 lines | 13 |
| `agent/agent.py` | 7,701 |
| `llm/llm.py` | 7,160 |
| `agent/chat_mixin.py` | 6,151 |
| `llm/openai_client.py` | 2,691 |
| `llm/adapters/__init__.py` | 340 |

### `LLM` class cohesion

95 methods, 6,779 lines. Three largest methods total 3,087 lines — 43% of the file.

| Lines | Location | Method | Branch/loop/try nodes |
|---|---|---|---|
| 1,675 | `llm.py:2557` | `get_response` | **194** |
| 969 | `llm.py:4706` | `get_response_async` | 115 |
| 443 | `llm.py:4233` | `get_response_stream` | 56 |
| 249 | `llm.py:5966` | `_build_completion_params` | 52 |
| 199 | `llm.py:413` | `__init__` | 10 |

### Adapter call sites — the A1 finding

`DefaultAdapter` declares **17 methods** (an earlier draft said 18; the 18th item,
`add_provider_adapter`, is a module-level function). Eleven methods have **zero** call sites
anywhere, and with the three module functions that is 12 dead items. Note also that
`LLMProviderAdapterProtocol` declares only **16** — it omits `get_streaming_adapter`, so that
method is not part of the protocol it claims to implement.

```
supports_streaming                        2
format_tool_result_message                1   (llm.py:1712)
get_default_settings                      1   (llm.py:690)
should_summarize_tools                    1
supports_prompt_caching                   1
supports_streaming_with_tools             1
--- zero call sites ---
recover_tool_calls_from_text              0   (inline copy at llm.py:3468-3500)
parse_tool_calls                          0
handle_empty_response_with_tools          0
post_tool_iteration                       0
format_tools                              0
get_streaming_adapter                     0
get_max_iteration_threshold               0
should_skip_streaming_with_tools          0
supports_structured_output                0
inject_cache_control                      0
extract_reasoning_tokens                  0
add_provider_adapter                      0   (public registration hook)
```

Ollama references (case-insensitive): `llm/llm.py` **145**, `llm/adapters/__init__.py` 19,
`llm/streaming_protocol.py` 11, `tools/call_executor.py` 6.

### Compensation coverage across the three response paths — the A2 finding

```
                                        get_response   _async   _stream
                                             1675 L     969 L     443 L
tool_result_mapping  (value fix-up)          8          0         0
max_tool_repairs     (repair loop)           2          0         0
force_tool_usage     (prompt inject)         1          0         0
_validate_and_filter_ollama_arguments        1          1         0
_generate_ollama_tool_summary                1          1         0
_handle_ollama_sequential_logic              1          1         0
_format_ollama_tool_result_message           1          1         1*  (indirect)
```

`get_response_stream` has none of the seven — except `_format_ollama_tool_result_message`,
which it reaches indirectly via `_create_tool_message` (`llm.py:6791`), so that row overstated
the gap. A fuller re-measurement found **16** divergent compensations, not 7; three of them run
*against* the sync path. The full matrix is in `06-adapter-revival.md` §2.6. `difflib` similarity of `get_response` against
`get_response_async` is **22.3%**, while the file's other four sync/async pairs are 76–91% —
so those two have diverged, not merely duplicated.

### Import graph — the I6 constraint

65 subpackages, 212 directed edges, **26 mutually-importing pairs**. Heaviest:

```
agent   <-> tools       53 + 1        llm/ imports: tools 10, streaming 7,
agent   <-> approval    28 + 1                      agent 4, telemetry 2,
agent   <-> config      25 + 1                      auth 2, compaction 2,
agent   <-> llm         19 + 4                      context 1, thinking 1
llm     <-> tools       10 + 1
context <-> llm          2 + 1        15 subpackages import llm/
```

### Reachability — the A3 finding

21 modules call a provider SDK directly, bypassing both clients: 23 `litellm.completion/acompletion`,
7 `litellm.embedding/aembedding`, 16 `chat.completions.create`, 3 bare `OpenAI()`.

These nine contain **zero** occurrences of `api_base` or `base_url`, so there is no parameter
to set — "run everything locally" is currently unachievable, not merely unconfigured:

```
memory/memory.py          workflows/workflows.py     eval/judge.py
eval/grader.py            eval/accuracy.py           context/compressor.py
context/optimizer.py      lite/__init__.py           telemetry/performance_monitor.py
```

Worst single case, `memory/memory.py:2186-2192`:

```python
from openai import OpenAI
client = OpenAI()                    # no base_url, no api_key
response = client.chat.completions.create(
    model=llm or "gpt-4o-mini", ...
```

Hardcoded defaults in code (excluding docstrings): **105** `"gpt-4o-mini"`, **17**
`"text-embedding-3-small"`. Sixteen of the 105 are the identical line
`self.llm if hasattr(self,'llm') else "gpt-4o-mini"` in `agent/context_agent.py`.

### Stringly-typed provider identity — the A6 finding

**77 occurrences of 23 distinct string predicates** across `src/`. The same provider is
tested inconsistently, which is precisely how D3 and D4 arose:

```
 9  startswith("anthropic/")     gemini tested 3 ways:   gpt tested 4 ways:
 8  startswith("ollama/")          startswith("gemini")    startswith('gpt-')
 7  "ollama" in                    startswith("gemini/")   startswith("gpt-")
 6  startswith("gemini")           startswith('gemini-')   startswith("gpt")
 5  startswith("openai/")                                  "gpt" in
 5  startswith("claude")
 3  ":11434" in
```

### Accretion history — why boundaries matter here

| File | First | Now | Commits | Ever shrank |
|---|---|---|---|---|
| `llm/llm.py` | 1,212 (Jan 2025) | 7,160 | 251 | never, in 18 sampled months |
| `agent/agent.py` | 1,251 (Jan 2025) | 7,701 | 472 | once — the split below |
| `agent/chat_mixin.py` | created Apr 2026 | 6,151 | 150 | — |

On **2026-04-01** `agent.py` was split 8,915 → 5,030 by extracting `chat_mixin.py`. Five
months later the two halves total **13,852 lines — 55% above the pre-split file**, growing
~33 lines/day. Moving code did not create a boundary. This is the argument for I6 being a
*test* rather than a convention.

---

## 4. Dependency facts

| Package | Version present | Status |
|---|---|---|
| `httpx` | 0.28.1 | **hard transitive dep** of required `openai>=2.0.0` (`httpx<1,>=0.23.0`) |
| `aiohttp` | 3.14.1 | direct required core dep |
| `openai` | 2.44.0 | direct required core dep |
| `litellm` | 1.90.2 | optional (`llm`, `memory` extras) |

`pyproject.toml` declares **17 optional extras** — `a2ui, api, all, auth, autonomy, crawl,
dakera, graph, knowledge, llm, mcp, memory, mongodb, os, sandbox, search, telemetry` — and
**none of them is local**. `import praisonaiagents` measures 0.04 s, so imports are lazy and
cheap; discovery latency is the only startup cost to manage.

**Conclusion (superseded).** This section originally concluded `local/` should use `httpx`.
That was reversed by the normative decision in `07-local-package-spec.md` §3: `httpx` is present
only as an **undeclared transitive** edge (`openai -> httpx`), so building the dependency sink on
it means a future `openai` release dropping `httpx` would silently break `local/`. The client is
therefore stdlib `urllib.request`, and the boundary test forbids `httpx`/`requests`/`aiohttp`.
The measurement above stands; only the recommendation drawn from it was wrong.

---

## 5. litellm prefix resolution vs ours

litellm 1.90.2 resolves all of these; PraisonAI's `_detect_provider` recognises only `ollama/`:

```
ollama/llama3.2       -> ollama   OllamaAdapter    repairs=2
ollama_chat/llama3.2  -> openai   DefaultAdapter   repairs=0     <- litellm's RECOMMENDED prefix
lm_studio/qwen        -> openai   DefaultAdapter   repairs=0
vllm/x                -> openai   DefaultAdapter   repairs=0
hosted_vllm/x         -> openai   DefaultAdapter   repairs=0
huggingface/x         -> openai   DefaultAdapter   repairs=0
```

---

## 6. Known-bad environment note

`mervinpraison/praisonai-qwen3.5-9b-tamil-en2ta:latest` does **not load** on Ollama 0.33.2:
`Failed to load CLIP model from ...sha256-11540ddc21b3...`, HTTP 500. The vision projector
blob is the failing piece. Use `qwen3:0.6b` for local verification instead. Unrelated to this
work, but it will waste an agent's time if not known.


---

## 7. The three response paths disagree — measured, not inferred

Live Ollama, `temperature=0`, identical prompt and tool, two trials, reproducible
(script in `06-adapter-revival.md` §2.7):

```
sync    calls=2   'Paris: 21C sunny. Paris: 21C sunny.'
async   calls=1   'Paris: 21C sunny'
stream  calls=10  ''
```

> **Corrected 2026-09-03.** An earlier draft recorded the sync path returning
> `'{\n\n\n}'` with one tool call. That did not reproduce; the figures above did,
> across two trials. The finding is unchanged — the paths disagree and the stream
> path is broken — but the `'{\n\n\n}'` sample should not be cited.

Three facts follow, and they reframe the work:

1. **The best-compensated path produces the worst answer.** `get_response` carries 16 of the 18
   compensations and calls the tool twice, returning a doubled answer;
   `get_response_async` carries 8 and returns the correct answer once. More compensation is
   not the goal — *the same* compensation is.
2. **The stream path is not under-compensated, it is broken.** It burns all 10 iterations of
   `max_iter`, invokes the tool **ten times** for a one-tool question, and yields nothing. That
   is a cost and side-effect amplifier, not a formatting defect.
3. Leading hypothesis for the sync/async split: `OLLAMA_FINAL_ANSWER_PROMPT` (`llm.py:5302`,
   async only). **Still a hypothesis, not a measurement** — it was not settled during order 06,
   because the corrected baseline changed what needs explaining.

## 8. Two test-infrastructure traps

- **`src/praisonai-agents/tests/` is almost entirely outside CI.** The only tests any workflow
  runs from it are `tests/smoke/test_subscription_auth.py` and
  `tests/unit/auth/test_agent_auth_wiring.py`. `tests/unit/test_adapter_registry.py` (38 tests)
  and all 13 files in `tests/unit/llm/` run **nowhere**. Put new tests in
  `src/praisonai/tests/unit/llm/`, which is run.
- **`test_ollama_tool_reliability.py` tests a copy, not the product.** Its `MockLLM`
  re-implements `_is_ollama_provider`, `_apply_ollama_defaults`, `_validate_tool_call`,
  `_should_force_tool_usage` and both prompt templates. It cannot fail in response to any change
  in `llm.py`. Do not treat it as a safety net.


## 9. Test-gating facts (order 04)

- **`not network`, not `provider_ollama`, is what deselects the mocked base_url suite.** The gating
  plugin implies `network` from *any* provider marker (`test_gating.py:235-238`) and every CI
  expression contains `not network`. Editing the workflows' `-m` strings accomplishes nothing.
- `tests/unit/**` is **exempt** from provider auto-detection (`test_gating.py:215`,
  `test_type != 'unit'`). That is why `tests/unit/llm/test_ollama_tool_reliability.py` runs in CI
  while the integration file does not — and why live tests placed under `tests/unit/` need an
  **explicit** marker.
- `-m provider_ollama` currently selects **32 tests across 5 files**; only 7 are Ollama tests.
- **4 of the 7 tests in `test_base_url_api_base_fix.py` fail when actually executed** —
  `LLMResponseError: 'str' object has no attribute 'choices'`. The mock returns a dict; the
  tool-calling loop needs an object with `.choices`.
- **`tests/test_double_api_fix.py` makes a real network call when forced to run.** `llm.py` routes
  `gpt-4o-mini` through `litellm.responses` (`llm.py:6434`), not `litellm.completion`, so its patch
  no longer intercepts (verified: 401 from `api.openai.com/v1/responses`). It is currently masked
  by an unconditional auto-skip — **anyone who "fixes" the skip without fixing the mock gets live
  billed calls.**
- **`network_guard.py` disables itself** for anything under `/integration/`, `/e2e/`, `/live/`
  (lines 103-105) and for any `provider_*`-marked test (96-100). The suite's network blocker does
  not cover the tests most likely to make network calls.
- **A live Ollama suite already exists** and has never run:
  `tests/integration/test_ollama_tool_calling_live.py`, 230 lines, 7 tests, gated on
  `PRAISONAI_TEST_OLLAMA`. It is broken against `main` — all 7 pass `verbose=True` to `Agent()`,
  and two pass `force_tool_usage=` / `max_tool_repairs=`; all three now raise `TypeError`.
- **`qwen3:0.6b` is 522 MB** (not ~400 MB) and reports `completion, tools, thinking` — **no
  vision**. Reliability through `Agent`: default 3/4; `force_tool_usage="always"` + `temperature=0`
  **6/6**; multi-step arithmetic 0/2 (one hung past 90 s).

---

### Src Praisonai Agents Docs Local Model Layer 04 Test Gating (`src/praisonai-agents/docs/local-model-layer/04-test-gating.md`)

# 04 — D7: provider markers are assigned per file, so mocked tests are gated as if live

**Branch:** `fix/gating-per-test-provider-markers`
**Measured:** clean worktree at `origin/main` (`2591aa405`), working tree clean.
**Owns:** `src/praisonai/tests/_pytest_plugins/test_gating.py`, both `pytest.ini` files,
`src/praisonai/tests/conftest.py`, `tests/integration/test_base_url_api_base_fix.py`,
`tests/unit/cli/test_test_command.py`.
**Must not edit:** any `praisonaiagents/` source; `.github/workflows/**` (order 05).

> **The audit's stated root cause was wrong, and the correction changes the fix.**
> `provider_ollama` is a red herring. **`not network` deselects all 7 tests on its own**, because
> the plugin implies `network` from *any* provider marker and the file also matches
> `provider_openai`. **Removing `not provider_ollama` from the workflows would change nothing.**
> The fix must be marker-side, not workflow-side. This is why order 04 touches no YAML.

---

## 1. Corrections to the audit

| # | Claim | Verdict |
|---|---|---|
| 1 | 4 CI marker expressions carry `not provider_ollama` | **True but incomplete** — there is a 5th, non-CI location: `src/praisonai-code/praisonai_code/cli/commands/test.py:67` (`praisonai test --tier main`). |
| 2 | 7 tests, all deselected | **Exactly true** (`collected 7 items / 7 deselected / 0 selected`). **Stated cause is wrong** — see the callout above. |
| 3 | The file never inspects `litellm.completion` kwargs | **True** (only `mock_completion.assert_called()`). **And worse: 4 of the 7 tests fail outright when executed.** They are not merely toothless, they are broken. |
| 4 | `test_double_api_fix.py`: 0 asserts, 34 prints | **True. And worse:** all 3 tests are auto-`skip`ped in every configuration, and when forced to run its `patch('litellm.completion')` no longer intercepts — `llm.py` routes `gpt-4o-mini` through `litellm.responses`, so it makes a **real network call** (verified: 401 from `api.openai.com/v1/responses`). |
| 5 | `test_ollama_tool_reliability.py` asserts against MockLLM | **True.** 541 lines, MockLLM at 23–197, 28 tests, all pass. **Quantified:** 2 of the 8 re-implemented methods (`_apply_ollama_defaults`, `_try_parse_tool_call_json`) **do not exist on the real `LLM` at all.** |
| 6 | agents-side ollama tests gated only by `OLLAMA_HOST` | **True**, and `test_ollama_fix_openai` is gated only by `OPENAI_API_KEY` — a live **billed** call on a plain `pytest`. Mitigating: no CI workflow runs these two files. |
| 7 | No ollama live job | **True for CI**, but the audit **missed that the suite already exists**: `tests/integration/test_ollama_tool_calling_live.py`, 230 lines, 7 tests, gated on `PRAISONAI_TEST_OLLAMA=1`. It is **broken against current `main`**. See order 05. |

---

## 2. Reproduce before the fix

```bash
cd src/praisonai && export PYTHONPATH=$(cd ../praisonai-agents && pwd)
CI_M="not slow and not network and not local_service and not provider_anthropic and not provider_google and not provider_ollama and not provider_grok_xai and not provider_groq and not provider_cohere"
```

**R1 — 100% deselected:**
```bash
python -m pytest tests/integration/test_base_url_api_base_fix.py -m "$CI_M" --collect-only -q --disable-warnings
# collected 7 items / 7 deselected / 0 selected
```

**R2 — `provider_ollama` is a red herring.** Rerun R1 with `and not provider_ollama` **removed**:
still `7 deselected / 0 selected`. `not network` does it alone.

**R3 — the whole file is tagged.** With a marker-dump plugin, all seven items carry the identical
set `['integration', 'network', 'provider_ollama', 'provider_openai', 'skip']` — including the six
that never mention Ollama.

**R4 — 4 of 7 fail when actually executed:**
```bash
PRAISONAI_ALLOW_NETWORK=1 PRAISONAI_TEST_PROVIDERS=all OPENAI_API_KEY=sk-fake-offline \
  python -m pytest tests/integration/test_base_url_api_base_fix.py -o addopts="" -q --tb=no -rA
# 4 failed, 3 passed
```
All four fail with `LLMResponseError: ... 'str' object has no attribute 'choices'`. The three that
pass are the three that never call `get_response()`.

**R5 — `-m provider_ollama` selects 4× more than it should:**
```
   7 tests/integration/test_base_url_api_base_fix.py
   7 tests/integration/test_ollama_tool_calling_live.py
  11 tests/integration/test_rag_integration.py
   4 tests/integration/test_setup_integration.py
   3 tests/test_double_api_fix.py
```
**32 selected; only 7 are Ollama tests.** This is why order 04 is a hard prerequisite for order 05 —
`-m provider_ollama` is currently not a usable selector.

---

## 3. Root cause

`test_gating.py:153-166` scans the **entire file**:

```python
153  def _detect_providers_in_file(filepath: Path) -> Set[str]:
154      """Detect which providers are referenced in a test file."""
...
161      content = _get_file_content(filepath)
162      detected = set()
163      for marker, pattern in PROVIDER_PATTERNS.items():
164          if pattern.search(content):
165              detected.add(marker)
166      return detected
```

Line 28 is `'provider_ollama': re.compile(r'\b(ollama)\b', re.IGNORECASE)`. One occurrence inside
`test_ollama_environment_variable_compatibility` tags all seven items (applied at lines 213–230).

Note line 215: `if item.fspath and test_type != 'unit'` — **`tests/unit/**` is exempt**, which is
why `tests/unit/llm/test_ollama_tool_reliability.py` runs in CI while the integration file does not.

**The second mechanism, which the audit missed**, is lines 235–238:

```python
235          # 3. Add network marker if any provider marker is present
236          provider_markers = {m for m in existing_markers if m.startswith('provider_')}
237          if provider_markers and 'network' not in existing_markers:
238              item.add_marker(pytest.mark.network)
```

A mocked test that merely *mentions* `openai` gets `network`, and every CI expression contains
`not network`. Lines 262–267 then convert it into a runtime skip.

**Sub-defect 3.** Lines 59, 145, 177, 234 are all bare `mock_completion.assert_called()`. Nothing
reads `call_args`. Measured: `LLM(model='openai/mistral', base_url='http://localhost:4000',
api_key='sk-test').get_response("test", stream=False)` calls `litellm.completion` with
`base_url='http://localhost:4000'` and `api_base=None`. **So the file's title is stale** — the real
invariant is *`base_url` survives into the call*, not "maps to `api_base`".

---

## 4. The change

**Design decision: AST per-test marking, not file splitting.**

- *Split the file* — cost cheap, **benefit zero** (measured, R2): the six non-Ollama tests still
  match `provider_openai`, still get `network`, still get deselected. It also leaves `-m
  provider_ollama` selecting 32 tests and fixes nothing for the other 14 mixed-provider files.
  **Rejected.**
- *AST per-test marking* — one change in one plugin, fixes the class of problem, and is the
  prerequisite for order 05's selector to mean anything. **Recommended.**

### Sub-change 1 — per-test provider detection via AST

Keep `_detect_providers_in_file` (it now serves only the `network` marker) and add:

```
/* Detailed source-code truncated for AI context efficiency. */
```

Add `import ast`, a `_file_provider_cache: Dict[str, Optional[Dict[tuple, Set[str]]]] = {}` next to
`_file_content_cache` (line 46), and clear it in `pytest_configure` (186) and
`pytest_sessionfinish` (294).

### Sub-change 2 — `offline` opt-out, and pin `network` to the file

Replace lines 213–230 with a version that (a) honours an explicit `offline` marker, (b) calls
`_detect_providers_for_item`, and (c) **keeps `network` whole-file derived**:

```python
                offline = 'offline' in existing_markers
                if not offline:
                    detected_providers = _detect_providers_for_item(item)
                    for marker, pattern in PROVIDER_PATTERNS.items():
                        if pattern.search(item.nodeid):
                            detected_providers.add(marker)
                    for provider in detected_providers:
                        if provider not in existing_markers:
                            item.add_marker(getattr(pytest.mark, provider))
                    # The `network` marker stays WHOLE-FILE derived. Narrowing
                    # the provider markers must not, by itself, un-deselect a
                    # test that is really live -- only `offline` does that.
                    if _detect_providers_in_file(filepath) and 'network' not in existing_markers:
                        item.add_marker(pytest.mark.network)
```

**Why `network` stays file-derived — this is the whole backward-compatibility story and is not
optional.** Measured: if per-test narrowing were also allowed to narrow `network`, **48 currently-
deselected integration tests would newly select, 25 of them with no `skipif` — they would actually
execute**, across nine files including `test_rag_live.py` and `test_model_routing_real.py`, in a
suite where the network guard is disabled for everything under `/integration/`
(`network_guard.py:103-105`). Pinning `network` to the file makes sub-change 1 provably
**selection-neutral** under every existing `-m` expression, while still making `-m provider_ollama`
mean what it says.

Register the marker in both `pytest.ini` files and `tests/conftest.py`:
```
    offline: Fully mocked - opt out of provider/network auto-marking
```

### Sub-change 3 — opt the file in, and make it guard its bug

Add `pytestmark = pytest.mark.offline` plus a response factory:

```python
def make_completion_response(text="Test response"):
    """A litellm.completion stand-in the LLM tool-calling loop can consume.

    A bare dict is NOT sufficient: the loop reads ``.choices[0].message`` and a
    dict raises ``'str' object has no attribute 'choices'``.
    """
    resp = MagicMock()
    resp.choices = [MagicMock()]
    resp.choices[0].message.content = text
    resp.choices[0].message.tool_calls = None
    resp.choices[0].finish_reason = "stop"
    return resp
```

For each of the four broken tests: replace the dict `return_value` with
`make_completion_response(...)`, pass `stream=False` to `get_response`, and replace
`mock_completion.assert_called()` with a real kwarg assertion:

```python
        kwargs = mock_completion.call_args.kwargs
        assert kwargs['base_url'] == 'http://localhost:4000'
        assert kwargs['api_key'] == 'sk-test'
        assert kwargs['model'] == 'openai/mistral'
```

- `test_koboldcpp_specific_scenario` → `kwargs['base_url'] == "http://127.0.0.1:5001/v1"`
- `test_litellm_documentation_example_compatibility` → `kwargs['base_url'] == "http://0.0.0.0:4000"`
- `test_ollama_environment_variable_compatibility` → `kwargs['model'] == 'ollama/llama2'` **and**
  `'base_url' not in kwargs` (none was configured; the env path must not inject one)

All four were run standalone against `main` and pass. Leave the three currently-passing tests alone.

Update the stale module docstring ("maps base_url to api_base" → "base_url must reach litellm") but
**do not rename the test functions** — the nodeids are referenced in issue discussion, and renaming
would change what the nodeid scan at plugin lines 224–226 sees.

---

## 5. Backward-compatibility contract

Baseline, measured (`tests/integration/`, CI ignores applied): **290 collected, 187 selected,
103 deselected** under the CI marker expression.

> Caveat for the executing agent: a cold first invocation on a fresh interpreter has been observed
> to report `157/260`, apparently an optional-dependency import warming effect. **Run it twice**;
> `187/290/103` is stable from the second run on. Take your own baseline before touching anything.

**Tests whose selection status changes: exactly 7**, all in `test_base_url_api_base_fix.py`, all
deselected → selected. Post-fix expectation: **194/290 (96 deselected)**. Nothing else moves in
either direction — that is what the file-derived `network` guarantees.

Intended change under `-m provider_ollama` (32 → 9):

| file | before | after |
|---|---|---|
| `test_ollama_tool_calling_live.py` | 7 | 7 |
| `test_base_url_api_base_fix.py` | 7 | 0 (`offline`) |
| `test_rag_integration.py` | 11 | 1 |
| `test_setup_integration.py` | 4 | 0 |
| `test_double_api_fix.py` | 3 | 1 |

**The risk, stated plainly.** Un-deselecting tests turns CI red if any fail. **They do: 4 of the 7
fail today** (R4). This is not hypothetical.

**Mitigation — mandatory, not optional: land the gating fix and the four repairs in the same PR.**
Do not merge sub-changes 1+2 with the `pytestmark` but without the repairs. **Quarantining with
`xfail` is explicitly rejected** — the repairs are ~10 lines each, verified working, and an `xfail`
here would recreate the exact defect being fixed (a test that names a bug and does not guard it).

**Escape hatch.** If the 7 prove flaky in CI for a reason not reproducible locally, revert
**sub-change 3 only**. Selection returns to 187/290/103 and the plugin improvements stay.

---

## 6. Tests to add

In `tests/unit/cli/test_test_command.py` (the existing home of gating-plugin tests, and already in
`EXCLUDED_PATHS`, so these cannot be auto-marked by the thing they test), add
`class TestProviderMarkerGranularity` with:

- `test_ollama_does_not_leak_to_sibling_tests` — **THE meta-test.** If this fails, D7 has regressed.
- `test_openai_does_not_leak_to_sibling_tests`
- `test_plain_test_gets_no_provider_markers`
- `test_decorators_are_scanned` — a `@pytest.mark.parametrize("m", ["ollama/llama2"])` must mark it
- `test_unparseable_file_falls_back_to_whole_file` — conservative over-marking on a parse failure
- `test_network_marker_remains_whole_file_derived` — pins the decision that keeps this change
  selection-neutral for the 96 still-deselected tests
- `test_offline_marker_is_registered` — both `pytest.ini` files, or every use warns

No new dependency: `ast`, `tmp_path` and `configparser` are stdlib/pytest builtins.

---

## 7. Verification and acceptance

```bash
# 1. The 7 are now selected
python -m pytest tests/integration/test_base_url_api_base_fix.py -m "$CI_M" --collect-only -q
# expect: 7 selected, 0 deselected

# 2. They pass offline, with no keys and no services
env -u OPENAI_API_KEY -u ANTHROPIC_API_KEY -u OLLAMA_HOST \
  python -m pytest tests/integration/test_base_url_api_base_fix.py -m "$CI_M" -o addopts="" -q
# expect: 7 passed

# 3. Selection neutral everywhere else
python -m pytest tests/integration/ $IG -o addopts="" -q --collect-only -m "$CI_M" | tail -1
# expect: 194/290 tests collected (96 deselected)

# 4. `-m provider_ollama` now means Ollama  -> 7 + 1 + 1, not 32
# 5. Meta-tests pass
# 6. The three CI shards reproduced verbatim do not regress
# 7. The two pytest.ini marker tables stay in sync
```

**Acceptance gate:** `tests/integration/` collects **194/290 (96 deselected)** — exactly seven more
than baseline, all seven from `test_base_url_api_base_fix.py` — **and passes with
`OPENAI_API_KEY`, `ANTHROPIC_API_KEY` and `OLLAMA_HOST` all unset and no Ollama server running.**

**PR title:** `fix(tests): mark provider tests per test function, not per file`

---

## 8. Filed for separate PRs

- **`tests/test_double_api_fix.py`'s mock no longer intercepts.** `llm.py` routes `gpt-4o-mini`
  through `litellm.responses` (`llm.py:6434`), not `litellm.completion`. Forced to run, it makes a
  **real OpenAI request** (verified: 401 for `https://api.openai.com/v1/responses`). Today it is
  masked by an unconditional auto-`skip` — **anyone who "fixes" the skip without fixing the mock
  gets live billed calls.**
- **`network_guard.py` disables itself for `/integration/`, `/e2e/`, `/live/`** (lines 103–105) and
  for any `provider_*`-marked test (96–100). The suite's network blocker does not cover the tests
  most likely to make network calls.

---

### Src Praisonai Agents Docs Local Model Layer 05 Live Ci Job (`src/praisonai-agents/docs/local-model-layer/05-live-ci-job.md`)

# 05 — Live local-model CI job

**Branch:** `feat/ci-ollama-live-job`
**Depends on:** order `04` must merge first. Before it, `-m provider_ollama` selects 32 tests
across 5 files (25 of which are not Ollama tests) and this job is unbuildable.
**Owns:** `.github/workflows/test-optimized.yml`,
`src/praisonai/tests/integration/test_ollama_tool_calling_live.py`.
**Must not edit:** `test_gating.py` (order 04); the `smoke` / `main` / `openai-live` jobs; anything
in `test-core.yml`; `src/praisonai-agents/tests/test_ollama_{fix,async_fix}.py`.

---

## 1. The suite already exists — and is broken

The audit concluded "no ollama live job, and no live suite". The first half is right; **the second
is wrong**. `src/praisonai/tests/integration/test_ollama_tool_calling_live.py` is 230 lines,
7 tests, gated at lines 19–22 on `PRAISONAI_TEST_OLLAMA`. It has never run anywhere.

Measured against `main`, **it cannot run** — three `Agent()` kwargs are now rejected:

```
$ python -c "from praisonaiagents import Agent; Agent(name='C', llm='ollama/qwen3:0.6b', verbose=True)"
TypeError: Agent.__init__() got unexpected keyword argument(s): verbose
  verbose: verbosity moved into output=; use output='verbose' (or output=OutputConfig(verbose=True)).

$ ... Agent(..., force_tool_usage="always")   -> TypeError: unexpected keyword argument(s): force_tool_usage
$ ... Agent(..., max_tool_repairs=3)          -> TypeError: unexpected keyword argument(s): max_tool_repairs
```

All 7 tests use `verbose=True`; two also use the other two. **Every test errors on construction.**
The modern form, verified working:

```python
Agent(name="C",
      llm={"model": "ollama/qwen3:0.6b", "force_tool_usage": "always", "max_tool_repairs": 3},
      tools=[calculator])
# -> llm_instance.force_tool_usage == 'always', llm_instance.max_tool_repairs == 3
```

So this order is **"fix a dead test file and wire it up"**, not "write a live suite".

---

## 2. Model selection

Measured on a real Ollama 0.33.2 host:

```
$ ollama list
qwen3:0.6b   7df6b6e09427   522 MB
$ ollama show qwen3:0.6b
  parameters       751.63M      quantization  Q4_K_M      context length  40960
  Capabilities:    completion, tools, thinking
```

**Two corrections:** the blob is **522 MB**, not ~400 MB; and it is **not vision capable** —
`completion, tools, thinking` only. Tools + thinking is all this job needs.

**Reliability, measured end-to-end through `praisonaiagents.Agent`:**

| configuration | trials | tool invoked + correct answer | latency |
|---|---|---|---|
| default | 4 | **3/4** — one run returned `{}` with no tool call | 0.5–5.4 s |
| `force_tool_usage="always"`, `temperature=0` | 6 | **6/6** | 0.4–4.0 s |
| indirect prompt ("I know it's easy, but use the tool") | 1 | 0/1 — emitted `{"type": "calculator", ...}`, wrong key | 0.6 s |
| multi-step `(17+25)+(8+9)` | 2 | 1 hung past 90 s; 1 answered 42 instead of 59 | — |

**Conclusion: `qwen3:0.6b` is the right model, but only the forced, zero-temperature, single-call
prompt is CI-deterministic.**

Rejected alternatives: `qwen2.5:0.5b` (~400 MB, older tool calling, unmeasured — no reason to
prefer it over a verified model); `llama3.2:1b` (~1.3 GB, 2.5× the cache for no measured gain);
`smollm2:135m` (**no `tools` capability — disqualifying**); `olmo-3` (the file's current default,
~7B, far too large per run). Keep `olmo-3` as the *local* default so developer workflow is
unchanged; let CI override via env var.

**Cache:** `~/.ollama/models`, keyed `${{ runner.os }}-ollama-models-${{ env.OLLAMA_TEST_MODEL }}`.
**No `restore-keys`** — a partial restore of a *different* model's blobs is worse than a clean
pull, and a stale key would silently test the wrong model.

**Install:** pinned release tarball, not `curl https://ollama.com/install.sh | sh`. The install
script tracks latest, so the job would silently change what it tests, and it pulls GPU runtimes a
CPU-only runner never uses. Expect ~20–60 s tarball + ~30–90 s cold model pull, near-zero on a
cache hit — **the executing agent must confirm real timings on the first green run and write them
into a YAML comment.**

**Gating:** `if: github.event_name == 'schedule' || github.event.inputs.tier == 'extended' ||
github.event.inputs.tier == 'nightly'` — byte-identical to `extended-anthropic` (line 467),
`extended-google` (525), `extended-groq` (585), `extended-xai` (644), `extended-cohere` (703).
**It never runs on a pull request.**

---

## 3. One deliberate departure from the sibling jobs

Every existing live job ends `|| echo "... tests completed"`, so **it can never fail**. That is
defensible for key-dependent jobs — a rotated secret should not page anyone — but it is exactly
the "test that cannot fail" pattern this whole effort exists to remove, and **Ollama needs no
secret**: availability is fully under the job's control.

So the job has **two run steps**:
1. a **required** minimum-contract step with **no `|| echo`**;
2. an **informational** step for the measured-flaky remainder, keeping the sibling style.

**Do not merge them.**

---

## 4. Test-file changes

1. After `pytestmark`, add the model indirection:
   ```python
   # CI overrides this with a small, fast model; local runs keep olmo-3.
   OLLAMA_MODEL = "ollama/" + os.getenv("PRAISONAI_OLLAMA_TEST_MODEL", "olmo-3")
   ```
2. Replace all 7 hard-coded `llm="ollama/olmo-3"` with `llm=OLLAMA_MODEL`.
3. Remove `verbose=True` from all 7 `Agent(...)` calls. Where verbosity is wanted: `output="verbose"`.
4. Move `force_tool_usage="always"` and `max_tool_repairs=3` into an `llm` dict.
5. Add the CI-minimum test as a new first class — **the only assertion in the file with a measured
   6/6 pass rate**:

```python
class TestOllamaCIMinimum:
    """The minimum contract a local model must satisfy: a tool call round-trips.

    Deliberately narrow. Measured on qwen3:0.6b: this exact configuration
    (forced tool usage, temperature 0, single arithmetic step) passed 6/6.
    The default configuration passed 3/4 and multi-step prompts were worse --
    those live in TestOllamaToolCallingLive, which CI runs informationally.
    """

    def test_tool_call_round_trips(self, ollama_available):
        from praisonaiagents import Agent

        invocations = []

        def add(a: int, b: int) -> int:
            """Add two integers together.

            Args:
                a: First number to add
                b: Second number to add
            """
            invocations.append((a, b))
            return a + b

        agent = Agent(
            name="CI Calculator",
            llm={"model": OLLAMA_MODEL, "force_tool_usage": "always", "temperature": 0},
            tools=[add],
        )
        result = agent.chat("Compute 17 + 25. You MUST use the calculator tool.")

        # 1. the model actually called our function, with the right arguments
        assert invocations == [(17, 25)], f"tool was not invoked: {invocations!r}"
        # 2. the tool's return value made it back into the model's answer
        assert "42" in str(result), f"tool result did not round-trip: {result!r}"
```

Reuse the existing `ollama_available` fixture (lines 48–53) — it already probes
`http://localhost:11434/api/tags` and skips cleanly. Do not add a second probe.

### Why both assertions are needed

`qwen3:0.6b` answers `17 + 25 = 42` **correctly with no tools at all** (measured, 1.2 s,
`tools=[]`). So a bare `assert "42" in result` is satisfied by a model that ignores tools entirely.
The `invocations == [(17, 25)]` half is what proves the tool call was emitted, parsed and
dispatched with the right arguments; the `"42"` half proves the return value was fed back and
reached the final answer. Anything beyond this — multi-step chains, repair loops, resisting
distraction — is measured-flaky on a 0.6B model and belongs in the informational step.

---

## 5. The YAML

Insert after `extended-cohere`'s `Skip notice` step (ends line 760), before the `legacy-unit`
banner. Key fragments:

```
/* Detailed source-code truncated for AI context efficiency. */
```

And in `test-summary` (line 838): extend `needs: [smoke, main, extended-ollama]` and add the
summary rows. `test-summary` is already `if: always()`, so a skipped `extended-ollama` on PRs
reports `skipped` rather than blocking.

---

## 6. Verification and acceptance

```bash
ollama pull qwen3:0.6b
cd src/praisonai && export PYTHONPATH=$(cd ../praisonai-agents && pwd)

# Must be 6/6 before this ships.
for i in $(seq 1 6); do
  PRAISONAI_TEST_OLLAMA=1 PRAISONAI_ALLOW_NETWORK=1 PRAISONAI_LIVE_TESTS=1 \
  PRAISONAI_TEST_PROVIDERS=ollama PRAISONAI_OLLAMA_TEST_MODEL=qwen3:0.6b \
    python -m pytest tests/integration/test_ollama_tool_calling_live.py::TestOllamaCIMinimum \
    -o addopts="" -q --timeout=120 2>&1 | tail -1
done

# The gate still holds with the env var absent:
python -m pytest tests/integration/test_ollama_tool_calling_live.py -o addopts="" -q --collect-only
# expect: collected, all skipped by the module pytestmark

# Nothing leaked onto the PR path:
grep -n "extended-ollama" -A3 .github/workflows/test-optimized.yml | grep "if:"
python -c "import yaml; yaml.safe_load(open('.github/workflows/test-optimized.yml')); print('yaml ok')"

# Then: gh workflow run "Optimized Test Suite" -f tier=extended
```

**Acceptance gate:** a manual `workflow_dispatch` with `tier=extended` shows `extended-ollama`
**green**, with "Run Ollama minimum contract (required)" reporting `1 passed` — **and** the same
workflow triggered by a pull request shows `extended-ollama` **skipped**.

**PR title:** `ci: add nightly live-Ollama job exercising a real local model`

---

### Src Praisonai Agents Docs Local Model Layer 06 Adapter Revival (`src/praisonai-agents/docs/local-model-layer/06-adapter-revival.md`)

# 06 — A1/A2: make the provider adapter load-bearing

**Measured against:** `origin/main` @ `2591aa405`, 2026-09-03, live Ollama 0.33.2 on
`127.0.0.1:11434`, model `qwen3:0.6b`.
**Blocked by:** order `02-d3-provider-detection` (both edit `llm/llm.py`; land 02 first).
**Owns:** `llm/adapters/__init__.py`, `llm/protocols.py` (`LLMProviderAdapterProtocol` only),
`llm/llm.py` (the three response paths), new tests under `src/praisonai/tests/unit/llm/`.
**Must not edit:** `agent/agent.py`, `llm/llm.py:_detect_provider`,
`llm/llm.py:_is_ollama_provider` (order 02), `tests/_pytest_plugins/test_gating.py`,
`.github/workflows/**` (orders 04 and 05).

> **This order overturns the ledger's first framing.** The README originally said "wire the
> twelve dead methods". Measurement says otherwise: **12 of 20 items should be DELETED**, only
> **3 wired**. Six of the deletions have no inline equivalent anywhere — they are pure
> speculative API, and an agent told to "wire up the adapter" would *invent* an implementation
> with no test that could ever have failed. That is the specific failure §1.1 exists to prevent.

---

## 1. Decision table — the deliverable

`DefaultAdapter` declares **17 methods** (not 18 — see §2.1). With the module-level hook
`add_provider_adapter` and two module functions, that is the 20 items below. Six methods are
live; eleven are dead.

| # | Item | `DefaultAdapter` returns | Overridden by | Live calls | Inline equivalent in `llm.py` | **Decision** | Justification |
|---|---|---|---|---|---|---|---|
| 1 | `supports_prompt_caching()` | `False` | Anthropic→`True` | 1 — `llm.py:1533` | none (adapter *is* the impl) | **LEAVE** | Already the single source of truth. |
| 2 | `should_summarize_tools(iter)` | `iter >= 5` | Ollama→`>= 1` | 1 — `llm.py:1992` | none | **LEAVE** | Live, pinned by an existing test. |
| 3 | `format_tools(tools)` | identity | Gemini→wraps internal tools | **0** | `llm.py:2449-2457` — **opposite shape** (inline passes internal tools through unwrapped; adapter wraps in `{'type':'function','function':tool}`) | **DELETE** | Wiring it would change what Gemini receives. Adapter version untested against a real Gemini request. |
| 4 | `post_tool_iteration(state)` | `pass` | Ollama→sets `state['needs_summary']` | **0** | `llm.py:3572-3579` (sync), `5170-5177` (async) | **DELETE** | Sets a flag no code reads. The real behaviour is *append a message and `continue`* — not expressible through a `None`-returning state mutator. |
| 5 | `supports_structured_output()` | `False` | Anthropic, Gemini→`True` | **0** | `model_capabilities.supports_structured_outputs(model)` at `llm.py:2293, 6090, 6399` | **DELETE** | A working, litellm-backed, per-*model* implementation is already live. The adapter's per-*provider* boolean is a strictly worse duplicate. |
| 6 | `supports_streaming()` | `True` | Anthropic→`False` | 2 — `llm.py:5075, 5360` | none | **LEAVE** | Live, but async-only **by design** — see §5.10. Do not widen it. |
| 7 | `supports_streaming_with_tools()` | `True` | Ollama/Anthropic/Gemini→`False` | 1 — `llm.py:2172`, consumed by all three paths | none | **LEAVE** | The one adapter method genuinely load-bearing today. |
| 8 | `get_streaming_adapter()` | `get_streaming_adapter("default")` | all three override | **0** | **none** | **DELETE** | Pure speculative API. It is the *only* production reference to `llm/streaming_protocol.py` (387 lines) — that whole module is reachable from nothing else. See §7. |
| 9 | `get_max_iteration_threshold()` | `10` | Ollama→`1` | **0** | `OLLAMA_SUMMARY_ITERATION_THRESHOLD = 1` (`llm.py:273`), used at `3821`, `5446` | **DELETE** | Duplicates #2 under a different name with no consumer. Wiring it would change the threshold from 1 to 10 for every non-Ollama provider — a behaviour change, not a refactor. |
| 10 | `format_tool_result_message(fn, result, id)` | OpenAI `role:tool` | Ollama→natural-language `role:user` | 1 — `llm.py:1712` (Ollama branch only) | **default branch inlined 3×**: `3773-3785` (sync), `5278-5290` (async), `6793-6807` (`_create_tool_message`, stream) | **WIRE** | Its default body has zero consumers, so aligning it with the three copies is unobservable — then all three collapse to one call. Step 06.3. |
| 11 | `handle_empty_response_with_tools(state)` | `False` | Ollama→`iter>=1 and results and not text` | **0** | `llm.py:3844-3845` (sync), `5467-5468` (async) — **exact predicate match** | **WIRE** | The one dead method whose inline equivalent matches its signature exactly, in two paths. Step 06.4. |
| 12 | `get_default_settings()` | `{}` | Ollama→`{max_tool_repairs:2, force_tool_usage:'auto'}` | 1 — `llm.py:690` | none | **LEAVE** | Live — and it is *why* A2 is a silent failure: it sets knobs two of three paths ignore (§5.3). |
| 13 | `parse_tool_calls(raw)` | `raw["choices"][0]["message"].get("tool_calls")` | none | **0** | `llm.py:3465` (dict), `4591` (`getattr` on object), `5146`, `5378` | **DELETE** | The `Dict[str, Any]` signature cannot express the litellm `ModelResponse` object that `4591` actually receives. Wiring requires changing the signature — i.e. inventing API. No provider overrides it, so there is no divergence to abstract. |
| 14 | `should_skip_streaming_with_tools()` | `False` | Gemini→`True` | **0** | `llm.py:3122-3124` (sync only) — **and that branch is unreachable** | **DELETE** | `GeminiAdapter.supports_streaming_with_tools()` is already `False`, so `llm.py:3117` sets `use_streaming = False` before `3122` is evaluated. Delete the method *and* the dead branch. |
| 15 | `recover_tool_calls_from_text(text, tools)` | `None` | Ollama→JSON parse | **0** | `llm.py:3468-3500` (sync only) | **WIRE** | A1's flagship duplicate: 33 inline lines vs 30 adapter lines doing the same job. Highest value, hence last. Step 06.5. |
| 16 | `inject_cache_control(messages)` | identity | **none — not even `AnthropicAdapter`** | **0** | `llm.py:2312-2326` + four helpers at `2191/2205/2233/2244` | **DELETE** | A stub with no implementation anywhere. The real behaviour needs a 4-breakpoint budget and a history index; a flat `messages -> messages` signature carries neither. |
| 17 | `extract_reasoning_tokens(response)` | `0` | **none** | **0** | `llm.py:5807-5810` inside `_track_token_usage` | **DELETE** | No provider overrides it and none needs to — `_usage_value`/`_detail_value` already handle every shape litellm returns. |
| 18 | `add_provider_adapter(name, adapter)` *(module fn)* | registers into `_provider_adapters` | — | **0** anywhere incl. tests/docs | none | **LEAVE — hand off to order 02** | A registered name is **unreachable**: the sole caller `get_provider_adapter` (`llm.py:682`) is only ever passed `_detect_provider()`'s output, which can be exactly `ollama\|anthropic\|gemini\|openai\|default`. Fixing it is a 3-line change in a region order 02 owns. |
| 19 | `list_provider_adapters()` *(module fn)* | sorted keys | — | **0** anywhere | none | **DELETE** | Exported, undocumented, zero consumers including tests. |
| 20 | `has_provider_adapter(name)` *(module fn)* | `name in _provider_adapters` | — | **0** anywhere | none | **DELETE** | Same — plus it is *wrong*: no `.lower()`, so `has_provider_adapter("Ollama")` is `False` while `get_provider_adapter("Ollama")` succeeds. Untested dead code with a latent bug. |

**Totals: 4 LEAVE, 1 LEAVE-and-hand-off, 12 DELETE, 3 WIRE.**

### 1.1 Why "no inline equivalent" is the decisive column

Six of the twelve deletions have **no inline equivalent at all** — nothing in `llm.py` does the
job they declare: `get_streaming_adapter`, `inject_cache_control`, `extract_reasoning_tokens`,
`add_provider_adapter`, `list_provider_adapters`, `has_provider_adapter`.

These are **pure speculative API**. There is no behaviour to move into them. An agent handed
"wire up the adapter" without this column will invent an implementation, and that invented code
will have no test that could ever have failed.

The other six deletions have an inline equivalent that is **incompatible** (different output
shape: #3; different type signature: #13), **strictly worse** (#5, #9), **unreachable** (#14),
or **not expressible through the declared signature** (#4). Wiring any of them is a behaviour
change wearing a refactor's clothes.

---

## 2. Measurement corrections

Method: `ast` walk of `llm.py` for function extents and node counts; repo-wide `grep` for call
sites, re-run receiver-aware (§6) to eliminate same-name false positives;
`difflib.SequenceMatcher` on function source slices.

**Confirmed exactly:** `adapters/__init__.py` 340 lines; `llm.py` 7,160; `get_response` at
`2557`, 1,675 lines, **194** branch nodes; `get_response_stream` at `4233`, 443 lines, **56**;
`get_response_async` at `4706`, 969 lines; similarity 22.3% vs 75.6/77.8/84.4/90.5% for the
other four pairs; Ollama references `llm.py` **145 lines** / 154 occurrences,
`adapters/__init__.py` **19 lines** / 20; all 20 call-site counts as listed; the
`recover_tool_calls_from_text` duplicate at `3468-3500` vs `160-189`.

**Five corrections:**

| # | Claim | Measured | Note |
|---|---|---|---|
| 2.1 | "`DefaultAdapter` defines 18 methods" | **17 methods** | The 18th listed item, `add_provider_adapter`, is a module-level function. `LLMProviderAdapterProtocol` declares only **16** — it omits `get_streaming_adapter`, so that method is not even part of the protocol it claims to implement. |
| 2.2 | `get_response_async` = 109 branch nodes | **115** under the metric that yields 194 and 56 for the other two; **112** excluding `ExceptHandler` | 109 matches neither metric. Correct `00-ground-truth.md`. |
| 2.3 | `max_tool_repairs`: 2 in `get_response` | **2 lines, 3 occurrences** (`3583`×2, `3599`×1) | The original table mixes line counts and occurrence counts. |
| 2.4 | `_format_ollama_tool_result_message`: 1 / 1 / **0** | 1 / 1 / **1 (indirect)** | The stream path reaches it via `_create_tool_message` (`6791-6792`), called at `4489`, `4497`, `4661`. **The stream path is not missing Ollama tool-result formatting** — the original table overstates the gap. |
| 2.5 | Seven compensations diverge | **Sixteen** | Nine further asymmetries, three of which run *against* the sync path. §2.6. |

### 2.6 Complete compensation matrix (line hits per path)

```
/* Detailed source-code truncated for AI context efficiency. */
```

`*` indirect — correction 2.4.

### 2.7 The divergence is observable — and not in the direction assumed

> **CORRECTED 2026-09-03, during step 06.4.** The original figures in this section
> recorded the sync path returning `'{\n\n\n}'` with 1 tool call. **That does not
> reproduce.** Re-measured on `origin/main`, twice, `temperature=0`, same prompt and
> tool, the sync path returns 2 tool calls and a doubled answer. The stream result
> reproduced exactly. Every branch of the 06.1–06.6 stack was then bisected against
> `main` and all produce byte-identical output, confirming the stack is
> refactor-only.
>
> **The headline finding stands** — the three paths disagree and the stream path is
> broken. Only the specific `'{\n\n\n}'` sample was unreproducible. Do not cite it,
> and do not treat it as a regression signal.

Live Ollama, `temperature=0`, identical prompt and tool, two trials (corrected):

```
T1 sync    calls=2   out='Paris: 21C sunny. Paris: 21C sunny.'
T1 async   calls=1   out='Paris: 21C sunny'
T1 stream  calls=10  out=''
T2 sync    calls=2   out='Paris: 21C sunny. Paris: 21C sunny.'
T2 async   calls=1   out='Paris: 21C sunny'
T2 stream  calls=10  out=''
```

Reproduce:

```bash
cd src/praisonai-agents && python3 - <<'EOF'
import sys, os, asyncio; sys.path.insert(0,'.'); os.environ.setdefault('OPENAI_API_KEY','x')
from praisonaiagents.llm.llm import LLM
def get_weather(city: str) -> str:
    """Get the weather for a city."""
    return f"{city}: 21C sunny"
P = "What is the weather in Paris? Use the tool."
for path in ("sync","async","stream"):
    calls=[]
    def exec_tool(name,args,**kw): calls.append(name); return get_weather(**args)
    llm=LLM(model="ollama/qwen3:0.6b", base_url="http://127.0.0.1:11434")
    if path=="sync":     out=llm.get_response(prompt=P,tools=[get_weather],execute_tool_fn=exec_tool,temperature=0)
    elif path=="async":  out=asyncio.run(llm.get_response_async(prompt=P,tools=[get_weather],execute_tool_fn=exec_tool,temperature=0))
    else:                out="".join(str(c) for c in llm.get_response_stream(prompt=P,tools=[get_weather],execute_tool_fn=exec_tool,temperature=0))
    print(f"### {path:6} tool_calls={len(calls)} out={out!r}")
EOF
```

Three consequences, and they reframe the order:

1. **The best-compensated path produces the worst answer.** `get_response` has 16 of the 18
   compensations and calls the tool twice, returning a doubled answer.
   `get_response_async` has 8 and returns the correct answer once. More compensation is
   not the goal; *the same* compensation is.
2. **The stream path is not under-compensated, it is broken.** It burns all 10 iterations of
   `max_iter`, invokes the tool **10 times** for a one-tool question, and yields nothing. That
   is a real cost and side-effect amplifier, not a formatting defect.
3. **Leading hypothesis for the sync/async split: `OLLAMA_FINAL_ANSWER_PROMPT`**
   (`llm.py:5302`, async only). Async appends *"Based on the tool results above, please provide
   the final answer"* and re-requests; sync does not, so it runs another tool iteration
   instead and concatenates the result twice. **This is a hypothesis, not a measurement**,
   and it was not settled during order 06 — the corrected baseline changed what needs
   explaining. Whoever takes the §5.7 follow-up should settle it first.

**None of the three baselines may change during Steps 06.1–06.6.** Every step is a
behaviour-preserving refactor. `'{\n\n\n}'` stays `'{\n\n\n}'`. Fixing it is this order's
*successor*, and it needs these characterization tests to be safe.

---

## 3. Preconditions for every step

```bash
# 1. Order 02 must have landed.
git log --oneline origin/main | head -20 | grep -i "provider.detection\|_detect_provider"

# 2. Branch from origin/main, never from a sibling order's branch.
git fetch origin main && git worktree add /path/to/wt-06 -b <step-branch> origin/main

# 3. Ollama up, correct model present.
curl -s 127.0.0.1:11434/api/version                                  # {"version":"0.33.2"}
curl -s 127.0.0.1:11434/api/show -d '{"model":"qwen3:0.6b"}' | \
  python3 -c 'import json,sys; print(json.load(sys.stdin)["capabilities"])'
                                                # ['completion','tools','thinking']

# 4. Green baseline on the two suites this order can break.
cd src/praisonai-agents && PYTHONPATH=. python -m pytest tests/unit/test_adapter_registry.py -q  # 38 passed
cd src/praisonai && PYTHONPATH=../praisonai-agents python -m pytest tests/unit/llm/ -q
```

### 3.1 Three test-infrastructure traps

**Trap A — `src/praisonai-agents/tests/` is almost entirely outside CI.** Grepping every
workflow: the only tests run from that directory are `tests/smoke/test_subscription_auth.py`
and `tests/unit/auth/test_agent_auth_wiring.py` (`test-optimized.yml:110-113`).
**`tests/unit/test_adapter_registry.py` (38 tests) and all 13 files in `tests/unit/llm/` are run
by no workflow at all.** Consequences:

- Deleting `GeminiAdapter.format_tools` breaks
  `test_adapter_registry.py::test_gemini_adapter_formats_internal_tools` and **no CI job will
  tell you**. Run that file by hand in every step.
- **All new tests in this order go to `src/praisonai/tests/unit/llm/`**, which *is* run — by
  `test-core.yml` (`subdirs` shard) and `test-optimized.yml` (main job).
- Do not fix the CI gap here; `.github/workflows/**` belongs to orders 04 and 05. §7 hands it over.

**Trap B — `test_ollama_tool_reliability.py` tests a copy, not the product.**
`src/praisonai/tests/unit/llm/test_ollama_tool_reliability.py` (541 lines, 28 tests, all green)
defines `class MockLLM` which *re-implements* `_is_ollama_provider`, `_apply_ollama_defaults`,
`_validate_tool_call`, `_should_force_tool_usage` and both prompt templates. Its own docstring
says *"copied from actual LLM class"*. **It cannot fail in response to any change in `llm.py`.**
Do not treat it as a safety net and do not extend it. Every characterization test in this order
instantiates the real `praisonaiagents.llm.llm.LLM`.

**Trap C — the auto provider-marker does not apply under `tests/unit/`.** `test_gating.py:214`
guards provider auto-detection with `if item.fspath and test_type != 'unit'`. So a file under
`tests/unit/llm/` mentioning "ollama" is *not* auto-gated and **will** run in CI. Live-server
tests therefore need an **explicit** `pytestmark`; verified that the CI marker expression then
deselects them (`1 collected / 1 deselected`).

---

## 4. The WIRE sequence

Six steps, each one branch, one commit, one adapter method, independently revertible. Lowest
risk first.

### Step 06.0 — record the `OLLAMA_FINAL_ANSWER_PROMPT` experiment (no ship)

Branch: none. Deliverable: one row appended to `00-ground-truth.md` recording whether adding the
async-only final-answer append at `llm.py:3838` changes the sync path's `'{\n\n\n}'`. Revert the
local patch with `git checkout --`. This exists so the successor order need not re-derive it.

### Step 06.1 — the reachability ratchet (test only, zero source change)

**Branch:** `test/adapter-reachability-ratchet`
**Source changes:** none. If your diff touches `praisonaiagents/`, you are on the wrong step.

Add `src/praisonai/tests/unit/llm/test_llm_adapter_seam.py` — full text in §6. It carries a
`KNOWN_DEAD` frozenset seeded with exactly the eleven names measured today. Later steps delete
names from that set; the set never grows.

**Verify:**
```bash
cd src/praisonai && PYTHONPATH=../praisonai-agents python -m pytest \
  tests/unit/llm/test_llm_adapter_seam.py -q            # expect 4 passed
```
Then prove the ratchet bites — temporarily drop one name from `KNOWN_DEAD` and confirm
`test_no_new_dead_adapter_methods` fails. **A ratchet you have not seen fail is not a ratchet.**

**Rollback:** `git revert <sha>` — deletes one test file.

### Step 06.2 — delete the twelve speculative surfaces

**Branch:** `refactor/delete-dead-adapter-surface`

**Delete from `llm/adapters/__init__.py`:**

| Lines | What |
|---|---|
| `26-27` | `DefaultAdapter.format_tools` |
| `29-30` | `DefaultAdapter.post_tool_iteration` |
| `32-33` | `DefaultAdapter.supports_structured_output` |
| `41-44` | `DefaultAdapter.get_streaming_adapter` |
| `46-47` | `DefaultAdapter.get_max_iteration_threshold` |
| `68-73` | `DefaultAdapter.parse_tool_calls` |
| `75-76` | `DefaultAdapter.should_skip_streaming_with_tools` |
| `81-82` | `DefaultAdapter.inject_cache_control` |
| `84-85` | `DefaultAdapter.extract_reasoning_tokens` |
| `108-110` | `OllamaAdapter.get_streaming_adapter` |
| `112-113` | `OllamaAdapter.get_max_iteration_threshold` |
| `191-197` | `OllamaAdapter.post_tool_iteration` |
| `212-213` | `AnthropicAdapter.supports_structured_output` |
| `223-225` | `AnthropicAdapter.get_streaming_adapter` |
| `238-240` | `GeminiAdapter.should_skip_streaming_with_tools` |
| `242-243` | `GeminiAdapter.supports_structured_output` |
| `245-258` | `GeminiAdapter.format_tools` |
| `264-266` | `GeminiAdapter.get_streaming_adapter` |
| `321-328` | `list_provider_adapters`, `has_provider_adapter` |
| `13` | `from ..streaming_protocol import ...` — now unused |
| `12` | `from ..model_capabilities import GEMINI_INTERNAL_TOOLS` — now unused |
| `338-339` | the two `__all__` entries |

**Keep** `add_provider_adapter` and its `__all__` entry (§7 hands it to order 02).

**Delete from `llm/protocols.py`** the matching stubs: `294-296`, `298-300`, `302-304`,
`314-316`, `330-332`, `334-336`, `342-344`, `346-348`. Also strip the
`format_tools`/`post_tool_iteration` lines from the class docstring example at `276-282`, which
would otherwise document deleted API.

`LLMProviderAdapterProtocol` is `@runtime_checkable`, so `isinstance` only checks method
presence — deleting a name from both the protocol and `DefaultAdapter` keeps the two
`..._implements_protocol` tests green.

**Delete the one unreachable inline branch** in `llm/llm.py`, verbatim:

```python
3120:                        
3121:                        # Gemini has issues with streaming + tools, disable streaming for Gemini when tools are present
3122:                        if use_streaming and formatted_tools and self._is_gemini_model():
3123:                            logging.debug("Disabling streaming for Gemini model with tools due to JSON parsing issues")
3124:                            use_streaming = False
3125:                        
```

Replace `3120-3125` with a single blank line. **Proof it is unreachable** — three lines above:

```python
3116:                        use_streaming = stream
3117:                        if formatted_tools and not self._supports_streaming_tools():
3118:                            # Provider doesn't support streaming with tools, use non-streaming
3119:                            use_streaming = False
```

`_supports_streaming_tools()` returns `self._provider_adapter.supports_streaming_with_tools()`
(`llm.py:2172`), which `GeminiAdapter` overrides to `False`. So for Gemini-with-tools, `3119`
already sets `use_streaming = False` and the `3122` guard can never be true. Verified:

```
$ python3 -c "from praisonaiagents.llm.adapters import get_provider_adapter as g; \
  print(g('gemini/gemini-2.0-flash').supports_streaming_with_tools())"
False
```

`get_response_async` and `get_response_stream` have no equivalent branch. One-path edit, so §8's
two-path rule does not apply.

**Also update `KNOWN_DEAD`**: remove the nine deleted method names, leaving
`{"handle_empty_response_with_tools", "recover_tool_calls_from_text"}`.

**Non-Ollama behaviour identical**, asserted three ways: (1) Step 06.1's
`test_no_dead_name_is_actually_live` proves every deleted name had zero call sites; (2) new test
`test_gemini_with_tools_never_streams` pins the deletion at the level of the surviving guard;
(3) `test_adapter_registry.py` must still pass with **one deletion** —
`test_gemini_adapter_formats_internal_tools` (lines `347-363`) tests `GeminiAdapter.format_tools`
and must be removed in the same commit. That is the only test in the repo exercising any deleted
surface (verified by repo-wide `grep` for each of the twelve names).

**Characterization tests first**, in
`src/praisonai/tests/unit/llm/test_llm_response_path_characterization.py`:
- `test_gemini_with_tools_never_streams` — assert `_supports_streaming_tools()` is `False` and
  `_is_gemini_model()` is `True`; assert the value of `_supports_streaming_tools()` for every
  `(model, tools_present)` in `{gemini, gpt-4o, ollama/qwen3:0.6b} × {True, False}` matches a
  hard-coded expectation table.
- `test_deleted_adapter_names_are_absent` — `not hasattr(DefaultAdapter, name)` for each of the
  nine, so a later merge cannot silently resurrect them.

**Verify live:** run the §2.7 script. All three outputs byte-identical to baseline
(`'{\n\n\n}'`, `'Paris: 21C sunny'`, `''`), stream tool-call count still 10. A change means you
deleted something live.

**Rollback:** `git revert <sha>`. Pure deletion, no state, no migration.

### Step 06.3 — WIRE `format_tool_result_message` for the default branch

**Branch:** `refactor/wire-default-tool-result-message`

**Why safe:** `DefaultAdapter.format_tool_result_message`'s body currently has **zero**
consumers. `llm.py:1712` is reached only through `_format_ollama_tool_result_message`, whose
call sites are guarded by `_is_ollama_provider()` and which forces an `OllamaAdapter` if
`_provider_adapter` is something else. So the default body can be rewritten to match the three
inline copies with no observable change.

The three inline copies to be replaced are at `llm.py:3770-3785` (sync), `5275-5290` (async),
and `6791-6807` (`_create_tool_message`, the stream path's formatter). All three implement the
same cascade: `None` → `"Function returned an empty output"`; a dict with `'error'` → an error
sentence; a list whose first element has `'error'` → the same; otherwise `json.dumps`. Path 3
differs in one respect — it wraps `json.dumps` in `try/except (TypeError, ValueError)` and falls
back to `str(result)`.

**Replacement.** Give `DefaultAdapter.format_tool_result_message` the union body, adopting path
3's guard (strictly safer — paths 1 and 2 raise on a non-serializable result):

```python
    def format_tool_result_message(self, function_name: str, tool_result: Any, tool_call_id: Optional[str] = None) -> Dict[str, Any]:
        # Standard OpenAI-style tool result message.
        if tool_result is None:
            content = "Function returned an empty output"
        elif isinstance(tool_result, dict) and 'error' in tool_result:
            content = (f"Error: {tool_result.get('error', 'Unknown error')}. "
                       "Please inform the user that the operation could not be completed.")
        elif (isinstance(tool_result, list) and tool_result
                and isinstance(tool_result[0], dict) and 'error' in tool_result[0]):
            content = (f"Error: {tool_result[0].get('error', 'Unknown error')}. "
                       "Please inform the user that the operation could not be completed.")
        else:
            try:
                content = json.dumps(tool_result)
            except (TypeError, ValueError):
                content = str(tool_result)
        message = {"role": "tool", "content": content}
        message["tool_call_id"] = tool_call_id if tool_call_id is not None else f"call_{function_name}"
        return message
```

(`import json` at module top of `adapters/__init__.py`; `OllamaAdapter.recover_tool_calls_from_text`
imports it function-locally at line 166 — leave that alone in this step.)

Then make `_create_tool_message` (`llm.py:6772`) the single formatter and delegate:

```python
        if is_ollama:
            return self._format_ollama_tool_result_message(function_name, result)
        adapter = getattr(self, '_provider_adapter', None)
        if adapter is None:
            from .adapters import DefaultAdapter
            adapter = DefaultAdapter()
        return adapter.format_tool_result_message(function_name, result, tool_call_id)
```

and replace `3770-3785` with

```python
                            else:
                                messages.append(self._create_tool_message(
                                    function_name, tool_result, tool_call_id, is_ollama=False))
```

and `5275-5290` with the same at async indentation. Path 3 needs no call-site change — it *is*
`_create_tool_message`.

**This edits two of the three response paths, so §8's rule applies:** the commit must carry
`test_tool_result_message_identical_across_paths`, parametrized over all three. Without it,
split into two commits (sync first, async second), each with a path-specific test.

**Tests, written and passing against `main` first:**
- `test_default_tool_result_message_matches_legacy_shape` — nine `tool_result` fixtures
  (`None`, `{}`, `{"error": "x"}`, `[{"error":"y"}]`, `[]`, `"str"`, `3`, `{"a":1}`, and a
  `set()` — the non-serializable case) × expected message dict, hard-coded from the *pre-change*
  inline bodies.
- `test_non_serializable_tool_result_no_longer_raises` — marked `xfail(strict=True)` on `main`.
  **This is a deliberate divergence:** for a `set()`, paths 1 and 2 previously raised
  `TypeError` and now produce `str(...)`. That is a bug fix, not a preservation. Call it out in
  the commit message so it appears as a test-outcome diff rather than a silent edit.
- `test_tool_result_message_identical_across_paths` — parametrized over `("sync","async","stream")`;
  patch `_completion_with_retry` / `_acompletion_with_retry` to return a canned tool call, then
  assert the `messages` list is **equal across all three paths** for a `DefaultAdapter` model.
  Fails on `main` for the `set()` fixture; passes after. That is the intended ratchet.

**Verify live:** §2.7 script must reproduce all three baselines exactly. Ollama takes the
`is_ollama` branch, so this step must not perturb it at all.

> **Trap when testing the non-Ollama path locally:** `_is_ollama_provider` (`llm.py:719`) matches
> `:11434` in `base_url`, so pointing at a local Ollama through the OpenAI-compatible route
> *still* yields `OllamaAdapter`. Use a proxy or a mocked transport. **Do not** work around it by
> editing `_is_ollama_provider` — that method belongs to order 02.

**Rollback:** `git revert <sha>`. Adapter body and three call sites revert together.

### Step 06.4 — WIRE `handle_empty_response_with_tools`

**Branch:** `refactor/wire-handle-empty-response-with-tools`

The only dead method whose signature already matches its inline predicate. Inline at
`llm.py:3842-3852` (sync) and `5465-5475` (async); `get_response_stream` has no equivalent (§5.5).

**Replace the predicate only** (lines `3844-3845` and `5467-5468`) with:

```python
                        if self._provider_adapter.handle_empty_response_with_tools({
                            'iteration_count': iteration_count,
                            'accumulated_tool_results': accumulated_tool_results,
                            'response_text': response_text or '',
                        }):
```

The body (`3846-3852` / `5469-5475`) stays exactly where it is, unreflowed. **Do not** move
`_generate_ollama_tool_summary` into the adapter in this step — it is 82 lines with a
`_format_search_results_summary` dependency and is shared by `_handle_ollama_sequential_logic`.
One method per step.

**Semantic equivalence — and the one real risk.** The current predicate leads with
`self._is_ollama_provider()`. After the change, Ollama-treatment is decided by *dispatch*:
`OllamaAdapter` returns the predicate, `DefaultAdapter` returns `False`. **That is not identical
to `_is_ollama_provider()`** — `_detect_provider` (`llm.py:640-671`) maps by route prefix and
base-url hints, and `get_provider_adapter` (`adapters:311`) additionally matches
`"ollama" in name_lower`. The union is *wider*: e.g. `model="my-ollama-model"` with no ollama
base-url gets `OllamaAdapter` while `_is_ollama_provider()` is `False`.

**Therefore this step must add the exact-equivalence assertion, or it is not behaviour-preserving:**

`test_ollama_adapter_selection_matches_is_ollama_provider` — parametrized over 14
model/base_url combinations (`ollama/llama3`, `ollama/qwen3:0.6b`, `my-ollama-model`,
`ollama_chat/llama3`, `llama3`+`base_url=...:11434`, `llama3`+`OPENAI_BASE_URL=...:11434`,
`gpt-4o`, `claude-3-5-sonnet`, `gemini/gemini-2.0-flash`, `bedrock/anthropic.claude-3`,
`vertex_ai/gemini-1.5-pro`, `openrouter/anthropic/claude-3`, `""`, `None`), asserting
`isinstance(llm._provider_adapter, OllamaAdapter) == llm._is_ollama_provider()`.

**Run it on `main` first.** If any row fails, that row is a pre-existing divergence and **this
step is blocked** until order 02 reconciles the two functions — record the failing rows in
`00-ground-truth.md` and stop. Do not paper over it by keeping `_is_ollama_provider()` in the
condition alongside the adapter call; that would leave the adapter non-load-bearing, which is
the whole defect.

**Characterization tests first**, `src/praisonai/tests/unit/llm/test_llm_empty_response_compensation.py`:
- `test_empty_response_after_tools_yields_summary_sync` / `..._async` — mocked completion:
  iteration 0 returns a tool call, iteration 1 returns `content=""`. Assert the returned string
  equals the `_generate_ollama_tool_summary` output.
- `test_whitespace_only_response_counts_as_empty` — iteration 1 returns `"   \n "`. Pins the
  `.strip()` semantics; the adapter's `state.get('response_text','').strip()` and the inline
  `response_text.strip() == ""` agree **only if `response_text` is never `None`** — hence the
  `response_text or ''` in the replacement.
- `test_non_empty_response_after_tools_returns_model_text` — iteration 1 returns `"{\n\n\n}"`.
  Must return `'{\n\n\n}'`. **This is the §2.7 sync baseline; it must not improve in this step.**
- `test_default_adapter_never_takes_empty_response_branch` — `gpt-4o`; patch
  `_generate_ollama_tool_summary` with a `Mock` and assert `not called`. The non-Ollama identity
  assertion.
- `test_iteration_zero_never_takes_branch` — empty response at iteration 0 must fall through to
  the `3572` tool-usage prompt, not the summary.

All six against `main` first, then committed **with** the refactor (they cover both edited paths).

**Update `KNOWN_DEAD`** → `{"recover_tool_calls_from_text"}`.

**Rollback:** `git revert <sha>`.

### Step 06.5 — WIRE `recover_tool_calls_from_text`

**Branch:** `refactor/wire-recover-tool-calls-from-text`
Highest value, highest risk, therefore last. Inline at `llm.py:3468-3500`, **sync only**.

**Replacement for all 33 lines:**

```python
                    # Recover tool calls the provider emitted as response text.
                    if not tool_calls and response_text and formatted_tools:
                        recovered = self._provider_adapter.recover_tool_calls_from_text(
                            response_text, formatted_tools)
                        if recovered:
                            tool_calls = recovered
                            logging.debug(f"Recovered tool calls from response text: {tool_calls}")
```

**Four measured behavioural deltas, each argued inert:**

| Delta | Inline | Adapter | Resolution |
|---|---|---|---|
| `id` format | `f"tool_{iteration_count}"` / `f"tool_{i}_{idx}"` | `f"call_{name}_{idx}_{hash(text)%10000}"` | **Inert for Ollama.** The id never reaches the model: the assistant turn omits `tool_calls` entirely for Ollama (`3633-3638`) and the tool reply is `role:"user"` with no `tool_call_id` (`3760-3762`). Pin with `test_recovered_tool_call_id_never_reaches_messages`. |
| List with no `"name"` entries | `[]` | `None` | Equivalent at every consumer: `3504` (`if not tool_calls and ...`) and `3623` (`if tool_calls and ...`) treat them alike, as does the replacement's `if recovered:`. Pin with `test_list_without_name_keys_does_not_dispatch`. |
| Exceptions caught | `(JSONDecodeError, KeyError)` | `(JSONDecodeError, TypeError, KeyError)` | Adapter is strictly wider — can only stop a failure, never cause one. Note in the commit message. |
| Guard | `_is_ollama_provider() and ...` | dispatch | Same widening as 06.4. **Reuse `test_ollama_adapter_selection_matches_is_ollama_provider` as a hard precondition** — do not land 06.5 unless it is green. |
| Debug logging | two distinct messages | none in adapter | The replacement logs one message at the call site, so the "recovery happened" signal survives. The single-vs-multiple distinction is lost; state that in the commit message. |

**Non-Ollama identity.** `DefaultAdapter`, `AnthropicAdapter` and `GeminiAdapter` all inherit
`recover_tool_calls_from_text -> None`, so no non-Ollama provider can enter the branch.
Asserted by `test_no_text_recovery_for_default_adapter` — `gpt-4o`, mocked response whose
`content` is exactly `'{"name": "get_weather", "arguments": {"city": "Paris"}}'` and whose
`tool_calls` is `None`. Assert `execute_tool_fn` is never called and the returned string is that
JSON text verbatim. **This test must pass identically on `main` and after** — it is the single
most important assertion in this step, because it is the one an over-eager wiring would break.
Parametrize for `claude-3-5-sonnet` and `gemini/gemini-2.0-flash` too.

**Characterization tests first**, `src/praisonai/tests/unit/llm/test_llm_text_tool_call_recovery.py`:

| Test | Input `content` | Asserted |
|---|---|---|
| `test_recovers_single_json_tool_call` | `'{"name":"get_weather","arguments":{"city":"Paris"}}'` | called once with `("get_weather", {"city":"Paris"})` |
| `test_recovers_multiple_json_tool_calls` | `'[{"name":"a","arguments":{}},{"name":"b","arguments":{}}]'` | called twice, in order |
| `test_dict_without_name_key_does_not_dispatch` | `'{"arguments":{"city":"Paris"}}'` | not called; text returned verbatim |
| `test_list_without_name_keys_does_not_dispatch` | `'[{"arguments":{}}]'` | not called |
| `test_malformed_json_does_not_dispatch` | `'{"name": "get_weather"'` | not called; no exception escapes |
| `test_empty_text_does_not_dispatch` | `''` | not called |
| `test_no_tools_means_no_recovery` | valid JSON call, `tools=None` | not called |
| `test_native_tool_calls_take_precedence` | valid JSON text **and** a native `tool_calls` naming `other_tool` | `other_tool` runs; text not parsed |
| `test_xml_recovery_still_reachable_after_json_recovery_fails` | `'<tool_call>{"name":"get_weather","arguments":{"city":"Paris"}}</tool_call>'`, Qwen model | dispatches via the XML block at `3502-3558` |
| `test_recovered_tool_call_id_never_reaches_messages` | valid JSON call | no appended message contains `tool_call_id` or `tool_calls` |
| `test_arguments_are_json_encoded_string` | `'{"name":"a","arguments":{"n":1}}'` | `function.arguments` is the **string** `'{"n": 1}'`, not a dict — what `_parse_tool_call_arguments` expects |

`test_xml_recovery_still_reachable_after_json_recovery_fails` is the guard for a subtle
interaction: the inline list branch sets `tool_calls = []` *before* recovery, and the XML block
at `3504` re-checks `if not tool_calls`. The replacement never assigns a falsy value, so the XML
path stays reachable — but only this test proves it.

**Update `KNOWN_DEAD`** → `frozenset()`, and change `test_no_new_dead_adapter_methods` to assert
the set is empty. Leave the allowlist mechanism in place (empty) so a future addition has an
obvious, reviewable place to be justified.

**Verify live — mandatory for this step**, because `qwen3:0.6b` emits JSON-as-text reliably at
`temperature=0`:

```bash
git checkout origin/main
for i in 1 2 3; do <§2.7 script>; done > /tmp/before.txt 2>&1
git checkout refactor/wire-recover-tool-calls-from-text
for i in 1 2 3; do <§2.7 script>; done > /tmp/after.txt 2>&1
diff <(grep '^### sync'   /tmp/before.txt) <(grep '^### sync'   /tmp/after.txt)
diff <(grep '^### async'  /tmp/before.txt) <(grep '^### async'  /tmp/after.txt)
diff <(grep '^### stream' /tmp/before.txt) <(grep '^### stream' /tmp/after.txt)
```

Expected: empty diffs. `tool_calls=1` on sync in particular — a change to `tool_calls=0` means
recovery stopped firing (the adapter is not being reached); a change in `out` means the id or
the `[]`/`None` delta was not as inert as measured.

Also run the server-free adapter equivalence check:
```bash
python3 -c "
from praisonaiagents.llm.adapters import OllamaAdapter
a = OllamaAdapter()
for txt in ['{\"name\":\"w\",\"arguments\":{\"c\":\"P\"}}',
            '[{\"name\":\"a\",\"arguments\":{}},{\"name\":\"b\",\"arguments\":{}}]',
            '{\"arguments\":{}}', '[{\"arguments\":{}}]', '{\"name\":\"w\"', '']:
    r = a.recover_tool_calls_from_text(txt, [{'name':'w'}])
    print(repr(txt)[:40], '->', [(c['function']['name'], c['function']['arguments']) for c in (r or [])])
"
```

**Rollback:** `git revert <sha>`. The 33 inline lines come back intact; `KNOWN_DEAD` must be
restored to `{"recover_tool_calls_from_text"}` in the same revert.

### Step 06.6 — port `_validate_and_filter_ollama_arguments` to the stream path

**Branch:** `fix/stream-path-ollama-argument-filtering`

The one A2 gap that belongs in *this* order rather than a follow-up, because it is
**pre-dispatch, provider-shaped and streaming-safe**: it runs before `execute_tool_fn`, so
nothing has been yielded that would need retracting.

Present at `3690` (sync) and `5240` (async); absent from both stream branches. Insert after
`llm.py:4433` (streaming branch) and after `4639` (fallback branch), mirroring `5238-5240`:

```python
                            # Validate and filter arguments for Ollama provider
                            if is_ollama and tools:
                                arguments = self._validate_and_filter_ollama_arguments(function_name, arguments, tools)
```

One response path (twice), so §8's two-path rule does not apply — but both insertion points
need coverage: `test_stream_filters_ollama_arguments_streaming_branch` and
`..._fallback_branch`, in `src/praisonai/tests/unit/llm/test_llm_stream_ollama_parity.py`.

Drive the fallback branch with an Ollama model (which reports
`supports_streaming_with_tools() is False`, so `4304-4306` sends it there). Drive the streaming
branch with `gpt-4o` plus a monkeypatched `_provider_adapter` reporting Ollama — and assert in
the test that this is the only way to reach it, which documents that **the streaming branch is
unreachable for real Ollama today**.

**Non-Ollama:** the `if is_ollama and tools` guard makes it a no-op; assert with
`test_stream_does_not_filter_arguments_for_default_adapter` (patch with a `Mock`, assert
`not called` for `gpt-4o`).

**Verify live:** §2.7 script. The stream line must **still** read `tool_calls=10 out=''`.
**Do not fix that here** — it is the successor order's job (§5.5). Any improvement means you
changed more than one thing.

**Rollback:** `git revert <sha>`.

---

## 5. The async/stream gap — disposition per compensation

Every row of §2.6 gets one of: **(a)** part of an order-06 step, **(b)** a separate follow-up
order, **(c)** deliberately out of scope. No row is left unassigned.

### 5.1 `tool_result_mapping` — 8/0/0 → **(c) out of scope, and recommend deletion**

Do **not** port it. Read what it does (`llm.py:3682-3688`, `3724-3735`):

```python
3684:  for arg_name, arg_value in list(arguments.items()):
3685:      if isinstance(arg_value, str) and arg_value in tool_result_mapping:
3686:          # Replace function name with its result
3687:          arguments[arg_name] = tool_result_mapping[arg_value]
...
3729:  elif isinstance(tool_result, str):
3730:      import re
3731:      match = re.search(r'\b(\d+)\b', tool_result)
3732:      if match:
3733:          tool_result_mapping[function_name] = int(match.group(1))
```

It silently rewrites a user-supplied tool argument whenever that argument's *string value
happens to equal a previously-called function's name*, substituting the first integer found
anywhere in that function's string result. `get_weather` returning `"Paris: 21C sunny"`
registers `21`; a later call with `city="get_weather"` would receive `21`.

This is a **data-corruption hazard, not a compensation**. Porting it to async and stream would
triple the exposure and violate the ledger's closing obligation ("no order may add a fifth copy
of any compensation"). **Recommendation:** a separate order to remove it, gated on a
characterization test proving no example or test depends on it.

### 5.2 `max_tool_repairs` + `_validate_tool_call` + `TOOL_CALL_REPAIR_PROMPT` — 2/1/1 sync only

→ **(b) follow-up for async; (b) follow-up for stream's fallback branch only; (c) impossible in
the true streaming branch.**

*Async:* mechanically portable — same request/response shape, same `messages` list, same
`iteration_count` accounting. But it is *schema validation*, provider-independent, and not
adapter-shaped, so it is not A1 work. Separate order.

*Stream — the honest split:*
- **The non-streaming fallback branch (`4553-4667`) can have it.** This is where Ollama,
  Anthropic and Gemini with tools actually land (`4304-4306`), so in practice it covers every
  provider that would need repair. Nothing has been yielded at validation time when `content` is
  empty — and when `content` is non-empty it has already been yielded at `4614`, so
  repair-and-retry would produce a *duplicate* prose emission. Correct rule: validate before
  dispatch; on failure append the repair prompt and loop **without** re-yielding prose already sent.
- **The true streaming branch (`4308-4551`) cannot have repair-and-retry.** A tool call is
  assembled from deltas (`_process_tool_calls_from_stream`, `llm.py:6752`) and is complete only
  when the stream ends — by which time every content delta has already been `yield`ed to the
  caller's `for` loop. **You cannot un-yield.** What *is* possible while streaming: (i) refuse to
  dispatch an invalid call; (ii) yield additional chunks; (iii) raise. What is not possible:
  retract, rewrite, or replace anything already emitted.

  **Honest user-facing behaviour:** on a validation failure in the true streaming branch, do not
  silently drop the call (today's behaviour is worse — it drops it *and* yields nothing) and do
  not attempt a repair round. Raise `LLMResponseError` naming the tool and the validation error.
  A caller that wants repair should not be streaming; the SDK already knows how to express that
  choice — `_supports_streaming_tools()` — and the honest extension is for repair-requiring
  configurations to report `False` there, sending the turn to the fallback branch where repair
  is possible. Title that order: *"tool-call repair is a non-streaming capability; make the
  streaming gate say so."*

### 5.3 `force_tool_usage` / `_should_force_tool_usage` / `FORCE_TOOL_USAGE_PROMPT` — 1/0/0

→ **(b) immediate follow-up, elevated priority.** This should be order 06's direct successor.

`get_default_settings()` (live, `llm.py:690`) sets `force_tool_usage = 'auto'` for **every**
Ollama `LLM`, on all three paths. `_should_force_tool_usage` is consulted **only** at
`llm.py:3561`, inside `get_response`. So `Agent(llm="ollama/...", stream=True)` accepts the
setting, reports it on `self.force_tool_usage`, and never acts on it. **A setting accepted and
ignored is exactly what root `AGENTS.md` forbids.**

Portability: `_should_force_tool_usage` (`1768-1788`) is pure —
`(response_text, tool_calls, formatted_tools, iteration_count) -> bool` — and the action is one
`messages.append` plus `continue`. Trivial for async. For stream: fine in the fallback branch;
in the true streaming branch it is an *additional* request after prose was already yielded,
which is legal (yielding more is always possible) but changes the stream's shape. That order
must state which of the two it does.

### 5.4 `_validate_and_filter_ollama_arguments` — 1/1/0 → **(a) Step 06.6**

Pre-dispatch, streaming-safe, guarded by `is_ollama and tools`. Done in this order.

### 5.5 `_generate_ollama_tool_summary` + `_handle_ollama_sequential_logic` + `OLLAMA_SUMMARY_ITERATION_THRESHOLD` — 1/1/0

→ **(b) separate follow-up — and this is where the measured stream failure lives.**

The §2.7 stream result — 10 tool invocations, zero output — is caused by their absence: nothing
breaks the fallback `while fallback_iterations < max_fallback_iterations` loop (`4572`) when
Ollama keeps re-emitting a tool call with empty `content`, and nothing synthesizes an answer at
the end. The loop exhausts `max_iter`, logs at `4665-4667`, and falls off the end of the
generator having yielded nothing.

Streaming feasibility: **fully possible.** Yielding a synthesized summary as a final chunk is
additive — the impossibility in §5.2 is about *retracting*, not appending.

Why it is a separate order: it **changes the stream contract**. A turn that currently yields
nothing would begin yielding synthesized text the model never produced. That needs its own
characterization baseline and its own answer to the alternative. The two options, stated plainly
for that order to choose between:
- **Synthesize** (matches sync/async): consistent across paths; risks presenting
  `str(tool_result)` as if the model wrote it.
- **Raise** (`LLMResponseError("provider produced no answer after N tool iterations")`): honest,
  and consistent with `00-ground-truth.md` §2's rule that a fabricated answer is worse than an error.

**Recommendation for that order: raise on the stream path, keep synthesis on sync/async**, and
record the asymmetry as intentional — a streaming consumer has already rendered partial output
and a synthesized tail is indistinguishable from model text, whereas a sync caller gets one
return value it can inspect. But that is a product decision and must be made in its own order
with its own review, not smuggled in here.

### 5.6 `OLLAMA_TOOL_USAGE_PROMPT` — 1/1/0 → **(b) follow-up, bundled with §5.5**

Same shape (append a message, re-request), same branch, same tests. Bundle it.

### 5.7 `OLLAMA_FINAL_ANSWER_PROMPT` — 0/**1**/0 → **(b) follow-up; the gap runs against `get_response`**

`llm.py:5298-5303`, async only. The "sync compensates most" framing is wrong here, and per §2.7
this is the leading candidate for why sync returns `'{\n\n\n}'` while async returns the right
answer. Step 06.0 settles it.

The follow-up that adds it to sync is a **behaviour change** — sync output would go from
`'{\n\n\n}'` to `'Paris: 21C sunny'` — so it needs Step 06.4's characterization tests in place
first, with `test_non_empty_response_after_tools_returns_model_text` deliberately updated in
that commit. **That test failing is the signal that the fix landed.**

### 5.8 `_register_deferred_if_any` — 1/**0**/1 → **(b) follow-up; async is the odd one out**

Present in sync (`2918`) and stream (`4461`), missing from async. Deferred media follow-ups
registered by a tool are dropped on the async path. Not adapter-shaped, not Ollama-specific.

### 5.9 `_manage_context_in_loop` (1/1/0) and `_finalise_on_limit` (2/2/0) → **(b) follow-up**

`get_response_stream` performs no in-loop context management and no max-steps finalisation. Both
are provider-independent and streaming-compatible (context trimming happens before the request;
finalisation appends a final chunk). One order, both fixes, one test per branch.

### 5.10 `supports_streaming()` — live in async only → **(c) out of scope; do not "fix" this**

It looks like an asymmetry to close. It is not. `AnthropicAdapter.supports_streaming()` returns
`False` for a reason its own comment states:

```python
215:    def supports_streaming(self) -> bool:
216:        # litellm.acompletion with stream=True returns a ModelResponse (not async generator)
217:        # for Anthropic in the async path, causing 'async for requires __aiter__' error
218:        return False
```

The defect is **specific to `litellm.acompletion`**. Consulting it from `get_response` or
`get_response_stream` would disable Anthropic streaming entirely in the sync and generator
paths, **where it works** — a real regression for users, dressed as consistency. Leave the call
sites as they are. The honest cleanup is a rename (`supports_async_streaming`) or a docstring,
both public-surface changes needing their own order and a deprecation shim under I1.

---

## 6. The anti-regression test

Location: `src/praisonai/tests/unit/llm/test_llm_adapter_seam.py` — chosen because that
directory **is** run by CI and `src/praisonai-agents/tests/unit/` is not (§3.1 Trap A).

```
/* Detailed source-code truncated for AI context efficiency. */
```

### 6.1 What this test cannot do — stated so nobody mistakes it for a ceiling

1. **It cannot detect an unreachable call site.** `should_skip_streaming_with_tools` is the
   proof: had `llm.py:3122` called it, this test would pass — while the branch stayed dead
   because `3117` short-circuits first. Reachability is semantic; this test measures syntax.
2. **It cannot detect a call site never *taken* at runtime** — behind `if False`, behind a config
   flag nobody sets, or in a `try` whose `except` swallows everything (which is how
   `_create_tool_message`'s absence hid for so long, per its own docstring at `6776-6786`).
3. **One call site is enough to satisfy it. This test does not detect A2 at all.** A method
   called only from `get_response` passes just as well as one called from all three. A2's guard
   is the per-path parity tests in Steps 06.3, 06.4 and 06.6, and there is no cheap general form.
4. **The receiver allowlist is a heuristic.** A call through an unusually-named local
   (`a = get_provider_adapter(p); a.foo()`) is invisible. Mitigation: `ADAPTER_RECEIVERS` covers
   every naming used in `llm/` today, and a new name is a reviewable one-line addition. Dropping
   the allowlist instead produces false *positives* — `openai_client.format_tools` would mask
   `DefaultAdapter.format_tools` — which is worse, because it hides dead code rather than
   over-reporting it.
5. **It scans `praisonaiagents/llm/` only.** An adapter method called from `agent/` or `memory/`
   would be reported dead. No such call exists today (verified repo-wide); widen the root if that
   changes.
6. **It runs only where CI runs it.** If order 04 or 05 later brings
   `src/praisonai-agents/tests/unit/` into CI, move it next to `test_adapter_registry.py` — but
   not before.

---

## 7. Handoffs — work this order deliberately does not do

| To | What | Why not here |
|---|---|---|
| **order 02** | Make `add_provider_adapter` reachable: have `_detect_provider` consult the adapter registry (e.g. `if has_provider_adapter(prefix): return prefix`) before falling back to `"openai"`, plus `test_registered_custom_adapter_is_selected`. Today a registered name can never be passed to `get_provider_adapter` — **the hook is a lie**. If order 02 declines, the correct disposition flips to **DELETE** under root `AGENTS.md`. | `_detect_provider` belongs to order 02. Related: `00-ground-truth.md` §5 shows `ollama_chat/`, `lm_studio/`, `vllm/` all resolving to `DefaultAdapter` — the same registry gap. |
| **order 02** | Reconcile `_is_ollama_provider()` with `isinstance(adapter, OllamaAdapter)`. Steps 06.4 and 06.5 replace the former with the latter and are **blocked** if `test_ollama_adapter_selection_matches_is_ollama_provider` fails on `main`. | Same ownership. |
| **orders 04 / 05** | `src/praisonai-agents/tests/unit/` — incl. `test_adapter_registry.py` (38 tests) and all 13 files in `tests/unit/llm/` — is run by **no** workflow. Add it to a shard. | `.github/workflows/**` is theirs. |
| **a new order** | `llm/streaming_protocol.py`: 387 lines, 4 adapter classes, 3 public functions, 11 Ollama references. After Step 06.2 deletes `DefaultAdapter.get_streaming_adapter`, its only production importer is gone and **the whole module is dead** (only `tests/test_architectural_fixes.py` — itself outside CI — imports it). Decide: delete, or wire as the streaming seam. | Deleting a 387-line module is not "one adapter method"; it needs its own risk assessment. Do not fold it into 06.2. |
| **a new order** | `OLLAMA_SUMMARY_ITERATION_THRESHOLD = 1` (`llm.py:273`) is applied to **all** providers at `3821` and `5446`: `elif tool_summary_text is None and iteration_count > self.OLLAMA_SUMMARY_ITERATION_THRESHOLD: continue`. For a non-Ollama provider at `iteration_count >= 2` this `continue` skips both the `max_iterations` safety check (`3826`) and the `response_text = ""` reset (`3837`). Latent, provider-independent, a behaviour change to fix. | Not adapter wiring; §1 row 9 explains why `get_max_iteration_threshold` is not the answer. |
| **follow-up orders** | §5.2, §5.3, §5.5, §5.6, §5.7, §5.8, §5.9 — one order each, in that priority order. **§5.3 first**: it is the only one where a live setting is silently ignored. | Each changes behaviour; order 06 is refactor-only. |

---

## 8. Hard constraints — and what each means concretely here

1. **Never edit two of the three response paths in one commit without a test covering both.**
   Steps 06.2, 06.5, 06.6 touch one path each — the rule is inert. Step 06.3 touches sync +
   async + the stream's formatter: it ships `test_tool_result_message_identical_across_paths`,
   parametrized over all three. Step 06.4 touches sync + async: it ships both
   `..._sync` and `..._async` in the same commit. Both, or split.

2. **No new abstraction layer.** `llm/adapters/` is the abstraction; this order makes it
   load-bearing. Do not add a quirk registry, a compensation table, a strategy object, a mixin,
   or a new module (ledger I7). Twelve of the twenty decisions are DELETE precisely because the
   temptation here is to build rather than remove. Step 06.3 is the only step that *adds* code to
   the adapter, and only by moving three identical copies into the method that already declares
   the job.

3. **Backward compatibility is mandatory (I1).** Nothing in `praisonaiagents.llm.adapters` is
   re-exported from `praisonaiagents.llm` or `praisonaiagents` (verified: no adapter name appears
   in either `__init__.py`'s lazy-import map), and none is documented under `docs/`. The Step
   06.2 deletions are therefore not public-surface removals in practice. `add_provider_adapter`
   is kept anyway, being the one name a third party would plausibly have found. If a reviewer
   disagrees about `list_provider_adapters` / `has_provider_adapter`, keep them and add them to
   `KNOWN_DEAD` with that reason — do not argue about it mid-step.

4. **`get_response` is 1,675 lines with 194 branch points.** Any diff inside `llm.py:2557-4231`
   must: quote at least three unmodified lines above and below the change; change **only** the
   lines named in this order — no reindentation of neighbours, no reflowing long lines, no
   comment tidy-ups, no `black`/`ruff --fix` over the file, no import reordering; keep the diff's
   line count within a few lines of the replacement's, so `git show --stat` is a truthful summary
   of scope; and be reviewed with `git diff -U10` before pushing. If the diff shows a hunk you
   did not intend, revert the file and redo the edit by hand.

5. **One adapter method per commit, one commit per branch, every step independently revertible.**

6. **Characterization test first, always.** Every step's tests must be written against
   `origin/main`, run, and observed green *before* the source edit. A test written after the
   change pins the change, not the behaviour. Where a step intentionally changes behaviour (only
   Step 06.3's non-serializable-result case), the test asserting the old behaviour must be marked
   `xfail(strict=True)` in the same commit, so the change is visible as a test-outcome diff
   rather than a silent edit.

7. **Update `README.md` §4 row 06 in the same commit as each step** — one line only, to avoid
   conflicts with concurrent orders.

---

## 9. Step summary

| Step | Branch | Item | Paths edited | Risk | Reverts to |
|---|---|---|---|---|---|
| 06.0 | — | — | none (throwaway probe) | none | n/a |
| 06.1 | `test/adapter-reachability-ratchet` | ratchet | none | none | 1 test file |
| 06.2 | `refactor/delete-dead-adapter-surface` | 9 methods + 2 module fns | sync ×1 (dead branch) | very low — zero call sites, proven | pure deletion |
| 06.3 | `refactor/wire-default-tool-result-message` | `format_tool_result_message` | sync, async, stream-formatter | low — default body has no consumers today | 3 inline copies |
| 06.4 | `refactor/wire-handle-empty-response-with-tools` | `handle_empty_response_with_tools` | sync, async | medium — guard widens from `_is_ollama_provider()` to adapter dispatch | 2 predicates |
| 06.5 | `refactor/wire-recover-tool-calls-from-text` | `recover_tool_calls_from_text` | sync | medium-high — 4 measured deltas, all argued inert | 33 inline lines |
| 06.6 | `fix/stream-path-ollama-argument-filtering` | A2 port | stream (both branches) | low — pre-dispatch, guarded | 2 insertions |

**End state:** `KNOWN_DEAD` empty, `DefaultAdapter` at 8 methods all with live call sites,
`llm.py` shorter by ~90 lines, and a CI-enforced test that makes A1 recurrence a red build.

A2 is **measured, dispositioned and partly closed — not solved.** §5 names the seven successor
orders and which of them is genuinely impossible while streaming.

---

### Src Praisonai Agents Docs Local Model Layer 07 Local Package Spec (`src/praisonai-agents/docs/local-model-layer/07-local-package-spec.md`)

# 07 — `praisonaiagents/local/` API specification

**Branch:** `feat/local-model-resolver`
**Status:** normative specification. No implementation exists yet.
**Owns:** `praisonaiagents/local/**` (new), `src/praisonai/tests/unit/llm/local/**` (new).
Touches nothing else. Tests live under `src/praisonai/tests/` — **not** `src/praisonai-agents/tests/` —
because CI runs `cd src/praisonai && pytest tests/unit/` and collects nothing from the
agents-package tree (see `00-ground-truth.md`). Tests placed there run nowhere, so the
import-boundary and no-socket guards below would silently never execute.
**Verified on:** 2026-09-03, macOS (Darwin 27.0.0), Ollama 0.33.2 live on `127.0.0.1:11434`,
`llama-server` build 7620 present, `mlx_lm.server` present.

An implementing agent may implement **one module in isolation** by reading only §2
(constraints), §4 (layering), and that module's own section. Claims marked *unverified* are
unproven data, not fact — do not promote them without a live check.

---

## 1. Purpose

`local/` answers three questions and returns the answers as frozen data:

1. **What is running on this machine?** — `discover.py`
2. **What can that model actually do?** — `capabilities.py`
3. **What will it silently get wrong?** — `quirktable.py`

`target.py` folds those into one `LocalTarget`. `manage.py` returns *remedy data* (command
lines, PATH facts) without executing anything. `embed.py` returns an `EmbeddingTarget`.

Behaviour — request mutation, retries, schema rewriting, streaming repair — lives in
`llm/adapters/` and is out of scope. See §12.

---

## 2. The two hard constraints

### 2.1 Dependency sink

Every file in `local/` may import **only** (a) the Python standard library and (b) sibling
modules inside `local/` via **single-dot** relative imports.

Forbidden without exception: any `praisonaiagents` import (absolute or `..`-relative),
`litellm`, `openai`, `pydantic`, `httpx`, `requests`, `aiohttp`, `anyio`, `rich`, `yaml`,
`posthog`, and any other distribution.

### 2.2 Data, never behaviour

Every public return value is a frozen, slotted, hashable dataclass, or a `frozenset`/`tuple`
of them. `local/` must never mutate a request payload, retry, sleep-and-retry, issue a
chat/completion/embedding **inference** call, start or stop a process, write to disk, or read
a config file. The only writes anywhere are two process-local dicts in `target.py` (§9).

Allowed HTTP: `GET`, plus exactly one `POST` — `POST {base}/api/show {"model": ...}` — which
reads a manifest, performs no inference, and does not load weights (verified).

---

## 3. Decision: HTTP client is stdlib `urllib.request`

**This overrides the ledger's earlier suggestion of `httpx`.** The reasoning:

`httpx==0.28.1` is installed, but only **transitively**: `openai -> httpx`. `pyproject.toml`
never declares it. Building a dependency sink on an undeclared transitive edge means a future
`openai` release that drops `httpx` silently breaks `local/` — exactly the class of silent
failure this package exists to catalogue. Declaring it would either add an 18th extra (making
the sink optional, so the bypass sites still cannot rely on it) or add a hard dependency to
the one package whose selling point is that everything can import it.

`aiohttp` *is* a hard dependency, but it is async-only — forcing an event loop into the
synchronous `Agent.__init__` — and costs ~40 ms to import on a hot path.

The cited weaknesses of `urllib.request` do not bite here. **No pooling:** a full resolve
issues at most 4 loopback requests, then caches for 30 s. **Clumsy timeouts:**
`urlopen(req, timeout=t)` applies `t` to connect and to each socket read, which is all
loopback needs; the total budget is enforced by the caller. **No concurrency:**
`concurrent.futures.ThreadPoolExecutor` is stdlib and handles the port fan-out.

The boundary test hard-forbids `httpx`/`requests`/`aiohttp` so this cannot drift.

---

## 4. Layering and naming

### 4.1 Module layers (acyclic; layer *n* imports only layers < *n*)

| Layer | Module | May import |
|---|---|---|
| 0 | `capabilities.py` | stdlib only (`enum`, `dataclasses`, `typing`, `json`) |
| 1 | `quirktable.py` | stdlib, `.capabilities` |
| 1 | `discover.py` | stdlib (`urllib.request`, `urllib.error`, `json`, `os`, `socket`, `time`, `concurrent.futures`, `dataclasses`, `enum`, `typing`), `.capabilities` |
| 2 | `target.py` | stdlib (`os`, `time`, `threading`, `asyncio`, `functools`, `urllib.parse`, `ipaddress`, `dataclasses`, `typing`), `.capabilities`, `.quirktable`, `.discover` |
| 3 | `manage.py` | stdlib (`shutil`, `dataclasses`, `enum`, `typing`), `.capabilities`, `.discover`, `.target` |
| 3 | `embed.py` | stdlib, `.capabilities`, `.discover`, `.target` |
| 4 | `__init__.py` | the five above |

`capabilities.py` is the **vocabulary module**: it owns `LocalEngine`, `ApiStyle`, `Cap` and
`Evidence` in addition to the capability parsers. This is the only placement that yields a
cycle-free graph across the fixed 7-file layout.

### 4.2 Naming collision audit

The name `runtime` is **taken**: `praisonaiagents/runtime/` is the agent-execution harness,
`pyproject.toml` declares a `praisonai.runtimes` entry-point group, and examples use
"runtime" for tool sandboxes.

| Name | Already exists at | Ruling |
|---|---|---|
| `runtime`, `Runtime`, `*Runtime*` | `praisonaiagents/runtime/` | **Banned.** Use `engine`. |
| `RuntimeCapability`, `RuntimeCapabilityMatrix` | `runtime/capabilities.py:19,50` | Banned. Ours is `Cap`. |
| `resolve_runtime()` | `runtime/resolve.py:232` | Ours is `local.resolve()`, namespace-qualified only. Never re-export a bare `resolve`; if ever promoted, the name is `resolve_local`. |
| `RuntimeResolver`, `RuntimeResolutionResult` | `runtime/resolve.py:67`, `runtime/resolver.py:37` | Banned. |
| `ProbeResult` | `bots/protocols.py:651` | **Banned.** Ours are `ProbeSpec`, `Discovery`, `HttpReply`. |
| `CapabilityValidator`, `CapabilityDescriptor` | `skills/capability_validator.py:74`, `gateway/protocols.py:5460` | Banned. |
| `capabilities.py`, `embed.py` (basenames) | `runtime/`, `embedding/` | **Allowed** — different dotted paths, relative imports only. Do not "fix" by renaming. Note `embedding/embed.py` exposes `embedding()`; ours exposes `embedding_target()`. Never name anything in `local/` `embedding()`. |
| `engine`, `Engine`, `LocalEngine`, `Quirk`, `ApiStyle`, `LocalTarget`, `Cap` | no hits | **Free.** Adopted. |

`local/` is **not** added to `_LAZY_IMPORTS` in `praisonaiagents/__init__.py`, and **no** new
extra is added to `pyproject.toml`.

### 4.3 Sync vs async

**Both, sync-primary.** `discover()`, `resolve()`, `capabilities()`, `models()`,
`embedding_target()` are the primitives. Each has an `a`-prefixed twin implemented as exactly:

```python
async def aresolve(*args: Any, **kwargs: Any) -> LocalTarget:
    """Async twin of resolve(); runs the sync probe in the default executor."""
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(None, functools.partial(resolve, *args, **kwargs))
```

`Agent.__init__` is synchronous and may be called from inside a running event loop; an
async-native core would force `asyncio.run()` (which raises there) or a hand-rolled asyncio
HTTP parser. The executor costs one thread for <= 1.5 s, and only on a cache miss. Both twins
share one cache and one lock.

### 4.4 `LocalTarget` carries `litellm_model`

**Yes**, as `Optional[str]`, computed by the pure function `litellm_model_for(engine, model_id)`.

Without it, each bypass site re-derives a prefix, and they have already diverged:
`llm/llm.py:_detect_provider()` knows only `ollama/`; `llm/model_providers.py` matches only
`model.startswith("ollama/")`; `llm/openai_client.py:_supports_responses_api` knows `ollama/`
**and** `ollama_chat/`; `agent/agent.py:_PROVIDER_DEFAULT_MODELS` hardcodes `ollama/llama3.2`.
A pure `(engine, model_id) -> str` mapping is data, so §2.2 holds.

| `engine` | `litellm_model` | Caller must also pass |
|---|---|---|
| `OLLAMA` | `f"ollama/{model_id}"` | `api_base=target.base_url` |
| `LM_STUDIO` | `f"lm_studio/{model_id}"` | `api_base=target.openai_base_url` |
| `VLLM` | `f"hosted_vllm/{model_id}"` | `api_base=target.openai_base_url` |
| all others | `f"openai/{model_id}"` | `api_base=target.openai_base_url`, `api_key=target.api_key` |
| any engine with `model_id is None` | `None` | — |

**`OLLAMA` maps to `ollama/`, never `ollama_chat/`** — even though `ollama_chat/` is the
better litellm route — because `_detect_provider()` returns `"openai"` for an `ollama_chat/`
model, silently losing `OllamaAdapter` and its streaming guard. Revisit only after work order
`02` teaches that call site the extra prefixes.

---

## 5. Data model

### 5.1 `capabilities.py` — vocabulary

```
/* Detailed source-code truncated for AI context efficiency. */
```

### 5.2 `quirktable.py` — the silent-failure catalogue

```
/* Detailed source-code truncated for AI context efficiency. */
```

Meaning of each Ollama quirk, one line each:

| Quirk | Symptom | Severity |
|---|---|---|
| `FORMAT_AND_TOOLS_MUTUALLY_DESTRUCTIVE` | JSON format + tools suppresses the tool call; the model fabricates an answer | SILENT |
| `TOOL_SCHEMA_KEYWORDS_STRIPPED` | `minLength`, `format`, `default`, `additionalProperties`, `$ref`, `oneOf` dropped before the model sees them | SILENT |
| `TOOL_PARAM_TYPE_MUST_BE_BARE_STRING` | `"type": ["object","null"]` 400s the whole request | HARD |
| `UNKNOWN_OPTIONS_ACCEPTED_AND_IGNORED` | Unrecognised `options` keys return 200 and change nothing | SILENT |
| `THINK_FIELD_IGNORED_ON_OPENAI_ROUTE` | `think` dropped on `/v1/*`; use `reasoning_effort` | SILENT |
| `THINKING_WITH_TOOLS_YIELDS_EMPTY_TURN` | Empty content, zero tool calls, `finish_reason="stop"` | SILENT |
| `NATIVE_ROUTE_NEVER_SETS_TOOL_FINISH_REASON` | `/api/chat` reports "stop" even with `tool_calls` present | SILENT |
| `TOOL_CALLS_ARRIVE_WHOLE_NOT_INCREMENTAL` | Streamed tool calls come in one chunk, not deltas | SILENT |
| `STREAM_ERROR_ENDS_WITHOUT_DONE` | Mid-stream failure yields an empty delta and no `[DONE]` | SILENT |
| `SAMPLING_DEFAULTS_FORCED_TO_ONE` | Omitted `temperature`/`top_p` become 1.0, not the model's defaults | SILENT |
| `CONTEXT_OPTION_CHANGE_RELOADS_MODEL` | Changing `num_ctx`/`num_batch`/`num_gpu` forces a full reload | COST |
| `KEEP_ALIVE_IS_GLOBAL_LAST_WRITER_WINS` | `keep_alive` is per-model and process-wide, not per-request | SILENT |
| `BODYLESS_403_ON_NON_LOCAL_HOST_HEADER` | Non-local `Host` header gets HTTP 403 with a zero-byte body | HARD |
| `TOOLS_REQUIRE_SERVER_FLAGS` | Tool calls come back as assistant text (vLLM needs BOTH `--enable-auto-tool-choice` AND `--tool-call-parser`; llama-server needs `--jinja`) | SILENT |
| `SINGLE_MODEL_PER_PROCESS` | The request's `model` field is ignored — asking for B gets A's answer | SILENT |
| `MODEL_ID_IS_A_FILE_PATH` | The reported model id is a filesystem path | SILENT |
| `CAPS_ASSUMED_ENGINE_UNIDENTIFIED` | Engine is `UNKNOWN`; every `Cap` is `Evidence.TABLE` guesswork | SILENT |

Route scoping (normative): `NATIVE_ROUTE_NEVER_SETS_TOOL_FINISH_REASON` is
`api_styles=(OLLAMA_NATIVE,)`; `THINK_FIELD_IGNORED_ON_OPENAI_ROUTE` and
`SAMPLING_DEFAULTS_FORCED_TO_ONE` are `api_styles=(OPENAI_CHAT, OPENAI_COMPLETIONS)`;
`THINKING_WITH_TOOLS_YIELDS_EMPTY_TURN` is `requires_caps={Cap.THINKING, Cap.TOOLS}`;
`TOOLS_REQUIRE_SERVER_FLAGS` is `engines=(VLLM, LLAMA_CPP, LLAMAFILE)`;
`CAPS_ASSUMED_ENGINE_UNIDENTIFIED` is `engines=(UNKNOWN,)`. Everything else in the Ollama
block is `engines=(OLLAMA,)`, all styles.

`quirktable.py` performs no network, no I/O and reads no environment variable.

### 5.3 `discover.py` — probing types

```
/* Detailed source-code truncated for AI context efficiency. */
```

The default `Transport` is built inside `discover.py` and is the only thing in the package
that touches a socket.

### 5.4 `target.py` — the product

```python
@dataclass(frozen=True, slots=True)
class LocalTarget:
    engine: LocalEngine
    base_url: str                                # no trailing slash, no /v1
    openai_base_url: str                         # base_url + "/v1"
    api_style: ApiStyle
    model_id: str | None
    caps: frozenset[Cap]
    quirks: frozenset[Quirk]
    litellm_model: str | None
    api_key: str                                 # placeholder "local"; never "" (openai rejects "")
    engine_version: str | None
    evidence: tuple[tuple[str, Evidence], ...]   # sorted by field name; per-field provenance
    extra: tuple[tuple[str, str], ...]           # sorted by key; engine-specific facts
    probed_at: float

    def supports(self, cap: Cap) -> bool: ...
    def has_quirk(self, quirk: Quirk) -> bool: ...
    def evidence_for(self, field: str) -> Evidence: ...   # Evidence.UNKNOWN if absent
    def get_extra(self, key: str, default: str | None = None) -> str | None: ...
    def as_dict(self) -> dict[str, object]: ...           # JSON-safe, for logs and doctors
```

`evidence`/`extra` are **tuples of pairs, not dicts**, so `LocalTarget` stays frozen *and*
hashable — a `dict` field would make the generated `__hash__` raise `TypeError` at runtime.

### 5.5 Exceptions (defined in `target.py`)

```python
class LocalError(Exception): ...
class NoLocalEngineError(LocalError): ...
class EngineUnreachableError(LocalError):
    base_url: str
    reason: str          # "refused" | "timeout" | "reset" | "http_<status>"
    source: str          # "spec" | "PRAISONAI_LOCAL_BASE_URL" | "OLLAMA_HOST" | ...
class HostHeaderRejectedError(EngineUnreachableError): ...
class ModelNotAvailableError(LocalError):
    model_id: str
    available: tuple[str, ...]
class InvalidLocalSpecError(LocalError, ValueError): ...
```

`local/` deliberately does **not** subclass `praisonaiagents.errors.PraisonAIError` — that
would import upward and break §2.1. Wrapping is the integration layer's job.

---

## 6. `capabilities.py`

```
/* Detailed source-code truncated for AI context efficiency. */
```

`DEFAULT_CAPS` (normative floor):

| engine | caps |
|---|---|
| `OLLAMA` | `CHAT, COMPLETION, STREAMING, JSON_OBJECT, JSON_SCHEMA, EMBEDDINGS_ENDPOINT` |
| `LLAMA_CPP` | `CHAT, COMPLETION, STREAMING, JSON_SCHEMA, JSON_OBJECT, EMBEDDINGS_ENDPOINT` |
| `MLX_LM` | `CHAT, COMPLETION, STREAMING` |
| `LM_STUDIO` | `CHAT, COMPLETION, STREAMING, JSON_SCHEMA, JSON_OBJECT, EMBEDDINGS_ENDPOINT` |
| `VLLM` | `CHAT, COMPLETION, STREAMING, JSON_SCHEMA, JSON_OBJECT, EMBEDDINGS_ENDPOINT, PARALLEL_TOOL_CALLS` |
| `TRANSFORMERS_SERVE` | `CHAT, STREAMING` |
| `LLAMAFILE`, `LOCALAI`, `RAMALAMA` | `CHAT, COMPLETION, STREAMING` |
| `UNKNOWN` | `CHAT, STREAMING` |

`Cap.TOOLS` and `Cap.VISION` are **never** in `DEFAULT_CAPS` — claiming them without server
evidence is exactly the silent failure this package prevents. `Cap.STREAMING_WITH_TOOLS` is
granted only when the server reports `TOOLS` **and** the engine's quirk set lacks
`TOOL_CALLS_ARRIVE_WHOLE_NOT_INCREMENTAL`.

---

## 7. `discover.py` and the probe table

```
/* Detailed source-code truncated for AI context efficiency. */
```

### 7.1 The probe table (actual literal)

Port collisions are real: **8080** is claimed by `llama-server`, `mlx_lm`, `llamafile`,
LocalAI and RamaLama; **8000** by vLLM and `transformers serve`. Identity is therefore
**never** inferred from a port — a `ProbeSpec` matches only when every `Rule` in `identity`
holds, and `RuleKind.ABSENT` rules exist specifically to separate co-tenants of one port.

```
/* Detailed source-code truncated for AI context efficiency. */
```

`LLAMAFILE`, `LOCALAI` and `RAMALAMA` are enum members with `DEFAULT_CAPS` entries but **no
`ProbeSpec`**: they are reachable only via `PRAISONAI_LOCAL_ENGINE`. Adding a row requires a
discriminator verified on a live server. A `ProbeSpec` with `verified=False` is still probed —
it is the *note* that is unproven, not the port.

---

## 8. `target.py` — `resolve()` and precedence

```python
DEFAULT_API_KEY: str = "local"
ENV_BASE_URL: str = "PRAISONAI_LOCAL_BASE_URL"
ENV_ENGINE:   str = "PRAISONAI_LOCAL_ENGINE"
ENV_MODEL:    str = "PRAISONAI_LOCAL_MODEL"
ENV_TTL:      str = "PRAISONAI_LOCAL_TTL"
ENV_NEG_TTL:  str = "PRAISONAI_LOCAL_NEG_TTL"
ENV_TIMEOUT:  str = "PRAISONAI_LOCAL_TIMEOUT"

def resolve(spec=None, *, timeout=None, refresh=False, transport=None) -> LocalTarget: ...
async def aresolve(...) -> LocalTarget: ...
def resolve_or_none(spec=None, **kwargs) -> LocalTarget | None: ...
async def aresolve_or_none(...) -> LocalTarget | None: ...
def build_target(discovery, model_id, *, caps=None, caps_evidence=Evidence.TABLE,
                 model_evidence=Evidence.SERVER) -> LocalTarget: ...   # pure
def litellm_model_for(engine, model_id) -> str | None: ...             # pure
def parse_spec(spec) -> tuple[LocalEngine | None, str | None, str | None]: ...
def parse_ollama_host(value: str) -> str | None: ...
def select_model(discovery, *, transport=None, timeout=0.4) -> str | None: ...
def clear_cache() -> None: ...
def cache_info() -> dict[str, int]: ...
```

`parse_ollama_host` applies Ollama's own rules: empty/whitespace -> `None`; contains `://` ->
parsed as a URL where an absent port means **80 for http and 443 for https, not 11434**; all
digits (`"11500"`) or a leading colon (`":11500"`) -> `http://127.0.0.1:11500`; otherwise
`host[:port]` with default port 11434 and scheme http. IPv6 must be bracketed; an unbracketed
IPv6 literal returns `None`.

### 8.1 Resolution precedence

Sources are consulted in this order. **Authoritative** means its failure raises;
**inferential** means its failure falls through.

1. **`spec` argument — authoritative.**
   - `None` / `""` / `"local"` / `"auto"` -> contributes nothing; go to 2.
   - `"<engine>/<model>"` -> pins `engine` and `model_id` (`Evidence.SPEC`); the base URL
     still comes from 2-5, restricted via `probe_endpoint(expect=engine)`.
   - a URL -> pins `base_url`; an optional `#model` fragment pins `model_id`. Probed for
     identity; answering but matching no discriminator gives `engine=UNKNOWN`.
   - anything else -> `InvalidLocalSpecError(f"Cannot parse local spec {spec!r}. Expected None, 'local', '<engine>/<model>', a base URL, or '<url>#<model>'.")`
   - A pinned `base_url` that does not answer -> `EngineUnreachableError(source="spec")`.
     **No fallback** — silently talking to a different server than the caller named is the
     failure mode this package exists to prevent.
2. **`PRAISONAI_LOCAL_BASE_URL` — authoritative.** `PRAISONAI_LOCAL_ENGINE`, if set to a valid
   `LocalEngine` value, skips identity probing and pins the engine (`Evidence.ENV`); an
   invalid value raises `InvalidLocalSpecError`.
3. **`OLLAMA_HOST` — authoritative.** Via `parse_ollama_host()`, with `expect=OLLAMA`. This is
   where the bare-host / `http://` asymmetry bites, which is why the error must print the
   resolved URL.
4. **`OPENAI_BASE_URL`, then `OPENAI_API_BASE` — inferential.** Used **only** if the host is
   loopback (`127.0.0.0/8`, `::1`, `localhost`) or RFC1918/link-local. A public host is
   ignored — it is normally a cloud proxy. Falls through to 5, recording the skip reason.
5. **Probe-table scan — inferential.** `discover(host="127.0.0.1")` in table order, ports
   concurrent, within `budget`. The first non-`blocked` `Discovery` in table order wins, so
   Ollama on 11434 beats an unidentified server on 8000.
6. **Nothing found.** If step 5 produced only `blocked` discoveries, raise
   `HostHeaderRejectedError`. Otherwise `NoLocalEngineError`.

### 8.2 Error message templates (exact)

```
No local model runtime found. Probed 127.0.0.1 ports 11434 (ollama), 8080 (llama_cpp, mlx_lm), 1234 (lm_studio), 8000 (vllm, transformers_serve) in 1.5s; nothing answered. Start one (e.g. `ollama serve`, then `ollama pull qwen3:0.6b`) or set PRAISONAI_LOCAL_BASE_URL to its address.
```
When step 4 was skipped for being non-local, append exactly:
` Ignored OPENAI_BASE_URL='https://api.openai.com/v1': not a local address.`

```
Local runtime at http://127.0.0.1:80 did not answer (refused). It was named explicitly by OLLAMA_HOST='http://127.0.0.1', so no other port was probed. Note that OLLAMA_HOST with an explicit http:// scheme and no port means port 80, not 11434.
```
The trailing sentence appears only when `source == "OLLAMA_HOST"` and the parsed port is 80 or 443.

```
Local runtime at http://192.168.1.10:11434 returned HTTP 403 with an empty body. Ollama rejects any request whose Host header is not localhost or an IP address; set OLLAMA_HOST on the server to allow this origin.
```

```
Model 'llama3.2' is not served by ollama at http://127.0.0.1:11434. Available: qwen3:0.6b, mervinpraison/praisonai-qwen3.5-9b-tamil-en2ta:latest. Pull it with `ollama pull llama3.2`.
```

### 8.3 `select_model()` — deterministic choice

Applied only when no source pinned a model:

1. `PRAISONAI_LOCAL_MODEL` if set — validated against the model list; a miss raises `ModelNotAvailableError`.
2. If the engine has `Quirk.SINGLE_MODEL_PER_PROCESS` -> the single id reported, or `None`.
3. If the list has exactly one entry -> that entry.
4. Otherwise prefer entries whose reported capabilities include `tools` (Ollama's `/api/tags`
   carries `capabilities` per entry — verified); tie-break newest `modified_at`; final
   tie-break lexicographic ascending. **Never** guess a model not in the list.
5. Empty list -> `None` (and `litellm_model` is `None`).

### 8.4 Timeouts

`timeout=None` -> `float(os.environ.get(ENV_TIMEOUT, "1.5"))`, clamped to `[0.05, 30.0]`; a
non-numeric value falls back to 1.5 without raising. Per-request timeout is
`min(0.4, total/3)`. `resolve()` must return or raise within `total + 0.2` s.

---

## 9. Caching

| Question | Answer |
|---|---|
| **What is cached** | Two dicts in `target.py`: `_TARGETS: dict[str, tuple[float, int, LocalTarget]]` (deadline, pid, target) and `_NEGATIVES: dict[str, tuple[float, int, str, str]]` (deadline, pid, exception class name, message). Nothing else. |
| **Cache key** | `"\x00".join((spec or "*", PRAISONAI_LOCAL_BASE_URL, PRAISONAI_LOCAL_ENGINE, PRAISONAI_LOCAL_MODEL, OLLAMA_HOST, OPENAI_BASE_URL, OPENAI_API_BASE, f"{timeout:.3f}"))`. Every input that can change the answer is in the key, so an env change is a natural miss rather than a stale hit. |
| **TTL** | Positive 30.0 s (`PRAISONAI_LOCAL_TTL`); negative 5.0 s (`PRAISONAI_LOCAL_NEG_TTL`). `0` disables; negative or non-numeric falls back to the default without raising. Negatives are cached so "nothing running" does not cost 1.5 s on every `Agent()` in a loop. |
| **Invalidation** | (a) deadline passed; (b) `refresh=True`; (c) `clear_cache()`; (d) key change; (e) `os.getpid()` differs from the stored pid — a forked child must re-probe rather than inherit the parent's view. |
| **Where** | **Process-local only. Never on disk.** A disk cache goes stale across `ollama pull` / `ollama serve --port`, needs locking and per-user `/tmp` permissions, and is persistent mutable state — i.e. behaviour, which §2.2 forbids. |
| **Thread safety** | One module-level `_CACHE_LOCK = threading.Lock()`, held **only** around dict reads and writes, **never** across I/O. Two threads missing at once both probe; the second write wins; both callers get an equally valid target. `LocalTarget` is frozen, so a shared instance cannot be mutated. `aresolve` runs `resolve` in an executor and shares the same dicts and lock — no second cache. |
| **Re-raise** | A negative hit raises a **fresh** exception built from the stored class name and message — never a stored exception object, which would carry a stale traceback and references to dead frames. |

---

## 10. Failure semantics

`probe_endpoint()` and `discover()` never raise for network conditions.

| Condition | Transport result | `probe_endpoint` | `resolve()` |
|---|---|---|---|
| Connection refused | `HttpReply(0, b"", "refused")` | `None` | authoritative -> `EngineUnreachableError(reason="refused")`; inferential -> skip |
| Timeout | `HttpReply(0, b"", "timeout")` | `None` | as above, `reason="timeout"` |
| Reset / partial read | `HttpReply(0, b"", "reset")` | `None` | as above, `reason="reset"` |
| DNS failure (`socket.gaierror`) | `HttpReply(0, b"", "refused")` | `None` | as above |
| **Bodyless 403** (verified: Ollama, non-local Host header, `size_download=0`) | `HttpReply(403, b"", "http")` | `Discovery(blocked="host_header_rejected")` | skipped as a candidate; if it is the only one -> `HostHeaderRejectedError`; otherwise its reason is appended to `NoLocalEngineError`. **Never** silently reported as "nothing found". |
| 401/403 **with** a body | `HttpReply(401\|403, body, "http")` | `Discovery(blocked="auth_required")` | same handling, different message clause |
| Other 4xx/5xx | `HttpReply(status, body, "http")` | `None` unless an `ABSENT` rule wanted 404/405 | skip / `EngineUnreachableError(reason=f"http_{status}")` |
| Malformed JSON | `HttpReply(200, junk, None)` | `JSON_KEY` rules fail; `ABSENT` rules **succeed**; a matched `BODY_PREFIX`/`STATUS_OK` identity still stands with `models=()` | target built with `caps=default_caps(engine)`, evidence `TABLE`. Never raises. |
| Unknown runtime on a known port (200, no discriminator) | — | `Discovery(engine=UNKNOWN, api_style=OPENAI_CHAT if /v1/models parsed else OPENAI_COMPLETIONS, evidence=TABLE)` | `caps={CHAT, STREAMING}`, `quirks={CAPS_ASSUMED_ENGINE_UNIDENTIFIED}`, `litellm_model=f"openai/{model_id}"`. The quirk is the honest signal that everything here is a guess. |
| Non-UTF-8 body | decoded with `errors="replace"` | per rule | — |
| Reply larger than 1 MiB | truncated at 1 MiB | rules see truncated bytes | — |

The default transport must catch `urllib.error.HTTPError` (a subclass of `URLError` **and** a
response object — read its body, do not let it escape), `urllib.error.URLError`, `OSError`,
`socket.timeout`, `TimeoutError`, `ValueError` (bad URL) and `http.client.HTTPException`. It
must set `Host` implicitly (never override it) and send `Accept: application/json` and
`User-Agent: praisonaiagents-local/1`.

---

## 11. `manage.py` and `embed.py`

### 11.1 `manage.py` — remedy data, executes nothing

```python
class RemedyKind(str, Enum):
    INSTALL = "install"            # engine not on PATH
    START = "start"                # installed but not listening
    PULL_MODEL = "pull_model"      # listening but model absent
    ENABLE_TOOLS = "enable_tools"  # listening but launched without tool flags
    SET_ENV = "set_env"            # reachable but an env var points elsewhere

@dataclass(frozen=True, slots=True)
class Remedy:
    engine: LocalEngine
    kind: RemedyKind
    argv: tuple[str, ...]              # ("ollama", "pull", "qwen3:0.6b"); () for SET_ENV
    env: tuple[tuple[str, str], ...]
    docs_url: str
    note: str

def remedies(engine=None, *, kind=None, model_id=None) -> tuple[Remedy, ...]: ...  # pure
def binary_name(engine) -> str | None: ...
def binary_path(engine) -> str | None: ...            # shutil.which only
def installed_engines() -> tuple[LocalEngine, ...]: ...

@dataclass(frozen=True, slots=True)
class LocalModel:
    model_id: str
    engine: LocalEngine
    size_bytes: int | None
    modified_at: str | None            # ISO-8601 verbatim as the server reports it
    caps: frozenset[Cap]
    family: str | None

def installed_models(discovery, *, timeout=0.4, transport=None) -> tuple[LocalModel, ...]: ...
async def ainstalled_models(...) -> tuple[LocalModel, ...]: ...
```

`manage.py` **never** imports `subprocess`, `os.system`, `os.popen` or `pty`, and never calls
`os.exec*`. It emits `argv` tuples for a caller (a CLI, a doctor, an error message) to run or
print. That is the line between data and behaviour, and it is a test.

### 11.2 `embed.py`

```python
EMBED_DEFAULT_MODELS: Mapping[LocalEngine, str | None]   # OLLAMA -> "nomic-embed-text"

@dataclass(frozen=True, slots=True)
class EmbeddingTarget:
    engine: LocalEngine
    base_url: str
    endpoint: str                  # base_url + "/v1/embeddings", or the native path
    model_id: str | None
    dimensions: int | None         # from server metadata or a static table; None when unknown
    litellm_model: str | None
    api_key: str
    evidence: tuple[tuple[str, Evidence], ...]
    def as_dict(self) -> dict[str, object]: ...

def embedding_target(target, *, model_id=None, timeout=0.4, transport=None) -> EmbeddingTarget:
    """Model choice: model_id > PRAISONAI_LOCAL_EMBED_MODEL > EMBED_DEFAULT_MODELS > None.

    Dimensions come from server metadata only: for Ollama, POST /api/show and read the
    model_info key ending in ".embedding_length" (verified: qwen3.embedding_length == 1024).
    """
    # Raises LocalError when the target carries Quirk.NO_EMBEDDINGS_ENDPOINT or lacks
    # Cap.EMBEDDINGS_ENDPOINT; ModelNotAvailableError when a named model is not served.

async def aembedding_target(...) -> EmbeddingTarget: ...
def default_embed_model(engine) -> str | None: ...
```

**`dimensions` is never obtained by embedding a probe string.** That would be an inference
call — cost, model load, behaviour. `None` is the correct answer when metadata is silent.

### 11.3 `__init__.py`

Re-exports only; no logic, no `os.environ` reads, no lazy machinery (every submodule is
stdlib-only, so eager import is cheap).

```python
__all__ = [
    "LocalEngine", "ApiStyle", "Cap", "Evidence", "Severity", "Quirk",
    "Discovery", "HttpReply", "ProbeSpec", "Rule", "RuleKind", "Transport",
    "discover", "adiscover", "probe_endpoint", "probe_table", "models", "amodels",
    "capabilities", "acapabilities", "default_caps",
    "parse_ollama_capabilities", "parse_llama_cpp_props",
    "parse_lm_studio_models", "parse_openai_models",
    "QuirkNote", "note", "all_notes", "notes_for", "quirks_for", "silent_quirks",
    "LocalTarget", "resolve", "aresolve", "resolve_or_none", "aresolve_or_none",
    "build_target", "litellm_model_for", "parse_spec", "parse_ollama_host",
    "select_model", "clear_cache", "cache_info",
    "Remedy", "RemedyKind", "LocalModel", "remedies", "binary_name", "binary_path",
    "installed_engines", "installed_models", "ainstalled_models",
    "EmbeddingTarget", "embedding_target", "aembedding_target", "default_embed_model",
    "LocalError", "NoLocalEngineError", "EngineUnreachableError",
    "HostHeaderRejectedError", "ModelNotAvailableError", "InvalidLocalSpecError",
]
```

---

## 12. Tests

All under `src/praisonai/tests/unit/llm/local/` — the tree CI actually collects
(`cd src/praisonai && pytest tests/unit/`). Do **not** place them under
`src/praisonai-agents/tests/`, which no workflow runs (see `00-ground-truth.md`); the guards
below would then never execute. Every test carries `pytestmark = pytest.mark.unit`. The markers
`network`, `local_service` and `provider_ollama` are **forbidden** in this directory — a test
needing a live server belongs in `tests/integration/`, out of scope here.

**Files:** `__init__.py`, `conftest.py`, `fixtures/`, `test_import_boundary.py`,
`test_discover.py`, `test_capabilities.py`, `test_quirktable.py`, `test_target.py`,
`test_cache.py`, `test_manage.py`, `test_embed.py`, `test_async_parity.py`.

### 12.1 `conftest.py` provides exactly three things

- **`no_sockets`** (autouse, session-scoped): monkeypatches `socket.socket.__init__` to
  `raise AssertionError("tests/unit/llm/local must not open a socket")`. This is *the* mechanism
  that proves offline safety — a test that forgets to inject a transport fails loudly instead
  of silently hitting a developer's live Ollama.
- **`fake_transport(routes, *, default=HttpReply(0, b"", "refused"))`** — a `Transport`
  callable that also records calls, so tests can assert "exactly one request was made" and
  "no POST was issued".
- **`recorded(name)`** — reads `fixtures/<name>` from disk. No network.

### 12.2 `fixtures/` — byte-for-byte captures from this machine, 2026-09-03

`ollama_root.txt`, `ollama_api_version.json`, `ollama_api_tags.json` (both models, with
`capabilities` and `modified_at`), `ollama_api_show_qwen3_0_6b.json` (`capabilities`,
`details`, `model_info` incl. `qwen3.context_length: 40960`, `qwen3.embedding_length: 1024`),
`ollama_v1_models.json`, plus clearly-labelled hand-written-from-docs
`llama_cpp_props.json`, `lm_studio_api_v0_models.json`, `vllm_version.json`, `malformed.txt`,
`empty_403.bin`.

### 12.3 Test inventory

| File | Test | How it avoids the network |
|---|---|---|
| `test_import_boundary.py` | `test_only_stdlib_imports` | `ast.parse()` each `local/*.py`; every absolute import root must be in `sys.stdlib_module_names`. No import executed. |
| | `test_no_praisonaiagents_import` | AST: no import whose module starts with `praisonaiagents`. |
| | `test_no_parent_relative_imports` | AST: every `ImportFrom` has `level <= 1`. `level >= 2` is the escape hatch that breaks the sink. |
| | `test_forbidden_distributions` | AST: import roots ∩ `{litellm, openai, pydantic, httpx, requests, aiohttp, anyio, rich, yaml, posthog, numpy}` is empty. |
| | `test_loads_standalone_from_file_path` | `importlib.util.spec_from_file_location` loads `local/` **without** executing `praisonaiagents/__init__.py`, proving the sink property. Filesystem only. |
| | `test_no_third_party_in_sys_modules` | After the standalone load, newly-added `sys.modules` contains no forbidden distribution. |
| | `test_import_via_parent_package_also_works` | `import praisonaiagents.local` in a `subprocess -I`; asserts exit 0 and no `litellm`/`openai` in the printed module list. |
| | `test_manage_has_no_subprocess` | AST of `manage.py`: no `subprocess`/`os.system`/`os.popen`/`pty` import, no `os.exec*` call. |
| | `test_sloc_ceiling` | Counts non-blank, non-comment lines per file against §13. Filesystem only. |
| | `test_public_api_is_frozen` | `__all__` equals a literal list held in the test, so an addition is a deliberate edit. |
| `test_discover.py` | `test_ollama_identity_from_recorded_root` | `fake_transport` + recorded fixtures. |
| | `test_ollama_not_matched_by_port_alone` | Transport returns 200 `"hello"` on 11434 → `UNKNOWN`, not `OLLAMA`. |
| | `test_port_8080_collision_llama_cpp_vs_mlx` | `/props` yields `build_info` → `LLAMA_CPP`; `/props` 404 + `/health` 200 → `MLX_LM`. |
| | `test_port_8000_collision_vllm_vs_transformers` | `/version` present → `VLLM`; `/version` 404 + `/health` 200 → `TRANSFORMERS_SERVE`. |
| | `test_connection_refused_yields_no_candidate` | Default transport reply is `refused`; returns `()`, raises nothing. |
| | `test_timeout_yields_no_candidate` | `HttpReply(0, b"", "timeout")`. |
| | `test_bodyless_403_marks_blocked` | `HttpReply(403, b"", "http")`; asserts `blocked == "host_header_rejected"`. |
| | `test_malformed_json_does_not_raise` | `malformed.txt`. |
| | `test_probe_table_rows_are_wellformed` | Pure: unique engines, non-empty `identity`, methods in `{GET, POST}`, paths start with `/`, non-empty `note`. |
| | `test_discover_respects_budget` | Transport counts, never `time.sleep`s; asserts request count ≤ ports × rules. |
| | `test_models_uses_get_only` | Recorded call log has no `POST`. |
| `test_capabilities.py` | `test_parse_ollama_capabilities_covers_recorded_payload` | Recorded show → `{COMPLETION, CHAT, TOOLS, THINKING}`. |
| | `test_unknown_capability_string_is_ignored` | Pure `{"capabilities": ["teleportation"]}`. |
| | `test_default_caps_exhaustive_over_engines` | Pure. |
| | `test_default_caps_never_claim_tools_or_vision` | Pure. |
| | `test_llama_cpp_props_modalities` | Recorded fixture. |
| | `test_capabilities_degrades_to_table_on_failure` | Transport `refused` → `(default_caps(engine), Evidence.TABLE)`. |
| | `test_pure_parsers_take_no_transport` | `inspect.signature` has no `transport` parameter. |
| `test_quirktable.py` | `test_every_quirk_has_a_note` | Pure: `set(Quirk) == set(NOTES)`. |
| | `test_every_note_is_self_consistent` | Pure: key matches `note.quirk`; `engines` non-empty; strings non-empty. |
| | `test_ollama_openai_route_quirks` | Pure: contains `THINK_FIELD_IGNORED_ON_OPENAI_ROUTE` + `THINKING_WITH_TOOLS_YIELDS_EMPTY_TURN`, excludes `NATIVE_ROUTE_NEVER_SETS_TOOL_FINISH_REASON`. |
| | `test_ollama_native_route_quirks` | Pure: the inverse. |
| | `test_thinking_quirk_requires_both_caps` | Pure: absent when `TOOLS` not in `caps`. |
| | `test_unknown_engine_gets_caps_assumed_quirk` | Pure. |
| | `test_quirktable_reads_no_environment` | AST: no `os.environ`/`getenv`. |
| `test_target.py` | `test_precedence_spec_url_wins_over_every_env` | All env set via `monkeypatch`; transport keyed to the spec URL only. |
| | `test_precedence_env_base_url_beats_ollama_host` | `monkeypatch` + transport. |
| | `test_ollama_host_bare_host_defaults_11434` | Pure. |
| | `test_ollama_host_with_scheme_defaults_80` | Pure: `"http://127.0.0.1"` → `":80"`. |
| | `test_ollama_host_bare_port_forms` | Pure: `"11500"` and `":11500"`. |
| | `test_openai_base_url_ignored_when_not_local` | Asserts skip + appended message clause. |
| | `test_openai_base_url_used_when_loopback` | Transport-backed. |
| | `test_explicit_source_unreachable_raises_and_does_not_fall_through` | Transport refuses the pinned URL but would answer on 11434; asserts the raise **and** that 11434 was never requested. |
| | `test_nothing_found_message_is_exact` | Empty transport; asserts the full string equals the §8.2 literal. |
| | `test_blocked_only_raises_host_header_error` | 403-bodyless transport. |
| | `test_model_selection_prefers_tools_then_recency` | Recorded tags → `qwen3:0.6b`. |
| | `test_model_not_available_lists_alternatives` | `PRAISONAI_LOCAL_MODEL=llama3.2` + recorded tags. |
| | `test_litellm_model_for_every_engine` | Pure, parametrised over all members. |
| | `test_ollama_never_maps_to_ollama_chat` | Pure; guards the §4.4 decision. |
| | `test_target_is_frozen_and_hashable` | Pure: `hash(t)` works; assignment raises `FrozenInstanceError`. |
| | `test_as_dict_is_json_serialisable` | Pure: `json.dumps(t.as_dict())`. |
| `test_cache.py` | `test_hit_does_not_reprobe` | Counting transport; second call adds zero. |
| | `test_ttl_expiry_reprobes` | `monkeypatch target.time.time`; never sleeps. |
| | `test_refresh_bypasses_cache` | Counting transport. |
| | `test_env_change_changes_key` | `monkeypatch.setenv` between calls. |
| | `test_negative_result_is_cached_and_reraised_fresh` | Asserts two distinct exception objects, identical messages, one probe round. |
| | `test_pid_change_invalidates` | `monkeypatch target.os.getpid`. |
| | `test_concurrent_resolve_is_consistent` | 16 threads, in-memory transport; all results equal, no exception. |
| | `test_clear_cache_empties_both_dicts` | `cache_info()`. |
| `test_manage.py` | `test_remedies_exist_for_every_engine` | Pure. |
| | `test_remedy_argv_is_a_tuple_of_str` | Pure. |
| | `test_binary_path_uses_shutil_which_only` | `monkeypatch shutil.which`; asserts no other probing, no execution. |
| | `test_installed_engines_never_executes` | `monkeypatch subprocess` attributes to raise; asserts untouched. |
| `test_embed.py` | `test_embedding_target_from_recorded_show` | Recorded fixture. |
| | `test_dimensions_from_model_info_embedding_length` | Pure: `qwen3.embedding_length` → `1024`. |
| | `test_context_length_lands_in_extra` | Pure: `40960`. |
| | `test_mlx_lm_has_no_embeddings_endpoint` | Pure: raises per §11.2. |
| | `test_embed_never_posts_an_inference_request` | Call log has no request to any `/embeddings` path. |
| `test_async_parity.py` | `test_public_api_parity` | Reflection over `__all__`: every sync public callable has an `a`-twin with an identical signature. |
| | `test_aresolve_matches_resolve` | `asyncio.run` + the same fake transport. |
| | `test_aresolve_shares_the_cache` | Counting transport across one sync and one async call. |

---

## 13. LOC budget

A prior extraction in this repo grew **55%** past its pre-split size in five months
(`agent.py` split 8,915 → 5,030 on 2026-04-01; the two halves total 13,852 today). Budgets
are therefore enforced by `test_sloc_ceiling` (non-blank, non-comment lines), not suggested.

| Module | Estimate | Ceiling |
|---|---|---|
| `__init__.py` | 60 | 90 |
| `capabilities.py` | 150 | 200 |
| `quirktable.py` | 200 (mostly data) | 260 |
| `discover.py` | 220 | 300 |
| `target.py` | 180 | 240 |
| `manage.py` | 120 | 160 |
| `embed.py` (local embedder selection) | 100 | 140 |
| **package total** | **1120** | **1300** |

**Raised 2026-09-05 (1150 -> 1300)** to admit `embed.py`. It closes a data leak: a local
agent embedded against OpenAI, sending the user's documents and queries off the machine.
The ceiling test failed on the addition, which is the mechanism working -- the budget was
raised deliberately here rather than absorbed silently.

Per-file ceilings sum to 1510, but the **package** ceiling of 1300 binds first — one module
may grow only if another shrinks. Raising a ceiling requires editing this document in the same
commit. Exceeding it is a failing test, not a review comment.

---

## 14. Worked examples

### (a) Only Ollama running — `Agent(llm="local")`

```python
from praisonaiagents import Agent
agent = Agent(instructions="Summarise this", llm="local")
# integration site calls: local.resolve("local")
```

Four loopback requests (~6 ms on this machine): `GET /` → `Ollama is running`;
`GET /api/version`; `GET /api/tags`; `POST /api/show {"model":"qwen3:0.6b"}`.

Model choice: two models present, so §8.3 rule 4 applies — `qwen3:0.6b` reports
`["completion","tools","thinking"]` while the 9B tamil model reports
`["tools","thinking","completion","vision"]`. Both have `tools`, so the tie-break is
`modified_at` recency, which also selects `qwen3:0.6b`.

```
/* Detailed source-code truncated for AI context efficiency. */
```

`NATIVE_ROUTE_NEVER_SETS_TOOL_FINISH_REASON` is **absent** — `api_style` is `OPENAI_CHAT` and
that quirk is native-route-only. `Cap.VISION` is **absent** — `qwen3:0.6b` reports no vision
(verified twice; vision belongs to the other installed model).
`Cap.STREAMING_WITH_TOOLS` is absent because `TOOL_CALLS_ARRIVE_WHOLE_NOT_INCREMENTAL` is present.

### (b) `Agent(llm="ollama/qwen3:0.6b")` with `OLLAMA_HOST=127.0.0.1`

Step 1 pins `engine=OLLAMA` and `model_id` (`Evidence.SPEC`); step 3 supplies the base URL —
`parse_ollama_host("127.0.0.1")` → `http://127.0.0.1:11434` (bare host ⇒ 11434). Three
requests: `GET /`, `GET /api/version`, `POST /api/show`. `/api/tags` is **not** fetched
because the model was named.

Result identical to (a) except:
```python
evidence=(('api_style', Evidence.TABLE), ('base_url', Evidence.ENV),
          ('caps', Evidence.SERVER), ('engine', Evidence.SPEC),
          ('engine_version', Evidence.SERVER), ('model_id', Evidence.SPEC),
          ('quirks', Evidence.TABLE)),
```

Had the user written `OLLAMA_HOST=http://127.0.0.1` (explicit scheme, no port ⇒ **port 80**),
step 3 is authoritative and nothing answers on 80:

```
EngineUnreachableError: Local runtime at http://127.0.0.1:80 did not answer (refused). It was named explicitly by OLLAMA_HOST='http://127.0.0.1', so no other port was probed. Note that OLLAMA_HOST with an explicit http:// scheme and no port means port 80, not 11434.
```

It does **not** quietly fall back to 11434.

### (c) Nothing running

Six ports across four numbers probed concurrently; all refused within ~2 ms.

```
NoLocalEngineError: No local model runtime found. Probed 127.0.0.1 ports 11434 (ollama), 8080 (llama_cpp, mlx_lm), 1234 (lm_studio), 8000 (vllm, transformers_serve) in 1.5s; nothing answered. Start one (e.g. `ollama serve`, then `ollama pull qwen3:0.6b`) or set PRAISONAI_LOCAL_BASE_URL to its address.
```

The negative is cached for 5 s, so a loop constructing 100 agents pays the probe cost once.
`local.resolve_or_none("local")` returns `None` instead. `local.remedies(kind=RemedyKind.INSTALL)`
supplies the `argv` a CLI can print — `local/` neither runs it nor formats it for a terminal.

---

## 15. Integration points

Named only. This document designs **no** changes to these sites; each is a separate work order
with its own review. Line numbers are against `main` @ `2591aa405`.

| # | Call site | What it reads from `LocalTarget` |
|---|---|---|
| 15.1 | `agent/agent.py:305-345` — `_PROVIDER_DEFAULT_MODELS` / `_resolve_default_model()` | `litellm_model`. Today hardcodes `("OLLAMA_HOST", "ollama/llama3.2")` — a model that need not be pulled. |
| 15.2 | `agent/agent.py:2049-2112` — `base_url`/`api_key` plumbing | `openai_base_url`, `api_key`, `litellm_model` |
| 15.3 | `agent/agent.py:373` — `_apply_default_llm` base_url path | `openai_base_url` |
| 15.4 | `llm/llm.py:621` — `_detect_provider()` | `engine` (replaces prefix guessing) |
| 15.5 | `llm/llm.py:701` — `_is_ollama_provider()` | `engine` |
| 15.6 | `llm/adapters/__init__.py` — `get_provider_adapter()`, `OllamaAdapter` | `quirks`, `caps` |
| 15.7 | `llm/adapters/__init__.py` — `OllamaAdapter.get_default_settings()` + `llm/llm.py:273` | `quirks` |
| 15.8 | `llm/streaming_protocol.py:285-372` — `OllamaStreamingAdapter` | `TOOL_CALLS_ARRIVE_WHOLE_NOT_INCREMENTAL`, `STREAM_ERROR_ENDS_WITHOUT_DONE` |
| 15.9 | `llm/model_capabilities.py:106/141/173/204` | `caps` — litellm's map has no entry for a local tag, so these fall to name heuristics today |
| 15.10 | `llm/openai_client.py:645-660` — `_supports_responses_api` | `engine`, `api_style` |
| 15.11 | `llm/model_providers.py:_BUILTINS["ollama"]` | `engine` |
| 15.12 | `llm/sanitize.py`, `agent/chat_mixin.py:690-720` | `TOOL_SCHEMA_KEYWORDS_STRIPPED`, `TOOL_PARAM_TYPE_MUST_BE_BARE_STRING`, `FORMAT_AND_TOOLS_MUTUALLY_DESTRUCTIVE` |
| 15.13 | `tools/call_executor.py:125,141,256,294,351,364` — the `is_ollama: bool` field | `engine` |
| 15.14 | `embedding/embed.py:13` — `embedding()` | `EmbeddingTarget.litellm_model`, `.endpoint`, `.dimensions` |
| 15.15 | `runtime/health_check.py`, `runtime/doctor_registry.py` | `LocalTarget.as_dict()`, `manage.remedies()` |
| 15.16 | `llm/failover.py`, `llm/model_router.py` | `caps` — to avoid routing a tool call to a model without `Cap.TOOLS` |

---

## 16. Non-goals

Each with the reason, so a later contributor does not "add the obvious missing feature".

1. **Not an HTTP client for inference.** litellm and `openai` own that transport; a second one doubles the streaming bug surface.
2. **No chat, completion or embedding inference calls.** Any request whose reply depends on model weights is out. Metadata only.
3. **No process management.** Never starts, stops, restarts or pulls. Returns `argv` for someone else. Starting a server is a privileged side effect with no correct default.
4. **No request mutation, no schema rewriting.** Stripping a `oneOf` for Ollama is behaviour and belongs in `llm/adapters/`; `local/` only says the stripping will happen.
5. **No retries, no backoff, no circuit breaking.** `llm/retry_utils.py`, `llm/rate_limiter.py` and `llm/failover.py` exist; a second policy would silently compete.
6. **No disk cache, no config file.** Persistent state goes stale across `ollama pull`, needs locking, and is behaviour.
7. **No LAN or subnet scanning.** Loopback and explicitly-named hosts only. Sweeping a subnet is a security event, not a feature.
8. **No credential handling.** `api_key` is the fixed placeholder `"local"`; a server behind real auth is named explicitly by the caller.
9. **No model downloading, quantisation choice or VRAM estimation.** Hardware fit is a separate problem with a separate error surface.
10. **No new dependency and no 18th extra.** See §3.
11. **No cloud-provider detection.** `llm/model_providers.py` owns that; overlapping creates a second source of truth for provider ids.
12. **No top-level export.** Reached as `praisonaiagents.local`; nothing added to `_LAZY_IMPORTS`, so the sink cannot be dragged into the package import graph by an `__init__` edit.
13. **No `praisonaiagents.errors` inheritance.** Would import upward and break §2.1; wrapping is the integration layer's job.
14. **No Pydantic models.** Would add a hard-dependency edge and drag validation behaviour into a data package. Frozen dataclasses only.
15. **No support for engines lacking a verified discriminator.** `LLAMAFILE`, `LOCALAI`, `RAMALAMA` are reachable only via `PRAISONAI_LOCAL_ENGINE` until someone verifies an identity endpoint live. Guessing from port 8080 is the exact mistake this table is designed to avoid.

---

--- METRICS ---
- Files Extracted: 18
- Estimated Token Budget: ~75745 tokens
- Canonical Reference: https://codewiki.google/github.com/MervinPraison/PraisonAI
