langchain-hs brings mathematical certainty and functional architecture to AI development. Build robust agents with pure AST pipelines, cyclic state machines, Model Context Protocol (MCP), and production OpenTelemetry.
Whether you are coming from Python LangChain looking for stability, or from the Haskell community building AI systems for the first time.
Tired of Python agents crashing at 3 AM due to a missing dictionary key, a silently mutated state variable, or a runtime type mismatch? Haskell solves the hardest problems in agentic engineering:
StateReducer s). State transitions cannot accidentally mutate or leak memory.
FromJSON. If an LLM hallucinates an invalid field, the type system safely catches it.
|>> (sequential), &>& (parallel fan-out), and >>># (fallback resilience) without writing boilerplate.
Langchain.Prelude provides intuitive functions like invoke, runReActAgent, and emptyStateGraph that feel as natural as Python.
If you know functional programming or backend architecture but haven't worked with LLM orchestration frameworks, here is the entire agentic paradigm in four simple concepts:
systemMessage, userMessage) to an LLM (Ollama, OpenAI, Gemini) and receive a typed assistant response.
Switch between local inference (Ollama), cloud APIs (OpenAI / OpenRouter), and Google Gemini. Every example includes realistic terminal output.
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Monad.Except (runExceptT)
import qualified Data.Text.IO as T
import Langchain.Prelude
import Langchain.Provider.Ollama
main :: IO ()
main = do
-- Connect to local Ollama instance (DeepSeek, Llama 3, Gemma, etc.)
model <- newOllama "llama3.2" defaultConfig
let msg = [userMessage "Explain why Haskell's type system makes AI agents more reliable in 2 sentences."]
res <- runExceptT $ invoke model msg Nothing
case res of
Left err -> T.putStrLn $ errorMessage err
Right m -> T.putStrLn $ extractMessageText mHaskell's static type system prevents common agent failures like missing dictionary keys or unexpected nulls before code ever reaches production. Furthermore, pure state transitions guarantee that autonomous agents cannot silently mutate variables behind your back.
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Monad.Except (runExceptT)
import qualified Data.Text.IO as T
import Langchain.Prelude
import Langchain.Provider.OpenAI
main :: IO ()
main = do
-- Connect to OpenAI or OpenRouter using environment API key
model <- newOpenAI "sk-proj-..." "gpt-4o"
let msg = [userMessage "Explain why Haskell's type system makes AI agents more reliable in 2 sentences."]
res <- runExceptT $ invoke model msg Nothing
case res of
Left err -> T.putStrLn $ errorMessage err
Right m -> T.putStrLn $ extractMessageText mBy modeling agent state and tool schemas with algebraic data types, Haskell eliminates runtime shape mismatches and unhandled edge cases. Strict effect separation also ensures that agent side effects are tracked, auditable, and easily isolated.
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Monad.Except (runExceptT)
import qualified Data.Text.IO as T
import Langchain.Prelude
import Langchain.Provider.Gemini
main :: IO ()
main = do
-- Connect to Google Gemini using Interactions v1 OpenAPI client
model <- newGemini "AIzaSy..." "gemini-3.6-flash" Nothing
let msg = [userMessage "Explain why Haskell's type system makes AI agents more reliable in 2 sentences."]
res <- runExceptT $ invoke model msg Nothing
case res of
Left err -> T.putStrLn $ errorMessage err
Right m -> T.putStrLn $ extractMessageText mStrong compile-time verification prevents runtime state corruption and missing attribute errors across asynchronous agent pipelines. Furthermore, Haskell's pure functions allow deterministic replay and testing of multi-agent interactions.
From guaranteed JSON extraction to autonomous ReAct tool loops, here is how you build real systems.
Parse LLM output directly into strongly typed Haskell records using FromJSON and ToSchema.
data Developer = Developer
{ name :: Text
, language :: Text
, years :: Int
} deriving (Show, Generic, FromJSON, ToSchema)
runExtraction :: IO ()
runExtraction = do
m <- newOllama "llama3.2" defaultConfig
let opts = withStructuredOutput (Proxy @Developer) defaultOllamaConfig
res <- runLangchainT () $ invoke m prompt (Just opts)
print res{ "name": "Alan", "language": "Haskell", "years": 8 }
Equip LLMs with effectful Haskell functions. The model emits structured tool calls that execute safely.
-- Create filesystem search tool
let fsTool = findFilesTool @IO defaultSecurityPolicy
toolCfg = withTools [fsTool] defaultOllamaConfig
-- LLM chooses and invokes tool
resp <- invoke model prompt (Just toolCfg)
case messageToolCalls resp of
Just (tCall:_) -> do
out <- toolExecute fsTool (toolCallArguments tCall)
print outTool: find_files {"pattern": "*.hs"}
Observation: ["src/Main.hs", "src/Agent.hs", "src/Tools.hs"]
Dynamic multi-turn reasoning and acting loop that evaluates tool observations until reaching final answers.
main :: IO ()
main = do
m <- newOllama "qwen2.5:7b" defaultConfig
let tools = [readFileTool Nothing defaultSecurityPolicy]
agent = defaultReActAgent m tools
res <- runExceptT $ runReActAgent agent [userMessage "Check server status in /tmp/status.txt"]
print res[Step 1] Thought: Read /tmp/status.txt
Action: read_file {"path": "/tmp/status.txt"}
Observation: Status: Operational, Uptime: 99.98%
[Step 2] Final Answer: Server is fully operational with 99.98% uptime.
LangGraph state machines with STM memory checkpointers, pure reducers, and Human-in-the-Loop review.
workflow :: StateGraph WorkflowState IO
workflow = emptyStateGraph workflowReducer
& addNode "planner" plannerNode
& addNode "reviewer" reviewerNode
& addEdge startNodeId "planner"
& addConditionalEdge "reviewer" router
[ ("approved", endNodeId)
, ("revise", "planner")
][planner] Generated Draft v1 -> [reviewer] Needs Work [planner] Generated Draft v2 -> [reviewer] Approved! Final State: iterations = 2, status = "APPROVED"
langchain-hs is fully documented and published on the official Haskell package repository.
Access full Haddock signatures, typeclass definitions, and release notes anytime.
Every component features dual Ollama/OpenAI examples, verified build targets, and complete Haskell signatures.
langchain-hs-core defines AST pipelines (RunnableTree), multi-modal ContentBlock, and streaming without ANY HTTP dependencies.
TVar & SQLite checkpointers, Human-in-the-Loop interrupts, time-travel history replay, and Graphviz DOT export.
Tool m instances.
withSpan), structured JSON logs, three-state Circuit Breaker, exponential backoff retries, and token cost calculation.