ollama-haskell-0.2.0.0: Haskell client for ollama.
Copyright(c) 2025 Tushar Adhatrao
LicenseMIT
MaintainerTushar Adhatrao <[email protected]>
Stabilityexperimental
Safe HaskellNone
LanguageHaskell2010

Data.Ollama.Generate

Description

This module provides functions and types for generating text using an Ollama model. It includes APIs for sending generation requests, both in IO (generate) and monadic (generateM) contexts, with support for streaming and non-streaming responses. The GenerateOps type configures the generation request, allowing customization of the model, prompt, images, format, and other parameters. The defaultGenerateOps provides a convenient starting point for configuration.

The module supports advanced features like Base64-encoded images, custom templates, and model-specific options (e.g., temperature). It also includes validation to ensure required fields are non-empty.

Example:

>>> let ops = defaultGenerateOps { modelName = "gemma3", prompt = "Write a poem." }
>>> generate ops Nothing
Right (GenerateResponse ...)
Synopsis

Generate Texts

generate :: GenerateOps -> Maybe OllamaConfig -> IO (Either OllamaError GenerateResponse) Source #

Generates text using the specified model and configuration.

Validates the GenerateOps configuration and sends a POST request to the "api/generate" endpoint. Supports both streaming and non-streaming responses based on the stream field in GenerateOps. Returns Right with a GenerateResponse on success or Left with an OllamaError on failure.

Example:

>>> let ops = defaultGenerateOps { modelName = "gemma3", prompt = "Write a short poem." }
>>> generate ops Nothing
Right (GenerateResponse ...)

generateM :: MonadIO m => GenerateOps -> Maybe OllamaConfig -> m (Either OllamaError GenerateResponse) Source #

MonadIO version of generate for use in monadic contexts.

Lifts the generate function into a MonadIO context, allowing it to be used in monadic computations.

Example:

>>> import Control.Monad.IO.Class
>>> let ops = defaultGenerateOps { modelName = "gemma3", prompt = "Hello!" }
>>> runReaderT (generateM ops Nothing) someContext
Right (GenerateResponse ...)

Configuration

defaultGenerateOps :: GenerateOps Source #

Default configuration for text generation.

Provides a default GenerateOps with the "gemma3" model and an empty prompt. Other fields are set to Nothing or default values. Can be customized by modifying fields as needed.

Example:

>>> let ops = defaultGenerateOps { modelName = "customModel", prompt = "Hello!" }
>>> generate ops Nothing

data GenerateOps Source #

Configuration for a text generation request.

Constructors

GenerateOps 

Fields

  • modelName :: !Text

    The name of the model to use for generation (e.g., "gemma3").

  • prompt :: !Text

    The prompt text to provide to the model for generating a response.

  • suffix :: Maybe Text

    Optional suffix to append to the generated text (not supported by all models).

  • images :: !(Maybe [Text])

    Optional list of Base64-encoded images to include with the request.

  • format :: !(Maybe Format)

    Optional format specifier for the response (e.g., JSON).

    Since: 0.1.3.0

  • system :: !(Maybe Text)

    Optional system text to include in the generation context.

  • template :: !(Maybe Text)

    Optional template to format the response.

  • stream :: !(Maybe (GenerateResponse -> IO (), IO ()))

    Optional streaming functions: the first handles each response chunk, the second flushes the stream.

  • raw :: !(Maybe Bool)

    Optional flag to return the raw response.

  • keepAlive :: !(Maybe Int)

    Optional override for how long (in minutes) the model stays loaded in memory (default: 5 minutes).

  • options :: !(Maybe ModelOptions)

    Optional model parameters (e.g., temperature) as specified in the Modelfile.

    Since: 0.1.3.0

  • think :: !(Maybe Bool)

    Optional flag to enable thinking mode.

    Since: 0.2.0.0

validateGenerateOps :: GenerateOps -> Either OllamaError GenerateOps Source #

Validates GenerateOps to ensure required fields are non-empty.

Checks that the modelName and prompt fields are not empty. Returns Right with the validated GenerateOps or Left with an OllamaError if validation fails.

Example:

>>> validateGenerateOps defaultGenerateOps
Left (InvalidRequest "Prompt cannot be empty")
--
-- @since 0.2.0.0

Response and Configuration Types

data GenerateResponse Source #

Result type for generate function containing the model's response and meta-information.

Constructors

GenerateResponse 

Fields

data Format Source #

Format specification for the chat output.

Since: 0.1.3.0

Instances

Instances details
ToJSON Format Source # 
Instance details

Defined in Data.Ollama.Common.Types

Show Format Source # 
Instance details

Defined in Data.Ollama.Common.Types

Eq Format Source # 
Instance details

Defined in Data.Ollama.Common.Types

Methods

(==) :: Format -> Format -> Bool #

(/=) :: Format -> Format -> Bool #

data OllamaConfig Source #

Configuration for the Ollama client. Used across all requests to customize behavior such as timeouts, retries, custom HTTP manager, and lifecycle hooks. -- -- @since 0.2.0.0

Constructors

OllamaConfig 

Fields

Instances

Instances details
Generic OllamaConfig Source # 
Instance details

Defined in Data.Ollama.Common.Config

Associated Types

type Rep OllamaConfig 
Instance details

Defined in Data.Ollama.Common.Config

type Rep OllamaConfig = D1 ('MetaData "OllamaConfig" "Data.Ollama.Common.Config" "ollama-haskell-0.2.0.0-FoTQnIMi8UeBjcOZ65CLdd" 'False) (C1 ('MetaCons "OllamaConfig" 'PrefixI 'True) (((S1 ('MetaSel ('Just "hostUrl") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Text) :*: S1 ('MetaSel ('Just "timeout") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Int)) :*: (S1 ('MetaSel ('Just "onModelStart") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe (IO ()))) :*: S1 ('MetaSel ('Just "onModelError") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe (IO ()))))) :*: ((S1 ('MetaSel ('Just "onModelFinish") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe (IO ()))) :*: S1 ('MetaSel ('Just "retryCount") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe Int))) :*: (S1 ('MetaSel ('Just "retryDelay") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe Int)) :*: S1 ('MetaSel ('Just "commonManager") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe Manager))))))
type Rep OllamaConfig Source # 
Instance details

Defined in Data.Ollama.Common.Config

type Rep OllamaConfig = D1 ('MetaData "OllamaConfig" "Data.Ollama.Common.Config" "ollama-haskell-0.2.0.0-FoTQnIMi8UeBjcOZ65CLdd" 'False) (C1 ('MetaCons "OllamaConfig" 'PrefixI 'True) (((S1 ('MetaSel ('Just "hostUrl") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Text) :*: S1 ('MetaSel ('Just "timeout") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 Int)) :*: (S1 ('MetaSel ('Just "onModelStart") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe (IO ()))) :*: S1 ('MetaSel ('Just "onModelError") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe (IO ()))))) :*: ((S1 ('MetaSel ('Just "onModelFinish") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe (IO ()))) :*: S1 ('MetaSel ('Just "retryCount") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe Int))) :*: (S1 ('MetaSel ('Just "retryDelay") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe Int)) :*: S1 ('MetaSel ('Just "commonManager") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 (Maybe Manager))))))

defaultOllamaConfig :: OllamaConfig Source #

A default configuration pointing to localhost:11434 with 90s timeout and no hooks or retry logic.

defaultModelOptions :: ModelOptions Source #

Default model options for API requests.

Provides a default ModelOptions configuration with all fields set to Nothing, suitable as a starting point for customizing model parameters like temperature or token limits.

Example:

>>> let opts = defaultModelOptions { temperature = Just 0.7 }

Error Types

data OllamaError Source #

Represents all possible errors that may occur when using the Ollama client.

Since: 0.2.0.0

Constructors

HttpError HttpException

Low-level HTTP exception (connection failure, etc.)

DecodeError DecodingErrorMessage DecodingFailedValue

Failure to decode a JSON response, includes message and raw value

ApiError Text

Error returned from Ollama's HTTP API

FileError IOException

Error during file operations (e.g., loading an image)

JsonSchemaError String

Mismatch in expected JSON schema or structure

TimeoutError String

Request timed out

InvalidRequest String

Request is malformed or violates input constraints

Instances

Instances details
Exception OllamaError Source # 
Instance details

Defined in Data.Ollama.Common.Error

Generic OllamaError Source # 
Instance details

Defined in Data.Ollama.Common.Error

Associated Types

type Rep OllamaError 
Instance details

Defined in Data.Ollama.Common.Error

Show OllamaError Source # 
Instance details

Defined in Data.Ollama.Common.Error

Eq OllamaError Source # 
Instance details

Defined in Data.Ollama.Common.Error

type Rep OllamaError Source # 
Instance details

Defined in Data.Ollama.Common.Error