Spec: Local AI Stack (Ollama + LangGraph + Checkpointers + Phoenix)¶
- ID: 010-local-ai-stack
- Status: shipped
- Owner: @copilot
- Created: 2026-05-02
- Roadmap Epic:
local-ai-plan.md(a raw planning note, deleted 2026-10-22 as superseded by this spec and docs/local-ai.md; see git history) - Constitution Compliance: confirmed against docs/constitution.md §1 (open-source, privacy-first, local), §2 (tech stack: Ollama + LangGraph), §3 (provenance), §11 (continuous evolution). Phase 7 of the source plan (Continue.dev / PearAI / Aider) is explicitly removed because AGENTS.md "Development Orchestration" forbids non-Copilot coding agents.
1. Problem & Motivation¶
local-ai-plan.md (since deleted; see git history) sketched a fully local, agent-orchestrated stack (Ollama → LangGraph → Postgres/Redis checkpointers → self-hosted API/Studio → Phoenix). Today the repo only ships the Ollama container in docker-compose.yml and lists langgraph + ollama in backend/pyproject.toml but no LangGraph workflow runs against a real Ollama model with durable state. Agents in backend/app/agents/crews/ carry TODOs (BL-20260430-03, BL-20260430-04) precisely because the local LLM substrate is incomplete.
This spec lands the smallest defensible local-AI substrate so the rest of the roadmap (LegalAnalyst, PrecedentHunter, IngestionScout HITL) can stop stubbing LLM calls.
2. Goals¶
- G1: A LangGraph workflow runs end-to-end against the local Ollama container with durable state (Postgres checkpointer) and survives a backend restart.
- G2: Default model set is fixed and machine-pullable for Apple Silicon laptops (32–64 GB unified memory):
llama3.1:8b-instruct-q4_K_M,mistral:7b-instruct-q4_K_M,nomic-embed-text. - G3: Every LLM call from a LangGraph node logs through
app.core.provenancewith model name, prompt template id, latency, and token counts — same contract CrewAI crews already use. - G4: A self-hosted Arize Phoenix instance receives OpenTelemetry traces from every LangGraph + CrewAI run; trace ids are returned in agent responses.
- G5: One repeatable command (
make local-ai-up) brings the entire stack online and pulls the default models on first boot.
3. Non-Goals¶
- NG1: Self-hosted LangGraph Cloud API + Studio container (Phase 5 of the source plan). Deferred to BACKLOG — adds a heavy image and is not required for any current spec.
- NG2: vLLM / multi-GPU / Linux server tier. Apple Silicon laptop is the default target; other tiers are documented but not configured.
- NG3: IDE integration with Continue.dev / PearAI / Aider (Phase 7 of source plan). Forbidden by AGENTS.md "Development Orchestration"; GitHub Copilot is the only sanctioned dev surface.
- NG4: Replacing existing CrewAI crews with LangGraph rewrites. CrewAI stays; LangGraph runs alongside for stateful, resumable workflows.
- NG5: Air-gapped deployment hardening, Prometheus/Grafana dashboards. BACKLOG.
4. User Stories¶
- As a Law AI backend developer, I want
from app.agents.graphs import legal_workflowto invoke a real LangGraph that calls Ollama and persists state to Postgres, so I can stop stubbing_call_llm()in crew tests. - As an ops engineer, I want
make local-ai-upto start Ollama + Postgres + Redis + Phoenix + backend in one command and warm-pull the default models, so onboarding fits in a single coffee. - As a legal analyst using
/api/analysis, I want every response to include aphoenix_trace_urlso I can audit the exact retrieval + LLM steps that produced an answer.
5. Functional Requirements¶
- FR-1: Add
langchain-ollama>=0.2.0,langgraph-checkpoint-postgres>=2.0.0,langgraph-checkpoint-redis>=0.0.5,arize-phoenix-otel>=0.6.0,opentelemetry-instrumentation-fastapi>=0.48b0to backend/pyproject.toml under a new[project.optional-dependencies].local-aiextra plus the basedependenciesfor the runtime pieces (langchain-ollama,arize-phoenix-otel, OTEL instrumentation). - FR-2: Introduce
backend/app/agents/graphs/runtime.pyexposingbuild_checkpointer() -> BaseCheckpointSaverthat returnsPostgresSaverwhenLANGGRAPH_CHECKPOINTER=postgres(default),RedisSaverwhen=redis, andMemorySaverwhen=memory(test-only). - FR-3: Introduce
backend/app/agents/graphs/legal_workflow.py— a 3-node LangGraph (retrieve→analyze→cite_check) that usesChatOllama(base_url=settings.OLLAMA_BASE_URL, model=settings.OLLAMA_DEFAULT_MODEL)and the checkpointer from FR-2. Returns a PydanticLegalWorkflowOutputwithanswer,citations,trace_id,phoenix_trace_url,human_approval_required. - FR-4: Add
backend/app/core/telemetry.pythat registers an OpenTelemetry tracer provider exporting to Phoenix (PHOENIX_COLLECTOR_ENDPOINT, defaulthttp://phoenix:6006/v1/traces) at FastAPI lifespan startup; instrument FastAPI + httpx; instrument LangGraph runs via the LangChain OpenTelemetry callback. - FR-5: Extend
backend/app/core/provenance.py(or its successor) so every LangGraph node decorator@logged_node(name=...)records{node, model, prompt_id, prompt_version, input_hash, output_hash, latency_ms, token_in, token_out, trace_id}to the existing provenance store. - FR-6: Add a
phoenixservice to docker-compose.yml (arizephoenix/phoenix:latest, port 6006), wirePHOENIX_COLLECTOR_ENDPOINTinto thebackendservice env, and add a depends_on edge. - FR-7: Replace the inline
command:in theollamaservice with abackend/scripts/ollama-bootstrap.shthat pulls the FR-1 default model set (llama3.1:8b-instruct-q4_K_M,mistral:7b-instruct-q4_K_M,nomic-embed-text) idempotently and is safe to re-run; mount it into the container. - FR-8: Add
make local-ai-up,make local-ai-down,make local-ai-pulltargets to Makefile and aStart Local AI Stacktask to .vscode/tasks.json. - FR-9: Add
GET /api/agents/health/local-aireturning{ollama: {reachable, models}, checkpointer: {kind, reachable}, phoenix: {reachable, ui_url}}so the existing Agent Ops dashboard (spec 003) can surface stack health. - FR-10: Document the stack in
docs/local-ai.md(architecture diagram, env vars, model matrix for laptop / workstation / server tiers, troubleshooting).
6. Non-Functional Requirements¶
- NFR-PERF-1:
legal_workflow.invoke({...})returns within p95 < 30 s on an Apple Silicon laptop withllama3.1:8b-instruct-q4_K_Mand a single-document context (≤ 4 k tokens). Slow paths are surfaced as Phoenix spans. - NFR-RESILIENCE-1:
legal_workflowresumes from the last checkpoint on backend restart; an integration test kills the process mid-run and assertsstate.values == prior_valuesafter.get_state(config). - NFR-PRIVACY-1: No outbound HTTP calls to non-localhost destinations during workflow execution. Enforced by a test that monkey-patches
httpx.AsyncClientand asserts onlylocalhost/ollama/phoenixhosts are hit. - NFR-AUDIT-1: Every LangGraph node call appears in both
app.core.provenancestorage and Phoenix; trace ids match across stores. Verified by an integration test. - NFR-OSS-1: All new dependencies are MIT/Apache-2.0/AGPL-3.0 (Phoenix is Elastic 2.0 / Apache-2.0 — confirm and pin). No proprietary services.
- NFR-HITL-1:
LegalWorkflowOutput.human_approval_requiredisTruewhenever thecite_checknode flags any citation asunverified(source: "ollama-hallucination-check"). - NFR-TEST-COV-1: New modules under
backend/app/agents/graphs/andbackend/app/core/telemetry.pyreach ≥ 80% line coverage inpytest --cov=app.
7. Data Model Impact¶
No new Neo4j nodes. Adds Postgres tables owned by langgraph-checkpoint-postgres:
checkpoints,checkpoint_writes,checkpoint_blobs— created idempotently byPostgresSaver.setup()on lifespan startup.
Migration is handled by the library; we expose it via app.db.checkpointer.ensure_schema() called from app.main lifespan. Documented in docs/data-model.md §"LangGraph Checkpointer Tables" (new subsection — author it as part of FR-10).
8. API Surface¶
GET /api/agents/health/local-ai(FR-9) — responseLocalAIHealthPydantic model:
class LocalAIHealth(BaseModel):
ollama: OllamaHealth # reachable: bool, models: list[str]
checkpointer: CheckpointerHealth # kind: Literal["postgres","redis","memory"], reachable: bool
phoenix: PhoenixHealth # reachable: bool, ui_url: str
POST /api/analysisandPOST /api/agents/runresponses gain optionalphoenix_trace_url: str | Noneandlanggraph_thread_id: str | Nonefields (additive, backwards-compatible). Existing Pydantic models inbackend/app/models/are extended, not replaced.
9. Agent / Crew Impact¶
- New:
LegalWorkflow(LangGraph) underbackend/app/agents/graphs/legal_workflow.py. Documented in docs/agent-roles.md under a new "Stateful Workflows" subsection (FR-10). - Modified:
LegalAnalystcrew (backend/app/agents/crews/legal_analyst.py) gains an opt-inuse_langgraph: bool = Falseflag that, when true, delegates toLegalWorkflow.invoke(...). Default behavior unchanged so other specs do not break. - No changes to
IngestionScout,PrecedentHunterin this spec — they continue to log viacore.provenanceand now automatically appear in Phoenix once FR-4 lands.
10. Acceptance Criteria¶
- AC-1: Given
make local-ai-upon a clean machine, when the script finishes, thencurl localhost:11434/api/tagslists all three default models,curl localhost:6006returns Phoenix's UI HTML, andcurl localhost:8000/api/agents/health/local-aireturns all three subsystemsreachable: true. - AC-2: Given the backend is running, when I
POST /api/analysiswith{"question": "What is the holding of Marbury v. Madison?", "use_langgraph": true}, then I receive a 200 with non-emptyanswer, ≥ 1citations, a non-nullphoenix_trace_url, and a non-nulllanggraph_thread_id. - AC-3: Given a workflow run completed at thread
T, when I restart the backend container and callLegalWorkflow.get_state(config={"configurable":{"thread_id":"T"}}), then state values equal the pre-restart snapshot. (NFR-RESILIENCE-1) - AC-4: Given a workflow run, when I open
phoenix_trace_url, then I see one root span per node (retrieve,analyze,cite_check) with model name, prompt id, and latency attributes; the trace id matches the row stored byapp.core.provenance. (NFR-AUDIT-1) - AC-5: Given the test suite runs with no network access (
pytest -m "not network"), whentests/agents/graphs/test_legal_workflow.pyexecutes against aMemorySaver-backed graph and a fakeChatOllama, then it passes and reports ≥ 80% coverage for the new modules. (NFR-TEST-COV-1) - AC-6: Given
cite_checkflags an unverified citation, when the workflow returns, thenhuman_approval_required is Trueand the response surfaces the offending citation withsource: "ollama-hallucination-check". (NFR-HITL-1) - AC-7: Given a run is in progress, when an outbound
httpxcall targets any host other thanlocalhost,ollama, orphoenix, then the test intests/core/test_local_ai_privacy.pyfails. (NFR-PRIVACY-1)
11. LegalBench Impact¶
- Tasks affected:
core_reasoning,precedent_retrieval(smoke set used by [Run LegalBench Eval] task). - Expected delta: ≥ 0 pp. This spec swaps the LLM substrate, not the reasoning logic, so we expect parity. Regression > 2 pp blocks the PR; cause is a model/quantization mismatch and the fix is to pin
OLLAMA_DEFAULT_MODELin.env.exampleto whatever the eval was run against.
12. Risks & Open Questions¶
- R-1: Phoenix container image footprint and license. Mitigation: pin a specific tag, confirm Apache-2.0 of the OSS components, document the upstream license terms in
docs/local-ai.md. If license ambiguity surfaces, fall back to Langfuse (also self-hostable) and re-record in BACKLOG. - R-2:
langgraph-checkpoint-postgresrequires Postgres ≥ 13 withpg_trgm; our compose usespostgres:16-alpineso we are fine, but theinit-db.shmustCREATE EXTENSION IF NOT EXISTS pg_trgm;. - R-3: First-boot model pulls (≈ 9 GB) make
make local-ai-upslow. Mitigation: pulls are backgrounded byollama-bootstrap.sh; readiness probe waits only formistral:7b-instruct-q4_K_M(smallest) before declaring success; rest stream in. - R-4:
ChatOllamatoken-count reporting is best-effort. Mitigation: when missing, logtoken_in=None, token_out=Nonerather than0so dashboards can distinguish "unknown" from "actually zero".
13. Out of Scope / Follow-ups¶
Tracked in tasks.md ## Follow-ups Discovered and mirrored to BACKLOG.md:
- Self-hosted LangGraph API + Studio container (Phase 5 of source plan).
- Linux + NVIDIA workstation tier (GPU runtime in compose, vLLM optional).
- Server / multi-GPU tier with Prometheus + Grafana.
- Backfill
LegalAnalystandPrecedentHunter(BL-20260430-03, BL-20260430-04) ontoLegalWorkflowonce it has parity. - Air-gapped deployment hardening + offline model bundle.