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

9. Let’s AI

Anton Antich 1    

(1)

Schaffhausen, Schaffhausen, Switzerland

As I started working on this book, it became impossible to ignore what is happening in the world of AI, or artificial intelligence. Full disclosure: I may be biased as we are currently building a platform for easy creation of AI agents (integrail.ai – and, yes, we do use Haskell for parts of the solution), but still, we may argue about the extent to which AI has influenced and will influence our lives, but we will all agree that it has. In the second part of this book, we will continue building different real-world programs while introducing more and more advanced concepts. Many of these examples will be AI related, on one hand, and, on the other hand, if you use a simple agent or two when learning Haskell and when building programs, you will become much more productive than anything that was possible previously. We will build such agents together, in Haskell, for Haskell.

Before we do, we need to make a brief overview of what Agentic AI, enabled by the advances in generative AI and especially the advent of LLMs, or large language models, is.

Agentic AI and Large Language Models

AI is an old term; the topic has always fascinated people. It fell in and out of fashion, depending on the technology available. We had invented “ perceptron ” – the first ever attempt to create artificial neural networks , or ANNs, over 70 years ago. We had a decade or so of “expert systems” in the 1980s. We witnessed a deep learning revolution that allowed us to train multi-layered ANNs in the 2000s. This brought immense advancements in computer vision and enabled “self-driving” vehicles. We had a brief spotlight on so-called Deep Reinforcement Learning with AlphaGo and AlphaZero beating humans at Go and chess – something that seemed impossible for Go not so long ago. Now, it is difficult to find a person who hasn’t at least heard of “ ChatGPT ” and maybe even other “chatbots,” and some vendors and individuals dangle the promise of “artificial general intelligence” “sometime soon.”

Herein lies a slight problem. Large language models , or LLMs, based on so-called transformers architecture, are an amazing tool. OpenAI with GPT, Anthropic with Claude, Google with Gemini, and Meta with a bunch of excellent and open source Llama models are all based on this same architecture. The good news is using today’s level of technology, we can create amazing versatile AI agents that are able to perform a lot of mundane tasks on our behalf, as well as be very helpful in learning and creative endeavors. Bad news: People en masse don’t really understand how to utilize LLMs efficiently and are trying to get some overhyped results from the “ chatbots ” such as ChatGPT , are failing at that, and become disillusioned.

We will try to show a better way in the second part of this book, following the journey of internalizing increasingly more sophisticated Haskell concepts along the way.

We will not be building ANNs or LLMs from scratch in Haskell, even though we could. For better or worse, Python is a de facto standard in AI development, and even though Haskell is very well suited for the architectures of ANNs, that’s the reality. So we will focus on applications of AI using Haskell, reusing the models that were built in and are being run on Python.

LLMs in a Nutshell

Since this is not a book on ANN architectures, I will mostly focus on practical issues instead of going deep into technical details. In a nutshell, an LLM is an ANN that learns to do one thing only: given the context of a bunch of so-called tokens , it predicts the probability of the next token. That’s it. In the last couple of years, there has been very visible progress on improving how LLMs perceive the context first and foremost through so-called “attention” techniques, and this gave us increase in the amount of input information they are able to process while still not being lost. However, the core principle remains the same – predict the probability of the next token based on all the previous.

So how come they can be so efficient at certain tasks, so that people even talk about “reasoning” and the like? If they only learned the information they’ve seen, we could explain that LLMs are able to answer “tricky” questions such as “how many tennis balls fit into Boeing 747” – since they have seen this question answered in the training data multiple times. But if you ask them “how many children’s cubes fit into a Tesla car,” they would still give you a very close train of thought, even though I doubt anyone ever formulated this problem this exact way – and this trait gives visibility of their ability to “reason.” How is that possible?

The answer lies in another breakthrough in natural language representation studies – so-called vector embeddings . Using some very smart techniques, every word, token, 1 or more complex concepts described as a phrase are converted into multidimensional vectors. It turns out that words and concepts represented this way lie very close in the vector space if they are close in meaning. For instance, a famous example shows that king – queen = man – woman in the vector space. This means that when LLMs predict probability of the next token and are asked about “children’s cubes” instead of “tennis balls” – these concepts lie very close in the vector space, so the “tennis balls” line of reasoning is then applied to the “children’s cubes” – we get this impression of the ability to reason (which it is to a certain extent – in a sense, LLM learns “by analogy”).

Vector embeddings gave rise to vector databases as well, a very fast developing area in AI, since they allow you to search “by meaning” instead of by keyword. We will discuss the importance of this down the line.

What are LLMs good at?

  • Text transformation, following the name of the architecture. Thanks to those vector embeddings, if you want to convert between any formats, they do it very well. Text to JSON or SQL, translation between languages, explaining what software code does in human language, etc. This leads to a number of applications, such as

    • Any integrations.

    • Learning assistance.

    • Translation.

    • Customer support/natural language answering tasks.

    • “Understanding” images. Latest multimodal models do this extremely well, and not surprisingly – after all, it is simply “translation” between pixels and text.

  • Text generation , and I mean any kind of text (including code or pretty much anything that can be classified as a language – if they were trained on this data, of course). This one is obvious and is probably the most common use case, used widely in business already.

What are LLM limitations? The two most known arguably are

  • So-called hallucinations . When you ask any question of LLMs, they tend to produce an answer no matter what (it’s their underlying math after all) and do it very convincingly. So, if we are not an expert in the field, how in the world will we know if what they are telling us is true?!

  • Inability to properly model the world knowledge in any “logical” sense of the word. For instance, if you ask LLMs “who is the mother of Tom Cruise,” they will tell you, correctly, “Mary Lee Pfeifer.” But if you rephrase the question and ask “who is the son of Mary Lee Pfeifer,” you won’t get an answer. The reason is that they have seen lots of context where Mary Lee was called the mother of Tom Cruise, but very rarely any texts where Tom Cruise was called a son of Mary Lee. And since there is no “internal” logical, reasoning mechanism inside LLMs, this becomes another significant limitation on the way to “true” AI.

As we shall see, the first problem can be solved in a multitude of ways and fairly easily. The second is more difficult, but even with this limitation, LLMs will help us with a number of hard, or at least annoying, problems.

Three Ways to Make LLMs Better

The image shows a code snippet defining "data InputT m a," a monad transformer for a line-reading application. It lists instances such as MonadTrans, MonadFail, MonadFix, MonadIO, Applicative, Functor, Monad, MonadCatch, MonadMask, and MonadThrow, each associated with "InputT m" and linked to a source.

Figure 9-1

Typical LLM and the ways to make it better

Vector RAG

Take a look at Figure 9-1 , which shows high-level LLM schematics and the ways to improve their performance . The easiest way to virtually kill hallucinations and provide high-quality output is so-called RAG, or retrieval augmented generation. The way it works is pretty straightforward – whatever the user is asking of the LLM is getting converted into vector embeddings, and a search in the vector database to find pieces of context close in meaning is performed. Then, these relevant pieces of context are being fed as part of the input to the LLM. This way, LLMs stop hallucinating and provide output that follows the meaning in the immediate context. In the worst case, you can always make the LLM respond directly “I don’t know” in case it is not 100% sure of the correct answer via prompting. This is the easiest, most straightforward, but very efficient way to make LLMs useful for you or your business personally – build different vectorized knowledge bases, attach them to LLM-based agents, and enjoy much higher quality of the results than with “generic” chatbots from the leading vendors.

Additional Fine-Tuning

All of the available commercial “ chatbots ” on the market as of this writing have gone through a so-called “human feedback reinforcement learning” stage. It’s additional extensive training to make LLMs better suited for a question-and-answer type of conversation, as well as the way to “align” the values and attitudes the LLM learns to what humans want it to have.

However, you can also do additional fine-tuning yourself. Normally, you would need at least several thousands – better yet, tens of thousands – of data samples if you want your fine-tuning to influence the LLM weights. Very unscientifically, I would estimate that proper context building with RAG and other techniques should cover 95% of cases for you, but for some specific cases, where deep vertical knowledge is required, for instance, fine-tuning can be your answer. It also makes sense if you use certain vast context day in and day out – so it will be less expensive to spend once to fine-tune the model instead of wasting tokens at each request.

Better Original Training Data

Available LLMs are usually trained on everything vendors can get their hands on – Wikipedia, “all of the Internet,” books, tweets, GitHub code, what have you. This provides versatility, but also lots of noise. There is research that if you use high-quality training data only in the first place, you need less of it and you need fewer-parameter LLMs to learn it. However, training even a three-billion-parameter model from scratch is a very expensive endeavor, so unless you are a big corporation with very deep pockets, this way is not currently accessible.

Haskell and LLMs

As mentioned in an aside above, we will not be building any neural networks from scratch in Haskell, even though we could. First of all, Python is the language of choice for AI, for better or for worse. Second, even if we do build a simple transformer, e.g., of GPT-2 level, training it properly is very expensive, unpractical, and adds no value in terms of either learning Haskell or doing AI. What we can and will do in Haskell is build a framework with a number of different programs that automate work with different AI agents and that can serve as a solid foundation for you to build your own cool AI agents in Haskell.

We will get there gradually, step by step. First, we will aim to create a “simple” chatbot, powered by various different LLMs, but we will be doing that in frames of a larger-scale design of the whole framework that will allow us to work with our agents via web and via terminal (and operating system in general), as well as having a MongoDB layer to provide persistence for various documents with optional vector search functionality. Then, as we build and flesh out this framework, we will gradually increase the complexity of AI that we will be doing. From the chatbot to multimodal and multi-LLM agents, to integrations with external systems, and to self-learning techniques – unleashing the power of AI agents and your creativity along the way.

Big Picture of the Haskell AI Framework

Here is a high-level description of what we want to have as an end result:

  • An “AI agents core ”:

    • Ability to connect to various AI (generative models) APIs

    • Ability to work with any external APIs to integrate with external systems

    • A lightweight DSL to describe AI agents and build them dynamically at runtime

  • Knowledge layer: MongoDB for storage and optional vector search. Why MongoDB and not some SQL database? For one, SQL databases are very well known and well described in the Haskell world as well, so it is more interesting to work with Mongo as a no-SQL leader very widespread in the web programming world. As a bonus, it has very good built-in vector search functionality, which we will need for RAG as described above.

  • Different ways to work with the system:

    • Via terminal, using an excellent Haskeline library

    • Via web, with all the consequences of working with JSON, security, etc.

    • Autonomous “agentic mode”

To design and build such a solution, or even something close to it, will require from us not only applying everything we’ve learned so far but also the knowledge of many other advanced Haskell concepts, such as mutable variables, web servers, multi-threading, vectors and type families, etc. Some of these topics and parts of the framework we will discuss in more detail, and some will only skim merely giving you a direction for further studies or development on your own. But as we progress, I hope that the beauty of Haskell and the typed functional approach to programming in general will captivate you more and more, so that you become a devoted user yourself.

Terminal Chatbot

As they say, before we fly, we gotta crawl. Well, I would argue we learned to crawl in the first part of the book , so let’s try at least walking. To do that, we will build a prototype starting point of our AI framework – a simple terminal LLM-powered chatbot. Even though it is simple, it won’t be so easy, as we will need to address the following:

  • Calling LLMs via API

  • Logging errors and general application status (so maybe a Writer monad in the stack?)

  • Reading configuration and settings to know how to connect to various APIs (so maybe a Reader monad in the stack?)

  • Interacting with the user in the terminal using Haskeline (which provides its’ own monad – so integrating it will be a very educational experience)

  • Potentially, saving conversation histories and providing additional context

Let’s start!

As we have been discussing and practicing, we need to start thinking about the large-scale program structure (in our case the monad transformer stack, as we don’t know any other ways yet), as well as about which functions and types we are going to need and on which floors they should live. As we will use Haskeline as our terminal UI (see Figure 9-2 ), let’s see what kind of interface it provides. Go to hackage.haskell.org, as usual, and search for “haskeline.”

The image shows a code snippet defining "data InputT m a," a monad transformer for a line-reading application. It lists instances such as MonadTrans, MonadFail, MonadFix, MonadIO, Applicative, Functor, Monad, MonadCatch, MonadMask, and MonadThrow, each associated with "InputT m" and linked to a source.

Figure 9-2

InputT transformer, provided by the Haskeline library

As we can see, InputT is a monad transformer that also has instances for all kinds of IO-related monads, starting with MonadIO itself. This means that all the functionality of IO is available inside InputT. Since we will probably need Reader–Writer–State monads as well, we have a conundrum – where to put InputT in a stack? The consideration is very easy – since it will provide the UI, it has to have access to all of the rest of functionality. As you remember, we can lift functions from the lower floors but not vice versa, so we should put InputT on the top.

Another neat trick provided for us by Haskell’s mtl library is this: since Reader–Writer–State are so common a pattern, there is a separate kind of monad called just RWS, which, as you can guess, provides the functionality of all three of these monads. It makes our life much more convenient as well, since dealing with a stack of 5+ monads would require quite a bit of interface-related plumbing to write concise code.

High-Level Design

Thus, preliminarily, we think that the monad stack for our terminal chatbot will look like Figure 9-3 .

Diagram titled "Application Monad" with three stacked sections. The top section is labeled "InputT: terminal UI," the middle section is "RWS: State, environment, logs," and the bottom section is "IO: API Calls." Each section represents a component of the application monad structure.

Figure 9-3

Monad transformer stack for the terminal chatbot

Now we need to start thinking which functions and types live where. In the first version of our bot, we will use OpenAI API. It is a de facto standard, which other LLM providers try to follow when they define theirs, so it’s worth it to review in detail. To use it you will need to get your own OpenAI security token – just navigate to their website, register, and create your own API token. In the next chapters we will discuss alternative ways to use LLMs as well – one possibility is to run new Llama models (Llama-3.2 at the time of this writing) locally, which requires quite a bit of additional Python-related setup, but no API keys.

Here are some other key requirements that we will need to use in our chatbot application:

  • Reading configuration and settings from an .env file, using the dotenv package

  • Converting to/from JSON values, using Data.Aeson from the aeson package

  • Making HTTP API calls, using the series of functions from the Network.HTTP… namespace, spread out throughout several packages

  • Various text and bytestring manipulations

Be ready to have these libraries open on Hackage, along with OpenAI API docs (this is optional as I will explain how to use it in detail).

Initial RWS Monad

Let’s start implementing our design gradually. First, we’ll create an outline for our RWS Monad by stacking it on top of IO and set up placeholder types for our state and read-only environment variables. We will be gradually extending them as we build out our chatbot.

You should put the environment variables to the .env file in the root folder of the project. You should have a template file called .env.template in the repository – copy it to .env and fill in the missing info:

OPENAI_ORG=

OPENAI_TOKEN=

OPENAI_URL_CHAT=https://api.openai.com/v1/chat/completions

OPENAI_URL_MODELS=https://api.openai.com/v1/models

Never commit the .env file to public repositories – as it will contain all the secrets we will use in the project, such as API keys and other authentication-related info.

Our first task is to read the environment and set up our internal, read-only environment in the RWS monad that we will be using. For now, our read-only environment will contain only the list of LLM providers:

-- src/StackTypes.hs

...

import LLM.OpenAI (ProviderData)

data Settings = Settings {

    llmProviders :: [ProviderData]

}

The ProviderData type will also be built gradually. For now we will use only the following information to set up our initial program:

-- src/LLM/OpenAI.hs

...

data ProviderData = ProviderData {

    providerName :: Text,

    providerKey :: BS.ByteString, -- with Bearer for now to be faster

    chatCompletionURL :: String

} deriving (Show)

We will need the functions to read the environment and configure the initial Settings object, which for now will only contain the settings for openai as a provider:

-- src/Init.hs

...

buildOpenAISettings :: IO ProviderData

buildOpenAISettings = do

    -- doing pattern match because we will have checked for presence before

    (Just key) <- lookupEnv "OPENAI_TOKEN"

    (Just url) <- lookupEnv "OPENAI_URL_CHAT"

    pure $ ProviderData {

    providerName = "openai",

    providerKey = pack key,

    chatCompletionURL = url,

    providerDefaultOptions = defaultChatOptions

}

initConfig :: IO Settings

initConfig = do

    loadFile defaultConfig

    oa <- buildOpenAISettings

    pure $ Settings { llmProviders = [oa]}

There are two straightforward methods: one finds openai-specific configuration in the environment, and the other one reads the environment from the .env file and calls various functions to build the final settings. For now it’s only openai. You may also notice that we are taking a shortcut in buildOpenAISettings by pattern-matching directly into (Just x) . We are doing so because eventually we will have an additional check that makes sure all needed environment variables are present – and it makes our code here less cumbersome as we don’t have to deal with Nothing values. The pack function converts the String value that is read from the environment to the ByteString that we will need for our token down the line.

Now let’s define our RWS on the IO monad and see how the environment we just read can be used in the main program:

-- src/App.hs

...

import Control.Monad.RWS

import StackTypes (Settings, AppState)

type App = RWST Settings [String] AppState IO

Here we are defining a monad transformer stack App that consists of the RWS monad with read-only environment type Settings, type for Writer – simple list of Strings (we will change this in the future) – and AppState for state (currently empty), sitting on top of the IO monad.

Now, the challenge beginners often have is this. To execute our program in “main” (even without InputT on top yet), we need to use a function runRWST :: RWST r w s m a -> r -> s -> m (a, s, w) that takes our RWST (or App) action, initial settings, and initial state and then returns IO (a, state, writerOutput). So how do we give the initial settings and state to such a function? Well, you simply run a couple of IO computations that build the initial settings and state for you by reading the disk and network, interacting with the user, etc. and then pass them to runRWST. Again, if you carefully read and decode the types, it becomes very easy to understand. For instance, for our very simple current program state, we could write main something like the following:

main :: IO ()

main = do

    settings <- initConfig

    print settings

    runRWST mainAction settings initialState

The logic is you build the read-only settings once before the program is initiated, and then they become read-only and pure for all practical purposes inside whatever crazy monad transformer stack you may have.

The above illustrates how you can start with a pretty general application skeleton, including your monad stack, and then gradually build it by expanding the state and environment types, as well as designing the problem domain types and functions as usual. Let us follow our own advice and move to the following.

Designing the OpenAI Interface

In this section, we will dive into the details of how we interface with OpenAI’s APIs to build a seamless connection for our chatbot. The goal is to abstract out the complexities of the API, allowing Haskell users to easily send messages, receive responses, and manage configuration options, all while keeping everything typed and functional.

We will cover a few key aspects that are central to working with OpenAI’s API using Haskell :

  • Converting to and from JSON for the API request/response

  • Handling OpenAI message formats

  • Sending requests to the API for chat completion

Converting Between Haskell Types and JSON

In order to interact with OpenAI’s API, our Haskell types need to be converted to and from JSON . OpenAI requires requests to be sent in a specific JSON format, and responses are returned in JSON as well. Thankfully, Haskell’s aeson library provides us with powerful tools to make this conversion seamless by leveraging typeclasses like ToJSON and FromJSON.

The Message Type

The Message type represents a single message in the chat interaction. When working with OpenAI models like GPT, you typically send a list of messages with different roles (user, assistant, or system). Here’s our Message type:

data Message = Message

  { role :: Text -- "user" | "assistant" | "system"

  , content :: Text

  , tool_calls :: Maybe [Text]

  , tool_call_id :: Maybe Text

  } deriving (Show, Generic)

instance ToJSON Message

instance FromJSON Message

The role field determines who is sending the message (the user, the assistant, or an internal system message). The content holds the actual text of the message. Optionally, you can include tool_calls and tool_call_id for more advanced interactions, such as invoking external tools during conversations, but we won’t be using those for now.

By deriving Generic, we can automatically implement the ToJSON and FromJSON instances, allowing the aeson library to handle the JSON conversion for us.

ChatOptions: Configuring the Chat Interaction

Chat interactions with OpenAI models can be fine-tuned through various configuration options. These options are sent as part of the API request and allow you to control behavior such as the length of the response, temperature (how predictable the model output should be), whether the response is streamed, and more:

data ChatOptions = ChatOptions {

    stream :: Bool,

    frequency_penalty :: Maybe Float,

    logprobs :: Maybe Bool,

    top_logprobs :: Maybe Int,

    max_tokens :: Maybe Int,

    presence_penalty :: Maybe Float,

    response_format :: Maybe Object,

    seed :: Maybe Int,

    stop :: Maybe [Text],

    stream_options :: Maybe Object,

    temperature :: Maybe Float,

    top_p :: Maybe Float,

    tools :: Maybe [Object],

    tool_choice :: Maybe Text,

    user :: Maybe Text

} deriving (Show, Generic)

instance ToJSON ChatOptions

instance FromJSON ChatOptions

This ChatOptions type models the configurable settings that the OpenAI API accepts. For example:

  • stream allows response streaming, where chunks of the response are delivered as soon as they’re ready.

  • temperature controls the randomness of the model’s responses. Higher values (e.g., 0.8) result in more random responses, while lower values (e.g., 0.2) make the model more focused and deterministic.

We also provide a defaultChatOptions to simplify using the API without the need to manually specify all the options from scratch. This default configuration is geared toward enabling streaming responses, with a temperature of 1 (balanced creativity) and no specific penalties or stopping conditions.

Working with JSON is ubiquitous when developing any web-related applications, so let’s spend some time discussing the aeson library. It provides a set of tools to easily convert between Haskell types and their JSON equivalents, as well as to parse and generate JSON efficiently.

The core of aeson revolves around two typeclasses:

  • ToJSON: Defines how a Haskell type can be serialized into JSON

  • FromJSON: Defines how JSON can be deserialized into a Haskell type

When you have a Haskell value that you want to send as JSON (e.g., in an API request), you need to convert it into a Value (another type provided by aeson that represents JSON). Similarly, when you receive JSON (e.g., an API response), you need to convert it back into your Haskell types using FromJSON.

How ToJSON and FromJSON Work

The easiest way to leverage aeson for JSON conversion is through the automatic derivation of ToJSON and FromJSON instances. Haskell’s GHC.Generics allows us to automatically derive these instances for most simple data types, provided that the types involved are also instances of ToJSON and FromJSON.

Let’s revisit our Message type:

{-# LANGUAGE DeriveGeneric #-}

import GHC.Generics (Generic)

import Data.Aeson (ToJSON, FromJSON)

data Message = Message

  { role :: Text  -- "user", "assistant", "system"

  , content :: Text

  , tool_calls :: Maybe [Text]

  , tool_call_id :: Maybe Text

  } deriving (Show, Generic)

instance ToJSON Message

instance FromJSON Message

Here’s what’s happening:

  1. 1.

    We derive the Generic typeclass for Message. This allows Haskell’s compiler to automatically generate a “generic representation” of the type. Unfortunately, we cannot go into the details of this mechanism here; suffice it to know that it allows Haskell to then do lots of automatic manipulations with your types that saves boilerplate.

  2. 2.

    By deriving Generic , we can automatically derive ToJSON and FromJSON instances using aeson. This means we don’t need to manually write code to convert a Message to/from JSON – huge timesaver!

With this in place, we can now serialize (ToJSON) and deserialize (FromJSON) Message values without any additional effort.

Here’s how you would convert a Message into a JSON Value:

import Data.Aeson (encode)

let message = Message "user" "Hello, OpenAI!" Nothing Nothing

let jsonMessage = encode message   -- JSON representation of the message

On the flip side, deserializing JSON back into a Message looks like this:

import Data.Aeson (decode )

import Data.ByteString.Lazy.Char8 (pack, unpack)

let jsonString = "{\"role\": \"user\", \"content\": \"Hello, OpenAI!\"}"

let maybeMessage = decode (pack jsonString) :: Maybe Message_

If the JSON string matches the structure of Message, decode will return Just Message; otherwise, it will return Nothing.

By default, aeson will map fields in your data structure to JSON key–value pairs based on the field names . For example

Message { role = "user", content = "Hi", tool_calls = Nothing, tool_call_id = Nothing }

will be encoded into

{

  "role": "user",

  "content": "Hi",

  "tool_calls": null,

  "tool_call_id": null

}

This is great for most use cases, but what if you have slightly different requirements? For instance, what if the API expects snake_case keys instead of camelCase or you want to rename some of the fields?

In such cases, you can customize how the conversion works by providing your own implementations of ToJSON and/or FromJSON.

Let’s say we want the Message type to be serialized with snake_case field names instead of the default camelCase:

{-# LANGUAGE OverloadedStrings #-}

import Data.Aeson (ToJSON, FromJSON, object, (.=), withObject, (.:))

instance ToJSON Message where

  toJSON (Message role content toolCalls toolCallId) =

    object [ "role" .= role

           , "content" .= content

           , "tool_calls" .= toolCalls

           , "tool_call_id" .= toolCallId

           ]

instance FromJSON Message where

  parseJSON = withObject "Message" $ \v -> Message

    <$> v .: "role "

    <*> v .: "content"

    <*> v .: "tool_calls"

    <*> v .: "tool_call_id"

Here, we’re manually specifying the JSON object structure in both directions:

  • toJSON converts a Message into a JSON object with the desired field names.

  • parseJSON converts a JSON object into a Message by extracting values from the corresponding keys.

This approach is useful when you need fine-grained control over the JSON structure, such as when integrating with APIs that have specific field naming conventions.

Handling Optional Fields

In the Message type , some fields are optional (e.g., tool_calls and tool_call_id, which are Maybe types). aeson handles this gracefully by encoding Nothing as null in JSON and decoding null back into Nothing:

let message = Message "user" "Hello!" Nothing Nothing

let jsonMessage = encode message

This will produce:

{

  "role": "user",

  "content": "Hello!",

  "tool_calls": null,

  "tool_call_id": null

}

When aeson encounters null in JSON, it correctly maps it back to Nothing in Haskell during decoding.

aeson in Action: API Requests and Responses

Now that we understand how ToJSON and FromJSON work, let’s see how they fit into the broader context of interacting with OpenAI’s API.

In the chatCompletion function, we send a POST request to OpenAI’s chat completion API. To do so, we first need to prepare the request body, which consists of the model ID, the list of messages, and the optional chat options.

Using the ToJSON instances, we can easily convert these Haskell values into JSON for the request body:

let obj = Data.Aeson.object [

            "model" .= modelId,

            "messages" .= toJSON messages

        ]

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

            $ applyBearerAuth key initialRequest

Here, we create a JSON object using the object function provided by aeson, which takes a list of key–value pairs. The .= operator is used to associate a key with its value (converted to JSON via toJSON). This allows us to easily build the JSON structure required for the API request.

When we receive a response from the API, it will be in JSON format. Using the FromJSON instance for OpenAIResponse, we can automatically decode the response body back into a Haskell value:

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

If the response JSON matches the structure of OpenAIResponse, decode will return Just OpenAIResponse; otherwise, it will return Nothing. This makes decoding responses safe and efficient, as we can handle the failure case when the JSON doesn’t match.

The OpenAIResponse type models the response from OpenAI’s API:

data OpenAIResponse = OpenAIResponse

  { id :: Text

  , object :: Text

  , created :: Int

  , model :: Text

  , choices :: [Choice]

  , usage :: Maybe Usage

  } deriving (Show, Generic)

instance ToJSON OpenAIResponse

instance FromJSON OpenAIResponse

Again, by deriving Generic, we can easily generate ToJSON and FromJSON instances. This allows us to seamlessly convert the entire response into a Haskell structure that we can work with in our application.

Conclusion on aeson

The aeson library provides a powerful and flexible mechanism for working with JSON in Haskell. By deriving ToJSON and FromJSON, we can almost always rely on automatic, type-safe conversions between Haskell data types and JSON. When needed, we can customize the serialization/deserialization process to fit specific requirements, such as renaming fields or handling optional values.

For our OpenAI interface, aeson allows us to effortlessly convert Haskell data (such as messages and options) into valid JSON for API requests and decode the responses back into Haskell types. This keeps our code clean, type-safe, and easy to modify as our API interactions evolve.

I encourage you to read the library documentation and experiment with different APIs to get a hang of it. Hopefully, the description above provides enough for you to start.

Sending API Requests: The chatCompletion Function

The core of our OpenAI interaction revolves around sending messages to the model and processing its response. For this, we define the chatCompletion function, which builds and sends the request to OpenAI’s API.

In the chatCompletion function , we use the http-client and http-conduit libraries to build a POST request and send it to OpenAI’s chat completion endpoint. The request includes

  • The model ID (e.g., “gpt-4o”) determining which model to use

  • The message list, which contains the conversation history

  • The chat options , which control response parameters like streaming, temperature, and maximum tokens

Here’s the full function:

chatCompletion :: Manager -> [Message] -> Text -> ProviderData -> Maybe ChatOptions -> (BS.ByteString -> IO()) -> IO ()

chatCompletion mgr messages modelId provider opts func = do

    let url = chatCompletionURL provider

    let key = providerKey provider

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

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

    httpSink postRequest $ \response -> do

        if statusCode (responseStatus response) /= 200

            then do

                liftIO $ print (responseStatus response)

                liftIO $ print (responseHeaders response)

            else mapM_C func

Let’s break this down:

  • Building the URL and authentication: The chatCompletionURL and providerKey are part of the ProviderData that contains the necessary information to interact with OpenAI . These include the endpoint URL and the authorization token (which we send via the applyBearerAuth function).

  • Building the JSON request: The request is built using a JSON object containing the modelId and the messages. We combine this message object with the ChatOptions using combineObjects, ensuring both are included in the request body. We discussed this in detail in the previous section.

  • Sending the request: Using httpSink, we perform the actual POST request. The response is handled in chunks, allowing us to process streaming results. This is useful when stream is set to True, as the model’s response is streamed in real time.

  • Processing the response: If the API returns a status code other than 200, we log the error (both the status code and the response headers). Otherwise, we pass each chunk of the response to the provided func callback for further processing.

Handling the Streaming Response

When the model responds in a streaming fashion (controlled by the stream option), the response is delivered as chunks of ByteString. We can process these chunks as they arrive by providing a function that handles each chunk, for example:

testChunk :: BS.ByteString -> IO ()

testChunk ch = do

    putStrLn $ unpack ch

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

    print jsonObject

This function decodes each chunk as an OpenAIResponse, allowing us to inspect the intermediate output before the full response is complete. The topic of streams and their handling is a vast and deep area that is well covered by other books and tutorials, so we will not go in detail on how to use the conduit library to work with streams – but I do encourage you to study it similar to aeson. With these two libraries in your “spell book,” you will be able to write high-performance, robust web-related code for any task. Here, we provide only a basic starting point.

Conclusion

We laid a great foundation for our AI chat agent in this chapter by doing initial rough design of the monad transformer stack for the app and writing some code for interacting with OpenAI and the environment. In this chapter’s code, we can test that everything works by executing the following main program (app/Main.hs):

{-# LANGUAGE OverloadedStrings #-}

module Main (main) where

import Init (initConfig)

import StackTypes (findProviderByName)

import Network.HTTP.Client (Manager, newManager)

import Network.HTTP.Client.TLS (tlsManagerSettings)

import LLM.OpenAI (chatCompletion, userMessage, testChunkStreaming)

main :: IO ()

main = do

    settings <- initConfig

    let prov = findProviderByName settings "openai"

    print prov

    manager <- newManager tlsManagerSettings

    chatCompletion manager [userMessage "hi"] "gpt-4o" prov Nothing testChunkStreaming

For now, we do not use our monad transformer stack at all – we will build it out in the next chapter. We just want to check in the good old IO that our OpenAI API interaction code is working. If you set up the OpenAI token correctly, you should see something like the following after running stack build , stack exec bot :

{19:04}~/dev/magicalhaskell/ch09:main ✗ ➭ stack exec bot

ProviderData {providerName = "openai", providerKey = "sk-proj-G4g2bmbFcIkOR1EEdiU2T3BlbkFJvmmBpQwSYxdhyOnf6Vhg", 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}}

Length is: 0

Nothing

{"id":"chatcmpl-ADE6iQUdKNFMlJmmNmhOB6M9ZJLex","object":"chat.completion.chunk","created":1727715856,"model":"gpt-4o-2024-05-13","system_fingerprint":"fp_057232b607","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]}

Length is: 286

Just (OpenAIResponse {id = "chatcmpl-ADE6iQUdKNFMlJmmNmhOB6M9ZJLex", object = "chat.completion.chunk", created = 1727715856, model = "gpt-4o-2024-05-13", choices = [Choice {message = Nothing, delta = Just (DeltaMessage {content = "", tool_calls = Nothing}), index = Just 0, finish_reason = Nothing, logprobs = Nothing}], usage = Nothing})

{"id":"chatcmpl-ADE6iQUdKNFMlJmmNmhOB6M9ZJLex","object":"chat.completion.chunk","created":1727715856,"model":"gpt-4o-2024-05-13","system_fingerprint":"fp_057232b607","choices":[{"index":0,"delta":{"content":"Hello"},"logprobs":null,"finish_reason":null}]}

Length is: 257

Just (OpenAIResponse {id = "chatcmp l-ADE6iQUdKNFMlJmmNmhOB6M9ZJLex", object = "chat.completion.chunk", created = 1727715856, model = "gpt-4o-2024-05-13", choices = [Choice {message = Nothing, delta = Just (DeltaMessage {content = "Hello", tool_calls = Nothing}), index = Just 0, finish_reason = Nothing, logprobs = Nothing}], usage = Nothing})

...

…proving that everything works and we can indeed listen to the streaming response coming back from OpenAI API.

Conclusion

In the next chapter, we will build up our monad transformer stack gradually to make our chat agent nice, useful, scalable, and a good foundation for your further experiments. We will also build a nicer OpenAI API so that we don’t need to deal with separate “chunks.” Then we will also expand the list of possible LLMs and agent functionality to work with and eventually will expand our framework with the web access functionality (in Chapter 11 ).

IMPROVING THE CHAT AGENT EXERCISES

  1. 1.

    Improve the OpenAI stream management function so that it creates a nice response message instead of logging all the meta information.

  2. 2.

    Start building the “State” floor in our monad transformer stack to keep track of the current conversation with the chat agent – keeping message history would be a good starting point.

In this chapter, we've embarked on an exciting journey into the world of AI, specifically focusing on leveraging large language models (LLMs) to build a terminal-based chatbot using Haskell. This endeavor not only introduces us to the practical applications of AI but also deepens our understanding of Haskell's advanced concepts and libraries.

Key takeaways from this chapter include

  • Understanding LLMs and their applications: We explored the capabilities and limitations of LLMs, such as text transformation, generation, and their potential for reasoning through vector embeddings. This foundational knowledge helps us appreciate the power and constraints of AI technologies.

  • Designing a monad transformer stack: We laid the groundwork for our chatbot by designing a monad transformer stack that includes RWS on top of IO, with InputT from the Haskeline library at the top. This design allows us to manage state, configuration, and user interaction effectively.

  • Interfacing with OpenAI’s API: We delved into the practical aspects of interacting with OpenAI’s API, including setting up authentication, sending requests, and handling streaming responses. This involved using Haskell’s aeson library for JSON conversion and http-client for HTTP requests.

  • Leveraging Haskell’s type system: Throughout the chapter, we utilized Haskell’s strong type system to ensure safe and efficient conversions between Haskell types and JSON, demonstrating the power of type safety in real-world applications.

  • Incremental development: We adopted an incremental approach to building our chatbot, starting with basic functionality and gradually expanding it. This method allows us to test and refine each component before moving on to more complex features.

In the next chapter, we'll further develop our chatbot, making it more robust and scalable, and lay the foundation for integrating web access and additional AI functionalities. This will set the stage for creating a comprehensive AI framework that can serve as a powerful tool for both learning and practical applications.

Footnotes

1

Tokens are several symbols – they can be one short English word or parts of bigger words. We could train LLMs based on whole words – but then they wouldn’t learn complex words or nonexistent words so well or based on separate characters – but then there is too much noise. So tokens, such as “un”-“natural,” turned out to be an optimal solution.