© 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_10

10. Terminal AI Chat Agent

Anton Antich 1    

(1)

Schaffhausen, Schaffhausen, Switzerland

In this chapter, we will finish our AI chat agent – let’s be unoriginal and call it “Jarvis” – to a full-featured terminal-based application . This will give us an opportunity to apply everything we’ve learned so far on the next level while creating something cool and exciting. Figure 10-1 shows a monad transformer stack we decided to use for our application.

Diagram titled "Application Monad" with three stacked components. The top component labeled "InputT: terminal UI" represents user interface input. The middle component labeled "RWS: State, environment, logs" indicates handling of state, environment, and logging. The bottom component labeled "IO: API Calls" signifies input/output operations through API calls. The components are enclosed in a purple rectangle.

Figure 10-1

Monad transformer stack for Jarvis

In the previous chapter we started designing the types and functions that allow us to work with the OpenAI API . They were all either pure or in the IO monad. We also defined a part of our monad stack using the RWST monad transformer – a cool abstraction, which combines Reader, Writer, and State monads into one. In this chapter, we will design and build all the missing pieces to make Jarvis functional.

The code for this chapter is in the “ch10” folder of the book’s GitHub repository.

Terminal UI Skeleton

Let us start with finishing the top-level program structure by adding the “top floor” of our transformer stack – InputT monad transformer from the Haskeline package. As always when we use external libraries, it’s a good idea to go to hackage.haskell.org, search for it, and read the docs as needed. Haskeline provides a nice and easy-to-use interface to working with terminal-based UI, with things such as history tracking and autocomplete out of the box. To start, we want to have a fully functional program that takes user input, goes to OpenAI API, and prints a response. We can create it very easily now, designing which functions and types should live on which floors of our monad stack, as we did in the previous chapters. To do this, we’ll need to restructure our files a little bit, further updating our architecture illustration (Figure 10-2 ).

Diagram titled "Application Monad" showing a layered structure. On the left, three stacked boxes labeled: "InputT: terminal UI," "RWS: State, environment, logs," and "IO: API Calls." To the right, text describes components: "src/App.hs – user interface" and "src/Middleware.hs – business logic," with types defined as "type App = InputT Mid" and "type Mid = RWST Settings [String] AppState IO." An arrow points to a cloud labeled "Pure Types and Functions," indicating integration with these components.

Figure 10-2

Current Jarvis architecture

As we shall soon see in detail, we again are applying the design approach from the previous chapters, where we clearly separate types and functions in separate “worlds”: pure for everything that we can make pure, IO “floor” for all kinds of functions that help us interact with the external world (such as OpenAI API), and RWS floor we now moved to the Middleware.hs file (used to be App.hs in the last chapter) – and it will contain all functions that deal with the business logic of the application and that require keeping state and reading our settings, but do not require direct interaction with the user. The UI actions will live on the top floor, inside the InputT monad in the src/App.hs file. Let us review the functions that are required to make a bare minimum of the interactive AI chatbot, in addition to the foundation we laid in the previous chapter.

Adding a Nicer Response Function

First, let’s change the function that processes the streaming OpenAI API response so that it gives us a nice textual message instead of all the JSON meta information as in the last chapter:

-- src/LLM/OpenAI.hs

...

processResp :: BS.ByteString -> IO ()

processResp ch = do

  mapM_

    ( \x -> do

        let jsonObject = decode (BL.pack x) :: Maybe OpenAIResponse

        case jsonObject of

          Nothing -> return ()

          Just resp -> do

            let chs = delta $ head $ choices resp

            case chs of

              Nothing -> return ()

              Just DeltaMessage {content = cnt} -> do

                putStr (T.unpack cnt)

    )

    (processString $ unpack ch)

This is the function that we will pass to the call to OpenAI API streaming response instead of the testChunkStreaming we used in the last chapter. What we do here is split the stream string with processString to get rid of the “data:” prefix to get to the list of JSON objects we are looking for. Various calls to pack and unpack have to do with conversions between different string formats – Text, ByteString, String, etc. This may get a little tedious to write, but with accurate reading of the type signatures, you’ll get a hang of it fast. Then, we mapM_ a “ lambda function ” defined right in the code over the resulting list of strings. mapM_ is simply a variant of mapping over a list, which allows us to map IO actions (instead of pure functions) while discarding the results – here we are only interested in side effects of putting characters on the screen. The mapped function itself converts JSON into our internal OpenAI response representation and then finds the needed textual response and outputs it directly to the terminal. Here we are cheating a bit by using an IO action (putStr) to put the characters on the screen – in the finished app we will have to make it a App() action so that we keep track of the conversation history in the state and use proper Haskeline functions for input/output, but now we just want to get to the result as fast as possible.

OPTIMIZE THE PROCESSRESP FUNCTION

The processResp function now has several case statements because we are dealing with Maybe values. Optimize its code to get rid of the case statements, for instance, by using the maybe function or fromMaybe operator.

Initialization

We need a bunch of initialization functions that read the environment and create the initial Settings object (that is used in the Read part of our RWS monad) and initial state AppState object (that is used in the State part of our RWS monad). To do that, we use IO (this is important). We cannot initialize those objects from inside the actual RWS monad – they are used as initial values in the call to our overall program – and we cannot do it “purely” either, since we need to read the environment. We defined the functions that initialize the settings in the src/Init.hs in the previous chapter. Now let’s extend it to also initialize the state :

-- src/StackTypes.hs

...

-- type that will hold the State for our App

data AppState = AppState {

    httpManager :: Manager,

    currentModelId :: Text,

    currentProvider :: ProviderData

}

-- src/Init.hs

...

-- 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

    let initSt = AppState manager "gpt-4o" prov

    pure (settings, initSt)

The initAll function currently calls initConfig to create our initial Settings object by reading the environment; then it builds the initial state by putting a default LLM provider (currently we have only one, OpenAI) and an HTTP manager object to help us make external API calls into the initial AppState. Then we “return” both as a pair.

Building the Monad Transformer Stack

The two top floor of our monad stack now can be constructed as well. The middleware, or Mid monad, doesn’t have any actions so far, but we need to at least create the monad itself. So the src/Middleware.hs file is very simple now:

{-# LANGUAGE OverloadedStrings, DuplicateRecordFields #-}

module Middleware

where

import Control.Monad.RWS

import StackTypes (Settings, AppState (AppState), findProviderByName)

-- monad that handles all application's business logic

type Mid = RWST Settings [String] AppState IO

We simply define Mid as an RWST monad transformer on top of IO that uses Settings for the Read monad, AppState for the State monad, and [String] – list of strings – for the Writer monad. The latter will be changed down the line, but we need to give some Monoid to the writer so starting with the simple one.

This definition alone, even though it’s just one line, allows us to use all the functions of Reader, Writer, and State monads.

Let’s move to the top, UI floor defined in the src/App.hs file:

{-# LANGUAGE OverloadedStrings, DuplicateRecordFields #-}

{-# LANGUAGE DeriveGeneric #-}

module App

where

import qualified System.Console.Haskeline as HL

import qualified Util.PrettyPrinting as TC

import Control.Monad.RWS

import Network.HTTP.Client (Manager)

import qualified Data.Text as T

import LLM.OpenAI

import Middleware (Mid)

import StackTypes

type App = HL.InputT Mid

loop :: App ()

loop = do

  st <- lift get

  let mgr = httpManager st

  let modelId = currentModelId st

  let pr = currentProvider st

  minput <- HL.getInputLine  (TC.as [TC.bold] "\nλInt. ")

  case minput of

    Nothing -> return ()

    Just ":quit" -> return ()

    -- Just (':':cmds) -> (processCommand (words cmds)) >> loop

    Just input -> do

      -- outputStrLn $ "Input was: " ++ input

      liftIO $ chatCompletion mgr [userMessage $ T.pack input] modelId pr Nothing processResp

      loop

For now, it contains one key function that is an action in the App monad – loop. This is a main loop of our application, which we will be gradually extending. For now, it does the following:

  • st <- lift get: We are getting the state from the underlying RWS monad . Note the use of “lift” – since we are currently on the “top floor” of our monad stack and the State functionality is provided by RWS, we need to lift the actions from that floor into ours!

  • In the next three lines, we bind various items that we will need to call the OpenAI API to specific variables.

  • minput <- …: Here we both output the prompt for our program and expect the input from the user.

  • The rest of the code deals with analyzing the user input. Now we only have two options:

    • :quit is a command to quit from Jarvis.

    • Any other input is treated as a message to the AI, which is done through another lifted call liftIO $ chatCompletion … – we looked at the chatCompletion function in detail in the last chapter, so feel free to review that discussion if you need to.

Main Program

We have all the pieces we need to make an actual program. All that is left is to construct our main function . It might seem tricky at first, as with all monad transformer stacks, but with time it will become your second nature:

{-# LANGUAGE OverloadedStrings #-}

module Main (main) where

import Init (initAll)

import StackTypes (findProviderByName)

import Network.HTTP.Client (Manager, newManager)

import Network.HTTP.Client.TLS (tlsManagerSettings)

import LLM.OpenAI (chatCompletion, userMessage, testChunkStreaming, processResp)

import System.Console.Haskeline

import App (loop)

import Control.Monad.RWS

main :: IO ()

main = do

    (sett, initSt) <- initAll

    runRWST (runInputT (defaultSettings {historyFile = Just ".jarvis_history"}) loop) sett initSt

    putStrLn "bye!"

Apart from all the imports, the main function is actually very, very simple. We initialize the initial Settings and AppState objects using initAll – an IO action we discussed above. Then we run our monad stack. Let’s unwind this line so that you understand how easy it is despite looking intimidating. To do that, we need the signatures for runRWST and runInputT:

runInputT :: (MonadIO m, MonadMask m) => Settings m -> InputT m a -> m a

runRWST :: RWST r w s m a -> r -> s -> m (a, s, w)

Now you can read the line from our main function as follows: runRWST <some action> sett initSt . Here sett is our Settings object, initSt our initial state, and the result will be m(a,s,w) or in our case IO ( (), AppState, [String]) – an IO action. As we are inside main, which is in the IO monad, everything is fine. Now let’s deal with <some action>. runRWST expects RWST r w s m a type for it – looks scary, but let’s make the substitutions and we will see it is merely RWST Settings [String] AppState IO () type, but if you recall our definition of Mid, it’s exactly Mid () ! So <some action> has to have this type. Now let’s see what it is runInputT (defaultSettings {historyFile = Just ".jarvis_history"}) loop . runInputT expects some Settings object, and here we are giving a defaultSettings object provided by Haskeline only with the history file name changed and then InputT m a action. If you recall, our App is defined as InputT Mid, and loop has the type App(), i.e., InputT Mid ()! That’s it. Everything typechecks. You just have to carefully go through the exercise of unwinding monad transformer stacks a couple of times, and then you will be able to do it in your sleep.

Now if you run the whole program with the changes above via stack build, stack exec jarvis, you should see something like

{11:25}~/dev/magicalhaskell/ch10:main ✗ ➭ stack exec jarvis

ProviderData {providerName = "openai", providerKey = "…", chatCompletionURL = "https://api.openai.com/v1/chat/completions", providerDefaultOptions = ChatOptions {stream = True, frequency_penalty = Nothing, logprobs = Nothing, top_logprobs = Nothing, max_tokens = Nothing, presence_penalty = Nothing, response_format = Nothing, seed = Nothing, stop = Nothing, stream_options = Nothing, temperature = Just 1.0, top_p = Nothing, tools = Nothing, tool_choice = Nothing, user = Nothing}}

λ Int. hi

Hello! How can I assist you today?

λ Int. is Haskell a good language?

Whether Haskell is a "good" programming language largely depends on your specific needs, goals, and preferences. Haskell is known for several distinctive features that can make it highly attractive in certain contexts:

### Pros of Haskell:

...

Pretty cool, eh? We already have a functional chatbot, even though a very limited one – it does not track the message history, we took some shortcuts when defining API functions, etc. However, what we do have is a full monad transformer stack, core API functions, and a fully functional program. Now we can build up some muscles around this skeleton and create a program of pretty much any complexity.

MESSAGE HISTORY EXERCISE

Think how you could approach tracking the message history in our chat agent. For this, we would need to change the processResponse function as well as amend our AppState to store everything properly before calling OpenAI API.

Building Muscles

So what else do we want in our program? In this chapter, let’s focus on adding three interesting features:

  • Keeping track of the message history, so that our conversations have context

  • Logging to a separate log file

  • Calculating usage to utilize the Writer monad functionality

Let’s start with logging – as it will be used by all the other features. We need to define our logging functions first to avoid having to adjust our core API twice.

Logging

We could of course write some kind of basic logger from scratch, but there are lots of very good libraries out there – and logging is not the type of functionality where we want to reinvent the wheel, so let’s just use what’s available. We will use the fast-logger package. As usual, go to hackage.haskell.org and search for it to read the docs. This is an extremely fast logger that also scales well on multiple cores – which is actually one of the very clear strengths of Haskell in general, but outside the scope of this book. However, since we are building a good foundation for potential production solutions, it makes sense to use it from the start – even though we won’t utilize its power to the full extent.

The code for the logger (and supporting terminal formatting functions) is in the folder src/Util. We are using fast-logger for the logging functionality, and on top of it we define the usual log levels, convenience functions to log in various levels – such as lg_err , lg_dbg , etc. – and additional state for housekeeping . Then there are a couple of initialization functions, which we will need to add to our initialization routine in main.

You can test how the logger outputs different level messages by loading the code into ghci by running stack ghci and then doing ghci> initLogger VERBOSE >>= testLogs . You should see output similar to that in Figure 10-3 .

A terminal window displays a series of log messages with timestamps. Each message has a different severity level indicated by color-coded labels: "FATAL" in red, "ERROR" in orange, "WARNING" in yellow, "INFO" in blue, "SUCCESS" in green, "DEBUG" in gray, and "VERBOSE" in white. The messages are generated by the command `initLogger VERBOSE >>= testLogs` in the GHCi environment.

Figure 10-3

Testing our logger

If you read the src/Util/Logger.hs file, you will notice that our functions there are all in the IO, and so require an explicit state object, since the type signatures all look like this:

lg :: LogLevels -> [Char] -> [String] -> LoggerState -> IO ()

This is of course not what we want to write every time, so we need to create proper logging actions inside the Mid monad – and if we want to use logging in the top floor, or the App monad, we can always lift them.

To do that, first we need to extend the AppState type to keep track of the logger state:

-- src/Util/Logger.hs

...

-- logger-specific state, keeping the current logger (can log to stdout or files, depending on which initialization function we use, and the clean up function

data LoggerState = LoggerState {

    logger::TimedFastLogger,

    cleanUpLogger:: IO(),

    level :: LogLevels

}

-- initializing logger state by creating a new timed logger (it takes care of time stamping automatically) and that writes to stdout. There is a similar function for file logging.

initLogger :: LogLevels -> IO LoggerState

initLogger lvl = do

    timeCache <- newTimeCache simpleTimeFormat

    (logger, cleanUp) <- newTimedFastLogger timeCache (LogStdout defaultBufSize)

    let st = LoggerState logger cleanUp lvl

    return st

...

-- src/StackTypes.hs

...

-- type that will hold the State for our App

data AppState = AppState {

    httpManager :: Manager,

    currentModelId :: Text,

    currentProvider :: ProviderData,

     loggerState :: LoggerState

}

-- Init.hs

...

-- 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

    lgState <- initLogger DEBUG

    let initSt = AppState manager "gpt-4o" prov lgState

    pure (settings, initSt)

As you can see from the above, we added loggerState as a separate field in the total application state, and then we adjust the initAll function to make sure the logger state is initialized as well.

Now we can create the logging actions in the Mid monad, which we will use most often.

EXERCISES

  1. 1.

    Change the initAll function above so that it reads the logging level from the .env file instead of being hardcoded.

  2. 2.

    Create logging actions in the Mid monad.

Creating the logging actions in the Mid monad using the functions we already have in IO is straightforward:

-- src/Middleware.hs

...

-- LOGGING --

lgFtl :: [Char] -> Mid ()

lgFtl msg = gets loggerState >>= liftIO . lg_ftl msg

lgErr :: [Char] -> Mid ()

lgErr msg = gets loggerState >>= liftIO . lg_err msg

lgWrn :: [Char] -> Mid ()

lgWrn msg = gets loggerState >>= liftIO . lg_wrn msg

lgInf :: [Char] -> Mid ()

lgInf msg = gets loggerState >>= liftIO . lg_inf msg

lgSuc :: [Char] -> Mid ()

lgSuc msg = gets loggerState >>= liftIO . lg_suc msg

lgDbg :: [Char] -> Mid ()

lgDbg msg = gets loggerState >>= liftIO . lg_dbg msg

lgVrb :: [Char] -> Mid ()

lgVrb msg = gets loggerState >>= liftIO . lg_vrb msg

We take the loggerState from the overall state and then feed it via a monadic bind operator to the corresponding IO logging action, which is then passed into liftIO – since we are in the Mid monad. Now we have nice shorthands for logging any log level message inside the Mid monad. Of course, you could also write a generic function that takes a log level as an argument, and then you wouldn’t need to define a separate function for each level – do this as an exercise.

Finally, let’s make sure we are using the version of the logger that writes to the file – simply change the initLogger function to initLoggerFile in the initAll, and all the logs will be written to the “.jarvis_logs” file. We don’t want to contaminate the console as we are interacting with Jarvis ourselves, but reviewing the logs later or by running tail -f .jarvis_logs in another terminal can be quite handy!

You may ask, “What about the Writer monad? Isn’t it good for logging ?!” Well, yes and no. It might be good for logging, but fast-logger provides a more efficient way to do that, so we don’t need to use the Writer monad machinery for this. However, it can be a good exercise.

EXERCISE

Use our logging methods and come up with a way to run logging via the Writer monad. To do it, you will need to come up with a data type that you will need to make an instance of Monoid and run logging functions inside the <> operator. Can you do it without breaking Semigroup and Monoid laws?

Usage Stats in the Writer Monad

Let us now build the Writer part of our RWS monad for something other than logging. OpenAI optionally returns usage statistics in tokens after each request – and this information is a good candidate to summarize at the end of each session, exactly what Writer functionality is good for. There is the following type in the src/LLM/OpenAI.hs:

data Usage = Usage

  { prompt_tokens :: Int

  , completion_tokens :: Int

  , total_tokens :: Int

  } deriving (Show, Generic)

It is exactly what is being returned from OpenAI as JSON and then converted to the respective Haskell data type. All we need to do to be able to use it “automatically” in the Writer part of our monad is make it an instance of Monoid .

EXERCISE

Make Usage an instance of Semigroup and Monoid (for which Semigroup is a prerequisite) by yourself before reading further.

This is a very straightforward exercise by this point, so I am sure you had no trouble writing:

instance Semigroup Usage where

  u1 <> u2 = Usage {

    prompt_tokens = prompt_tokens u1 + prompt_tokens u2,

    completion_tokens = completion_tokens u1 + completion_tokens u2,

    total_tokens = total_tokens u1 + total_tokens u2

  }

instance Monoid Usage where

  mempty = Usage 0 0 0

Semigroup defines a <> operator that combines two elements of our type with associativity, and Monoid adds an empty element to it. Now we can change the definition of our Mid monad as follows: type Mid = RWST Settings Usage AppState IO . Instead of a [String] Monoid , we give Usage as a Monoid to the Writer part of the RWS monad, and now we can use the tell function to update the result automatically.

However, before we are able to do that, we need to create a slightly different version of the function that calls OpenAI API and processes the streaming response. First, we need to make it a part of the App monad – since we will be outputting stuff to the terminal, which is our top floor in the stack. Second, we need to add some better error handling with logging as well as update the stream processing function so that it can be folded instead of mapped . To do that properly, we need to add the chat history functionality first.

Chat History

To illustrate why keeping track of chat history is important, you can run the program in its state from the previous section and go through the following line of questioning or something similar:

λ Int. who is Hemingway?

Ernest Hemingway was an influential American author and journalist, born on July 21, 1899, in Oak Park, Illinois, and died on July 2, 1961, in Ketchum, Idaho. He is known for his terse, economical writing style and for pioneering the "iceberg theory" of writing, where the deeper meaning in a story is hidden below the surface.

Hemingway authored numerous classic works of literature, including "The Sun Also Rises," "A Farewell to Arms," "For Whom the Bell Tolls," and "The Old Man and the Sea." He won the Nobel Prize in Literature in 1954, primarily for "The Old Man and the Sea." His experiences as an ambulance driver in World War I, a journalist during the Spanish Civil War, and an adventurer greatly influenced his writing.

Hemingway's lifestyle was as legendary as his prose; he was known for his love of adventure, his passion for hunting, fishing, and bullfighting, and his larger-than-life persona. Despite his external bravado, Hemingway had a complex inner life marked by bouts of depression, and he ultimately took his own life in 1961. His legacy lives on, with his works remaining a significant part of the Western literary canon.

λ Int. what is his best book?

It's a bit difficult to determine which specific "his" you're referring to without more context. The "best book" for any author can be subjective and depends on personal taste and what kind of themes or writing style you enjoy. Could you please provide the name of the author or more context so that I can provide a more accurate recommendation ?

λ Int.

As you can see from the above, our chat agent has no concept of the previous conversation and treats each message separately. When we ask “what is his best book,” we would expect the AI to deduce from the context that we are talking about Hemingway – but it doesn’t. So even though the bot in its current state can be quite useful to answer isolated questions, it won’t really keep any conversation with you. Let’s remedy that!

How about the Writer monad? I mean, all we need to do is to give our RWST transformer [Message] instead of [String] and we can build up the chat history automatically?!

Well, unfortunately, again, no. This looks very tempting – but the Writer monad gives you access to what is inside the “logging” Monoid only after you run the monadic action via runRWST/evalRWST and similar methods – and we only do that at the top level of our program. Of course, we could treat each interaction with the LLM API as a single Writer action and then get the resulting [Message] array as a result – but it would mean we’ll anyway need to keep the intermediate message arrays somewhere in the State, so it gets messy.

Another issue is that the context that an LLM can handle is limited, plus the tokens are not free – so ideally you want to give the LLM as much context as needed to perform its functions well, but not too much so that it does not lose attention and you do not overpay. To handle this, we will include a tunable parameter – number of messages to keep in the history to be sent to the LLM with every user request .

To do this, let’s update the AppState data type:

-- type that will hold the State for our App

data AppState = AppState {

    httpManager :: Manager,

    currentModelId :: Text,

    currentProvider :: ProviderData,

    loggerState :: LoggerState,

            messageHistory :: [Message],

            historySize :: Int

}

We have added the messageHistory and historySize parameters – and do not forget to update the initAll function in Init.hs so that it includes the new defaults: let initSt = AppState manager "gpt-4o" prov lgState [] 6 .

Now let’s get to reworking the function that calls OpenAI API. In order for us to achieve the desired result – namely, to be able to update usage data and message history after calling the OpenAI API – we need to change the main functions that work with it. Please review these changes carefully – if you are able to fully understand this code, you will have no issues with anything in Haskell. By now you should be armed enough to be able to do that:

-- src/LLM/OpenAI.hs

...

chatCompletion :: [Message] -> Text -> ProviderData -> Maybe ChatOptions -> LoggerState -> (BS.ByteString -> IO (String, Usage)) -> IO (String, Usage)

chatCompletion messages modelId provider opts lgState func = do

    -- Note: parseRequest_ throws an exception on invalid URLs, so in a real application, you should handle that.

    let url = chatCompletionURL provider

    let key = providerKey provider

    let fopts = Data.Maybe.fromMaybe (providerDefaultOptions provider) opts

    lg_dbg ("Calling chatCompletion with URL: " ++ url ++ " and key " ++ show key) lgState

    initialRequest <- parseRequest url

    let obj = Data.Aeson.object [

                "model" .= modelId,

                "messages" .= toJSON messages

            ]

    let request = setRequestBodyJSON (combineObjects obj (toJSON fopts))

            $ applyBearerAuth key initialRequest

    let postRequest = request { method = "POST" }

     -- Use withResponse to process the streaming response

    httpSink postRequest $ \response -> do

        if statusCode (responseStatus response) /= 200

            then do

                liftIO $ lg_err (show (responseStatus response)) lgState

                liftIO $ lg_err (show (responseHeaders response)) lgState

                foldMapMC (\x -> do

                                  let y = unpack x

                                  putStr y

                                  pure (y, mempty))

            else do

                -- Stream the response body to stdout

                foldMapMC func

The changes we made here are subtle, but important. First, we are now passing the LoggerState object explicitly to be able to use our logger. We are still in the IO monad, so there is no state , so we need to pass it explicitly. Second, we changed the mapM_C function in our response handler to foldMapMC , also from the conduit package (the type signature for chatCompletion is updated accordingly). This is a key change. With mapping, we go over all elements of some collection (a list, a stream, a tree, etc.), perform some operation with it, and optionally return a changed collection. With folding, we do the same, but we collect all results in some sort of accumulator value – in this case, it is (String, Usage) . The foldMapMC function takes care of accumulation for us automatically, thanks to the fact that both String and Usage are a Monoid, so their pair is a Monoid as well! And as we well know by now, we can “fold” Monoids easily using their built-in <> operator – and that’s exactly what foldMapMC does for us under the hood. The String in our accumulator is the final message – which we will put into message history – and Usage is, well, usage, which we will put to our Writer monad.

Now the only thing that’s left to make sure we have enough low-level API and can fix the rest of the program is to adjust the processResp function so that it returns the (String, Usage) object:

processResp :: BS.ByteString -> IO (String, Usage)

processResp ch = do

  foldM

    ( \acc x -> do

        let jsonObject = decode (BL.pack x) :: Maybe OpenAIResponse

        case jsonObject of

          Nothing -> return acc

          Just resp -> do

            if not (null (choices resp)) then do

              let chs = delta $ head $ choices resp

              case chs of

                Nothing -> return acc

                Just DeltaMessage {content = cnt} -> do

                  let str = T.unpack cnt

                  putStr str

                  return (fst acc ++ str, snd acc)

            else do

              let u = usage resp

              case u of

                Nothing -> return acc

                Just us -> return (fst acc, snd acc <> us)

    )

    ("", mempty) (processString $ unpack ch)

This is not optimized at all. I encourage you to think and optimize it, especially with all the Maybe checks. A slightly annoying complication for this function is that the chunks that OpenAI returns can contain several “data:” chunks, so we are forced to do another fold inside our function that’s being folded itself. One other way to optimize it is to use some more general functions from the Foldable typeclass instead of foldM. The changes done here are straightforward – we added the (String, Usage) accumulator that’s initialized to (“”, mempty), and then when there is meaningful input, we update this accumulator either by growing the message string or by adding the usage information.

Now we are ready to write a much nicer-looking high-level interface function in the Mid monad that will utilize this low-level interface changes:

-- src/Middleware.hs

...

chatCompletionMid :: Message -> Mid ()

chatCompletionMid message = do

    st <- get

    let provider = currentProvider st

    let msgs = messageHistory st

    let messages = msgs ++ [message]

    (asMsg, us) <- lift $ chatCompletion messages (currentModelId st) provider Nothing (loggerState st) processResp

    let messages' = messages ++ [assistantMessage $ pack asMsg]

    modify' (\s -> s {messageHistory = messages'})

    tell us

    pure ()

This is a much easier-to-use middleware function that uses our low-level chatCompletion function under the hood. Here we simply get the status, build a message list, then call the low-level function and update the status with new messages, and sum usages using Writer’s tell function.

Then, making changes to the main application loop, which is also simplified:

-- src/App.hs

...

loop :: App ()

loop = do

  lift $ lgInf "starting up Jarvis"

  minput <- HL.getInputLine  (TC.as [TC.bold] "\nλInt. ")

  case minput of

    Nothing -> return ()

    Just ":quit" -> return ()

    -- Just (':':cmds) -> (processCommand (words cmds)) >> loop

    Just input -> lift (chatCompletionMid $ userMessage $ T.pack input) >> loop

So much nicer. Now, let’s also make a small change to show the total usage after the user quits the session :

main :: IO ()

main = do

    (sett, initSt) <- initAll

    (_, _, w) <- runRWST (runInputT (defaultSettings {historyFile = Just ".jarvis_history"}) loop) sett initSt

    putStrLn "Total usage:"

    print w

    putStrLn "Bye!"

Now we are reading the results of runRWST, ignoring final state but outputting total usage. Try it! stack build, stack exec jarvis . Also feel free to open another terminal and run tail -f .jarvis_logs there to see the logs as well (Figure 10-4 ).

A terminal window displays a text-based interface with information about Ernest Hemingway. It describes Hemingway as an influential American author and journalist, highlighting his distinctive writing style known as the "iceberg theory." The text mentions his adventurous life, including his participation in World War I and the Spanish Civil War, and lists notable works such as "The Sun Also Rises," "A Farewell to Arms," and "The Old Man and the Sea," which won the Pulitzer Prize. The interface also shows log entries related to an API call, indicating a response about Hemingway's best books.

Figure 10-4

Testing chat history and logging – as you can see, “his books” question is now well understood

EXERCISE

Currently we have not implemented the message history limitation functionality. Do that now – make sure we are only sending no more than N previous messages to the chatCompletion function.

Conclusion

What an amazing job have we done! Constructed a real, “near-production”-quality Haskell program using a monad transformer stack; implemented external API calling and logging; utilized Reader, Writer, and State monads in one go; and again revisited the functional typed design approach. In the next chapters, we will further extend the functionality of our AI framework and will discuss other advanced Haskell concepts, such as mutable variables, vectors, and type families, along the way.

And by the way, you can start using the chatbot we created for help in learning Haskell even now! We will make it even more customizable as a Haskell helper, but even in its current form, you can start asking it Haskell-related questions and it should give you quite good answers. In the next chapter, we will show you some more specific use cases, which can be extremely helpful even for seasoned Haskell programmers – e.g., GHC is known for cryptic error messages, but asking our chatbot to explain them does wonders. Try it yourself or wait until the next chapter, where we will further improve the UI to assist us with such tasks.