Prismatic Ollama

Prismatic Ollama

185 files AI

Overview

Prismatic Ollama provides the platform's local AI inference capability through integration with Ollama. It enables sovereign, on-premise language model usage without sending data to external cloud providers. The module manages model lifecycle, request routing, response processing, and quality gate enforcement for AI-generated outputs.

Data sovereignty is a fundamental requirement for intelligence platforms handling sensitive OSINT, legal, and financial data. Prismatic Ollama ensures that no query or context data leaves the organization's infrastructure during AI-assisted analysis. Combined with the platform's NABLA epistemic framework, it provides AI capabilities where outputs are treated as signals requiring the same confidence scoring, provenance tracking, and multi-source validation as any other intelligence source.

Model Management

Coordinator Agent

The Ollama Coordinator Agent (AIAD-compliant) manages the full model lifecycle:

Model Discovery --> Health Check --> Load/Unload --> Request Routing --> Quality Gate
      |                |                |                 |                  |
   ollama list     Memory check     Memory-aware      Best model for     Pass/fail
   API call        + latency test   scheduling         task type          + fallback
Coordinator FunctionDescriptionAutomation
Auto-DiscoveryDetect available models on startupStartup hook
Health MonitoringPeriodic latency and accuracy testingEvery 60s
Memory ManagementLoad/unload models based on memory pressureThreshold-based
Version TrackingTrack model versions, trigger re-evaluation on updateOn model pull
FailoverAutomatic cloud fallback when local models unavailableCircuit breaker

Model Registry

# Check available models and their status
{:ok, models} = PrismaticOllama.list_models()

[
  %{name: "qwen3-coder", size: "7B", status: :loaded, memory_mb: 7200,
    capabilities: [:code_generation, :code_review, :refactoring]},
  %{name: "gpt-oss:20b", size: "20B", status: :available, memory_mb: 15800,
    capabilities: [:general_intelligence, :analysis, :summarization]},
  %{name: "deepseek-coder", size: "6.7B", status: :loaded, memory_mb: 6900,
    capabilities: [:code_analysis, :bug_detection, :documentation]}
]

Supported Models

ModelSizeResponse TimeMemoryPrimary UseAccuracy
qwen3-coder7B< 3s< 8GBCode generation, review> 85%
gpt-oss:20b20B< 5s< 16GBGeneral intelligence, analysis> 90%
deepseek-coder6.7B< 3s< 8GBCode analysis, bug detection> 85%

Cloud Fallback Architecture

When local models are unavailable or insufficient for a task, the coordinator transparently routes to cloud providers:

Request --> Local Model Available? --> YES --> Local Inference --> Quality Gate --> Result
                    |
                    NO (or quality gate fails)
                    |
            Cloud Fallback --> Cloud API --> Quality Gate --> Result
                    |
            Circuit Breaker monitors failure rate
Fallback TriggerConditionRecovery
Model UnavailableOllama not running or model not pulledAuto-pull attempt, then cloud
Memory PressureSystem memory > 90%Unload model, use cloud
Quality Gate FailureLocal output below quality thresholdRetry with cloud model
TimeoutResponse time exceeds 30sCancel local, route to cloud
Repeated Failures3+ consecutive failuresCircuit breaker opens for 60s

Cloud Provider Configuration

# Cloud fallback configuration
config :prismatic_ollama, :cloud_fallback,
  enabled: true,
  providers: [
    %{name: :anthropic, model: "claude-sonnet-4-20250514", priority: 1},
    %{name: :openai, model: "gpt-4o", priority: 2}
  ],
  circuit_breaker: %{
    failure_threshold: 3,
    reset_timeout_ms: 60_000
  }

Inference Pipeline

Request Processing

# Structured prompt with variable injection
{:ok, code} = PrismaticOllama.generate("Write an Elixir GenServer for rate limiting",
  model: "qwen3-coder",
  template: :code_generation,
  variables: %{language: "Elixir", pattern: "GenServer"},
  max_tokens: 2000,
  temperature: 0.3
)

# Code analysis with quality scoring
{:ok, analysis} = PrismaticOllama.analyze(source_code,
  model: "deepseek-coder",
  task: :quality_review,
  criteria: [:credo_compliance, :otp_patterns, :typespec_coverage]
)

# Structured entity extraction
{:ok, entities} = PrismaticOllama.extract(text,
  model: "gpt-oss:20b",
  schema: %{
    entities: [%{name: :string, type: :enum, confidence: :float}],
    relationships: [%{source: :string, target: :string, type: :string}]
  }
)

Pipeline Stages

StageFunctionImplementation
Template ResolutionApply prompt template with variablesETS-cached templates
Model SelectionChoose best model for task typeCapability matching + load balancing
Request DispatchSend to Ollama HTTP APIFinch HTTP client with streaming
Response ParsingExtract structured data from outputSchema-guided parsing with fallback
Quality GateValidate output meets quality standardsTask-specific validation rules
Result CachingCache results for identical promptsContent-hash based with TTL

Quality Gate Enforcement

AI-generated outputs are treated as untrusted signals requiring validation:

Quality CheckDescriptionFailure Action
Schema ComplianceOutput matches expected structureRetry with stricter prompt
Factual GroundingClaims reference verifiable dataFlag as ungrounded
Code CompilationGenerated code compiles without errorsRetry with error context
Credo ComplianceGenerated code passes Credo strictAuto-fix or retry
Confidence ScoringAI self-reported confidence meets thresholdRoute to larger model or cloud
NABLA IntegrationOutput treated as signal, not truthSignal Plurality requirement

NABLA Epistemic Integration

AI outputs are integrated into the belief graph as signals with explicit provenance:

# AI output registered as NABLA signal
signal = %{
  source: :ollama,
  model: "qwen3-coder",
  model_version: "2024.11",
  confidence: 0.82,  # Model-assessed confidence
  provenance: %{
    prompt_hash: "sha256:...",
    model_id: "qwen3-coder:latest",
    inference_time_ms: 2340,
    temperature: 0.3
  }
}

Performance Metrics

MetricTargetCurrentMeasurement
Response Time (7B)< 3s2.1s avgTelemetry p50
Response Time (20B)< 5s4.2s avgTelemetry p50
Memory Usage< 8GB per 7B model7.2GB:erlang.memory/0
Uptime> 99%99.7%Health check monitoring
Quality Gate Pass Rate> 85%88%Gate telemetry
Cloud Fallback Rate< 5%2.3%Routing telemetry

Architecture

Request --> Prompt Template --> Model Selector --> Ollama API --> Response Parser --> Quality Gate --> Result
              |                    |                  |               |                 |
         Variable           Capability +          HTTP/Stream     Structured       Pass/Fail
         Injection          Load Balance          via Finch       Extraction       + Fallback
ComponentImplementation
CoordinatorGenServer with ETS-backed model registry
HTTP ClientFinch with connection pooling and streaming
TemplatesETS-cached prompt templates with hot reload
Quality GatesConfigurable validation pipeline per task type
Circuit BreakerAuto-opens after 3 failures, resets after 60s
TelemetryFull event coverage for inference, quality, routing

Integration Points

Integrates WithPurpose
Prismatic MCPMCP tools use Ollama for local AI operations
Prismatic AgentsAgent AI capabilities backed by local inference
Prismatic NablaAI outputs as NABLA-managed signals
Prismatic ClaudeCloud fallback through Claude integration
Prismatic Quality IntelligenceAI-assisted quality analysis
  • NABLA Axioms -- AI outputs treated as signals with provenance tracking and confidence scoring
  • Multi-Paradigm Solving -- Multiple model capabilities (code, analysis, extraction) unified in single pipeline
  • Autonomous Self-Healing -- Automatic cloud fallback when local models are unavailable or fail quality gates

Connect & Contribute

Created by Tomáš Korcak (korczis) | Open Source under GHL