© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2025
A. Antich Magical Haskell https://doi.org/10.1007/979-8-8688-1282-8_12
12. Down the Rabbit Hole
Anton Antich 1
(1)
Schaffhausen, Schaffhausen, Switzerland
In this chapter, we will continue building up our AI agents framework using what we’ve learned and will learn some new advanced concepts along the way. What we want to achieve as an end result now starts to become more specific and real, so let’s recap:
-
We are creating an Agentic AI framework that allows access via terminal UI and via web.
-
We want to share as much code as possible between the two – so this will drive some redesign of what we created so far.
-
We need to add some sort of persistence layer – and we will use MongoDB for this purpose. SQL databases are very well covered including in Haskell context, but with the advent of LLMs, unstructured data becomes as important as or even more important than structured. MongoDB is the leader among no-SQL databases, so it makes sense to discuss its usage with Haskell.
-
We want to have advanced agent functionality , i.e.:
-
Ability to support multiple agents.
-
Agents should use multiple LLM and other steps, such as integrations with external existing systems.
-
We need to be able to have persistent editable “system prompts” for different LLMs, which influence their “tone of voice” and behavior in general.
-
-
We want to support so-called Vector RAG, or retrieval augmented generation.
We shall try to cover and implement as much of the functionality described above in the remaining chapters of this book, and in any case we will at least give specific pointers on how to implement this or that advanced functionality.
In this chapter, we will focus on adding the MongoDB persistence layer, on discussion of vectors and type families in the context of Vector RAG , and on restructuring the architecture of our framework to support both terminal and web API access properly, which will also drive a lot of mutable state–related discussions.
The code for this chapter is in the “ch12-1” folder of the book’s GitHub repository for the first part, and then we switch to the “ch12-2” starting with the “Redesigning Architecture: MRWST Monad Transformer” section.
MongoDB as a Persistence Layer
Before we are able to expand our web API functionality with global mutable state, we need to add the persistence layer – since a lot of AI agent improvements depend on it. Please install MongoDB locally using the instructions for your system. On Mac it is easily done with Homebrew and on Linux via package management of your system, and on Windows you’ll have to read the documentation on the https://www.mongodb.com/ website.
MongoDB is the leader among so-called “no-SQL ” databases. It stores JSON objects more or less directly and as such is very well suited to support web applications, since JSON is ubiquitous in the modern Web. We use it in production at integrail.ai, as well as many other SaaS companies, so learning to use it with Haskell is quite beneficial if you are planning to make production applications as well. The Haskell package that we will use to access Mongo is called mongoDB . As usual, feel free to look it up on Hackage and review the documentation as we go along. The library provides an interface of actions in the IO monad, which makes our lives easier as it gives us flexibility to use those actions from any monad transformer stack we decide to stick on top of the IO.
Before we start building up Mongo functionality, let’s make a couple of housekeeping changes that will make our program much more convenient to use: we will add the environment file check during startup sequence to make sure all the needed variables are present, and we will run both the web API and the terminal Jarvis UI in one main file – this will allow us to manage the web server directly from the terminal down the line.
First, don’t forget to copy the .env.template file to .env and add the missing variables there. These are the ones that must be filled in at this stage:
OPENAI_ORG=
OPENAI_TOKEN=
MAIN_MONGO_URI=
.
Make sure your Mongo connection string is in the MAIN_MONGO_URI in the .env file. Then, we extend the src/Init.hs file as follows:
-- main initialization function in IO to create initial State and Settings
initAll :: IO (Settings, AppState)
initAll = do
settings <- initConfig
let prov = findProviderByName settings "openai"
-- print prov
manager <- newManager tlsManagerSettings
lglev <- lookupEnv "LOG_LEVEL"
let (Just lglev') :: Maybe LogLevels = maybe (Just DEBUG) readMaybe lglev
lgState <- initLoggerFile lglev'
checkEnvironment lgState
let initSt = AppState manager "gpt-4o" prov lgState [] 6 (UIState True "")
pure (settings, initSt )
checkEnvironmentVar lgs var = do
e1 <- lookupEnv var
maybe (lg_err ("Environment variable missing: " ++ var) lgs)
(\x -> do lg_suc ("Loaded environment: " ++ var) lgs)
e1
checkEnvironment lgs = mapM_ (checkEnvironmentVar lgs) [
"OPENAI_ORG",
"OPENAI_TOKEN",
"OPENAI_URL_CHAT",
"OPENAI_URL_MODELS",
"OPENAI_URL_EMBEDDINGS",
"MAIN_MONGO_URI"
]
We added a simple function that checks for the presence of all the needed variables and logs it, respectively. Eventually, it would be good to add distinction between warnings – for variables that are missing but not critical – and critical errors, for variables that are needed to run properly, and so the program should exit in this case. This is a good exercise for you.
Finally, let’s make some small changes to the main code to run both the web server and the terminal UI in one program:
-- app/Main.hs
...
main :: IO ()
main = do
(sett, initSt) <- initAll
wid <- forkOS $ mainServer 8080 sett initSt
evalRWST (lgInf "starting up Jarvis") sett initSt
showHeader
putStrLn "" >> putStrLn (as [white,bold] "[User]")
(_, _, w) <- runRWST (runInputT (defaultSettings {historyFile = Just ".jarvis_history"}) loop) sett initSt
...
We have added one simple line: wid <- forkOS $ mainServer 8080 sett initSt that starts our web server in a separate thread using the Control.Concurrent package. We adjusted the mainServer function slightly to avoid double initialization as well – it’s easy to see what it is. There is no need to do any cleanup, as when you exit the main thread (which is the terminal UI in our case), all child threads will be terminated as well. Let’s try it: stack build, stack exec jarvis . Also don’t forget to run tail -f .jarvis_logs in another terminal window to monitor the logs and navigate to localhost:8080 in the browser to check that both the web server and the terminal UI are working. You should see something similar to Figure 12-1 .
A terminal window displays the execution of a command to start the Jarvis AI System, version 1.0.0. Instructions for using the system are shown, including typing ":help" for assistance and using ":send" to send messages. The log below shows timestamps and status messages, indicating successful loading of various environments like OPENAI_ORG and OPENAI_TOKEN, with one error for a missing environment variable, TEST_ERROR. The system then starts up, and a debug message notes a received request.
Figure 12-1
Running Jarvis in both the terminal and web server modes. The top picture is the terminal UI , and the bottom shows logs from both UIs in one place
As you can see, both modes are working fine, and our log file is capturing the logs from both threads as well! Herein lies another problem and an opportunity for an advanced exercise: if both the UI thread and the web app thread will try to write the logs simultaneously, this may lead to an error. Build a proper synchronization mechanism for logging to the file as an exercise.
MongoDB Initialization
Great start! Now let’s begin working on the MongoDB functionality . The core Mongo-related types and initialization functions are in the src/Mongo/Core.hs file. Review it at your convenience, it is quite straightforward, and here are some highlights:
data MongoConnection = MongoReplica ReplicaSet T.Text
| MongoPipe Pipe T.Text
...
initMongo :: LoggerState -> IO MongoState
initMongo lgs = do
-- we know its there because we checked environment
(Just muri1) <- lookupEnv "MAIN_MONGO_URI"
ms1 <- parseMongoStr muri1
bdb <- connectToMongo ms1 lgs
return $ MongoState {
mainConnection = bdb
}
-- run a mongo action act using our connection conn
withMongoConnection :: MongoConnection -> Action IO a -> IO a
withMongoConnection conn act = do
pipe <- getPipe conn
db <- getDatabase conn
MNG.access pipe master db act
The MongoConnection data type stores connections to different MongoDBs, depending on their configuration. initMongo initializes our Mongo-related state, currently consisting of only one connection to the main database, but we will be expanding it along the line. It reads the environment variable for the connection string (note: currently only the “mongodb://…” type of connection strings is supported, not “srv://…”), parses it into a proper connection object, and then actually connects to the database. Of course, there is no connection pooling or functionality for checking for broken connections now – feel free to add it yourself as you are building a production app.
The last function, withMongoConnection, is a convenient wrapper that allows us to execute various MongoDB commands to avoid boilerplate. If you add the initMongo call to the initAll now and if your MongoDB is setup correctly, you should see something like Figure 12-2 in the logs.
A terminal log showing a sequence of events on October 4, 2024. Several environment variables are successfully loaded, such as OPENAI_ORG and OPENAI_TOKEN, indicated in green. An error message in red states that the environment variable TEST_ERROR is missing. Subsequent messages in blue and green indicate successful connections to localhost and MongoDB, and the startup of a service named Jarvis.
Figure 12-2
Startup logs with successful MongoDB connection
Adding a System Prompts Collection
To try out our Mongo functionality , let’s add one collection that we will be using for sure – the one that will hold our system prompts library, so that we can switch them at will for our AI agents. Create src/Mongo/SystemPrompts.hs as follows:
{-# LANGUAGE DeriveGeneric, ScopedTypeVariables, OverloadedStrings #-}
module Mongo.SystemPrompts
(
SystemPromptData(..),
insertSPD,
findAllSPD
)
where
import Data.Text (Text )
import Data.Time (UTCTime, getCurrentTime)
import GHC.Generics (Generic)
import Data.Aeson (ToJSON (toJSON), FromJSON, Value (Object))
import qualified Util.AesonBson as AB
import Database.MongoDB (Collection, insert, Value, find, Select (select), Cursor)
import Mongo.Core (withMongoConnection, MongoConnection)
data SystemPromptData = SystemPromptData {
title::Text,
sysPrompt :: Text,
createdAt :: UTCTime
} deriving (Show, Generic)
instance ToJSON SystemPromptData
instance FromJSON SystemPromptData
spdColName :: Collection
spdColName = "systemPrompts"
makeSPD :: Text -> Text -> IO SystemPromptData
makeSPD t sp = getCurrentTime >>= \x -> pure (SystemPromptData t sp x)
insertSPD :: MongoConnection -> Text -> Text -> IO Database.MongoDB.Value
insertSPD conn t sp = do
spd <- makeSPD t sp
let (Object jsn) = toJSON spd
let bsn = AB.bsonifyBound jsn
withMongoConnection conn $ insert spdColName bsn
-- findAllSPD :: MongoConnection ->
findAllSPD :: MongoConnection -> IO Cursor
findAllSPD conn = withMongoConnection conn $ find (select [] spdColName)
This is a very basic skeleton we’ll try to use for every collection in the database. First, we define our “schema” data type – SystemPromptData, very basic, just the title and a system prompt itself. createdAt is optional since Mongo stores the creation time in the object’s ID, but there is an option to use Text for _ids so we keep it there just in case. We of course make it an instance of ToJSON/FromJSON, as we will have to convert our objects to JSON. Then there are a couple of helper functions and two interface functions: insertSPD and findAllSPD. As you can see, we are forced to explicitly pass the connection object to each interface function, and we would also want to pass a loggerState to be able to log stuff – so it just screams, “Wrap me in the Reader monad!”
Before we do, which will also lead us to redesign the overall stack and architecture in general a bit – we will need to separate Reader, Writer, and global mutable State (so no more State monad) properly to support both the terminal and the web functionality. Let’s give it a quick try and make sure that at least the insertion function works. Put the following lines to the main function:
res <- insertSPD (mainConnection $ mongoSettings sett) "Jarvis" "You are a the best in the world Haskell developer. You enjoy sharing your knowledge."
print res
Build and run Jarvis once. Then don’t forget to delete or comment these lines out; otherwise, you will keep inserting this prompt at every start! To check that the document was inserted, log into Mongo shell with your development database and run
AtlasLocalDev rs-localdev [direct: primary] studio> db.systemPrompts.find()
[
{
_id: ObjectId('66ffecb4a7f094b789000000'),
createdAt: '2024-10-04T13:25:08.308062Z',
sysPrompt: 'You are a the best in the world Haskell developer. You enjoy sharing your knowledge.',
title: 'Jarvis'
}
]
Super, everything works , but we don’t want to expand the MongoDB interface before we update our monad stack properly – this way, our code will be much more concise and elegant. Let’s get to it!
Redesigning Architecture: MRWST Monad Transformer
If you recall from the previous chapter, our current architecture looks like Figure 12-3 .
Diagram showing a transition from a terminal UI setup to a web server monad structure. On the left, three stacked layers labeled "InputT: terminal UI," "RWS: State, environment, logs," and "IO: API Calls." An arrow points to the right, where the top layer changes to "ScottyT: web server monad" containing three "ActionT" blocks, while the "RWS" and "IO" layers remain the same.
Figure 12-3
Current AI framework architecture
We need to redesign it to accommodate the persistence layer based on MongoDB, where the Reader monad functionality looks perfect for the task, split our old RWS monad, recombine the new Reader and Writer parts of RWS, and then design global mutable state for multi-threaded access. But maybe we will be able to make it similar to the RWS monad even to avoid inventing new interface functions? If this list seems intimidating, it’s only a feeling – all of it is much easier to do than it might sound.
Switch to the “ch12-2” folder of the book’s GitHub repository at this point – there are quite a bit of changes to the code structure going forward.
We will take a hint from the Scotty package examples for global state and create a “fake” RWST monad transformer that will in fact be a ReaderT with global mutable state as Reader’s settings variable. Note that we will make it a generic monad transformer similar in interface to the RWST – so you are free to reuse it in Scotty-based projects that are fully independent of the AI framework we are building here. Let’s call it “mutable RWS,” so MRWS(T). Doing so will allow us to make minimal changes to the code we have already created – we will simply change our Mid monad to use MRWST under the hood instead of RWST, and everything should work automagically! The source file is src/Control/Monad/MRWS.hs, and let’s go through it step by step:
{-# LANGUAGE OverloadedStrings, GeneralizedNewtypeDeriving #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Control.Monad.MRWS
(MRWST,
runMRWST,
evalMRWST,
execMRWST,
ask ,
asks,
tell,
get,
gets,
modify,
R.lift,
R.liftIO)
where
import Control.Concurrent.STM
import Control.Monad.IO.Unlift (MonadUnliftIO(..))
import qualified Control.Monad.Reader as R
import Data.Kind (Type)
import Data.Functor ((<&>))
import Data.Bifunctor (Bifunctor(first))
import Conduit (MonadTrans)
import Control.Monad.Catch (MonadMask, MonadCatch, MonadThrow)
-- definition of the MRWST monad
newtype MRWST r w s (m :: Type -> Type) a =
MRWST { fakeRunMRWST :: R.ReaderT (r, TVar (s,w)) m a }
deriving (Applicative,
Functor,
Monad,
MonadThrow,
MonadTrans,
MonadCatch,
MonadMask,
R.MonadIO,
R.MonadReader (r, TVar (s,w)),
MonadUnliftIO)
Skipping the import/export parts, we get to our monad transformer definition. Thankfully, we do not have to build it from scratch, but rather we are taking a shortcut and using ReaderT under the hood. The newtype definition we discussed in the last chapter serves two purposes here: (1) hides the internal implementation of our monad and (2) makes sure GHC optimizes the runtime code significantly. We are deriving a number of typeclasses that our monad needs to function properly with Scotty and Haskeline monads. Forgetting all the clutter, here is the main part: MRWST r w s m a = ReaderT (r, TVar (s,w)) m a . What is happening here?
We are defining a “mutable RWS transformer” with type for the Reader settings r , Writer Monoid w , and State s that runs on top of the monad m and returns a value of type a . We are doing that by giving an old-and-tried ReaderT a special type (r, TVar (s,w)) , which defines a pair of read-only r and a pair of ( s tate, w riter) , which is in turn put in the mutable TVar box discussed in the last chapter. ReaderT gives us an ability to access the read-only (r, TVar (s,w)) at any point inside our monadic actions, but since TVar contents can be mutated, we also get the ability to update State s and Writer Monoid w – and this allows us to build a virtually identical interface to the “regular” RWST monad! Here is the run<monad> function, analogous to runRWST that we used so far in our code:
runMRWST :: (R.MonadIO m, Monoid w) =>
MRWST r w s m a -> r -> s -> m (a, s, w)
runMRWST act settings state = do
sw <- R.liftIO $ newTVarIO (state, mempty)
fin <- R.runReaderT (fakeRunMRWST act) (settings, sw)
sw' <- R.liftIO $ readTVarIO sw
pure (fin, fst sw', snd sw')
The complimentary evalMRWST and execMRWST that return the value and final Monoid (a, w) and state and final Monoid (s, w), respectively, are defined analogously. The runMRWST function gets an MRWST monadic action act , read-only Reader settings , and initial state , and then we do the following steps:
-
Initialize a new TVar with an initial state and empty element of our Monoid.
-
Unpack our monadic action with fakeRunMRWST to get to the ReaderT contents, and then run the ReaderT monadic action as usual, by using runReaderT act’ (settings, sw), where (settings, sw) is exactly the type of (r, TVar (s, w))! Then we bind the resulting value to the fin variable.
-
Finally, we read the final values of our TVar “box” – which will contain our final State and final Writer Monoid.
-
In the end, we return the (a, s, w) triple in the underlying m monad – just like the “normal” runRWST does .
Think about it and let it sink in. We are completely hiding the mutable machinery inside our monad and making the interface correspond 1:1 with pure, immutable RWST! So, for the end user of our monad, there will be no difference whether they use RWST or MRWST, but the latter will work in multi-threaded environments like a charm automatically.
Now that we have the “run to the underlying monad” functions, we can define (at least parts of) the usual Reader–Writer–State interfaces, with the help of an internal state-modifying function:
_modify :: R.MonadIO m => ((s,w) -> (s,w)) -> MRWST r w s m ()
_modify f = R.ask >>= R.liftIO . atomically . flip modifyTVar' f . snd
This function gets a function that modifies our mutable state – so only the pair of State and Writer Monoid – and modifies it by the following steps:
-
R.ask is a “free” Reader interface ask function that we get automatically for our monad. We use it to get access to the (r, TVar(s, w)) pair.
-
The result is being fed to snd (you have to read the functions using the point-free . operator right to left) to get to just TVar (s,w).
-
flip modifyTVar’ f modifies our TVar using the supplied pure function; flip is needed to make the order of arguments right.
-
atomically was discussed in the last chapter; it is needed to handle concurrency issues in the STM monad that gives us TVar.
-
liftIO is our usual lifting of the IO action (and all operations with TVar are in IO now) into our MRWST monad.
Beautiful, isn’t it? Now we can define the interface functions:
-- READER INTERFACE is semi-AUTOMATIC thanks to deriving MonadReader --
-- But we need to extract and manipulate with data a bit to make it
-- "really" like Reader:
ask :: Monad m => MRWST r w s m r
ask = R.asks fst
asks :: Monad m => (r -> a) -> MRWST r w s m a
asks sel = ask <&> sel
-- WRITER INTERFACE --
tell :: (R.MonadIO m, Semigroup w) => w -> MRWST r w s m ()
tell wrt = _modify (\(s,w) -> (s, w <> wrt))
-- STATE INTERFACE --
get :: R.MonadIO m => MRWST r w s m s
get = (R.ask >>= R.liftIO . readTVarIO . snd) <&> fst
gets :: R.MonadIO m => (s -> a) -> MRWST r w s m a
gets sel = sel <$> get
modify :: R.MonadIO m => (s -> s) -> MRWST r w s m ()
modify func = _modify (first func)
The above should be easy to follow for you by now. I encourage you to go through these functions line by line and look up functions and operators that are new for you – if you carefully follow the types, as is our usual way in Haskell, you will understand everything and will start getting an ability to write very concise Haskell code under your belt. For instance, <&> and first may be of note (don’t confuse with fst ). Here we have only defined parts of the RWST interface that we’ve used so far in our program, but now the real magic happens. All we need to do is redefine our Mid monad to use MRWST instead of RWST :
type Mid = MRWST Settings Usage AppState IO
Of course, you also need to update the imports – instead of RWS, import Control.Monad.MRWS that we have just defined above – and then update the runRWST functions to runMRWST and same for eval/exec.
That’s it. It takes literally three to four changed lines, and all the work we have done in the previous chapters is not wasted, but rather upgraded to use our new cool mutable RWST monad. Figure 12-4 is an updated architecture schematic showing our new design.
Diagram illustrating a system architecture with several components. On the left, a blue box labeled "Read-Only r" and "TVar (s, w): State mutable, Writer mutable" points to the right with an arrow. On the right, a larger blue box labeled "MRWST monad: ReaderT over" is connected to a smaller box labeled "IO: API Calls." Above, a yellow box labeled "ScottyT: web server monad" contains three smaller boxes labeled "ActionT." Adjacent is a gray box labeled "InputT: terminal UI." The diagram represents the interaction between different monads and components in a software system.
Figure 12-4
Our final architecture
By substituting the “old” RWST monad for our new MRWST, we get an excellent benefit of reusing all the code we have created so far and the ability to use both Scotty and Haskeline in one program, running in different threads. MRWST in turn uses a simple ReaderT under the hood, but this ReaderT gives us access to a complex (r, TVar (s,w)) data type shown on the left of the picture. Here, r stays pure and read-only by design, while we get an opportunity to update State and the Writer Monoid thanks to them being put inside a TVar “box.” At the same time, all the interface for users of the MRWST monad remains “pure”; there is no mention of mutability, threads, or TVar boxes!
If this doesn’t give you goosebumps, I don’t know what will.
EXERCISE
Define the remaining standard interface functions from Reader, Writer, and State for our MRWST monad.
Now that we have updated our architectural skeleton, we can continue building up muscles.
Vectors and Type Families
Type families may seem confusing for Haskell beginners at first, but they further extend the power of typeclasses to give us unparallelled flexibility in designing data types and interfaces. Since we are going to need vectors from an amazing vector library next, and they are built both using type families and advanced mutability concepts under the hood, let us try to understand type families just as gently as we did with typeclasses in the very early chapters of the book.
Recall Chapter 3 , where we discussed four kinds of functions possible in Type Theory:
-
“Normal functions”: a -> b in Haskell. Take a value of type a as an argument and return a value of type b as a result.
-
“Type functions”: Type -> Type in Haskell. Take some concrete type as an argument and return another concrete type as a result. The main mechanism to construct new algebraic data types (ADTs) in Haskell.
-
Functions from types to values: Type -> a in Haskell syntax. Take some concrete type as an argument and return a value of some type a as a result.
-
Functions from values to types: a -> Type in Haskell syntax. This is what people normally understand by “dependent types” and what is again strictly speaking not fully available in Haskell, but there is very active research and some GHC extensions allow some types (such as String or Nat) to be used in limited dependent functions.
Type Synonym Families
Let’s consider the “type functions ” first. We have said that our regular data types defined similar to data Maybe a = Just a | Nothing are in fact type functions, and we can rewrite this definition as Maybe (a : Type) = Just x : a + Nothing , which follows closely Haskell’s own GADT notation:
data Maybe a where
Nothing :: Maybe a
Just :: a -> Maybe a
This tells us that Maybe is a function that takes any type “a” as a parameter and creates a new type Maybe a out of it with the help of two constructor functions – Nothing and Just. This is a primary way to create new data types in Haskell. Maybe here has a type Type -> Type – it takes a type and creates a new type.
However, what if we want to not create new types, but have also a kind of “type functions,” which return existing types? For example, what if I want to have a function like this:
AddTypes :: Type -> Type -> Type
AddTypes Int Double = Double
AddTypes Int Float = Float
AddTypes Int String = Bool
This is a contrived example obviously, but the point is what if I want to do some type-level manipulations with types to calculate some type value dependent on other types? Well, turns out we can with type synonym families :
-- src/Misc/TypeFam.hs
{-# LANGUAGE TypeFamilies, MultiParamTypeClasses #-}
module Misc.TypeFam
where
import Data.Kind (Type)
type family AddTypes a b :: Type
type instance AddTypes Int Double = Double
type instance AddTypes Int String = Bool
-- then we can write:
func :: String -> AddTypes Int String
func "hello" = True -- OK, it is Bool
As you can see, type instance basically defines the type-level function that we want in the example above. Once the instances are defined, we can use them in function signatures. This might be useful when you want to have different types of some data structure depending on which types are used to create it or something, but frankly for practical purposes, I recommend to always start with associated type and data families, which we will discuss further on.
Data Families
Okay, so type synonym families enable us to perform some basic type-level calculations and manipulations. Let us now consider a poster “type function” from the first part of the book, List: data List a = Cons a (List a) | Nil . This is a “type function” similar to Maybe above – it takes a type and creates another type from it, but not just that, it tells us how to construct values of this type through the constructor functions. However, this is a somewhat limited approach since we define the same internal structure for all types in the universe.
What if we want to have different internal representations of the List data structure depending on what we are storing in this list? For example, I can represent the list of bits as a structure above, but it will be extremely inefficient – I will be much better off representing a list of bits as a sequence of unboxed (see the previous chapter, section “‘M’ Subchapter: Under the Hood of GHC”) bytes, but I still want to treat it as a “normal” list, i.e., to be able to apply all my versatile List functions. Turns out, with data families it is possible:
data family SuperList a :: Type
data instance SuperList Char = SCons !Char !(SuperList Char) | SNil
newtype instance SuperList () = SListUnit Int
type Bit = Bool
data instance SuperList Bit = SBitList [Word8]
Okay, this is pretty cool. Now what if I want to define some familiar List functions for this family, such as length and map? It is possible, but gets tedious, as we need to define everything via typeclasses:
class SLength a where
slength :: SuperList a -> Int
class SMap a b where
smap :: (a -> b) -> SuperList a -> SuperList b
instance SMap Char Char where
smap _ SNil = SNil
smap f (SCons c cs) = SCons (f c) (smap f cs)
instance SLength Char where
slength SNil = 0
slength (SCons _ xs) = 1 + slength xs
-- Instance for SuperList () (unmappable, no meaningful transformation)
instance SMap () () where
smap _ (SListUnit n) = SListUnit n
instance SLength () where
slength (SListUnit n) = n
instance SMap Char () where
smap _ lst = SListUnit (slength lst)
As you can see, even though length is fairly straightforward, when we start writing map, we are forced to write it for every possible pair of the “a” types our SuperList is defined for or leave some cases undefined – which is not ideal for any good library. So even though data families provide some additional flexibility, there are trade-offs you have to think about.
Type synonym and data families also allow you to do some fairly advanced type manipulations with various DataKinds extensions of GHC, but this is a very advanced topic out of scope of this book.
Associated Type and Data Families
Let’s revisit Chapter 3 a bit more. There, we have sort of formally introduced so-called sigma types and typeclasses, single- and multiparameter. We noted that single-parameter typeclasses such as Monoid add internal structure to our types, while multiparameter typeclasses add structure to the whole category of our program by defining relations between different types (see Figure 12-5 as an illustration).
Diagram illustrating a type system with three blue circles labeled "A: Type," "B: Type," and "String." The circle "A: Type" has a self-referential arrow labeled "*: A → A → A" and is associated with "Magma." Arrows labeled "Show" connect "A: Type" and "B: Type" to "String." An arrow labeled "Multiparameter typeclass depending on A and B" points from "A: Type" to "B: Type."
Figure 12-5
Category of a simple program and relations between types defined by typeclasses
We have defined a bunch of typeclasses practically in the first part of the book, so you should feel very comfortable with this concept. Now let’s forget Haskell for a minute and just do some “mathematical” write-ups of what typeclasses are. We won’t be using actual “Sigma” signs that we used in Chapter 3 as the notation gets cluttered; instead let’s invent our own notation and write a couple of familiar typeclasses in it:
Show = Sigma (a : Type) {
show : a -> String
}
Monoid = Sigma (a: Type) {
(<>) : a -> a -> a,
mempty : a,
some laws which cannot be formally written in haskell
}
Functor = Sigma (f : Type -> Type) {
fmap : (a -> b) -> f a -> f b,
some laws...
}
Monad = Sigma (m : Type -> Type) {
(>>=) : (a -> m b) -> m a -> m b,
pure : a -> m a,
some laws ...
}
SomeMulticlass = Sigma (a: Type, b : Type) {
someFunction : a -> b
}
You get the idea. Every typeclass has a number of variables it depends on (only type variables in the case of Haskell; they are listed in parentheses after Sigma) and then a list of functions that define some sort of structure for our types or relationships between types in case of multiparameter typeclasses. But even in the very first chapter we saw that there are “normal” functions between values and then there are “type functions” – which create new types from other types, such as List a, Maybe a, etc. Well, why are we limiting ourselves? How about including not just “normal” functions but also “type functions” in the list of functions that define our typeclass? I want to write something like
MyClass = Sigma (a : Type) {
-- we can write elem : a, so why not Type?
SomeType : Type
SomeTypeFunction : Type -> Type
func1 : someType -> a
func2 : someType -> SomeTypeFunction a
}
This way, I am introducing in the Sigma “interface” not just “normal” functions that depend on a : Type, but also new types and type functions . This obviously gives us additional flexibility, as we can define not just an actual interface to work with our a : Type, but also some data types, which will have different internal representation depending on which a : Type is used ! But isn’t it just what we saw in the previous two sections, only put inside a typeclass?
Exactly – this is what’s called associated type and data families in Haskell. I would argue that if you want to use type and data families at all, you are almost always better off using the associated version. It tends to produce much clearer and more maintainable code, which is very modular, as opposed to the “normal” type synonym and data families we looked at in the previous two sections.
Where can they be useful? Apart from the ubiquitous examples of various collections, how about type-safe database representations?
-- src/Misc/TypeFam.hs
{-# LANGUAGE TypeFamilies, MultiParamTypeClasses #-}
{-# LANGUAGE DataKinds #-}
import GHC.TypeLits (Symbol)
...
class Database a where
type TableName a :: Symbol
type Record a :: Type
data User = User { userId :: Int, userName :: String }
instance Database User where
type TableName User = "users"
type Record User = User
The above is an example of an associated type family. You need to enable the DataKinds extension for it to work, and then suddenly as you can see we are able to assign a type synonym to a string – in effect making the typeclass dependent not just on types , but on values ! This is way beyond the standard Haskell and one of the cool GHC extensions that you may want to experiment with as you dig deeper.
For an interesting associated data family example, how about a uniform file system interface regardless of how and where it is located?
class FileSystem fs where
data FileHandle fs
data MyFilePath fs
openFile :: MyFilePath fs -> IO (FileHandle fs)
closeFile :: FileHandle fs -> IO ()
data LocalFS
data CloudFS
instance FileSystem LocalFS where
data FileHandle LocalFS = LocalFileHandle Int -- File descriptor
data MyFilePath LocalFS = LocalPath String
openFile (LocalPath path) = putStrLn ("Opening local file at " ++ path) >> return (LocalFileHandle 1)
closeFile (LocalFileHandle fd) = putStrLn ("Closing local file with descriptor " ++ show fd)
instance FileSystem CloudFS where
data FileHandle CloudFS = CloudFileHandle Int
data MyFilePath CloudFS = CloudPath String
openFile (CloudPath path) = putStrLn ("Opening cloud file at " ++ path) >> return (CloudFileHandle 1)
closeFile (CloudFileHandle fd) = putStrLn ("Closing cloud file with descriptor " ++ show fd)
The above code is of course very simplified, but a similar approach can be taken to a lot of real-world cases that require different underlying representations of data while being “the same” concept in general – so that we would want to use a uniform interface to access and manipulate it.
EXERCISE
Come up with at least two vexamples of real-world problems where associated type families and associated data families can be a good and elegant solution.
As by now I hope you can see there is nothing complex in the type and data families in Haskell. It’s just that nomenclature and semantics of their implementation are somewhat confusing – from a type-theoretical point of view, standalone type and data families would simply be a type of type-level functions, potentially dependent on values as well, while associated families simply a type of sigma data types, just as typeclasses. But once you experiment with them a bit, they will become just as natural as typeclasses have become by now.
Vectors As Arrays in Haskell
Now we know enough to start using the vector library. As usual, feel free to search for it on Hackage and review the documentation as you are reading the book. Vectors in haskell are an answer to the question “what about arrays.” Lists are fine and ubiquitous, but not very performant. In many cases, especially when we work with numerical data, we want to be much faster. Also, we want to have mutable arrays in some cases – e.g., for database-like tasks, where performance is key as well.
All of these issues are addressed by the vector library. In fact, Haskell vectors' performance is sometimes better than that of the low-level C code! 1
Understanding Vectors: Boxed vs. Unboxed
At the heart of the “vector” library lies the differentiation between boxed and unboxed vectors . This distinction is crucial for understanding how the vectors achieve their remarkable efficiency and for choosing the right type of vector for your application.
-
Boxed vectors : These are akin to Haskell's lists but optimized for performance. Each element in a boxed vector is a reference to a value, allowing for heterogenous data types and lazy evaluation. However, because of the indirection involved, boxed vectors aren't the most efficient way to store primitive data types like numbers .
-
Unboxed vectors : In contrast, unboxed vectors store elements contiguously in memory, without any indirection. This makes them both time and space efficient for storing primitive types, as they make better use of CPU cache and reduce garbage collection overhead. The trade-off, however, is that they only support types that have instances of the Unbox typeclass, essentially restricting you to a fixed set of primitive data types.
Internal Implementation and Generic Interface
The vector library's internal implementation is finely tuned to balance flexibility with performance. This is achieved by leveraging Haskell’s powerful type system and GHC extensions. At a high level, the library provides a generic interface that abstracts over the boxed/unboxed dichotomy. This means you can write polymorphic functions that work with any kind of vector, leaving the specificity to the type inference engine.
Here’s a snippet that showcases the generic interface:
import qualified Data.Vector as V
import qualified Data.Vector.Generic as GV
import qualified Data.Vector.Unboxed as UV
squareElements :: (Num a, GV.Vector v a) => v a -> v a
squareElements = GV.map (^2)
boxedVecExample :: V.Vector Int
boxedVecExample = squareElements (V.fromList [1, 2, 3, 4])
unboxedVecExample :: UV.Vector Int
unboxedVecExample = squareElements (UV.fromList [1, 2, 3, 4])
In this example, squareElements is a function that works with both boxed and unboxed vectors, showcasing the generic interface’s power and elegance. This is achieved by using the mechanism of type families we just reviewed – boxed and unboxed vectors are represented internally differently, but there is the same interface available.
Mutable Vectors and the ST Monad: For When Performance Is Key
A standout feature of the vector library is its support for mutable vectors, found in the Data.Vector.Mutable and Data.Vector.Unboxed.Mutable modules. Mutable vectors provide imperative-style, in-place updates, enabling a significant performance boost in scenarios where repeated transformations or aggregations are needed – think numerical simulations or real-time data processing.
Here’s a basic illustration of using mutable vectors:
import qualified Data.Vector.Mutable as MV
import Control.Monad.ST (runST)
incrementVector :: Num a => [a] -> [a]
incrementVector lst = runST $ do
-- Convert the list to a mutable vector
mVec <- MV.new (length lst)
-- Write the input list into the mutable vector
forM_ (zip [0..] lst) $ \(i, value) -> MV.write mVec i value
-- Increment each element in the mutable vector
forM_ [0..(length lst - 1)] $ \i -> do
val <- MV.read mVec i
MV.write mVec i (val + 1)
-- Freeze the mutable vector to make it immutable and then convert to a list
frozenVec <- V.freeze mVec
return (V.toList frozenVec)
The incrementVector function demonstrates a common pattern: create a mutable vector, perform in-place updates, and convert it back to an immutable state. While this imperative approach may initially feel unfamiliar in the Haskell context, it’s an invaluable tool in optimizing performance-sensitive applications. What is happening here is an ST monadic action (hence runST, more on it below) where we
-
Create a mutable vector of the length of the incoming list.
-
Copy the list to the mutable vector.
-
Increment the values of the mutable vector in place, so no new memory allocations are happening – a very much “side-effectful” operation.
-
Then we “freeze” the vector to make it immutable, convert it to a list, and return as a result.
Of course all of these operations are possible without converting back and forth from lists working just with vectors.
An attentive reader might wonder, how in the world do we do a typical side-effectful “IO” operation – mutating memory – but then escape back into the pure world? There is no “IO” or another monad on top of the resulting list. We get it back nice and absolutely pure! How is that possible?
This is the magic of the ST monad (do not confuse with STM, which is Software Transactional Memory from where we get TVar, or with the State monad, which is a “normal” pure monad that we have used previously a lot). If you look at the Hackage documentation, you will read that shown in Figure 12-6 .
The image contains a description of the strict ST monad in programming. It explains that the ST monad allows for destructive updates and is escapable, unlike IO. A computation of type ST s returns a value of type a and executes in "thread" s. The S parameter can be an uninstantiated type variable within invocations of runST, or RealWorld within invocations of stToIO. It helps keep internal states of different invocations of runST separate from each other and from invocations of stToIO. The operations >>= and >> are strict in the state, though not in values stored in the state.
Figure 12-6
ST monad
This is a very advanced topic as the ST monad uses so-called rank-2 typing under the hood, but here is a brief explanation. It should be enough for you in practice, and if you want to learn more about higher rank types in Haskell, you can investigate separately.
You do not need to understand the internal workings of the ST monad or what rank-N types are to use them efficiently in practice. The below is for the inquisitive minds among you.
The ST monad in Haskell is a powerful construct that allows you to perform mutable operations safely within a local scope. Let’s break down the type signature of runST and how the ST monad works, to understand its unique features and benefits.
The type signature of runST is runST :: (forall s. ST s a) -> a .
Here’s how to interpret this:
-
ST s a: This represents a computation that performs mutable operations and eventually returns a value of type a . The s parameter is a type variable that is used to ensure the computations in the ST monad remain isolated and safe. It acts as a “phantom type,” which prevents you from mixing mutable states across different runST invocations. Basically, it’s a typing mechanism that makes sure you never address the same memory space from two different runST calls.
-
forall s.: This part is crucial and defines a 2nd rank type (see a simpler example below). It indicates that the computation is polymorphic over the state thread s . This means you can’t leak internal mutable state outside the scope of runST, because each call to runST will get its own isolated state.
-
a: The result returned by the runST function after executing the ST computation.
Here’s a step-by-step explanation of what’s happening with runST and how the ST monad is used:
-
Isolation of mutable state: The ST monad allows you to interact with mutable values safely within a controlled environment. Unlike the IO monad, which allows side effects that can propagate globally, the ST monad confines effects to the local computation within runST and guarantees that side effects do not “leak” into the pure Haskell world.
-
Type safety and purity: By leveraging the forall s . quantification, the ST computation ensures that no mutable state can escape its local scope. This is enforced by the Haskell type system; you can’t return mutable references or states created inside ST computations because they depend on the universally quantified s .
-
Efficiency: Though the operations look pure from the outside, they can be executed efficiently using in-place updates internally, akin to typical imperative programming. This allows for high-performance computations when manipulating complex data structures .
-
Transformation to pure values: The computation in ST s a transforms to a pure value a upon completion. The mutable operations are abstracted away, presenting users only with a pure API.
Here’s another simple example showcasing runST and the use of mutable references:
import Control.Monad.ST
import Data.STRef
sumST :: Num a => [a] -> a
sumST xs = runST $ do
sumRef <- newSTRef 0 -- Create a new mutable reference
mapM_ (modifySTRef sumRef . (+)) xs
readSTRef sumRef -- Return the pure result
result :: Int
result = sumST [1, 2, 3, 4, 5] -- usage
-
newSTRef is used to create a new mutable reference inside the ST computation.
-
modifySTRef modifies the value of an STRef.
-
readSTRef retrieves the value from a mutable reference.
The above computation sums a list of numbers purely, but achieves internal efficiency with mutable operations by doing it “in place.” It’s a testament to Haskell’s ability to abstract mutable computations into a purely functional interface, harnessing the expressiveness and safety of the type system. The interface to manipulate the mutable ST boxes is very similar to what we have seen with TVars previously.
Rank-N Types
Again, this is a very advanced topic, and you do not need to understand them to be able to use the ST monad . Here is a very brief aside for the curious. Consider the following code:
-- A function that takes a polymorphic function and applies it to a pair of values.
applyToBoth :: (forall a. a -> b) -> (b, b)
applyToBoth f = (f 1, f 'a')
-- A function f from above must work for ALL types uniformly; it means
-- it cannot depend on the input, so can be a constant function for instance
exampleF :: forall a. a -> Int
exampleF _ = 42
res :: (Int, Int)
res = applyToBoth exampleF
The function f in the applyToBoth definition is a polymorphic rank-2 function with the (forall a. a -> b) . This means that f must be able to take any type a as input and return a value of a specific b . Because f must work for any type a , it cannot make use of the specific contents of an input. Instead, it must treat every input uniformly.
There is not much practical use in the forall a. a type of definitions, aside from advanced tricks used in the ST monad. However, rank-2 (and rank-N) polymorphism can be quite useful in scenarios where you need to provide a high level of abstraction, particularly when working with higher-order functions or when you need more control over type inference and instantiation. Here are some real-world scenarios where rank-2 or rank-N polymorphism can be especially beneficial:
Callback functions: When you’re writing higher-order functions that accept callback functions, you might use rank-2 polymorphism to ensure these callbacks can work generically over a range of types. This can be crucial in GUI frameworks or event-driven libraries where callbacks might need to handle different types of events:
registerCallback :: (forall a. Show a => a -> IO ()) -> IO ()
registerCallback callback = do
callback 42 -- An integer
callback "Hello" -- A string
-- The callback function operates on any 'Show'able type.
The callback function that can be passed to registerCallback must work on every type that is a part of the Show typeclass.
Visitor pattern: The visitor pattern is a design pattern used in object-oriented programming where you might have a collection of elements, each of which can be visited and processed generically. In Haskell, you might leverage rank-2 polymorphism to ensure that the visitor function can handle any element type:
data HTMLElement = forall a. Render a => HTMLElement a
renderPage :: [HTMLElement] -> IO ()
renderPage elements = mapM_ (\(HTMLElement elem) -> render elem) elements
class Render a where
render :: a -> IO ()
Generic programming: Libraries like lens make heavy use of rank-N polymorphism to provide generic operations that work seamlessly over various data types . This leverages the ability to abstract over transformations that can apply generically, manipulating data structures in a highly reusable manner:
over :: ((forall f. Functor f => (a -> f b) -> s -> f t))
-> (a -> b) -> s -> t
In each of these cases, the ability to express higher-level abstractions without committing to specific types enhances code flexibility and reusability. This often involves more complex type signatures but results in very powerful and abstract designs, making rank-N polymorphism a vital tool in an advanced Haskell developer’s toolkit.
The main challenge of rank-N polymorphism is that Haskell cannot deduce the type signatures for you, so as soon as you start using it, you have to write out all types properly and carefully. But since it’s a good practice anyway, this should not be such a big obstacle if you decide to put rank-N into your Haskell “spell book.”
Vectors in Practice
But back to vectors! In practice, choosing between boxed and unboxed vectors, or deciding whether to use mutable vectors , largely depends on your specific use case. Do you need to store complex data structures with differing types? Boxed vectors might be your best bet. Or perhaps your task requires blazingly fast numerical computations with large datasets – unboxed vectors could be the way to go. For workloads demanding maximum speed, mutable vectors can deliver the performance needed by leveraging in-place updates.
The vector library, with its rich API and robust performance characteristics, exemplifies the power of Haskell’s type system combined with GHC optimizations. By understanding these various aspects, you’ll be well equipped to tackle performance-centric tasks efficiently and elegantly.
EXERCISES
-
1.
Refactor the mutable vector example to use unboxed vectors, measuring any performance improvements.
-
2.
Design a simple matrix multiplication function using vectors and discuss boxed vs. unboxed implementations' trade-offs .
-
3.
Implement a small simulation that uses mutable vectors to track and update a swarm of particles in 2D space.
More AI: Vector RAG
By now we have addressed almost all of the design goals for our AI framework: we redesigned the monad transformer stack in a very smart way to reuse all the previous code, we added MongoDB functionality, and we made sure the terminal and web UI can be used simultaneously. Sure, there are lots of feature improvements we can still add, but we have the foundation for us to develop the product in any way we want – all these new additions are just a technicality in the existing framework. We will discuss and implement some of them in the next, and last, chapter. For now, let’s address the last goal – supporting so-called Vector RAG , or retrieval augmented generation.
As discussed in Chapter 9 , LLMs perform much better when given proper context for interaction with the user. The easiest way to do it, while providing excellent quality, 2 is Vector RAG, described below (see also Figure 12-7 ). To give a simple example, if you are not Elon Musk or another very public persona, try asking any public chatbot “who is <my name>.” You will get an “I don’t know” answer or some sort of hallucination, depending on the settings. If on the other hand you provide some info about yourself, your project, your interests, etc. to the RAG-enabled AI agent, it will be able to respond the way you expect.
Flowchart illustrating a language model process. It starts with "User Input" and "Context" leading to a large language model (LLM) with billions of parameters. The LLM connects to "Vector Memory for Retrieval – CONTEXT!!!" and undergoes "Additional fine-tuning," "Human Feedback fine-tuning," and uses "Better training data." The output is "2048-4096 tokens."
Figure 12-7
Vector RAG illustration
The way it works is via text-to-vector embeddings – a smart way to represent semantic information via multidimensional numeric vectors. Remember the queen = king – man + woman example from Chapter 9 ? Amazingly, the “sense” of words and whole concepts gets captured by this approach very well. So, to implement Vector RAG, we need to follow the following steps:
-
Populate some database with relevant pieces of text, converted to vectors via embeddings API (we will use OpenAI for simplicity).
-
When a user interacts with any of our AI agents, we convert their input into vector Vi as well and then perform vector similarity search.
-
Compare Vi with all the vectors we have in our database by taking dot product (if our vectors are normalized to 1, and they are, it is equal to cosine of the angle between them, and so the closer the number to 1, the more similar are the vectors).
-
Then pick one to five (or up to you) pieces of the most relevant text from our database and put them into the LLM’s system prompt as part of the context.
This way, you can ensure that your agents “know” the information relevant to you and not just the vast corpus of publicly available data they were trained on. We will demonstrate the difference once we go through the current exercise.
Vector search is much better than simple keyword search, which was ubiquitous in the Google era – since it searches “by meaning,” not by a number of keywords. There are now lots of different vector database vendors to support the increasing demand for Vector RAG; in fact, MongoDB provides this functionality as well. However, at the time of this writing, to get the vector search and indexing functionality in a local MongoDB, you have to deploy it as an Atlas cluster, which is a pretty advanced devops task. Plus, it is much more educational to build a simple vector search ourselves using Haskell – and then you can switch to using Mongo in production if you wish to do so. However, what we are going to build is more than enough for personal use.
In-Memory Vector Engine
What we are going to build is very simple and straightforward In-Memory Vector Search Engine. Thanks to the design of the vector library, it will be very performant, and we will use MongoDB as persistent storage for the data. So the flow will work as shown in Figure 12-8 .
A flowchart illustrating a data processing sequence. The steps are: 1) At startup, read MongoDB and initialize in-memory storage. 2) Input text to store in Vector RAG. 3) Convert to vector using API. 4) Store in MongoDB and update in-memory storage. 5) When searching, use only in-memory. Each step is represented in a blue arrow pointing right.
Figure 12-8
In-Memory Vector RAG
WARM-UP EXERCISE
Experiment with different ways to implement the dot product function. Which ones perform better? Why?
Mongo Storage Part
Let’s start with defining the data type that we will store both in Mongo and in memory for our vector embeddings :
-- src/Mongo/MongoRAG.hs
...
data RAGData = RAGData {
title::Maybe Text,
textContent :: Text,
vectorContent :: U.Vector Float
} deriving (Show, Generic)
instance ToJSON RAGData
instance FromJSON RAGData
ragColName :: Collection
ragColName = "vectorRAG"
Everything is self-explanatory here – we have a data type that stores an optional title, text contents, and an embeddings vector. We derive the To/FromJSON instances as usual to be able to convert easier and define a Mongo collection name. Then, we need some low-level (IO) methods to insert new RAGData into Mongo and to find all existing RAGData (at startup):
-- LOWLEVEL interface
insertRAG :: MongoConnection -> RAGData -> IO Database.MongoDB.Value
insertRAG conn rgd = do
let (Object jsn) = toJSON rgd
let bsn = AB.bsonifyBound jsn
withMongoConnection conn $ insert ragColName bsn
-- findAllSPD :: MongoConnection ->
findAllRAG :: MongoConnection -> IO [RAGData]
findAllRAG conn = withMongoConnection conn $ do
cur <- find (select [] ragColName)
bsn <- rest cur
let results = map (fromJSON . Object . AB.aesonify) bsn
let res = [rag | Success rag <- results] -- Extract successful conversions
pure res
The first method is a straightforward call to the Mongo interface to insert a RAGData object , converted first to JSON and then to BSON document. findAllRAG is a bit more complicated as we first get a Cursor and convert it to a list, then we have to map the backward conversion from BSON document through JSON to RAGData, but since each conversion is represented as Either data type, we have to do another filter run. This function can be optimized quite a bit – try that on your own.
Finally, we are using the type family trick we discussed previously in this chapter to create a uniform but typed interface to work with various Mongo collections:
-- src/Mongo/MidLayer.hs
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
module Mongo.MidLayer
where
import Data.Kind (Type )
import Database.MongoDB (Value)
import Mongo.MongoRAG (RAGData, ragColName, insertRAG, findAllRAG)
import Data.Text (Text)
import MidMonad (Mid)
import Mongo.Core (MongoState(..))
import Control.Monad.MRWS
import StackTypes (Settings(..))
class MongoCollection a where
type Record a :: Type
colName :: Text
insertOne :: Record a -> Mid Value
findAll :: Mid [Record a]
instance MongoCollection RAGData where
type Record RAGData = RAGData
colName = ragColName
insertOne rgo = do
conn <- mainConnection <$> asks mongoSettings
liftIO $ insertRAG conn rgo
findAll = asks mongoSettings >>= (liftIO . findAllRAG) . mainConnection
Here we define an associated type family MongoCollection with two actions in our MRWST Mid monad – insertOne and findAll. Then we define an instance of this family for our RAGData type. Basically, all we have to do is extract mainConnection that stores our connection to Mongo from the Reader’s settings and then run the low-level methods we defined above.
Finally, two methods in the src/Middleware.hs to use our newly built interface:
buildRAGM :: Mid (V.Vector RAGData)
buildRAGM = do
-- Explicitly specify the type application for `RAGData`
records <- findAll @RAGData
return $ V.fromList records
-- openai ---------------------------------
embedTextMid :: Text -> Mid ()
embedTextMid txt = do
st <- get
let prov = currentProvider st
let mdlName = embeddingName (head embeddingModels)
v <- lift $ embedText txt mdlName prov (loggerState st)
_id <- insertOne @RAGData $ RAGData obj
lgDbg $ "Successfully inserted " ++ show _id
The first one, buildRAGM, returns a boxed vector of RAGData objects that we will use as an in-memory store – so all we do here is call the method from MongoCollection type family and convert the result to Vector. Note how we are calling the findAll method : findAll @RAGData . What the heck is this? Unfortunately, if we write simply findAll and hope for Haskell to figure out what the type of the result should be from the context, we will get a compiler error. So we have to tell findAll which type to set for the “a” type variable from the MongoCollection class – and this is done via @<TypeName> syntax. For this to work, you need to also enable the {-# LANGUAGE TypeApplications #-} extension.
Note
Using the TypeApplications extension, you can explicitly write which types to instantiate for polymorphic functions using func @<TypeName> syntax.
Even though it may seem there is enough information in the context to deduce the RAGData substitution, there are cases when it is not so, and in any cases writing findAll @<MyDataType > is cleaner and easier to maintain – then you know for sure what you will get as a result. It also looks cool.
The second function decodes the result of the OpenAI API embeddings call (the code is added to the LLM/OpenAI.hs file – there are no new concepts there, so feel free to peruse it on your own) and writes both the text and the resulting vector to the database. We have also expanded Commands.hs to include one more command – “:embed”. You can now use it to embed any text to our vector storage. We will also expand embedTextMid later on to make sure it updates our in-memory storage, not just the database.
In-Memory Store Part
Now that we have prepared the MongodDB layer properly, let’s make further adjustments to have the in-memory store up and running. First, let’s adjust our global application state to include the in-memory store:
data AppState = AppState {
httpManager :: Manager,
currentModelId :: Text,
currentProvider :: ProviderData,
loggerState :: LoggerState,
messageHistory :: [Message],
historySize :: Int,
uiState :: UIState,
memoryStore :: MemoryStorage
}
Trivial (and we will look at the MemoryStorage type in a bit). Then, we very slightly adjust our initAll function to initialize the in-memory store from MongoDB – memst <- findAllRAG $ mainConnection mongoState – and add the resulting vector to the initial State variable (also trivial).
By now, everything is set up for us to be able to work with the in-memory store. First, let’s define a function that will add a new item to the in-memory store – and we will call it after the insertion to Mongo. Look at the src/VectorStorage/InMemory.hs:
{-# LANGUAGE OverloadedStrings, DuplicateRecordFields #-}
{-# LANGUAGE DeriveGeneric #-}
module VectorStorage.InMemory
where
import Data.Text
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector as V
import Mongo.MongoRAG (RAGData (vectorContent))
type MemoryStorage = V.Vector RAGData
-- Function to add a new RAGData item to the MemoryStorage
addRAGData :: MemoryStorage -> RAGData -> MemoryStorage
addRAGData = V.snoc
Luckily, the vector library provides a function to append an item to a vector, so we are simply defining a synonym. Of course this operation is not very efficient (O(n)), but since we will be inserting new items rarely, it doesn’t matter; however, it makes a good exercise.
EXERCISE
Write a more efficient function for insertion data storage for RAGData. Hint: Use vectors that pre-allocate certain sizes and grow them in increments.
With this easy definition, all we need to do is adjust the embedTextMid function defined above to also update the in-memory store after inserting the new RAGData object into Mongo: modify (\s -> s { memoryStore = addRAGData (memoryStore s) obj}) . That’s it. Insertion of new items with embeddings defined via OpenAI API call is completely ready!
You can test the functionality by running Jarvis as usual (stack build, stack exec jarvis), typing or copying a couple of paragraphs of text, and running the :embed command, and you should see something like Figure 12-9 .
A terminal window displays a command execution for "stack exec jarvis," indicating a connection on port 8080. The screen shows a welcome message for the Jarvis AI System, version 1.0.0, with instructions for help using ":help." It explains multiline and single-line modes, highlighting commands ":send" and "Enter" in yellow and green, respectively. A user input mentions "Magical Haskell," a book about Haskell, Type Theory, and AI, followed by a successful embedding message in green.
Figure 12-9
Embedding new text in our vector storage
To check that it’s there, go to Mongo shell and run db.vectorRAG.find() .
Now we can turn to the exciting part – implementing vector search in our in-memory storage. Here is an outline of what we need to do:
-
Convert what the user inputs to a vector by going to OpenAI embeddings API.
-
Map over all our in-memory storage with the dot product function to calculate similarity.
-
Sort the results in descending order.
-
Take the top n results for further usage as context when interacting with AI agents.
EXERCISE
Try to implement the functionality above by yourself.
Let’s review the remaining low-level API code in the src/VectorStorage/InMemory.hs:
sortedSearchResults :: Int -> U.Vector Float
-> MemoryStorage -> V.Vector (Text, Float)
sortedSearchResults n v ms =
let sorted = sortedSearch v ms
in V.map (\(score, ind) -> (textContent (ms V.! ind), score)) (V.take n sorted)
sortedSearch :: U.Vector Float -> MemoryStorage -> V.Vector (Float, Int)
sortedSearch v ms = let x = dotProductAll v ms
in sortVectorByFloat x
dotProduct :: (Num a, U.Unbox a) => U.Vector a
-> U.Vector a -> a
dotProduct v1 v2 = U.sum $ U.zipWith (*) v1 v2
dotProductAll :: U.Vector Float -> MemoryStorage
-> V.Vector (Float, Int)
dotProductAll v = V.imap (\i el -> (v `dotProduct` vectorContent el, i))
-- Function to sort a boxed vector of tuples (Float, Int) by the Float component
sortVectorByFloat :: V.Vector (Float, Int)
-> V.Vector (Float, Int)
sortVectorByFloat = V.modify (sortBy (comparing (Down . fst)))
-- Function to sort a boxed vector of tuples (Float, Int) by the Float component
sortVectorByFloatM :: V.Vector (Float, Int)
-> V.Vector (Float, Int)
sortVectorByFloatM vec = runST $ do
-- Create a mutable copy of the vector
mvec <- V.thaw vec
-- Sort the mutable vector in-place
sortBy (comparing (Down . fst)) mvec
-- Freeze the mutable vector back to an immutable one
V.unsafeFreeze mvec
We have a bunch of interesting algorithmic code in this file. Let’s review them in the logical order , bottom-up:
-
dotProduct v1 v2 = U.sum $ U.zipWith (*) v1 v2: This is one of about ten possible implementations of the dot product for numerical vectors, but is the fastest. We are relying on tests we did a couple of years ago comparing performance of many of them against each other and C code here: https://medium.com/superstringtheory/once-more-on-haskell-vs-c-performance-a54498bfa91f .
-
dotProductAll maps our dot product over the whole memory storage, and then there are a couple of sorting methods provided – one pure and one in the ST monad. Test them both to check the performance!
-
Once everything is sorted, all we need to do is take the top n results and convert the intermediary (Float, Int) vector that stores similarity scores and indexes of the specific MemoryStorage element into actual (score, text) pairs using the sortedSearchResults function.
With this API in place – this is another highlight of Haskell, just several concise lines of code that implement quite advanced functionality – we can now implement an actual search function that will take the text from the current buffer, convert it to a vector, perform the search, and show the top results. To do this, we implement a searchRAGM function in the Mid monad:
-- src/Middleware.hs
...
searchRAGM :: Int -> Text -> Mid (V.Vector (Text, Float))
searchRAGM n txt = do
st <- get
let prov = currentProvider st
let mdlName = embeddingName (head embeddingModels)
v <- lift $ embedText txt mdlName prov (loggerState st)
let ms = memoryStore st
let res = sortedSearchResults n v ms
pure res
This is straightforward access to various settings and state items and then running an embeddings API call and actual search/sorting from the low-level API. Then, we add a new command to the terminal UI:
-- src/Commands.hs:
...
commandSearchRAG :: [String] -> App()
commandSearchRAG (x:_) =
let n = read x :: Int
in _commandSearchRAG n
commandSearchRAG _ = _commandSearchRAG 5
_commandSearchRAG :: Int -> App()
_commandSearchRAG n = do
txt <- currentLineBuffer <$> lift (gets uiState)
if T.length txt > 0 then do
res <- lift (searchRAGM n txt)
uis <- lift (gets uiState)
lift $ modify (\s -> s { uiState = uis { currentLineBuffer = ""}})
controlMessage [lgreen] "[Search Results:]"
V.mapM_ (\(txt, score) -> controlMessage [white] ("[" ++ show score ++ "] " ++ T.unpack (T.take 80 txt))) res
else controlMessage [yellow] "[WARNING] Your message is empty, please type something first"
Again, just some housekeeping – getting a current text buffer, calling previously defined searchRAGM, and then showing the results along with the similarity scores.
Fire up Jarvis, add some RAG items via the :embed command, and then try searching for various queries to check the similarity (Figure 12-10 ).
A terminal interface displays a user querying "What is Haskell?" followed by a search command. The search results show two entries: the first with a relevance score of 0.5671976, describing "Magical Haskell" as a book about Haskell, Type Theory, and AI; the second with a score of 0.25925466, simply stating "hello world."
Figure 12-10
Testing Vector RAG search
Isn’t this cool? We built the Vector RAG from scratch in about 200 lines of code! The more relevant items you add (also optimal size should be several paragraphs of text), the more accurate the similarity score will become. Normally, with a relatively full database, you want to set the minimum score around .75 or even .8 for RAG – but it is better to always experiment with your own dataset to check the right parameters. In the screenshot above, there are only three very sparse items; hence, the scores don’t look so good – but try copying some PDFs or just websites into your RAG and see what happens!
Finishing RAG
With all the amazing goodies we have done in the previous sections, just searching is not enough – for RAG to be fully functioning, we need to send the context to our AI agent as part of the system prompt. This should be an easy exercise for you – just change the setup of [Messages] that are being already sent to OpenAI API with every :send call. Try to do it before reading further.
Here is one way to implement it, adding a convenience “context builder” function to Middleware.hs:
-- build context out of the RAG results with a minimum threshold
buildContextM :: Float -> V.Vector (Text, Float) -> Mid Text
buildContextM minScore res = do
let fres = V.filter (\(_, sc) -> sc >= minScore) res
let txt = V.foldl' (\acc v -> acc `TX.append` "\n\n" `TX.append` (fst v)) "Please use the following additional context when answering the user but only if it is relevant:\n\n" fres
pure txt
It takes the results of our vector search, filters them by the minimum similarity score, and then folds into a single text message.
Then in the actual :send command, we add a couple of lines to adjust our current [Messages]:
-- send the text that is currently in the text buffer
commandSendText :: [String] -> App()
commandSendText _ = do
txt <- currentLineBuffer <$> lift (gets uiState)
if T.length txt > 0 then do
-- getting RAG context and updating the Messages history:
ctx <- lift (searchRAGM 3 txt >>= buildContextM 0.6)
msgs <- lift (gets messageHistory)
lift $ modify (\s -> s {messageHistory = systemMessage ctx : msgs} )
(asMsg, _) <- lift (chatCompletionMid $ userMessage txt)
uis <- lift (gets uiState)
lift $ modify (\s -> s { uiState = uis { currentLineBuffer = ""}})
let fmt = highlightCode "Markdown" (T.pack asMsg)
outputStrLn (T.unpack fmt)
else controlMessage [yellow] "[WARNING] Your message is empty, please type something first"
We run the RAG search, build context out of it, and then modify the messageHistory via usual helper functions in our Mid monad, nothing new here.
Now let’s test it and compare results (Figure 12-11 ).
Comparison image showing two responses to the question "What is magical haskell book?" from a user. The first response, labeled "Without RAG: Hallucinations," describes the book as an educational resource for learning Haskell programming, though not officially recognized. The second response, labeled "With RAG," describes the book as exploring Haskell's programming language, type theory, and AI applications, highlighting its functional programming paradigms and type system.
Figure 12-11
Testing Jarvis with RAG about Magical Haskell
As you can see, without RAG, Jarvis hallucinates and invents some suggestions about what the Magical Haskell book might be. With RAG, where I entered some very basic info about this book, it responds nicely and to the point. Experiment with your own data!
EXERCISE
Add several new commands to the Jarvis terminal UI to handle various settings, e.g.: turn RAG on/off, change the minimum similarity score, change the number of found items to make a part of the context, etc.
Conclusion
This has been the longest chapter so far, but we learned and did so much – type families, advanced mutability, the ST monad, rank-N types, vectors – and we applied all that by building our own in-memory vector storage with dot product search support and implemented RAG-enabled AI agents on top of that. That is quite an achievement before the next, and last, chapter, where we will further enhance our AI framework; discuss the amazing “last abstraction,” Arrows; and talk about many, many possibilities that you can make into reality using AI agents and the framework we have built!
Footnotes
1
See, for instance, this link: <Emphasis FontCategory="NonProportional">https://medium.com/superstringtheory/once-more-on-haskell-vs-c-performance-a54498bfa91f</ Emphasis>
2
There are more advanced ways to increase the quality of LLM output even more that are being actively researched. One of them is so-called Graph-RAG, where we store knowledge about the world in a graph database and then retrieve the relevant pieces together with unstructured Vector context. But this is out of scope for this book.