ollama-haskell

Hackage MIT License

Modern Haskell client library for the Ollama local LLM engine.

Features

  • Client-Centric Architecture: Thread-safe OllamaClient handle with connection pooling and resource management (newClient, defaultClient, clientFromEnv, withClient).
  • First-Class Streaming: conduit-based response streaming (chatStream, generateStream, pullStream, pushStream, createModelStream).
  • Model Context Protocol (MCP) Bridge: Bidirectional integration with mcp-server for converting between Ollama tools and MCP tools, running MCP servers via stdio or HTTP (Ollama.MCP).
  • Generic JSON Schema Derivation: Automatically derive JSON schemas from Haskell data types via GHC.Generics with ToSchema and formatFor.
  • Complete API Surface: Text generation, chat completions, vector embeddings, model management (list, show, copy, delete, pull, push, create), and system endpoints.
  • Structured Outputs DSL: Powerful SchemaBuilder DSL (|+, |++, |!, |!!) for type-safe JSON Schema structured responses.
  • Function / Tool Calling: Full support for tool definitions (Tool), tool calls (ToolCall), and execution results (toolResultMessage).
  • Thinking Models Support: Native support for reasoning models (qwen3.5, deepseek-r1) with Think / ThinkingLevel types.
  • Environment & Auth Integration: Robust URL normalization for OLLAMA_HOST and bearer token support for OLLAMA_API_KEY.
  • Configurable Resilience: Flexible retry policies (NoRetry, ConstantRetry, ExponentialRetry), custom timeouts, lifecycle callbacks, and structured logging.
  • Conversation Store: Transactional STM-backed InMemoryStore and ConversationStore typeclass for managing multi-turn chat sessions.
  • SDK Comparison Matrix: Detailed feature comparison against Python, JS/TS, and Go SDKs in COMPARISON.md.

Installation

Add ollama-haskell to your .cabal file:

build-depends:
    base >= 4.17 && < 5
  , ollama-haskell >= 0.4.1.0

Or using Stack in package.yaml:

dependencies:
  - ollama-haskell >= 0.4.1.0

Quick Start (5 Lines)

import Data.List.NonEmpty (NonEmpty ((:|)))
import Data.Text.IO qualified as TIO
import Ollama

main :: IO ()
main = do
  client <- defaultClient
  res <- chat client $ chatRequest "qwen3.5:2b" (userMessage "Why is the sky blue?" :| [])
  case res of
    Left err   -> print err
    Right resp -> mapM_ (TIO.putStrLn . messageContent) (crMessage resp)


Streaming Responses with Conduit

Stream LLM responses token-by-token in real time:

import Conduit (mapM_C, runConduit, (.|))
import Control.Monad.IO.Class (liftIO)
import Data.List.NonEmpty (NonEmpty ((:|)))
import Data.Text.IO qualified as TIO
import Ollama
import System.IO (hFlush, stdout)

main :: IO ()
main = do
  client <- defaultClient
  let req = chatRequest "qwen3.5:2b" (userMessage "Count from 1 to 5." :| [])

  -- Stream tokens to stdout as they arrive
  runConduit $
    chatStream client req .| mapM_C (\chunk -> liftIO $ do
      mapM_ (TIO.putStr . messageContent) (crMessage chunk)
      hFlush stdout
    )
  putStrLn ""

You can also accumulate all chunks at once with collectStream, or fold text with foldStream:

-- Collect all chunks:
chunks <- collectStream (chatStream client req)

-- Or fold into a single Text value:
fullText <- foldStream (\acc c -> acc <> maybe "" messageContent (crMessage c)) "" (chatStream client req)

Function & Tool Calling

Define function signatures and let the LLM execute structured tool calls:

import Data.List.NonEmpty (NonEmpty ((:|)))
import Ollama

calculatorTool :: Tool
calculatorTool = Tool "function" $ FunctionDef
  { fnName = "add"
  , fnDescription = Just "Add two numbers"
  , fnParameters = Just (FunctionParameters "object" Nothing (Just ["a", "b"]) Nothing Nothing Nothing)
  , fnStrict = Just True
  }

main :: IO ()
main = do
  client <- defaultClient
  let req = (chatRequest "qwen3.5:2b" (userMessage "What is 40 + 2?" :| []))
        { chatTools = Just [calculatorTool] }
  res <- chat client req
  case res of
    Left err   -> print err
    Right resp -> print (crMessage resp)

Structured Outputs (JSON Schema DSL)

Enforce structured JSON output formats using SchemaBuilder (re-exported directly from Ollama):

import Data.Text.IO qualified as TIO
import Ollama

personSchema :: Schema
personSchema = buildSchema $ emptyObject
  |+ ("name", JString)
  |+ ("age", JInteger)
  |! "name"

main :: IO ()
main = do
  client <- defaultClient
  let req = (generateRequest "qwen3.5:2b" "Generate a person profile.")
        { genFormat = Just (SchemaFormat personSchema) }
  res <- generate client req
  case res of
    Left err   -> print err
    Right resp -> TIO.putStrLn (grResponse resp)

Environment Variables & Configuration

Construct a client using environment variables (OLLAMA_HOST, OLLAMA_API_KEY):

main :: IO ()
main = do
  client <- clientFromEnv
  -- Automatically connects to OLLAMA_HOST with optional Authorization: Bearer header
  ...

Or configure custom retry policies and loggers:

customConfig :: OllamaClientConfig
customConfig = defaultConfig
  { configBaseUrl = "http://my-ollama-server:11434"
  , configTimeout = 120
  , configRetry   = ExponentialRetry 3 1000000 -- 3 retries with exponential backoff
  , configLogger  = Just (\level msg -> putStrLn $ "[" <> show level <> "] " <> show msg)
  }

main :: IO ()
main = withClient customConfig $ \client -> do
  ...

Feature Matrix

Feature Haskell (ollama-haskell) Official Python (ollama-python) Official JS/TS (ollama-js) Community Go (ollama/ollama)
Strict Type Safety ✅ Compile-time (PVP, Smart Constructors) ⚠️ Type hints (Runtime) ⚠️ TypeScript (Erased at runtime) ✅ Go Structs
Response Streaming conduit ($O(1)$ constant memory) ⚠️ Python Generator ⚠️ Async Iterator ⚠️ Go Channels
Structured Output Derivation GHC.Generics (ToSchema) ⚠️ Pydantic BaseModel ⚠️ Zod / JSON Schema ⚠️ Manual JSON Schema
Model Context Protocol (MCP) ✅ Native mcp-server Bridge ❌ Manual ❌ Manual ❌ Manual
Thinking / Reasoning Models ✅ Dedicated Think ADT ⚠️ Dict parameters ⚠️ Object properties ⚠️ Raw parameters
Transactional Chat Store ✅ STM InMemoryStore ❌ None ❌ None ❌ None
Built-in Mock Testing Ollama.Testing (Pure) ❌ None ❌ None ❌ None
Configurable Retry & Backoff ✅ Exponential & Constant ADT ❌ Manual ❌ Manual ❌ Manual
Token Throughput Metrics ✅ Native Calculation Helpers ⚠️ Raw nanoseconds ⚠️ Raw nanoseconds ⚠️ Raw nanoseconds
Environment Auto-Discovery clientFromEnv ✅ Default client ✅ Default client ✅ Default client

Documentation & References


License

MIT © 2024–2026 Tushar Adhatrao

Changes

Changelog

All notable changes to ollama-haskell will be documented in this file. The format is based on Keep a Changelog, and this project adheres to PVP (Haskell Package Versioning Policy).


[0.4.1.0] - 2026-08-25

Fixed

  • Conduit Streaming Socket Lifetime (Ollama.Client.Internal):
    • Fixed premature connection closure in requestStreaming by replacing transPipe runResourceT with exception-safe generator cleanup, ensuring streaming responses stream token-by-token across the full response without truncation.
  • Documentation & Tutorial Code Snippets:
    • Corrected STM conversation storage documentation in docs/tutorials/chat.markdown and docs/motivation.markdown to align with the actual Conversation API.
    • Replaced runConduitRes with runConduit in streaming examples.
    • Fixed missing toolName parameter in toolResultMessage in docs/tutorials/tool-calling.markdown.
    • Corrected field names (models / runningModels) in docs/tutorials/model-management.markdown.
    • Fixed lazy/strict text encoding in docs/tutorials/structured-outputs.markdown.
    • Corrected newMockClient serialized ByteString usage in docs/tutorials/testing.markdown.
    • Replaced collectStream with genuine real-time Conduit streaming in README.md.

Added

  • Model Capabilities Field (Ollama.Types.Model):
    • Added capabilities :: !(Maybe [Text]) to ModelInfo and updated FromJSON/ToJSON instances to support capability discovery from /api/tags (e.g. ["completion", "tools", "thinking"]).
  • Direct SchemaBuilder Re-export (Ollama):
    • Re-exported the full SchemaBuilder DSL (buildSchema, emptyObject, |+, |++, |!, |!!, JsonType(..), Property, Schema, objectOf, arrayOf, printSchema) directly from the top-level Ollama umbrella module.
  • End-to-End Live LLM Integration Test Suite:
    • 15 comprehensive live test cases in test-integration/Main.hs covering version, model inspection, non-streaming & streaming chat, structured JSON verification, tool calling round-trip, thinking models, embeddings, model lifecycle, and multi-turn STM memory persistence.
  • SDK Feature Matrix:
    • Multi-language SDK feature matrix embedded directly in README.md.

Changed

  • Dependency Cleanliness:
    • Removed unused resourcet package from library build-depends.
  • Documentation Redesign:
    • Completely restyled Hakyll documentation site with a minimal, restrained engineering aesthetic.

[0.4.0.0] - 2026-08-20

Added

  • Model Context Protocol (MCP) Integration (Ollama.MCP):
    • Full bidirectional integration with the Hackage mcp-server package (mcp-server >= 0.2 && < 0.3).
    • Seamless conversion between Ollama function calling definitions (Tool, ToolCall) and MCP definitions (ToolDefinition, ArgumentDefinition, Content, McpSchema).
    • Bridge functions: toolToMcpDefinition, mcpDefinitionToTool, toolCallToMcpArgs, mcpContentToToolOutput.
    • Re-exported MCP server runners (runMcpServerStdio, runMcpServerHttp, runMcpServerHttpWithConfig).
    • Dedicated unit test suite in Test.Ollama.Unit.MCP.
  • Automatic JSON Schema Derivation (Ollama.Types.Format.SchemaDerive):
    • Typeclasses ToSchema and ToJsonType enabling generic derivation of JSON schemas directly from Haskell record types via GHC.Generics.
    • Smart handling of optional fields (Maybe a omitted from required), nested records (JObject), lists (JArray), and simple sum enums (string enum).
    • Helper functions schemaFor and formatFor for effortless integration with chat / generate structured outputs.
    • Dedicated unit test suite in Test.Ollama.Unit.SchemaDerive.
  • Configurable Client Timeout:
    • Support for custom request timeout intervals in OllamaClientConfig (configTimeout).

Changed

  • PVP Compliance & Upper Bounds:
    • Added strict upper bounds for network-uri (>= 2.6 && < 2.8) and mcp-server (>= 0.2 && < 0.3).
    • Upgraded Stack resolvers and snapshot dependencies (lts-21.25, lts-22.44, lts-23.28, lts-24.52, nightly).

[0.3.0.0] - 2026-08-04

Added

  • OllamaClient Core: Thread-safe client handle with automatic connection manager lifecycle management (newClient, defaultClient, clientFromEnv, withClient).
  • First-Class Streaming Pipeline: conduit-based response streaming (chatStream, generateStream, pullStream, pushStream, createModelStream).
  • Stream Combinators: collectStream and foldStream in Ollama.Streaming.
  • Structured Output DSL: Type-safe SchemaBuilder DSL in Ollama.Types.Format.SchemaBuilder (|+, |++, |!, |!!) for constructing JSON Schemas.
  • Thinking / Reasoning Models Support: Think ADT (ThinkEnabled, ThinkDisabled, ThinkLevel) and ThinkingLevel (ThinkLow, ThinkMedium, ThinkHigh, ThinkMax) supporting models such as qwen3.5 and deepseek-r1.
  • Function / Tool Calling: Tool, FunctionDef, FunctionParameters, ToolCall, and toolResultMessage helper.
  • Environment Resolution: Automatic OLLAMA_HOST parsing and normalization in clientFromEnv supporting host:port, http://host:port, and bare host.
  • Authorization & Headers: Support for OLLAMA_API_KEY bearer tokens and custom configHeaders.
  • Configurable Resilience: RetryPolicy ADT (NoRetry, ConstantRetry, ExponentialRetry), lifecycle callbacks (configOnStart, configOnSuccess, configOnError), and structured logger configLogger.
  • Token Throughput Metrics: Metrics helpers chatEvalTokensPerSecond, chatPromptEvalTokensPerSecond, evalTokensPerSecond, promptEvalTokensPerSecond, tokensPerSecond.
  • Testing Infrastructure: Built-in mock testing module Ollama.Testing (newMockClient, withMockClient, mockGenerateResponse, mockChatResponse, mockEmbedResponse, mockListModelsResponse).
  • Conversation Store: Transactional STM-backed InMemoryStore and ConversationStore typeclass.
  • New API Endpoints: Ollama.API.Embed (/api/embed), Ollama.API.Blobs (/api/blobs), Ollama.API.Ps (/api/ps), Ollama.API.Version (/api/version).
  • Benchmark Suite: Criterion/tasty-bench suite in bench/Main.hs measuring serialization and throughput.

Changed

  • MonadIO / MonadUnliftIO Polymorphism: All API functions use MonadIO m => / MonadUnliftIO m => signatures instead of dual *M variants.
  • Typed Newtypes: ModelName, Digest, Base64Image, Duration, Version replace primitive string types.
  • Unified Error Type: OllamaError sum type with structured constructors and Exception instance.

Deprecated

  • embeddings endpoint (/api/embeddings) marked deprecated in favor of /api/embed.