Skip to main content

Brain

Status: Ready

Truth label: Current

Audience: System designer

Reader outcome: Start Brain, follow its chat pipeline, and know its providers, controls, memory systems, API groups, storage, and modules.

Last verified: 2026-09-13

Brain is AGENTASIAN's chat, retrieval, memory, and response-shaping service. The HTTP application is brain.api:app and listens on port 8081 in the standard launchers.

Start Brain​

python -m uvicorn brain.api:app --host 127.0.0.1 --port 8081

Use run-all.sh or run-all.bat for the normal local stack. Set AA_BIND_HOST=0.0.0.0 only after configuring the API token, allowed origins, project roots, and firewall.

Chat pipeline​

For POST /chat and POST /chat/stream, Brain:

  1. Resolves the requested provider and model.
  2. Resolves the independent reasoning lens and voice register. The older influence_profile field remains a compatibility adapter.
  3. Retrieves approved voice examples for the selected register.
  4. Searches relevant memory and CPMI records.
  5. Builds a trusted system prompt and a separate untrusted evidence section.
  6. Runs the LangGraph tool loop through the selected provider adapter.
  7. Applies conservative output linting.
  8. Optionally runs the local voice revision pass when requested and allowed.
  9. Records generation settings, retrieval provenance, usage, and trace lineage.

/chat/stream returns Server-Sent Events with context, tool, token, done, and error event types. The final done event carries the authoritative response and generation report.

Providers​

Brain chat supports:

ProviderAuthenticationModel discovery
OllamaLocal service at OLLAMA_BASE_URLLive /api/tags query
OpenAIOPENAI_API_KEYLive /v1/models query with a filtered fallback
AnthropicANTHROPIC_API_KEYLive /v1/models query with a filtered fallback
GoogleGOOGLE_API_KEYLive Google model list with a filtered fallback

GET /chat/providers returns only providers that are currently usable. Cortex builds its chat provider and model controls from this route. Every cloud provider is enumerated live per key, so a model released after this repo was last touched is selectable without a code change; the lists in brain/api.py apply only when a provider's list endpoint fails.

The route reports generation-control capability twice: generation_controls per provider, and generation_controls_by_model for each model it listed. They differ, and the per-model answer is the one to trust: the current Claude models reject temperature and top_p outright, and accepted reasoning-effort levels vary per model.

Embedding configuration is intentionally separate:

EMBEDDING_PROVIDER=ollama
EMBEDDING_MODEL=nomic-embed-text

Changing either value after indexing can make the stored Chroma collection incompatible. Brain records the embedding identity and rejects a mismatch.

Generation controls​

Requests may set:

  • temperature
  • top_p
  • frequency_penalty
  • generation_seed
  • stop_sequences

Validation runs after provider selection. Unsupported fields, invalid ranges, temperature plus top-p, blank stop values, and too many stops fail before the provider call. GET /chat/generation-controls reports provider capability metadata.

Reasoning and voice​

Reasoning and delivery are independent:

  • reasoning_lens selects trusted analytical guidance and eligible influence sources.
  • voice_register controls expression and cannot change the answer's facts.
  • influence_profile maps older paired profiles to their historical lens and register.

GET /chat/influences lists the registries and resolved defaults.

A register receives the exemplars its voice pack declares for it. The built-in pack declares none. Approved user examples live in the separate voice_examples collection. At most three are retrieved. Records marked local-only are never sent to a cloud provider.

Voice example routes:

GET /chat/voice-examples
POST /chat/voice-examples
PUT /chat/voice-examples/{example_id}
DELETE /chat/voice-examples/{example_id}

The deterministic output linter is enabled by default. The second local-model revision pass is disabled by default because acceptance testing found higher latency and inconsistent quality gains. See Voice Pipeline.

Memory systems​

Chroma collections​

Brain's semantic store is implemented in brain/memory/vector_store.py. Collections used by the current API include general knowledge, notes, conversations, learnings, rules, feedback, voice examples, and the CPMI semantic projection.

CPMI​

CPMI indexes repository memory files from Forge-registered projects:

  • the repository's agent instructions file
  • the repository's global rules file
  • the repository's voice guide or style guide
  • the changelog
  • the task ledger
  • the decisions record
  • the FAQ

Project-local files are authoritative in managed and direct sessions. Brain only indexes and retrieves them. cpmi.sqlite3 is the derived record and FTS5 store. Chroma's cpmi collection is a rebuildable semantic projection. Ranking combines lexical and semantic matches with scope, phase, freshness, and record type.

Repository controls are read directly and treated as instructions only for the target repository. Retrieved historical records are bounded and labeled as untrusted evidence.

Selected HTTP search routes apply project client scope. This is not yet one complete retrieval boundary: chat auto-search, LangGraph search tools, direct CPMI record reads, and direct knowledge-document reads query their stores without the same filter. Do not use Brain for confidential multi-client recall until those paths share one enforced gateway.

File ingestion​

POST /knowledge/ingest handles text, Markdown, PDF, and EPUB inputs through brain/memory/ingestion.py. Bulk ingestion is synchronous. Image-only PDFs and fixed-layout image-only EPUB files require a separate OCR step.

The request path is resolved on the Brain server. The route does not apply a dedicated ingestion-root allowlist, so it must remain operator-only.

API groups​

Health and chat​

MethodRoutePurpose
GET/healthService health
POST/chatComplete chat response
POST/chat/streamSSE chat response
GET/chat/providersUsable providers and live model choices
GET/chat/generation-controlsProvider generation capabilities
GET/chat/influencesReasoning and voice registries

Knowledge and CPMI​

MethodRoute groupPurpose
GET/knowledge/searchSearch a Chroma collection
POST/knowledge/addAdd one record
POST/knowledge/ingestIngest files or directories
GET/knowledge/collectionsCollection summary
GET/PUT/DELETE/knowledge/{collection}/documents/*Browse and edit records
POST/cpmi/indexRefresh registered repository memory
GET/cpmi/searchSearch CPMI
GET/cpmi/records/{record_id}Fetch one CPMI record
GET/cpmi/statsCPMI counts and status

Operations and learning​

MethodRoute groupPurpose
GET/POST/PUT/DELETE/rules*Global worker rules
POST/learningsStore a task outcome
GET/POST/feedback*Submit and inspect ratings
GET/POST/DELETE/conversations*Saved conversation files
GET/chat/turns/{turn_id}/traceSanitized chat trace
GET/chat/conversations/{conversation_id}/turnsConversation lineage
GET/config/api-keysOptional legacy-worker key distribution

/config/api-keys returns keys only when AA_ALLOW_KEY_DISTRIBUTION=true. CLI-agent engines use their own login and do not need this route.

Storage​

Brain reads DATA_DIR, which defaults to ~/.agent_asian.

PathContents
chroma/Semantic collections
conversations/Named saved conversations
cpmi.sqlite3Derived CPMI records and FTS5 index
traces.sqlite3Chat and task lineage index
traces/raw/Raw prompts and responses
chat_usage.jsonlChat usage ledger

Raw trace files can contain private prompts and responses. Keep the data root private and do not ingest traces/raw/ into knowledge.

Brain chat traces keep content hashes and manifests in the trace index. Forge task traces share the same trace database and currently include task result content in the indexed outcome; the Forge trace API is therefore content-bearing.

Main modules​

ModuleRole
brain/api.pyFastAPI routes and request validation
brain/chat.pyChat and streaming orchestration
brain/agent/graph.pyLangGraph agent and tools
brain/llm/router.pyProvider adapters
brain/llm/controls.pyGeneration validation and capability metadata
brain/memory/vector_store.pyChroma access
brain/memory/cpmi.pyRepository memory index
brain/influence_profiles.pyLens and register registries
brain/generation_report.pyPer-response settings report
brain/output_lint.pyProtected-span output normalization
brain/voice_revision.pyOptional local revision pass

See Configuration for every environment variable and Architecture for cross-service boundaries.