ollama-haskell 0.4.2.0 → 0.4.3.0
raw patch · 40 files changed
+2383/−66 lines, 40 filesdep ~aesondep ~basedep ~containersnew-component:exe:ollama-example-autonomous-agentnew-component:exe:ollama-example-structured-derivenew-component:exe:ollama-example-vram-lifecyclenew-component:exe:ollama-example-web-searchPVP ok
version bump matches the API change (PVP)
Dependency ranges changed: aeson, base, containers, text
API changes (from Hackage documentation)
+ Ollama: RegisteredTool :: !Tool -> !Map Text Value -> m (Either Text Value) -> RegisteredTool m
+ Ollama: StructuredResponse :: !a -> !ChatResponse -> StructuredResponse a
+ Ollama: ToolLoopConfig :: !Int -> !Maybe (Int -> Message -> IO ()) -> ToolLoopConfig
+ Ollama: [rtHandler] :: RegisteredTool m -> !Map Text Value -> m (Either Text Value)
+ Ollama: [rtTool] :: RegisteredTool m -> !Tool
+ Ollama: [srRawResponse] :: StructuredResponse a -> !ChatResponse
+ Ollama: [srValue] :: StructuredResponse a -> !a
+ Ollama: [tlcMaxTurns] :: ToolLoopConfig -> !Int
+ Ollama: [tlcOnTurn] :: ToolLoopConfig -> !Maybe (Int -> Message -> IO ())
+ Ollama: accumulateChat :: ChatResponse -> ChatResponse -> ChatResponse
+ Ollama: accumulateChatChunks :: [ChatResponse] -> Either OllamaError ChatResponse
+ Ollama: accumulateChatStream :: MonadUnliftIO m => ConduitT () ChatResponse m () -> m (Either OllamaError ChatResponse)
+ Ollama: accumulateGenerate :: GenerateResponse -> GenerateResponse -> GenerateResponse
+ Ollama: accumulateGenerateChunks :: [GenerateResponse] -> Either OllamaError GenerateResponse
+ Ollama: accumulateGenerateStream :: MonadUnliftIO m => ConduitT () GenerateResponse m () -> m (Either OllamaError GenerateResponse)
+ Ollama: accumulateStream :: MonadUnliftIO m => ([a] -> Either OllamaError a) -> ConduitT () a m () -> m (Either OllamaError a)
+ Ollama: chatStructured :: forall a m. (MonadIO m, FromJSON a, ToSchema a) => OllamaClient -> ChatRequest -> m (Either OllamaError (StructuredResponse a))
+ Ollama: chatWithTools :: MonadIO m => OllamaClient -> ChatRequest -> [RegisteredTool m] -> ToolLoopConfig -> m (Either OllamaError (Message, [Message]))
+ Ollama: data RegisteredTool m
+ Ollama: data StructuredResponse a
+ Ollama: data ToolLoopConfig
+ Ollama: decodeStreamLine :: FromJSON resp => ByteString -> Either OllamaError (Maybe resp)
+ Ollama: defaultToolLoopConfig :: ToolLoopConfig
+ Ollama: findRunningModel :: ModelName -> [RunningModel] -> Maybe RunningModel
+ Ollama: generateStructured :: forall a m. (MonadIO m, FromJSON a, ToSchema a) => OllamaClient -> GenerateRequest -> m (Either OllamaError (a, GenerateResponse))
+ Ollama: getModelVramUsage :: MonadIO m => OllamaClient -> ModelName -> m (Either OllamaError (Maybe Int64))
+ Ollama: isModelRunning :: MonadIO m => OllamaClient -> ModelName -> m (Either OllamaError Bool)
+ Ollama: matchesRunningModel :: ModelName -> RunningModel -> Bool
+ Ollama: newMockClientWithConfig :: MonadIO m => OllamaClientConfig -> ByteString -> m OllamaClient
+ Ollama: preloadModel :: MonadIO m => OllamaClient -> ModelName -> Maybe Duration -> m (Either OllamaError ())
+ Ollama: preloadModelWith :: MonadIO m => OllamaClient -> ModelName -> Maybe Text -> m (Either OllamaError ())
+ Ollama: unloadModel :: MonadIO m => OllamaClient -> ModelName -> m (Either OllamaError ())
+ Ollama.API.Chat: StructuredResponse :: !a -> !ChatResponse -> StructuredResponse a
+ Ollama.API.Chat: [srRawResponse] :: StructuredResponse a -> !ChatResponse
+ Ollama.API.Chat: [srValue] :: StructuredResponse a -> !a
+ Ollama.API.Chat: accumulateChat :: ChatResponse -> ChatResponse -> ChatResponse
+ Ollama.API.Chat: accumulateChatChunks :: [ChatResponse] -> Either OllamaError ChatResponse
+ Ollama.API.Chat: accumulateChatStream :: MonadUnliftIO m => ConduitT () ChatResponse m () -> m (Either OllamaError ChatResponse)
+ Ollama.API.Chat: chatStructured :: forall a m. (MonadIO m, FromJSON a, ToSchema a) => OllamaClient -> ChatRequest -> m (Either OllamaError (StructuredResponse a))
+ Ollama.API.Chat: data StructuredResponse a
+ Ollama.API.Chat: instance Data.Aeson.Types.FromJSON.FromJSON a => Data.Aeson.Types.FromJSON.FromJSON (Ollama.API.Chat.StructuredResponse a)
+ Ollama.API.Chat: instance Data.Aeson.Types.ToJSON.ToJSON a => Data.Aeson.Types.ToJSON.ToJSON (Ollama.API.Chat.StructuredResponse a)
+ Ollama.API.Chat: instance GHC.Classes.Eq a => GHC.Classes.Eq (Ollama.API.Chat.StructuredResponse a)
+ Ollama.API.Chat: instance GHC.Generics.Generic (Ollama.API.Chat.StructuredResponse a)
+ Ollama.API.Chat: instance GHC.Show.Show a => GHC.Show.Show (Ollama.API.Chat.StructuredResponse a)
+ Ollama.API.Generate: accumulateGenerate :: GenerateResponse -> GenerateResponse -> GenerateResponse
+ Ollama.API.Generate: accumulateGenerateChunks :: [GenerateResponse] -> Either OllamaError GenerateResponse
+ Ollama.API.Generate: accumulateGenerateStream :: MonadUnliftIO m => ConduitT () GenerateResponse m () -> m (Either OllamaError GenerateResponse)
+ Ollama.API.Generate: generateStructured :: forall a m. (MonadIO m, FromJSON a, ToSchema a) => OllamaClient -> GenerateRequest -> m (Either OllamaError (a, GenerateResponse))
+ Ollama.API.Models: preloadModel :: MonadIO m => OllamaClient -> ModelName -> Maybe Duration -> m (Either OllamaError ())
+ Ollama.API.Models: preloadModelWith :: MonadIO m => OllamaClient -> ModelName -> Maybe Text -> m (Either OllamaError ())
+ Ollama.API.Models: unloadModel :: MonadIO m => OllamaClient -> ModelName -> m (Either OllamaError ())
+ Ollama.API.Ps: findRunningModel :: ModelName -> [RunningModel] -> Maybe RunningModel
+ Ollama.API.Ps: getModelVramUsage :: MonadIO m => OllamaClient -> ModelName -> m (Either OllamaError (Maybe Int64))
+ Ollama.API.Ps: isModelRunning :: MonadIO m => OllamaClient -> ModelName -> m (Either OllamaError Bool)
+ Ollama.API.Ps: matchesRunningModel :: ModelName -> RunningModel -> Bool
+ Ollama.API.WebSearch: SearchResult :: !Text -> !Text -> !Text -> SearchResult
+ Ollama.API.WebSearch: WebFetchRequest :: Text -> WebFetchRequest
+ Ollama.API.WebSearch: WebFetchResponse :: !Text -> !Text -> WebFetchResponse
+ Ollama.API.WebSearch: WebSearchRequest :: !Text -> !Maybe Int -> WebSearchRequest
+ Ollama.API.WebSearch: WebSearchResponse :: [SearchResult] -> WebSearchResponse
+ Ollama.API.WebSearch: [srContent] :: SearchResult -> !Text
+ Ollama.API.WebSearch: [srTitle] :: SearchResult -> !Text
+ Ollama.API.WebSearch: [srUrl] :: SearchResult -> !Text
+ Ollama.API.WebSearch: [wfrContent] :: WebFetchResponse -> !Text
+ Ollama.API.WebSearch: [wfrTitle] :: WebFetchResponse -> !Text
+ Ollama.API.WebSearch: [wfrUrl] :: WebFetchRequest -> Text
+ Ollama.API.WebSearch: [wsResults] :: WebSearchResponse -> [SearchResult]
+ Ollama.API.WebSearch: [wsrMaxResults] :: WebSearchRequest -> !Maybe Int
+ Ollama.API.WebSearch: [wsrQuery] :: WebSearchRequest -> !Text
+ Ollama.API.WebSearch: data SearchResult
+ Ollama.API.WebSearch: data WebFetchResponse
+ Ollama.API.WebSearch: data WebSearchRequest
+ Ollama.API.WebSearch: instance Data.Aeson.Types.FromJSON.FromJSON Ollama.API.WebSearch.SearchResult
+ Ollama.API.WebSearch: instance Data.Aeson.Types.FromJSON.FromJSON Ollama.API.WebSearch.WebFetchRequest
+ Ollama.API.WebSearch: instance Data.Aeson.Types.FromJSON.FromJSON Ollama.API.WebSearch.WebFetchResponse
+ Ollama.API.WebSearch: instance Data.Aeson.Types.FromJSON.FromJSON Ollama.API.WebSearch.WebSearchRequest
+ Ollama.API.WebSearch: instance Data.Aeson.Types.FromJSON.FromJSON Ollama.API.WebSearch.WebSearchResponse
+ Ollama.API.WebSearch: instance Data.Aeson.Types.ToJSON.ToJSON Ollama.API.WebSearch.SearchResult
+ Ollama.API.WebSearch: instance Data.Aeson.Types.ToJSON.ToJSON Ollama.API.WebSearch.WebFetchRequest
+ Ollama.API.WebSearch: instance Data.Aeson.Types.ToJSON.ToJSON Ollama.API.WebSearch.WebFetchResponse
+ Ollama.API.WebSearch: instance Data.Aeson.Types.ToJSON.ToJSON Ollama.API.WebSearch.WebSearchRequest
+ Ollama.API.WebSearch: instance Data.Aeson.Types.ToJSON.ToJSON Ollama.API.WebSearch.WebSearchResponse
+ Ollama.API.WebSearch: instance GHC.Classes.Eq Ollama.API.WebSearch.SearchResult
+ Ollama.API.WebSearch: instance GHC.Classes.Eq Ollama.API.WebSearch.WebFetchRequest
+ Ollama.API.WebSearch: instance GHC.Classes.Eq Ollama.API.WebSearch.WebFetchResponse
+ Ollama.API.WebSearch: instance GHC.Classes.Eq Ollama.API.WebSearch.WebSearchRequest
+ Ollama.API.WebSearch: instance GHC.Classes.Eq Ollama.API.WebSearch.WebSearchResponse
+ Ollama.API.WebSearch: instance GHC.Generics.Generic Ollama.API.WebSearch.SearchResult
+ Ollama.API.WebSearch: instance GHC.Generics.Generic Ollama.API.WebSearch.WebFetchRequest
+ Ollama.API.WebSearch: instance GHC.Generics.Generic Ollama.API.WebSearch.WebFetchResponse
+ Ollama.API.WebSearch: instance GHC.Generics.Generic Ollama.API.WebSearch.WebSearchRequest
+ Ollama.API.WebSearch: instance GHC.Generics.Generic Ollama.API.WebSearch.WebSearchResponse
+ Ollama.API.WebSearch: instance GHC.Show.Show Ollama.API.WebSearch.SearchResult
+ Ollama.API.WebSearch: instance GHC.Show.Show Ollama.API.WebSearch.WebFetchRequest
+ Ollama.API.WebSearch: instance GHC.Show.Show Ollama.API.WebSearch.WebFetchResponse
+ Ollama.API.WebSearch: instance GHC.Show.Show Ollama.API.WebSearch.WebSearchRequest
+ Ollama.API.WebSearch: instance GHC.Show.Show Ollama.API.WebSearch.WebSearchResponse
+ Ollama.API.WebSearch: newtype WebFetchRequest
+ Ollama.API.WebSearch: newtype WebSearchResponse
+ Ollama.API.WebSearch: webFetch :: MonadIO m => OllamaClient -> WebFetchRequest -> m (Either OllamaError WebFetchResponse)
+ Ollama.API.WebSearch: webFetchRequest :: Text -> WebFetchRequest
+ Ollama.API.WebSearch: webFetchSimple :: MonadIO m => OllamaClient -> Text -> m (Either OllamaError Text)
+ Ollama.API.WebSearch: webFetchTool :: Tool
+ Ollama.API.WebSearch: webSearch :: MonadIO m => OllamaClient -> WebSearchRequest -> m (Either OllamaError WebSearchResponse)
+ Ollama.API.WebSearch: webSearchRequest :: Text -> WebSearchRequest
+ Ollama.API.WebSearch: webSearchSimple :: MonadIO m => OllamaClient -> Text -> m (Either OllamaError [SearchResult])
+ Ollama.API.WebSearch: webSearchTool :: Tool
+ Ollama.Conversation: RegisteredTool :: !Tool -> !Map Text Value -> m (Either Text Value) -> RegisteredTool m
+ Ollama.Conversation: ToolLoopConfig :: !Int -> !Maybe (Int -> Message -> IO ()) -> ToolLoopConfig
+ Ollama.Conversation: [rtHandler] :: RegisteredTool m -> !Map Text Value -> m (Either Text Value)
+ Ollama.Conversation: [rtTool] :: RegisteredTool m -> !Tool
+ Ollama.Conversation: [tlcMaxTurns] :: ToolLoopConfig -> !Int
+ Ollama.Conversation: [tlcOnTurn] :: ToolLoopConfig -> !Maybe (Int -> Message -> IO ())
+ Ollama.Conversation: chatWithTools :: MonadIO m => OllamaClient -> ChatRequest -> [RegisteredTool m] -> ToolLoopConfig -> m (Either OllamaError (Message, [Message]))
+ Ollama.Conversation: data RegisteredTool m
+ Ollama.Conversation: data ToolLoopConfig
+ Ollama.Conversation: defaultToolLoopConfig :: ToolLoopConfig
+ Ollama.Streaming: accumulateStream :: MonadUnliftIO m => ([a] -> Either OllamaError a) -> ConduitT () a m () -> m (Either OllamaError a)
+ Ollama.Streaming: decodeStreamLine :: FromJSON resp => ByteString -> Either OllamaError (Maybe resp)
+ Ollama.Testing: mockRunningModelsResponse :: [(ModelName, Int64)] -> RunningModelsResponse
+ Ollama.Testing: newMockClientRecording :: MonadIO m => ByteString -> m (OllamaClient, IO ByteString)
+ Ollama.Testing: newMockClientSequence :: MonadIO m => [ByteString] -> m OllamaClient
+ Ollama.Testing: newMockClientWithConfig :: MonadIO m => OllamaClientConfig -> ByteString -> m OllamaClient
+ Ollama.Testing: newMockClientWithStatus :: MonadIO m => Int -> ByteString -> m OllamaClient
Files
- CHANGELOG.md +44/−0
- README.md +7/−2
- examples/AutonomousAgent.hs +63/−0
- examples/BasicChat.hs +1/−1
- examples/ConversationStore.hs +15/−3
- examples/Embeddings.hs +3/−1
- examples/GenerateText.hs +1/−1
- examples/Logprobs.hs +1/−1
- examples/MCPBridge.hs +2/−2
- examples/MockTesting.hs +2/−2
- examples/ModelLifecycle.hs +2/−1
- examples/ModelManagement.hs +21/−4
- examples/StructuredDerive.hs +59/−0
- examples/SystemOne.hs +2/−2
- examples/Thinking.hs +1/−1
- examples/ToolCalling.hs +4/−4
- examples/Vision.hs +1/−1
- examples/VramLifecycle.hs +59/−0
- examples/WebSearch.hs +38/−0
- ollama-haskell.cabal +49/−1
- src/Ollama.hs +27/−0
- src/Ollama/API/Chat.hs +127/−5
- src/Ollama/API/Generate.hs +97/−4
- src/Ollama/API/Models.hs +62/−2
- src/Ollama/API/Ps.hs +60/−0
- src/Ollama/API/WebSearch.hs +288/−0
- src/Ollama/Client/Internal.hs +68/−19
- src/Ollama/Conversation.hs +124/−2
- src/Ollama/Streaming.hs +23/−1
- src/Ollama/Testing.hs +139/−6
- test/Main.hs +16/−0
- test/Test/Ollama/Property/Arbitrary.hs +121/−0
- test/Test/Ollama/Property/ModelLifecycle.hs +36/−0
- test/Test/Ollama/Property/Streaming.hs +49/−0
- test/Test/Ollama/Property/StructuredAndTools.hs +59/−0
- test/Test/Ollama/Property/WebSearch.hs +23/−0
- test/Test/Ollama/Unit/ModelLifecycle.hs +92/−0
- test/Test/Ollama/Unit/Streaming.hs +247/−0
- test/Test/Ollama/Unit/StructuredAndTools.hs +237/−0
- test/Test/Ollama/Unit/WebSearch.hs +113/−0
CHANGELOG.md view
@@ -4,6 +4,50 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [PVP (Haskell Package Versioning Policy)](https://pvp.haskell.org/). +## [0.4.3.0] - 2026-11-14++### Added+- **Ollama Cloud Web Grounding (`Ollama.API.WebSearch`)**:+ - Native client support for Ollama Cloud's live internet search (`POST /api/web_search`) and web extraction (`POST /api/web_fetch`) APIs, enabling real-time grounding for local reasoning models.+ - Domain types: `WebSearchRequest`, `SearchResult`, `WebSearchResponse`, `WebFetchRequest`, and `WebFetchResponse`.+ - Ergonomic functions: `webSearch`, `webSearchSimple`, `webFetch`, and `webFetchSimple`.+ - Pre-packaged tool definitions: `webSearchTool` and `webFetchTool` ready for autonomous tool-calling agents.+ - Re-exported all web search types and functions from `Ollama`.+- **Model Lifecycle & GPU VRAM Management (`Ollama.API.Models`, `Ollama.API.Ps`)**:+ - Added `unloadModel :: (MonadIO m) => OllamaClient -> ModelName -> m (Either OllamaError ())` to evict models and immediately reclaim GPU memory (`keep_alive = "0"`).+ - Added `preloadModel :: (MonadIO m) => OllamaClient -> ModelName -> Maybe Duration -> m (Either OllamaError ())` to warm up models before time-sensitive inference without generating response tokens.+ - Added `isModelRunning :: (MonadIO m) => OllamaClient -> ModelName -> m (Either OllamaError Bool)` in `Ollama.API.Ps` to inspect active VRAM residency.+ - Added `getModelVramUsage :: (MonadIO m) => OllamaClient -> ModelName -> m (Either OllamaError (Maybe Int64))` in `Ollama.API.Ps` to query exact active GPU VRAM footprint in bytes.+ - Re-exported all lifecycle helpers from `Ollama`.+- **Type-Safe Structured Output Samplers (`Ollama.API.Chat`, `Ollama.API.Generate`)**:+ - Added `chatStructured :: (MonadIO m, FromJSON a, ToSchema a) => OllamaClient -> ChatRequest -> m (Either OllamaError (StructuredResponse a))` to enforce compile-time JSON Schema derivation (`formatFor @a`) and automatically parse model responses into typed Haskell data types.+ - Added `generateStructured :: (MonadIO m, FromJSON a, ToSchema a) => OllamaClient -> GenerateRequest -> m (Either OllamaError (a, GenerateResponse))` for completion endpoints.+ - Added `data StructuredResponse a = StructuredResponse { srValue :: !a, srRawResponse :: !ChatResponse }` preserving both parsed output and full response metadata.+ - Re-exported structured output types and functions from `Ollama`.+- **Autonomous Multi-Turn Tool Execution Loop (`Ollama.Conversation`)**:+ - Added `chatWithTools :: (MonadIO m) => OllamaClient -> ChatRequest -> [RegisteredTool m] -> ToolLoopConfig -> m (Either OllamaError (Message, [Message]))` to orchestrate multi-turn tool calling workflows autonomously.+ - Added `RegisteredTool m` bundling a `Tool` definition with its execution handler `Map Text Value -> m (Either Text Value)`.+ - Added `ToolLoopConfig` and `defaultToolLoopConfig` with configurable recursion limits (`tlcMaxTurns`) and per-turn callbacks (`tlcOnTurn`).+ - Supports parallel tool execution in a single assistant turn and correlation with `toolResultMessageWithId`.+ - Re-exported all tool loop types and functions from `Ollama`.+- **Stream Accumulators (`Ollama.API.Chat`, `Ollama.API.Generate`)**:+ - Added pure chunk stream accumulators `accumulateChat` and `accumulateChatChunks` to combine partial streaming `ChatResponse` chunks into a single aggregated `ChatResponse`.+ - Added pure chunk stream accumulators `accumulateGenerate` and `accumulateGenerateChunks` to combine partial `GenerateResponse` chunks.+ - Re-exported stream accumulators from `Ollama`.+- **Testing Infrastructure (`Ollama.Testing`)**:+ - Added `newMockClientSequence :: (MonadIO m) => [ByteString] -> m OllamaClient` for deterministic unit testing of sequential multi-turn conversational agents.+- **Runnable Examples**:+ - Added `examples/AutonomousAgent.hs` (`ollama-example-autonomous-agent`).+ - Added `examples/StructuredDerive.hs` (`ollama-example-structured-derive`).+ - Added `examples/WebSearch.hs` (`ollama-example-web-search`).+ - Added `examples/VramLifecycle.hs` (`ollama-example-vram-lifecycle`).++### Fixed+- **NDJSON Stream Error Detection & Exception Propagation (`Ollama.Client.Internal`)**:+ - Fixed silent drop of malformed chunks or server error payloads (`{"error": "..."}`) in streaming conduit pipeline. Stream errors and mid-stream decode failures now immediately produce typed `StreamError` or `DecodeError` rather than silently ending the stream.++---+ ## [0.4.2.0] - 2026-10-25 ### Added
README.md view
@@ -17,6 +17,11 @@ - **Function / Tool Calling**: Full support for tool definitions (`Tool`), tool calls (`ToolCall`), and execution results (`toolResultMessage`). - **Thinking Models & Logprobs**: Native support for reasoning models (`Think` / `ThinkingLevel` with custom model-defined levels) and token log probabilities (`Logprob` / `TokenLogprob`). - **Environment & Auth Integration**: Robust URL normalization for `OLLAMA_HOST` and bearer token support for `OLLAMA_API_KEY`.+- **Type-Safe Structured Output Samplers**: High-level `chatStructured` and `generateStructured` enforcing JSON Schemas at the sampler level via `ToSchema` and automatically decoding responses into typed data types with typed `DecodeError` on failure.+- **Autonomous Multi-Turn Tool Execution**: Autonomous `chatWithTools` runner executing registered Haskell tool functions, supporting parallel tool calls, tool ID correlation, recursion limits, and per-turn callbacks.+- **Ollama Cloud Web Grounding**: Live web search (`webSearch`) and web content extraction (`webFetch`) via Ollama Cloud (`POST /api/web_search`, `POST /api/web_fetch`).+- **GPU VRAM & Model Lifecycle**: Explicit `preloadModel`, `unloadModel`, and GPU diagnostics (`isModelRunning`, `getModelVramUsage`).+- **First-Class Streaming & Accumulators**: `conduit`-based response streaming with robust error propagation (`StreamError`, `DecodeError`) and pure accumulators (`accumulateChat`, `accumulateGenerate`). - **Configurable Resilience**: Flexible retry policies (`NoRetry`, `ConstantRetry`, `ExponentialRetry`), custom timeouts, lifecycle callbacks, and structured logging. - **Conversation Store**: Transactional STM-backed `InMemoryStore` and `ConversationStore` typeclass for managing multi-turn chat sessions. - **SDK Comparison Matrix**: Detailed feature comparison against Python, JS/TS, and Go SDKs in [COMPARISON.md](docs/comparison.markdown).@@ -30,14 +35,14 @@ ```cabal build-depends: base >= 4.17 && < 5- , ollama-haskell >= 0.4.2.0+ , ollama-haskell >= 0.4.3.0 ``` Or using Stack in `package.yaml`: ```yaml dependencies:- - ollama-haskell >= 0.4.2.0+ - ollama-haskell >= 0.4.3.0 ``` ---
+ examples/AutonomousAgent.hs view
@@ -0,0 +1,63 @@+module Main (main) where++import Data.Aeson (Value (Number, String))+import Data.List.NonEmpty (NonEmpty ((:|)))+import Data.Map.Strict qualified as Map+import Data.Text qualified as T+import Ollama++-- | Calculator tool adding two numbers+calculatorTool :: RegisteredTool IO+calculatorTool =+ RegisteredTool+ { rtTool =+ toolDef+ "calculator"+ "Add two numbers together"+ ( objectParams+ [("a", numberParam (Just "First number")), ("b", numberParam (Just "Second number"))]+ ["a", "b"]+ )+ , rtHandler = \args -> case (Map.lookup "a" args, Map.lookup "b" args) of+ (Just (Number a), Just (Number b)) -> pure $ Right (Number (a + b))+ _ -> pure $ Left "Invalid numeric arguments"+ }++-- | Weather report tool+weatherTool :: RegisteredTool IO+weatherTool =+ RegisteredTool+ { rtTool =+ toolDef+ "get_weather"+ "Get current temperature and conditions for a city"+ (objectParams [("city", stringParam (Just "Name of the city"))] ["city"])+ , rtHandler = \args -> case Map.lookup "city" args of+ Just (String city) -> pure $ Right (String (city <> ": 22°C, Sunny with light breeze"))+ _ -> pure $ Left "City parameter missing"+ }++main :: IO ()+main = do+ client <- defaultClient+ putStrLn "=== Autonomous Agent Tool Loop Demo ==="+ let tools = [calculatorTool, weatherTool]+ prompt = userMessage "What is the weather in Tokyo and what is 137 + 482?"+ req = chatRequest "llama3.2:latest" (prompt :| [])+ cfg =+ defaultToolLoopConfig+ { tlcOnTurn = Just $ \turn msg -> do+ putStrLn $ "--- Turn " <> show turn <> " ---"+ case messageToolCalls msg of+ Just tcs -> putStrLn $ "Model requested " <> show (length tcs) <> " tool calls"+ Nothing -> putStrLn "Model reached final response"+ }++ putStrLn "Executing autonomous tool loop..."+ res <- chatWithTools client req tools cfg+ case res of+ Left err -> putStrLn $ "Error: " <> show err+ Right (finalMsg, history) -> do+ putStrLn "\n=== Final Answer ==="+ putStrLn $ T.unpack (messageContent finalMsg)+ putStrLn $ "\nTotal conversation turns in history: " <> show (length history)
examples/BasicChat.hs view
@@ -1,7 +1,7 @@ module Main (main) where import Data.List.NonEmpty (NonEmpty ((:|)))-import qualified Data.Text.IO as TIO+import Data.Text.IO qualified as TIO import Ollama main :: IO ()
examples/ConversationStore.hs view
@@ -1,6 +1,6 @@ module Main (main) where -import qualified Data.Text as T+import Data.Text qualified as T import Data.Time (getCurrentTime) import Ollama @@ -42,7 +42,17 @@ putStrLn "\n3. Listing conversations (listConversationsInMemory)..." allConvs <- listConversationsInMemory store putStrLn $ "Total active conversations: " <> show (length allConvs)- mapM_ (\c -> putStrLn $ " - ID: " <> T.unpack (conversationId c) <> " | Messages: " <> show (length (messages c)) <> " | Model: " <> show (unModelName (model c))) allConvs+ mapM_+ ( \c ->+ putStrLn $+ " - ID: "+ <> T.unpack (conversationId c)+ <> " | Messages: "+ <> show (length (messages c))+ <> " | Model: "+ <> show (unModelName (model c))+ )+ allConvs putStrLn "\n4. Loading specific conversation (loadConversationInMemory)..." loaded <- loadConversationInMemory store "sess-alpha-1"@@ -50,7 +60,9 @@ Nothing -> putStrLn "Error: failed to load conversation." Just c -> do putStrLn $ "Successfully loaded " <> T.unpack (conversationId c) <> ":"- mapM_ (\m -> putStrLn $ " [" <> show (messageRole m) <> "] " <> T.unpack (messageContent m)) (messages c)+ mapM_+ (\m -> putStrLn $ " [" <> show (messageRole m) <> "] " <> T.unpack (messageContent m))+ (messages c) putStrLn "\n5. Deleting conversation (deleteConversationInMemory)..." _ <- deleteConversationInMemory store "sess-beta-2"
examples/Embeddings.hs view
@@ -1,4 +1,5 @@ {-# OPTIONS_GHC -Wno-deprecations #-}+ module Main (main) where import Ollama@@ -19,7 +20,8 @@ [] -> putStrLn "No vector generated" putStrLn "\n=== Ollama Legacy Embeddings API (/api/embeddings) ==="- let legacyReq = EmbeddingsRequest (ModelName "nomic-embed-text") "Functional programming in Haskell" Nothing Nothing+ let legacyReq =+ EmbeddingsRequest (ModelName "nomic-embed-text") "Functional programming in Haskell" Nothing Nothing legacyRes <- embeddings client legacyReq case legacyRes of Left err -> putStrLn $ "Legacy Error: " <> show err
examples/GenerateText.hs view
@@ -1,6 +1,6 @@ module Main (main) where -import qualified Data.Text.IO as TIO+import Data.Text.IO qualified as TIO import Ollama main :: IO ()
examples/Logprobs.hs view
@@ -1,7 +1,7 @@ module Main (main) where import Data.List.NonEmpty (NonEmpty ((:|)))-import qualified Data.Text as T+import Data.Text qualified as T import Ollama main :: IO ()
examples/MCPBridge.hs view
@@ -1,8 +1,8 @@ module Main (main) where import Data.Aeson (Value (String))-import qualified Data.Map.Strict as Map-import qualified Data.Text as T+import Data.Map.Strict qualified as Map+import Data.Text qualified as T import Ollama main :: IO ()
examples/MockTesting.hs view
@@ -1,9 +1,9 @@ module Main (main) where import Data.Aeson (encode)-import qualified Data.ByteString.Lazy as BSL+import Data.ByteString.Lazy qualified as BSL import Data.List.NonEmpty (NonEmpty ((:|)))-import qualified Data.Text as T+import Data.Text qualified as T import Ollama main :: IO ()
examples/ModelLifecycle.hs view
@@ -10,7 +10,8 @@ customModel = ModelName "haskell-expert:latest" putStrLn "=== 1. Copying Model (copyModel) ==="- putStrLn $ "Copying " <> show (unModelName sourceModel) <> " to " <> show (unModelName destModel) <> "..."+ putStrLn $+ "Copying " <> show (unModelName sourceModel) <> " to " <> show (unModelName destModel) <> "..." copyRes <- copyModel client sourceModel destModel case copyRes of Left err -> putStrLn $ "Copy failed: " <> show err
examples/ModelManagement.hs view
@@ -1,6 +1,6 @@ module Main (main) where -import qualified Data.Text as T+import Data.Text qualified as T import Ollama main :: IO ()@@ -19,11 +19,19 @@ Left err -> putStrLn $ "Error listing models: " <> show err Right (ListResponse ms) -> do putStrLn $ "Found " <> show (length ms) <> " installed models:"- mapM_ (\m -> putStrLn $ " - " <> show (unModelName (miName m)) <> " (" <> show (miSize m `div` 1000000) <> " MB)") ms+ mapM_+ ( \m ->+ putStrLn $+ " - " <> show (unModelName (miName m)) <> " (" <> show (miSize m `div` 1000000) <> " MB)"+ )+ ms case ms of (firstModel : _) -> do- putStrLn $ "\n=== 3. Inspecting Model Details (showModel for " <> show (unModelName (miName firstModel)) <> ") ==="+ putStrLn $+ "\n=== 3. Inspecting Model Details (showModel for "+ <> show (unModelName (miName firstModel))+ <> ") ===" showRes <- showModel client (miName firstModel) case showRes of Left err -> putStrLn $ "Error showing model: " <> show err@@ -38,4 +46,13 @@ Left err -> putStrLn $ "Error listing running models: " <> show err Right (RunningModelsResponse rms) -> do putStrLn $ "Currently active models in VRAM: " <> show (length rms)- mapM_ (\rm -> putStrLn $ " - " <> show (unModelName (rmName rm)) <> " (VRAM: " <> show (rmSizeVram rm `div` 1000000) <> " MB)") rms+ mapM_+ ( \rm ->+ putStrLn $+ " - "+ <> show (unModelName (rmName rm))+ <> " (VRAM: "+ <> show (rmSizeVram rm `div` 1000000)+ <> " MB)"+ )+ rms
+ examples/StructuredDerive.hs view
@@ -0,0 +1,59 @@+module Main (main) where++import Data.Aeson (FromJSON, ToJSON)+import Data.List.NonEmpty (NonEmpty ((:|)))+import Data.Text (Text)+import Data.Text qualified as T+import GHC.Generics (Generic)+import Ollama++data PersonInfo = PersonInfo+ { personName :: !Text+ , personAge :: !Int+ , personOccupation :: !Text+ , personHobbies :: ![Text]+ }+ deriving stock (Show, Eq, Generic)+ deriving anyclass (FromJSON, ToJSON, ToSchema)++data BookSummary = BookSummary+ { bookTitle :: !Text+ , bookAuthor :: !Text+ , bookGenre :: !Text+ , bookRating :: !Double+ }+ deriving stock (Show, Eq, Generic)+ deriving anyclass (FromJSON, ToJSON, ToSchema)++main :: IO ()+main = do+ putStrLn "=== Type-Safe Structured Output Example ==="+ client <- defaultClient+ let mName = ModelName "qwen3.5:2b"++ putStrLn "\n1. chatStructured with Generic ToSchema..."+ let msgs =+ userMessage "Give me details for Alan Turing, age 41, mathematician, loves chess and running." :| []+ req = chatRequest mName msgs+ chatRes <- chatStructured @PersonInfo client req+ case chatRes of+ Left err -> putStrLn $ "Error in chatStructured: " <> show err+ Right (StructuredResponse person _raw) -> do+ putStrLn "Successfully decoded PersonInfo:"+ putStrLn $ " Name: " <> T.unpack (personName person)+ putStrLn $ " Age: " <> show (personAge person)+ putStrLn $ " Occupation: " <> T.unpack (personOccupation person)+ putStrLn $ " Hobbies: " <> show (personHobbies person)++ putStrLn "\n2. generateStructured with Generic ToSchema..."+ let genReq =+ generateRequest mName "Generate details for the book '1984' by George Orwell in dystopian fiction."+ genRes <- generateStructured @BookSummary client genReq+ case genRes of+ Left err -> putStrLn $ "Error in generateStructured: " <> show err+ Right (book, _raw) -> do+ putStrLn "Successfully decoded BookSummary:"+ putStrLn $ " Title: " <> T.unpack (bookTitle book)+ putStrLn $ " Author: " <> T.unpack (bookAuthor book)+ putStrLn $ " Genre: " <> T.unpack (bookGenre book)+ putStrLn $ " Rating: " <> show (bookRating book)
examples/SystemOne.hs view
@@ -1,7 +1,7 @@ module Main (main) where -import qualified Data.Map.Strict as Map-import qualified Data.Text as T+import Data.Map.Strict qualified as Map+import Data.Text qualified as T import Ollama main :: IO ()
examples/Thinking.hs view
@@ -2,7 +2,7 @@ import Data.List.NonEmpty (NonEmpty ((:|))) import Data.Maybe (isJust)-import qualified Data.Text.IO as TIO+import Data.Text.IO qualified as TIO import Ollama main :: IO ()
examples/ToolCalling.hs view
@@ -2,9 +2,9 @@ import Data.Aeson (Value (Number)) import Data.List.NonEmpty (NonEmpty ((:|)))-import qualified Data.Map.Strict as Map-import qualified Data.Scientific as Sci-import qualified Data.Text as T+import Data.Map.Strict qualified as Map+import Data.Scientific qualified as Sci+import Data.Text qualified as T import Ollama -- Define a tool using the ergonomic toolDef and objectParams smart constructors@@ -51,7 +51,7 @@ let result = case (Map.lookup "a" args, Map.lookup "b" args) of (Just (Number a), Just (Number b)) -> let sumVal = a + b- in T.pack (Sci.formatScientific Sci.Fixed Nothing sumVal)+ in T.pack (Sci.formatScientific Sci.Fixed Nothing sumVal) _ -> "Error: invalid arguments" putStrLn $ "Calculated result: " <> T.unpack result
examples/Vision.hs view
@@ -1,7 +1,7 @@ module Main (main) where import Data.List.NonEmpty (NonEmpty ((:|)))-import qualified Data.Text.IO as TIO+import Data.Text.IO qualified as TIO import Ollama main :: IO ()
+ examples/VramLifecycle.hs view
@@ -0,0 +1,59 @@+module Main (main) where++import Data.Text qualified as T+import Ollama++main :: IO ()+main = do+ putStrLn "=== Ollama GPU VRAM & Model Lifecycle Example ==="+ client <- defaultClient+ let targetModel = ModelName "qwen3.5:2b"++ putStrLn $ "\n1. Checking if " <> show (unModelName targetModel) <> " is currently running..."+ runningBefore <- isModelRunning client targetModel+ case runningBefore of+ Left err -> putStrLn $ "Error checking status: " <> show err+ Right isRun -> putStrLn $ "Is model running? " <> show isRun++ putStrLn "\n2. Preloading model into VRAM (preloadModel)..."+ preloadRes <- preloadModel client targetModel (Just (Duration (10 * 60 * 1000000000)))+ case preloadRes of+ Left err -> putStrLn $ "Preload error: " <> show err+ Right () -> putStrLn "Model successfully loaded into VRAM."++ putStrLn "\n3. Inspecting active VRAM footprint (getModelVramUsage)..."+ vramRes <- getModelVramUsage client targetModel+ case vramRes of+ Left err -> putStrLn $ "Error getting VRAM: " <> show err+ Right Nothing -> putStrLn "Model is not active in VRAM."+ Right (Just bytes) ->+ putStrLn $ "Model VRAM usage: " <> show (bytes `div` (1024 * 1024)) <> " MB"++ putStrLn "\n4. Listing all currently active models (/api/ps)..."+ psRes <- listRunning client+ case psRes of+ Left err -> putStrLn $ "Error listing processes: " <> show err+ Right (RunningModelsResponse rms) -> do+ putStrLn $ "Total resident models: " <> show (length rms)+ mapM_+ ( \rm ->+ putStrLn $+ " - "+ <> T.unpack (unModelName (rmName rm))+ <> " | VRAM: "+ <> show (rmSizeVram rm `div` (1024 * 1024))+ <> " MB | Expires at: "+ <> show (rmExpiresAt rm)+ )+ rms++ putStrLn "\n5. Evicting model from VRAM (unloadModel)..."+ unloadRes <- unloadModel client targetModel+ case unloadRes of+ Left err -> putStrLn $ "Unload error: " <> show err+ Right () -> putStrLn "Model successfully unloaded and VRAM freed."++ runningAfter <- isModelRunning client targetModel+ case runningAfter of+ Left err -> putStrLn $ "Error: " <> show err+ Right isRun -> putStrLn $ "Is model still resident? " <> show isRun
+ examples/WebSearch.hs view
@@ -0,0 +1,38 @@+module Main (main) where++import Data.Text qualified as T+import Ollama++main :: IO ()+main = do+ putStrLn "=== Ollama Cloud Web Grounding Example ==="+ client <- defaultClient++ putStrLn "\n1. Web Search (webSearch)..."+ let searchReq = webSearchRequest "Haskell programming language latest release"+ searchRes <- webSearch client searchReq+ case searchRes of+ Left err -> putStrLn $ "Search result (or auth required): " <> show err+ Right (WebSearchResponse results) -> do+ putStrLn $ "Found " <> show (length results) <> " search results:"+ mapM_+ ( \r ->+ putStrLn $+ " - ["+ <> T.unpack (srTitle r)+ <> "] ("+ <> T.unpack (srUrl r)+ <> ")\n "+ <> T.unpack (T.take 120 (srContent r))+ <> "..."+ )+ results++ putStrLn "\n2. Web Fetch (webFetch)..."+ let fetchReq = webFetchRequest "https://www.haskell.org"+ fetchRes <- webFetch client fetchReq+ case fetchRes of+ Left err -> putStrLn $ "Fetch result (or auth required): " <> show err+ Right resp -> do+ putStrLn $ "Fetched Title: " <> T.unpack (wfrTitle resp)+ putStrLn $ "Content snippet: " <> T.unpack (T.take 200 (wfrContent resp)) <> "..."
ollama-haskell.cabal view
@@ -1,6 +1,6 @@ cabal-version: 3.0 name: ollama-haskell-version: 0.4.2.0+version: 0.4.3.0 synopsis: Industry-grade Haskell client for Ollama local LLMs description: A type-safe Haskell client for interacting with@@ -80,6 +80,7 @@ Ollama.API.Ps Ollama.API.Version Ollama.API.SystemOne+ Ollama.API.WebSearch Ollama.Types Ollama.Types.Message Ollama.Types.Tool@@ -126,11 +127,19 @@ Test.Ollama.Unit.Types Test.Ollama.Unit.Error Test.Ollama.Unit.Config+ Test.Ollama.Unit.Streaming+ Test.Ollama.Unit.WebSearch+ Test.Ollama.Unit.ModelLifecycle+ Test.Ollama.Unit.StructuredAndTools Test.Ollama.Unit.SchemaBuilder Test.Ollama.Unit.SchemaDerive Test.Ollama.Unit.Testing Test.Ollama.Property.Arbitrary Test.Ollama.Property.Roundtrip+ Test.Ollama.Property.Streaming+ Test.Ollama.Property.WebSearch+ Test.Ollama.Property.ModelLifecycle+ Test.Ollama.Property.StructuredAndTools Test.Ollama.Golden.Chat Test.Ollama.Golden.Generate Test.Ollama.Golden.Embed@@ -214,6 +223,17 @@ , scientific >= 0.3 && < 0.4 , text +executable ollama-example-autonomous-agent+ import: warnings, lang+ main-is: AutonomousAgent.hs+ hs-source-dirs: examples+ build-depends:+ aeson+ , base+ , containers+ , ollama-haskell+ , text+ executable ollama-example-structured-output import: warnings, lang main-is: StructuredOutput.hs@@ -221,6 +241,34 @@ build-depends: aeson , base+ , ollama-haskell+ , text++executable ollama-example-structured-derive+ import: warnings, lang+ main-is: StructuredDerive.hs+ hs-source-dirs: examples+ build-depends:+ aeson+ , base+ , ollama-haskell+ , text++executable ollama-example-web-search+ import: warnings, lang+ main-is: WebSearch.hs+ hs-source-dirs: examples+ build-depends:+ base+ , ollama-haskell+ , text++executable ollama-example-vram-lifecycle+ import: warnings, lang+ main-is: VramLifecycle.hs+ hs-source-dirs: examples+ build-depends:+ base , ollama-haskell , text
src/Ollama.hs view
@@ -46,7 +46,16 @@ -- ** Chat chat,+ chatStructured,+ StructuredResponse (..),+ chatWithTools,+ RegisteredTool (..),+ ToolLoopConfig (..),+ defaultToolLoopConfig, chatStream,+ accumulateChat,+ accumulateChatChunks,+ accumulateChatStream, ChatRequest (..), ChatResponse (..), chatRequest,@@ -55,7 +64,11 @@ -- ** Generate generate,+ generateStructured, generateStream,+ accumulateGenerate,+ accumulateGenerateChunks,+ accumulateGenerateStream, GenerateRequest (..), GenerateResponse (..), generateRequest,@@ -79,6 +92,9 @@ ShowRequest (..), copyModel, deleteModel,+ unloadModel,+ preloadModel,+ preloadModelWith, ListResponse (..), ModelInfo (..), ModelDetails (..),@@ -112,11 +128,18 @@ -- ** System & Diagnostics getVersion, listRunning,+ isModelRunning,+ getModelVramUsage,+ matchesRunningModel,+ findRunningModel, RunningModelsResponse (..), -- ** System One Decision API module Ollama.API.SystemOne, + -- ** Ollama Cloud Web Grounding+ module Ollama.API.WebSearch,+ -- * Types & Primitives ModelName (..), mkModelName,@@ -201,9 +224,12 @@ HasDone (..), collectStream, foldStream,+ accumulateStream,+ decodeStreamLine, -- * Testing Infrastructure newMockClient,+ newMockClientWithConfig, withMockClient, mockGenerateResponse, mockChatResponse,@@ -235,6 +261,7 @@ import Ollama.API.Ps import Ollama.API.SystemOne import Ollama.API.Version+import Ollama.API.WebSearch import Ollama.Client import Ollama.Client.Config import Ollama.Conversation
src/Ollama/API/Chat.hs view
@@ -13,29 +13,38 @@ module Ollama.API.Chat ( ChatRequest (..), ChatResponse (..),+ StructuredResponse (..), chatRequest, chat,+ chatStructured, chatStream,+ accumulateChat,+ accumulateChatChunks,+ accumulateChatStream, chatEvalTokensPerSecond, chatPromptEvalTokensPerSecond, ) where import Conduit (ConduitT)+import Control.Applicative ((<|>)) import Control.Monad.IO.Class (MonadIO) import Control.Monad.IO.Unlift (MonadUnliftIO) import Data.Aeson+import Data.ByteString.Lazy qualified as BSL import Data.List.NonEmpty (NonEmpty) import Data.Maybe (catMaybes) import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Encoding qualified as TE import Data.Time (UTCTime) import GHC.Generics (Generic) import Ollama.Client (OllamaClient) import Ollama.Client.Internal (request, requestStreaming)-import Ollama.Error (OllamaError)-import Ollama.Streaming (HasDone (..))-import Ollama.Types.Common (Duration, Logprob, ModelName, Think, tokensPerSecond)-import Ollama.Types.Format (Format)-import Ollama.Types.Message (Message)+import Ollama.Error (OllamaError (..))+import Ollama.Streaming (HasDone (..), accumulateStream)+import Ollama.Types.Common (Duration, Logprob, ModelName (..), Think, tokensPerSecond)+import Ollama.Types.Format (Format, ToSchema, formatFor)+import Ollama.Types.Message (Message (..)) import Ollama.Types.Options (ModelOptions) import Ollama.Types.Tool (Tool) @@ -155,6 +164,45 @@ chat :: (MonadIO m) => OllamaClient -> ChatRequest -> m (Either OllamaError ChatResponse) chat client req = request client "POST" "/api/chat" (Just req {chStream = Just False}) +{- | A structured response containing both the typed decoded payload and the raw 'ChatResponse'.++@since 0.4.3.0+-}+data StructuredResponse a = StructuredResponse+ { srValue :: !a+ , srRawResponse :: !ChatResponse+ }+ deriving stock (Eq, Show, Generic)+ deriving anyclass (ToJSON, FromJSON)++{- | Perform a chat completion enforcing a JSON Schema derived from the type parameter @a@ via 'ToSchema',+and automatically decode the assistant message content into @a@.++If the model response fails to decode into @a@, returns 'DecodeError' containing the parse error and raw bytes.++@since 0.4.3.0+-}+chatStructured ::+ forall a m.+ (MonadIO m, FromJSON a, ToSchema a) =>+ OllamaClient ->+ ChatRequest ->+ m (Either OllamaError (StructuredResponse a))+chatStructured client req = do+ let structuredReq = req {chatFormat = Just (formatFor @a), chStream = Just False}+ res <- chat client structuredReq+ pure $ case res of+ Left err -> Left err+ Right raw ->+ case crMessage raw of+ Nothing -> Left (DecodeError "No message returned in chat response" "")+ Just msg ->+ let txt = messageContent msg+ bs = TE.encodeUtf8 txt+ in case eitherDecode (BSL.fromStrict bs) of+ Left parseErr -> Left (DecodeError (T.pack parseErr) bs)+ Right val -> Right (StructuredResponse val raw)+ {- | Streaming chat completion API yielding 'ChatResponse' chunks. @since 1.0.0.0@@ -177,3 +225,77 @@ chatPromptEvalTokensPerSecond :: ChatResponse -> Maybe Double chatPromptEvalTokensPerSecond ChatResponse {..} = tokensPerSecond <$> crPromptEvalCount <*> crPromptEvalDuration++{- | Combine two consecutive 'ChatResponse' chunks into an accumulated response.+Sequential text and thinking tokens are concatenated, tool calls are preserved in order,+and durations and completion flags from the latest chunk are maintained.++@since 0.4.3.0+-}+accumulateChat :: ChatResponse -> ChatResponse -> ChatResponse+accumulateChat r1 r2 =+ r2+ { crModel = if T.null (unModelName (crModel r1)) then crModel r2 else crModel r1+ , crCreatedAt = crCreatedAt r1+ , crMessage = combineMessages (crMessage r1) (crMessage r2)+ , crDone = crDone r1 || crDone r2+ , crDoneReason = crDoneReason r2 <|> crDoneReason r1+ , crTotalDuration = crTotalDuration r2 <|> crTotalDuration r1+ , crLoadDuration = crLoadDuration r2 <|> crLoadDuration r1+ , crPromptEvalCount = crPromptEvalCount r2 <|> crPromptEvalCount r1+ , crPromptEvalDuration = crPromptEvalDuration r2 <|> crPromptEvalDuration r1+ , crEvalCount = crEvalCount r2 <|> crEvalCount r1+ , crEvalDuration = crEvalDuration r2 <|> crEvalDuration r1+ , crLogprobs = combineLogprobs (crLogprobs r1) (crLogprobs r2)+ }+ where+ combineMessages Nothing m2 = m2+ combineMessages m1 Nothing = m1+ combineMessages (Just m1) (Just m2) =+ Just $+ m2+ { messageRole = messageRole m1+ , messageContent = messageContent m1 <> messageContent m2+ , messageImages = combineLists (messageImages m1) (messageImages m2)+ , messageToolCalls = combineLists (messageToolCalls m1) (messageToolCalls m2)+ , messageToolName = messageToolName m2 <|> messageToolName m1+ , messageThinking = combineText (messageThinking m1) (messageThinking m2)+ , messageToolCallId = messageToolCallId m2 <|> messageToolCallId m1+ }++ combineText Nothing t2 = t2+ combineText t1 Nothing = t1+ combineText (Just t1) (Just t2) = Just (t1 <> t2)++ combineLists Nothing l2 = l2+ combineLists l1 Nothing = l1+ combineLists (Just l1) (Just l2) = Just (l1 ++ l2)++ combineLogprobs Nothing lp2 = lp2+ combineLogprobs lp1 Nothing = lp1+ combineLogprobs (Just lp1) (Just lp2) = Just (lp1 ++ lp2)++{- | Accumulate a list of 'ChatResponse' chunks into a single unified 'ChatResponse'.+Returns 'InvalidRequest' if the input list is empty.++@since 0.4.3.0+-}+accumulateChatChunks :: [ChatResponse] -> Either OllamaError ChatResponse+accumulateChatChunks [] = Left (InvalidRequest "Cannot accumulate empty stream of ChatResponse")+accumulateChatChunks (c : cs) = Right (go c cs)+ where+ go acc [] = acc+ go acc (x : xs) =+ let acc' = accumulateChat acc x+ in acc' `seq` go acc' xs++{- | Fold over a streaming chat conduit and accumulate all emitted chunks into a single+final 'ChatResponse'.++@since 0.4.3.0+-}+accumulateChatStream ::+ (MonadUnliftIO m) =>+ ConduitT () ChatResponse m () ->+ m (Either OllamaError ChatResponse)+accumulateChatStream = accumulateStream accumulateChatChunks
src/Ollama/API/Generate.hs view
@@ -15,27 +15,34 @@ GenerateResponse (..), generateRequest, generate,+ generateStructured, generateStream,+ accumulateGenerate,+ accumulateGenerateChunks,+ accumulateGenerateStream, evalTokensPerSecond, promptEvalTokensPerSecond, generateFullText, ) where import Conduit (ConduitT)+import Control.Applicative ((<|>)) import Control.Monad.IO.Class (MonadIO) import Control.Monad.IO.Unlift (MonadUnliftIO) import Data.Aeson+import Data.ByteString.Lazy qualified as BSL import Data.Maybe (catMaybes) import Data.Text (Text) import Data.Text qualified as Text+import Data.Text.Encoding qualified as TE import Data.Time (UTCTime) import GHC.Generics (Generic) import Ollama.Client (OllamaClient) import Ollama.Client.Internal (request, requestStreaming)-import Ollama.Error (OllamaError)-import Ollama.Streaming (HasDone (..))-import Ollama.Types.Common (Base64Image, Duration, Logprob, ModelName, Think, tokensPerSecond)-import Ollama.Types.Format (Format)+import Ollama.Error (OllamaError (..))+import Ollama.Streaming (HasDone (..), accumulateStream)+import Ollama.Types.Common (Base64Image, Duration, Logprob, ModelName (..), Think, tokensPerSecond)+import Ollama.Types.Format (Format, ToSchema, formatFor) import Ollama.Types.Options (ModelOptions) {- | Request payload for text generation completion.@@ -191,6 +198,31 @@ (MonadIO m) => OllamaClient -> GenerateRequest -> m (Either OllamaError GenerateResponse) generate client req = request client "POST" "/api/generate" (Just req {genStream = Just False}) +{- | Perform a text completion enforcing a JSON Schema derived from the type parameter @a@ via 'ToSchema',+and automatically decode the generated response string into @a@.++If the model response fails to decode into @a@, returns 'DecodeError' containing the parse error and raw bytes.++@since 0.4.3.0+-}+generateStructured ::+ forall a m.+ (MonadIO m, FromJSON a, ToSchema a) =>+ OllamaClient ->+ GenerateRequest ->+ m (Either OllamaError (a, GenerateResponse))+generateStructured client req = do+ let structuredReq = req {genFormat = Just (formatFor @a), genStream = Just False}+ res <- generate client structuredReq+ pure $ case res of+ Left err -> Left err+ Right raw ->+ let txt = grResponse raw+ bs = TE.encodeUtf8 txt+ in case eitherDecode (BSL.fromStrict bs) of+ Left parseErr -> Left (DecodeError (Text.pack parseErr) bs)+ Right val -> Right (val, raw)+ {- | Streaming text completion API yielding 'GenerateResponse' chunks. @since 1.0.0.0@@ -229,3 +261,64 @@ | not (Text.null th) && not (Text.null r) -> th <> "\n\n" <> r | not (Text.null th) -> th (_, r) -> r++{- | Combine two consecutive 'GenerateResponse' chunks into an accumulated response.+Sequential text and thinking tokens are concatenated, and context, durations,+and completion flags from the latest chunk are maintained.++@since 0.4.3.0+-}+accumulateGenerate :: GenerateResponse -> GenerateResponse -> GenerateResponse+accumulateGenerate r1 r2 =+ r2+ { grModel = if Text.null (unModelName (grModel r1)) then grModel r2 else grModel r1+ , grCreatedAt = grCreatedAt r1+ , grResponse = grResponse r1 <> grResponse r2+ , grDone = grDone r1 || grDone r2+ , grDoneReason = grDoneReason r2 <|> grDoneReason r1+ , grContext = grContext r2 <|> grContext r1+ , grTotalDuration = grTotalDuration r2 <|> grTotalDuration r1+ , grLoadDuration = grLoadDuration r2 <|> grLoadDuration r1+ , grPromptEvalCount = grPromptEvalCount r2 <|> grPromptEvalCount r1+ , grPromptEvalDuration = grPromptEvalDuration r2 <|> grPromptEvalDuration r1+ , grEvalCount = grEvalCount r2 <|> grEvalCount r1+ , grEvalDuration = grEvalDuration r2 <|> grEvalDuration r1+ , grThinking = combineText (grThinking r1) (grThinking r2)+ , grImage = grImage r2 <|> grImage r1+ , grLogprobs = combineLogprobs (grLogprobs r1) (grLogprobs r2)+ , grCompleted = grCompleted r2 <|> grCompleted r1+ , grTotal = grTotal r2 <|> grTotal r1+ }+ where+ combineText Nothing t2 = t2+ combineText t1 Nothing = t1+ combineText (Just t1) (Just t2) = Just (t1 <> t2)++ combineLogprobs Nothing lp2 = lp2+ combineLogprobs lp1 Nothing = lp1+ combineLogprobs (Just lp1) (Just lp2) = Just (lp1 ++ lp2)++{- | Accumulate a list of 'GenerateResponse' chunks into a single unified 'GenerateResponse'.+Returns 'InvalidRequest' if the input list is empty.++@since 0.4.3.0+-}+accumulateGenerateChunks :: [GenerateResponse] -> Either OllamaError GenerateResponse+accumulateGenerateChunks [] = Left (InvalidRequest "Cannot accumulate empty stream of GenerateResponse")+accumulateGenerateChunks (g : gs) = Right (go g gs)+ where+ go acc [] = acc+ go acc (x : xs) =+ let acc' = accumulateGenerate acc x+ in acc' `seq` go acc' xs++{- | Fold over a streaming text generation conduit and accumulate all emitted chunks into+a single final 'GenerateResponse'.++@since 0.4.3.0+-}+accumulateGenerateStream ::+ (MonadUnliftIO m) =>+ ConduitT () GenerateResponse m () ->+ m (Either OllamaError GenerateResponse)+accumulateGenerateStream = accumulateStream accumulateGenerateChunks
src/Ollama/API/Models.hs view
@@ -29,18 +29,25 @@ -- * Delete deleteModel, DeleteRequest (..),++ -- * Preload & Unload (GPU VRAM Management)+ unloadModel,+ preloadModel,+ preloadModelWith, ) where import Control.Monad.IO.Class (MonadIO) import Data.Aeson import Data.Map.Strict (Map)-import Data.Maybe (catMaybes)+import Data.Maybe (catMaybes, fromMaybe) import Data.Text (Text)+import Data.Text qualified as T import GHC.Generics (Generic)+import Ollama.API.Generate (GenerateRequest (..), generateRequest) import Ollama.Client (OllamaClient) import Ollama.Client.Internal (request) import Ollama.Error (OllamaError)-import Ollama.Types.Common (ModelName)+import Ollama.Types.Common (Duration (..), ModelName) import Ollama.Types.Model (ListResponse (..), ModelDetails (..)) {- | Show model info request payload.@@ -177,3 +184,56 @@ -} deleteModel :: (MonadIO m) => OllamaClient -> ModelName -> m (Either OllamaError ()) deleteModel client model = request client "DELETE" "/api/delete" (Just $ DeleteRequest model)++{- | Unload a model from memory immediately by setting @keep_alive = 0@.+Sends an empty prompt generation request with @keep_alive = Just "0"@.++@since 0.4.3.0+-}+unloadModel ::+ (MonadIO m) =>+ OllamaClient ->+ ModelName ->+ m (Either OllamaError ())+unloadModel client model =+ preloadModelWith client model (Just "0")++{- | Preload a model into memory with an optional keep_alive 'Duration'.+Defaults to 5 minutes (@"5m"@) if 'Nothing' is provided.++@since 0.4.3.0+-}+preloadModel ::+ (MonadIO m) =>+ OllamaClient ->+ ModelName ->+ Maybe Duration ->+ m (Either OllamaError ())+preloadModel client model mbDur =+ preloadModelWith client model (formatDuration <$> mbDur)+ where+ formatDuration (Duration ns) =+ let secs = max 0 (ns `div` 1000000000)+ in T.pack (show secs) <> "s"++{- | Preload a model into memory with an optional keep_alive duration string+(e.g. @"5m"@, @"10m"@, @"-1"@). Defaults to @"5m"@ if 'Nothing' is provided.++@since 0.4.3.0+-}+preloadModelWith ::+ (MonadIO m) =>+ OllamaClient ->+ ModelName ->+ Maybe Text ->+ m (Either OllamaError ())+preloadModelWith client model mbKeepAlive = do+ let keepAliveText = fromMaybe "5m" mbKeepAlive+ req =+ (generateRequest model "")+ { genKeepAlive = Just keepAliveText+ }+ res <- request client "POST" "/api/generate" (Just req)+ pure $ case res of+ Left err -> Left err+ Right (_ :: Value) -> Right ()
src/Ollama/API/Ps.hs view
@@ -14,13 +14,22 @@ listRunning, RunningModelsResponse (..), RunningModel (..),+ isModelRunning,+ getModelVramUsage,+ matchesRunningModel,+ findRunningModel, ) where import Control.Monad.IO.Class (MonadIO) import Data.Aeson (Value)+import Data.Int (Int64)+import Data.List (find)+import Data.Maybe (isJust)+import Data.Text qualified as T import Ollama.Client (OllamaClient) import Ollama.Client.Internal (request) import Ollama.Error (OllamaError)+import Ollama.Types.Common (ModelName (..)) import Ollama.Types.Model (RunningModel (..), RunningModelsResponse (..)) {- | List models currently loaded into memory (@GET /api/ps@).@@ -29,3 +38,54 @@ -} listRunning :: (MonadIO m) => OllamaClient -> m (Either OllamaError RunningModelsResponse) listRunning client = request client "GET" "/api/ps" (Nothing :: Maybe Value)++{- | Check whether a 'ModelName' matches a loaded 'RunningModel'.+Matches against exact name, exact model identifier, or normalized @:latest@ tags.++@since 0.4.3.0+-}+matchesRunningModel :: ModelName -> RunningModel -> Bool+matchesRunningModel target rm =+ rmName rm == target+ || rmModel rm == target+ || unModelName (rmName rm) == targetWithLatest+ || unModelName (rmModel rm) == targetWithLatest+ || (hasLatest target && unModelName (rmName rm) == stripLatest target)+ where+ targetText = unModelName target+ targetWithLatest = if ":" `T.isInfixOf` targetText then targetText else targetText <> ":latest"+ hasLatest m = ":latest" `T.isSuffixOf` unModelName m+ stripLatest m = T.dropEnd 7 (unModelName m)++{- | Pure helper to find a running model by name in a list of loaded running models.++@since 0.4.3.0+-}+findRunningModel :: ModelName -> [RunningModel] -> Maybe RunningModel+findRunningModel target = find (matchesRunningModel target)++{- | Check if a model is currently loaded into memory (@GET /api/ps@).++@since 0.4.3.0+-}+isModelRunning :: (MonadIO m) => OllamaClient -> ModelName -> m (Either OllamaError Bool)+isModelRunning client target = do+ res <- listRunning client+ pure $ case res of+ Left err -> Left err+ Right (RunningModelsResponse models) ->+ Right (isJust (findRunningModel target models))++{- | Retrieve the GPU VRAM usage in bytes for a loaded model (@GET /api/ps@).+Returns 'Nothing' if the model is not currently loaded in memory.++@since 0.4.3.0+-}+getModelVramUsage ::+ (MonadIO m) => OllamaClient -> ModelName -> m (Either OllamaError (Maybe Int64))+getModelVramUsage client target = do+ res <- listRunning client+ pure $ case res of+ Left err -> Left err+ Right (RunningModelsResponse models) ->+ Right (rmSizeVram <$> findRunningModel target models)
+ src/Ollama/API/WebSearch.hs view
@@ -0,0 +1,288 @@+{- |+Module : Ollama.API.WebSearch+Copyright : (c) 2024-2026 Tushar Adhatrao+License : MIT+Maintainer : tusharadhatrao@gmail.com+Stability : stable+Portability : portable++Ollama Cloud Web Grounding endpoints (@https://ollama.com/api/web_search@ and @https://ollama.com/api/web_fetch@).++Enables real-time internet search and page extraction for local models.+Requires an Ollama account and API key set via @OLLAMA_API_KEY@ or 'Ollama.Client.Config.configApiKey'.++@since 0.4.3.0+-}+module Ollama.API.WebSearch (+ -- * Web Search+ WebSearchRequest (..),+ SearchResult (..),+ WebSearchResponse (..),+ webSearchRequest,+ webSearch,+ webSearchSimple,+ webSearchTool,++ -- * Web Fetch+ WebFetchRequest (..),+ WebFetchResponse (..),+ webFetchRequest,+ webFetch,+ webFetchSimple,+ webFetchTool,+) where++import Control.Monad.IO.Class (MonadIO)+import Data.Aeson (+ FromJSON (..),+ ToJSON (..),+ object,+ withObject,+ (.:),+ (.:?),+ (.=),+ )+import Data.Maybe (catMaybes)+import Data.Text (Text)+import Data.Text qualified as T+import GHC.Generics (Generic)+import Ollama.Client (OllamaClient (..))+import Ollama.Client.Config (OllamaClientConfig (..))+import Ollama.Client.Internal (request)+import Ollama.Error (OllamaError (..))+import Ollama.Types.Tool (+ Tool (..),+ intParam,+ objectParams,+ stringParam,+ toolDef,+ )++{- | Request payload for Ollama Cloud Web Search.++@since 0.4.3.0+-}+data WebSearchRequest = WebSearchRequest+ { wsrQuery :: !Text+ , wsrMaxResults :: !(Maybe Int)+ }+ deriving stock (Eq, Show, Generic)++instance ToJSON WebSearchRequest where+ toJSON WebSearchRequest {..} =+ object $+ catMaybes+ [ ("max_results" .=) <$> wsrMaxResults+ , Just ("query" .= wsrQuery)+ ]++instance FromJSON WebSearchRequest where+ parseJSON = withObject "WebSearchRequest" $ \v ->+ WebSearchRequest+ <$> v .: "query"+ <*> v .:? "max_results"++{- | Create a default 'WebSearchRequest' for a search query.++@since 0.4.3.0+-}+webSearchRequest :: Text -> WebSearchRequest+webSearchRequest query = WebSearchRequest query Nothing++{- | Individual search result returned by Ollama Cloud Web Search.++@since 0.4.3.0+-}+data SearchResult = SearchResult+ { srTitle :: !Text+ , srUrl :: !Text+ , srContent :: !Text+ }+ deriving stock (Eq, Show, Generic)++instance FromJSON SearchResult where+ parseJSON = withObject "SearchResult" $ \v ->+ SearchResult+ <$> v .: "title"+ <*> v .: "url"+ <*> v .: "content"++instance ToJSON SearchResult where+ toJSON SearchResult {..} =+ object+ [ "title" .= srTitle+ , "url" .= srUrl+ , "content" .= srContent+ ]++{- | Response payload returned by Ollama Cloud Web Search.++@since 0.4.3.0+-}+newtype WebSearchResponse = WebSearchResponse+ { wsResults :: [SearchResult]+ }+ deriving stock (Eq, Show, Generic)++instance FromJSON WebSearchResponse where+ parseJSON = withObject "WebSearchResponse" $ \v ->+ WebSearchResponse <$> v .: "results"++instance ToJSON WebSearchResponse where+ toJSON WebSearchResponse {..} =+ object ["results" .= wsResults]++{- | Request payload for fetching the content of a web page URL.++@since 0.4.3.0+-}+newtype WebFetchRequest = WebFetchRequest+ { wfrUrl :: Text+ }+ deriving stock (Eq, Show, Generic)++instance ToJSON WebFetchRequest where+ toJSON WebFetchRequest {..} =+ object ["url" .= wfrUrl]++instance FromJSON WebFetchRequest where+ parseJSON = withObject "WebFetchRequest" $ \v ->+ WebFetchRequest <$> v .: "url"++{- | Create a default 'WebFetchRequest' for a web URL.++@since 0.4.3.0+-}+webFetchRequest :: Text -> WebFetchRequest+webFetchRequest = WebFetchRequest++{- | Response payload containing extracted text from a web page.++@since 0.4.3.0+-}+data WebFetchResponse = WebFetchResponse+ { wfrTitle :: !Text+ , wfrContent :: !Text+ }+ deriving stock (Eq, Show, Generic)++instance FromJSON WebFetchResponse where+ parseJSON = withObject "WebFetchResponse" $ \v ->+ WebFetchResponse+ <$> v .: "title"+ <*> v .: "content"++instance ToJSON WebFetchResponse where+ toJSON WebFetchResponse {..} =+ object+ [ "title" .= wfrTitle+ , "content" .= wfrContent+ ]++-- | Resolve the base URL for Ollama Cloud web services.+webBaseUrl :: OllamaClientConfig -> Text+webBaseUrl cfg+ | "127.0.0.1" `T.isInfixOf` base || "localhost" `T.isInfixOf` base =+ "https://ollama.com"+ | otherwise = base+ where+ base = configBaseUrl cfg++{- | Perform a web search using Ollama Cloud.++Requires an API key configured via @OLLAMA_API_KEY@ or 'Ollama.Client.Config.configApiKey'.++@since 0.4.3.0+-}+webSearch ::+ (MonadIO m) =>+ OllamaClient ->+ WebSearchRequest ->+ m (Either OllamaError WebSearchResponse)+webSearch client req =+ case configApiKey (clientConfig client) of+ Nothing ->+ pure $+ Left+ (InvalidRequest "Ollama API key required for web search. Set OLLAMA_API_KEY or configApiKey.")+ Just _ -> do+ let endpoint = webBaseUrl (clientConfig client) <> "/api/web_search"+ request client "POST" endpoint (Just req)++{- | Convenience helper to perform a web search query string and return results directly.++@since 0.4.3.0+-}+webSearchSimple ::+ (MonadIO m) =>+ OllamaClient ->+ Text ->+ m (Either OllamaError [SearchResult])+webSearchSimple client query = do+ res <- webSearch client (webSearchRequest query)+ pure (wsResults <$> res)++{- | Fetch and extract text content from a web page URL.++Requires an API key configured via @OLLAMA_API_KEY@ or 'Ollama.Client.Config.configApiKey'.++@since 0.4.3.0+-}+webFetch ::+ (MonadIO m) =>+ OllamaClient ->+ WebFetchRequest ->+ m (Either OllamaError WebFetchResponse)+webFetch client req =+ case configApiKey (clientConfig client) of+ Nothing ->+ pure $+ Left+ (InvalidRequest "Ollama API key required for web fetch. Set OLLAMA_API_KEY or configApiKey.")+ Just _ -> do+ let endpoint = webBaseUrl (clientConfig client) <> "/api/web_fetch"+ request client "POST" endpoint (Just req)++{- | Convenience helper to fetch a web page URL and return its text content directly.++@since 0.4.3.0+-}+webFetchSimple ::+ (MonadIO m) =>+ OllamaClient ->+ Text ->+ m (Either OllamaError Text)+webFetchSimple client url = do+ res <- webFetch client (webFetchRequest url)+ pure (wfrContent <$> res)++{- | Callable 'Tool' definition for Ollama models to perform web searches.++@since 0.4.3.0+-}+webSearchTool :: Tool+webSearchTool =+ toolDef+ "web_search"+ "Perform a web search using Ollama Cloud to find real-time information."+ ( objectParams+ [ ("query", stringParam (Just "The search query string to look up."))+ , ("max_results", intParam (Just "Optional maximum number of search results to return (1-10)."))+ ]+ ["query"]+ )++{- | Callable 'Tool' definition for Ollama models to fetch web page content.++@since 0.4.3.0+-}+webFetchTool :: Tool+webFetchTool =+ toolDef+ "web_fetch"+ "Fetch and extract text content from a web page URL."+ ( objectParams+ [ ("url", stringParam (Just "The full HTTP/HTTPS URL of the web page to fetch."))+ ]+ ["url"]+ )
src/Ollama/Client/Internal.hs view
@@ -17,6 +17,8 @@ request, requestRaw, requestStreaming,+ decodeStreamLine,+ resolveUrl, ) where import Conduit (@@ -32,7 +34,7 @@ import Control.Monad.IO.Class (MonadIO (liftIO)) import Control.Monad.IO.Unlift (MonadUnliftIO) import Control.Retry qualified as Retry-import Data.Aeson (FromJSON, ToJSON, eitherDecode, encode)+import Data.Aeson (FromJSON (..), ToJSON, Value, eitherDecode, encode, withObject, (.:)) import Data.ByteString (ByteString) import Data.ByteString qualified as BS import Data.ByteString.Lazy qualified as BSL@@ -42,6 +44,8 @@ import Data.Text (Text) import Data.Text qualified as T import Data.Text.Encoding qualified as TE+import Data.Word (Word8)+import GHC.Generics (Generic) import Network.HTTP.Client import Network.HTTP.Types (statusCode) import Ollama.Client (OllamaClient (..))@@ -67,9 +71,7 @@ Maybe req -> m (Either OllamaError resp) request client reqMethod endpoint mbPayload =- liftIO $- withRetry client endpoint $- executeJsonRequest client reqMethod endpoint mbPayload+ liftIO (withRetry client endpoint (executeJsonRequest client reqMethod endpoint mbPayload)) {- | Dispatch a raw (non-JSON) request returning raw bytes. @@ -87,9 +89,7 @@ Maybe ByteString -> m (Either OllamaError ByteString) requestRaw client reqMethod endpoint mbPayload =- liftIO $- withRetry client endpoint $- executeRawRequest client reqMethod endpoint mbPayload+ liftIO (withRetry client endpoint (executeRawRequest client reqMethod endpoint mbPayload)) {- | Dispatch a conduit-based streaming API request. @@ -99,6 +99,47 @@ @since 1.0.0.0 -}++-- | Resolve an endpoint against a base URL, allowing absolute http(s) endpoints.+resolveUrl :: Text -> Text -> String+resolveUrl baseUrl endpoint+ | "http://" `T.isPrefixOf` endpoint || "https://" `T.isPrefixOf` endpoint = T.unpack endpoint+ | otherwise = T.unpack $ baseUrl <> endpoint++-- | Internal error envelope emitted by Ollama on stream failure.+newtype OllamaStreamError = OllamaStreamError+ { streamErrorMessage :: Text+ }+ deriving stock (Eq, Show, Generic)++instance FromJSON OllamaStreamError where+ parseJSON = withObject "OllamaStreamError" $ \v ->+ OllamaStreamError <$> v .: "error"++{- | Parse an individual NDJSON streaming line.++Detects empty lines, explicit server-side error objects (@{\"error\": \"...\"}@),+and valid target responses. Raises 'DecodeError' on malformed non-empty lines.++@since 0.4.3.0+-}+decodeStreamLine :: (FromJSON resp) => ByteString -> Either OllamaError (Maybe resp)+decodeStreamLine bs+ | BS.null (BS.filter (not . isSpaceWord8) bs) = Right Nothing+ | otherwise =+ case eitherDecode (BSL.fromStrict bs) of+ Right val -> Right (Just val)+ Left targetErr ->+ case eitherDecode @OllamaStreamError (BSL.fromStrict bs) of+ Right (OllamaStreamError msg) -> Left (ApiError 500 msg)+ Left _ ->+ case eitherDecode @Value (BSL.fromStrict bs) of+ Left jsonSyntaxErr -> Left (DecodeError (T.pack jsonSyntaxErr) bs)+ Right _ -> Left (DecodeError (T.pack targetErr) bs)++isSpaceWord8 :: Word8 -> Bool+isSpaceWord8 w = w == 32 || w == 9 || w == 10 || w == 13+ requestStreaming :: (MonadUnliftIO m, ToJSON req, FromJSON resp) => OllamaClient ->@@ -106,7 +147,7 @@ req -> ConduitT () resp m () requestStreaming OllamaClient {..} endpoint payload = do- let fullUrl = T.unpack $ configBaseUrl clientConfig <> endpoint+ let fullUrl = resolveUrl (configBaseUrl clientConfig) endpoint cfg = clientConfig initReq <- liftIO $ parseRequest fullUrl let req =@@ -123,17 +164,25 @@ , requestBody = RequestBodyLBS (encode payload) } resp <- liftIO $ responseOpen req clientManager- let bodyReader = responseBody resp- readChunk = liftIO $ brRead bodyReader `catch` \(_ :: HttpException) -> pure BS.empty- source = repeatM readChunk .| takeWhileC (not . BS.null)- (source .| CB.lines .| filterC (not . BS.null) .| parseAndYield)- `catchC` (\(e :: SomeException) -> liftIO (responseClose resp >> throwIO e))- liftIO $ responseClose resp+ let status = statusCode (responseStatus resp)+ if status < 200 || status >= 300+ then do+ bodyChunk <- liftIO $ brRead (responseBody resp)+ liftIO $ responseClose resp+ liftIO $ throwIO $ ApiError status (TE.decodeUtf8 bodyChunk)+ else do+ let bodyReader = responseBody resp+ readChunk = liftIO $ brRead bodyReader `catch` \(_ :: HttpException) -> pure BS.empty+ source = repeatM readChunk .| takeWhileC (not . BS.null)+ (source .| CB.lines .| filterC (not . BS.null) .| parseAndYield)+ `catchC` (\(e :: SomeException) -> liftIO (responseClose resp >> throwIO e))+ liftIO $ responseClose resp where parseAndYield = awaitForever $ \line -> do- case eitherDecode (BSL.fromStrict line) of- Left _err -> pure ()- Right val -> yield val+ case decodeStreamLine line of+ Left err -> liftIO $ throwIO err+ Right Nothing -> pure ()+ Right (Just val) -> yield val -- --------------------------------------------------------------------------- -- Core request execution@@ -148,7 +197,7 @@ Maybe req -> IO (Either OllamaError resp) executeJsonRequest OllamaClient {..} reqMethod endpoint mbPayload = do- let fullUrl = T.unpack $ configBaseUrl clientConfig <> endpoint+ let fullUrl = resolveUrl (configBaseUrl clientConfig) endpoint cfg = clientConfig initReq <- parseRequest fullUrl let timeoutMicro = configTimeout cfg * 1000000@@ -187,7 +236,7 @@ Maybe ByteString -> IO (Either OllamaError ByteString) executeRawRequest OllamaClient {..} reqMethod endpoint mbPayload = do- let fullUrl = T.unpack $ configBaseUrl clientConfig <> endpoint+ let fullUrl = resolveUrl (configBaseUrl clientConfig) endpoint cfg = clientConfig initReq <- parseRequest fullUrl let timeoutMicro = configTimeout cfg * 1000000
src/Ollama/Conversation.hs view
@@ -19,19 +19,35 @@ loadConversationInMemory, listConversationsInMemory, deleteConversationInMemory,++ -- * Autonomous Tool Calling Loop+ RegisteredTool (..),+ ToolLoopConfig (..),+ defaultToolLoopConfig,+ chatWithTools, ) where import Control.Concurrent.STM (TVar, atomically, modifyTVar', newTVarIO, readTVar, readTVarIO)+import Control.Monad (forM) import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.Reader (ReaderT, ask)-import Data.Aeson (FromJSON, ToJSON)+import Data.Aeson (FromJSON, ToJSON, Value, encode)+import Data.ByteString.Lazy qualified as BSL+import Data.Foldable (toList)+import Data.List.NonEmpty (nonEmpty) import Data.Map.Strict (Map) import Data.Map.Strict qualified as Map import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Encoding qualified as TE import Data.Time (UTCTime) import GHC.Generics (Generic)+import Ollama.API.Chat (ChatRequest (..), ChatResponse (..), chat)+import Ollama.Client (OllamaClient)+import Ollama.Error (OllamaError (..)) import Ollama.Types.Common (ModelName)-import Ollama.Types.Message (Message)+import Ollama.Types.Message (Message (..), toolResultMessage, toolResultMessageWithId)+import Ollama.Types.Tool (FunctionDef (..), Tool (..), ToolCall (..), ToolCallFunction (..)) {- | Recorded chat conversation session. @@ -108,3 +124,109 @@ loadConversation cid = ask >>= \store -> loadConversationInMemory store cid listConversations = ask >>= \store -> listConversationsInMemory store deleteConversation cid = ask >>= \store -> deleteConversationInMemory store cid++{- | A registered callable tool binding a 'Tool' definition to a monadic handler.+The handler receives argument key-value pairs decoded from the model's tool call+and returns either an error 'Text' or a serializable 'Value'.++@since 0.4.3.0+-}+data RegisteredTool m = RegisteredTool+ { rtTool :: !Tool+ , rtHandler :: !(Map Text Value -> m (Either Text Value))+ }++{- | Configuration for the multi-turn autonomous tool execution loop.++@since 0.4.3.0+-}+data ToolLoopConfig = ToolLoopConfig+ { tlcMaxTurns :: !Int+ -- ^ Maximum turn iterations permitted before aborting with 'InvalidRequest' (default: 10).+ , tlcOnTurn :: !(Maybe (Int -> Message -> IO ()))+ -- ^ Optional callback invoked on each assistant turn with the turn number and message.+ }++{- | Default configuration for 'chatWithTools' with 10 max turns and no callback.++@since 0.4.3.0+-}+defaultToolLoopConfig :: ToolLoopConfig+defaultToolLoopConfig =+ ToolLoopConfig+ { tlcMaxTurns = 10+ , tlcOnTurn = Nothing+ }++{- | Autonomous multi-turn tool calling execution loop.++Sends a 'ChatRequest' with registered tools attached. Whenever the model responds+with one or more tool calls, 'chatWithTools' evaluates their corresponding handlers,+formats the results as tool role messages (preserving IDs and correlation), appends+them to the message history, and continues the conversation until the model produces+a final assistant answer without tool calls or until 'tlcMaxTurns' is reached.++@since 0.4.3.0+-}+chatWithTools ::+ (MonadIO m) =>+ OllamaClient ->+ ChatRequest ->+ [RegisteredTool m] ->+ ToolLoopConfig ->+ m (Either OllamaError (Message, [Message]))+chatWithTools client initialReq tools config =+ go 1 (toList (chatMessages initialReq))+ where+ toolDefs = map rtTool tools+ toolMap = Map.fromList [(fnName (toolFunction (rtTool t)), rtHandler t) | t <- tools]++ go turn currentMessages+ | turn > tlcMaxTurns config =+ let errMsg = "Maximum tool loop turns (" <> T.pack (show (tlcMaxTurns config)) <> ") exceeded"+ in pure (Left (InvalidRequest errMsg))+ | otherwise = do+ case nonEmpty currentMessages of+ Nothing -> pure $ Left $ InvalidRequest "Cannot chat with empty message list"+ Just neMessages -> do+ let req =+ initialReq+ { chatMessages = neMessages+ , chatTools = Just toolDefs+ , chStream = Just False+ }+ chatRes <- chat client req+ case chatRes of+ Left err -> pure $ Left err+ Right resp ->+ case crMessage resp of+ Nothing ->+ pure $ Left $ DecodeError "No message returned in chat response" ""+ Just assistantMsg -> do+ case tlcOnTurn config of+ Just cb -> liftIO $ cb turn assistantMsg+ Nothing -> pure ()+ case messageToolCalls assistantMsg of+ Nothing ->+ pure $ Right (assistantMsg, currentMessages ++ [assistantMsg])+ Just [] ->+ pure $ Right (assistantMsg, currentMessages ++ [assistantMsg])+ Just toolCalls -> do+ toolResultMsgs <- forM toolCalls $ \tc -> do+ let fn = tcFunction tc+ fName = tcfName fn+ args = tcfArguments fn+ mbCallId = tcId tc+ resultContent <- case Map.lookup fName toolMap of+ Nothing ->+ pure $ "Error: tool '" <> fName <> "' is not available."+ Just handler -> do+ hRes <- handler args+ pure $ case hRes of+ Left errText -> "Error: " <> errText+ Right val -> TE.decodeUtf8 (BSL.toStrict (encode val))+ pure $ case mbCallId of+ Just cid -> toolResultMessageWithId resultContent fName cid+ Nothing -> toolResultMessage resultContent fName+ let updatedMessages = currentMessages ++ [assistantMsg] ++ toolResultMsgs+ go (turn + 1) updatedMessages
src/Ollama/Streaming.hs view
@@ -14,10 +14,15 @@ HasDone (..), collectStream, foldStream,+ accumulateStream,+ decodeStreamLine, ) where import Conduit (ConduitT, foldlC, runConduit, sinkList, (.|))-import Control.Monad.IO.Unlift (MonadUnliftIO)+import Control.Exception (catch)+import Control.Monad.IO.Unlift (MonadUnliftIO, withRunInIO)+import Ollama.Client.Internal (decodeStreamLine)+import Ollama.Error (OllamaError) {- | Typeclass for responses that indicate completion in a stream. @@ -39,3 +44,20 @@ -} foldStream :: (MonadUnliftIO m) => (b -> a -> b) -> b -> ConduitT () a m () -> m b foldStream f acc stream = runConduit $ stream .| foldlC f acc++{- | Accumulate a stream using a chunk accumulation function, catching any 'OllamaError'.++@since 0.4.3.0+-}+accumulateStream ::+ (MonadUnliftIO m) =>+ ([a] -> Either OllamaError a) ->+ ConduitT () a m () ->+ m (Either OllamaError a)+accumulateStream accChunks stream =+ withRunInIO $ \run ->+ ( do+ chunks <- run (collectStream stream)+ pure (accChunks chunks)+ )+ `catch` \(e :: OllamaError) -> pure (Left e)
src/Ollama/Testing.hs view
@@ -12,18 +12,25 @@ -} module Ollama.Testing ( newMockClient,+ newMockClientWithConfig,+ newMockClientRecording,+ newMockClientWithStatus,+ newMockClientSequence, withMockClient, mockGenerateResponse, mockChatResponse, mockEmbedResponse, mockListModelsResponse,+ mockRunningModelsResponse, ) where import Control.Monad.IO.Class (MonadIO (liftIO)) import Control.Monad.IO.Unlift (MonadUnliftIO) import Data.ByteString (ByteString)+import Data.ByteString qualified as BS import Data.ByteString.Char8 qualified as BS8-import Data.IORef (atomicModifyIORef, newIORef)+import Data.IORef (atomicModifyIORef, newIORef, readIORef)+import Data.Int (Int64) import Data.Text (Text) import Data.Time (Day (..), UTCTime (..)) import Network.HTTP.Client (@@ -36,17 +43,28 @@ import Ollama.API.Embed (EmbedResponse (..)) import Ollama.API.Generate (GenerateResponse (..)) import Ollama.Client (OllamaClient (..), closeClient)-import Ollama.Client.Config (defaultConfig)+import Ollama.Client.Config (OllamaClientConfig, defaultConfig) import Ollama.Types.Common (Digest (..), Duration (..), ModelName (..)) import Ollama.Types.Message (assistantMessage)-import Ollama.Types.Model (ListResponse (..), ModelDetails (..), ModelInfo (..))+import Ollama.Types.Model (+ ListResponse (..),+ ModelDetails (..),+ ModelInfo (..),+ RunningModel (..),+ RunningModelsResponse (..),+ ) {- | Construct an 'OllamaClient' that returns mock HTTP response bytes for any request. @since 1.0.0.0 -}-newMockClient :: (MonadIO m) => ByteString -> m OllamaClient-newMockClient bodyBytes = liftIO $ do++{- | Construct an 'OllamaClient' with custom configuration that returns mock HTTP response bytes.++@since 0.4.3.0+-}+newMockClientWithConfig :: (MonadIO m) => OllamaClientConfig -> ByteString -> m OllamaClient+newMockClientWithConfig cfg bodyBytes = liftIO $ do let httpResponse = "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: " <> BS8.pack (show (BS8.length bodyBytes))@@ -63,8 +81,15 @@ (pure ()) settings = defaultManagerSettings {managerRawConnection = pure (\_ _ _ -> mockConn)} mgr <- newManager settings- pure $ OllamaClient mgr defaultConfig True+ pure $ OllamaClient mgr cfg True +{- | Construct an 'OllamaClient' that returns mock HTTP response bytes for any request.++@since 1.0.0.0+-}+newMockClient :: (MonadIO m) => ByteString -> m OllamaClient+newMockClient = newMockClientWithConfig defaultConfig+ {- | Resource bracket helper to create a mock client, execute an action, and close resources. @since 1.0.0.0@@ -76,6 +101,85 @@ closeClient client pure res +{- | Construct an 'OllamaClient' that records all outbound request bytes written to it.+Returns the client and an action to read the captured request bytes.++@since 0.4.3.0+-}+newMockClientRecording :: (MonadIO m) => ByteString -> m (OllamaClient, IO ByteString)+newMockClientRecording bodyBytes = liftIO $ do+ reqRef <- newIORef BS.empty+ let httpResponse =+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: "+ <> BS8.pack (show (BS8.length bodyBytes))+ <> "\r\n\r\n"+ <> bodyBytes+ respRef <- newIORef [httpResponse]+ let mockConn =+ makeConnection+ ( atomicModifyIORef respRef $ \case+ [] -> ([], "")+ (x : xs) -> (xs, x)+ )+ (\written -> atomicModifyIORef reqRef (\acc -> (acc <> written, ())))+ (pure ())+ settings = defaultManagerSettings {managerRawConnection = pure (\_ _ _ -> mockConn)}+ mgr <- newManager settings+ let client = OllamaClient mgr defaultConfig True+ pure (client, readIORef reqRef)++{- | Construct an 'OllamaClient' returning an arbitrary HTTP status code and response body.++@since 0.4.3.0+-}+newMockClientWithStatus :: (MonadIO m) => Int -> ByteString -> m OllamaClient+newMockClientWithStatus code bodyBytes = liftIO $ do+ let httpResponse =+ "HTTP/1.1 "+ <> BS8.pack (show code)+ <> " Error\r\nContent-Type: application/json\r\nContent-Length: "+ <> BS8.pack (show (BS8.length bodyBytes))+ <> "\r\n\r\n"+ <> bodyBytes+ ref <- newIORef [httpResponse]+ let mockConn =+ makeConnection+ ( atomicModifyIORef ref $ \case+ [] -> ([], "")+ (x : xs) -> (xs, x)+ )+ (\_ -> pure ())+ (pure ())+ settings = defaultManagerSettings {managerRawConnection = pure (\_ _ _ -> mockConn)}+ mgr <- newManager settings+ pure $ OllamaClient mgr defaultConfig True++{- | Construct an 'OllamaClient' that returns a sequence of mock HTTP responses in order.+Each inbound request consumes the next response in the sequence.++@since 0.4.3.0+-}+newMockClientSequence :: (MonadIO m) => [ByteString] -> m OllamaClient+newMockClientSequence bodyList = liftIO $ do+ let formatResp b =+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: "+ <> BS8.pack (show (BS8.length b))+ <> "\r\n\r\n"+ <> b+ httpResponses = map formatResp bodyList+ respRef <- newIORef httpResponses+ let mockConn =+ makeConnection+ ( atomicModifyIORef respRef $ \case+ [] -> ([], "")+ (x : xs) -> (xs, x)+ )+ (\_ -> pure ())+ (pure ())+ settings = defaultManagerSettings {managerRawConnection = pure (\_ _ _ -> mockConn)}+ mgr <- newManager settings+ pure $ OllamaClient mgr defaultConfig True+ {- | Construct a mock 'GenerateResponse'. @since 1.0.0.0@@ -164,4 +268,33 @@ , quantizationLevel = "Q4_K_M" } , miCapabilities = Just ["completion"]+ }++{- | Construct a mock 'RunningModelsResponse'.++@since 0.4.3.0+-}+mockRunningModelsResponse :: [(ModelName, Int64)] -> RunningModelsResponse+mockRunningModelsResponse pairs =+ RunningModelsResponse+ { runningModels = map mkRunning pairs+ }+ where+ mkRunning (name, vram) =+ RunningModel+ { rmName = name+ , rmModel = name+ , rmSize = vram+ , rmDigest = Digest "sha256:1234567890abcdef"+ , rmDetails =+ ModelDetails+ { parentModel = Nothing+ , format = "gguf"+ , family = "llama"+ , families = ["llama"]+ , parameterSize = "7B"+ , quantizationLevel = "Q4_K_M"+ }+ , rmExpiresAt = UTCTime (ModifiedJulianDay 60000) 0+ , rmSizeVram = vram }
test/Main.hs view
@@ -4,14 +4,22 @@ import Test.Ollama.Golden.Embed qualified as GoldenEmbed import Test.Ollama.Golden.Generate qualified as GoldenGenerate import Test.Ollama.Golden.Models qualified as GoldenModels+import Test.Ollama.Property.ModelLifecycle qualified as PropertyModelLifecycle import Test.Ollama.Property.Roundtrip qualified as PropertyRoundtrip+import Test.Ollama.Property.Streaming qualified as PropertyStreaming+import Test.Ollama.Property.StructuredAndTools qualified as PropertyStructuredAndTools+import Test.Ollama.Property.WebSearch qualified as PropertyWebSearch import Test.Ollama.Unit.Config qualified as UnitConfig import Test.Ollama.Unit.Error qualified as UnitError import Test.Ollama.Unit.MCP qualified as UnitMCP+import Test.Ollama.Unit.ModelLifecycle qualified as UnitModelLifecycle import Test.Ollama.Unit.SchemaBuilder qualified as UnitSchemaBuilder import Test.Ollama.Unit.SchemaDerive qualified as UnitSchemaDerive+import Test.Ollama.Unit.Streaming qualified as UnitStreaming+import Test.Ollama.Unit.StructuredAndTools qualified as UnitStructuredAndTools import Test.Ollama.Unit.Testing qualified as UnitTesting import Test.Ollama.Unit.Types qualified as UnitTypes+import Test.Ollama.Unit.WebSearch qualified as UnitWebSearch import Test.Tasty tests :: TestTree@@ -21,11 +29,19 @@ [ UnitTypes.tests , UnitError.tests , UnitConfig.tests+ , UnitStreaming.tests+ , UnitWebSearch.tests+ , UnitModelLifecycle.tests+ , UnitStructuredAndTools.tests , UnitSchemaBuilder.tests , UnitSchemaDerive.tests , UnitTesting.testingTests , UnitMCP.tests , PropertyRoundtrip.tests+ , PropertyStreaming.tests+ , PropertyWebSearch.tests+ , PropertyModelLifecycle.tests+ , PropertyStructuredAndTools.tests , GoldenChat.tests , GoldenGenerate.tests , GoldenEmbed.tests
test/Test/Ollama/Property/Arbitrary.hs view
@@ -4,6 +4,7 @@ import Data.Text (Text) import Data.Text qualified as T+import Data.Time (UTCTime (..)) import Ollama import Ollama.Types.Message qualified as M import Test.QuickCheck@@ -54,3 +55,123 @@ instance Arbitrary Format where arbitrary = pure JsonFormat++instance Arbitrary UTCTime where+ arbitrary = pure (UTCTime (toEnum 59000) 0)++instance Arbitrary ToolCallFunction where+ arbitrary = ToolCallFunction <$> genNonEmptyText <*> pure mempty++instance Arbitrary ToolCall where+ arbitrary = ToolCall <$> arbitrary++instance Arbitrary TokenLogprob where+ arbitrary = TokenLogprob <$> genNonEmptyText <*> choose (-10.0, 0.0)++instance Arbitrary Logprob where+ arbitrary = Logprob <$> genNonEmptyText <*> choose (-10.0, 0.0) <*> pure Nothing++instance Arbitrary ChatResponse where+ arbitrary = do+ model <- arbitrary+ time <- arbitrary+ msg <- arbitrary+ done <- arbitrary+ doneReason <- oneof [pure Nothing, Just <$> genNonEmptyText]+ totalDur <- arbitrary+ loadDur <- arbitrary+ promptCount <- arbitrary+ promptDur <- arbitrary+ evalCount <- arbitrary+ evalDur <- arbitrary+ pure $+ ChatResponse+ { crModel = model+ , crCreatedAt = time+ , crMessage = Just msg+ , crDone = done+ , crDoneReason = doneReason+ , crTotalDuration = totalDur+ , crLoadDuration = loadDur+ , crPromptEvalCount = promptCount+ , crPromptEvalDuration = promptDur+ , crEvalCount = evalCount+ , crEvalDuration = evalDur+ , crLogprobs = Nothing+ }++instance Arbitrary GenerateResponse where+ arbitrary = do+ model <- arbitrary+ time <- arbitrary+ resp <- genNonEmptyText+ done <- arbitrary+ doneReason <- oneof [pure Nothing, Just <$> genNonEmptyText]+ context <- arbitrary+ totalDur <- arbitrary+ loadDur <- arbitrary+ promptCount <- arbitrary+ promptDur <- arbitrary+ evalCount <- arbitrary+ evalDur <- arbitrary+ thinking <- oneof [pure Nothing, Just <$> genNonEmptyText]+ pure $+ GenerateResponse+ { grModel = model+ , grCreatedAt = time+ , grResponse = resp+ , grDone = done+ , grDoneReason = doneReason+ , grContext = context+ , grTotalDuration = totalDur+ , grLoadDuration = loadDur+ , grPromptEvalCount = promptCount+ , grPromptEvalDuration = promptDur+ , grEvalCount = evalCount+ , grEvalDuration = evalDur+ , grThinking = thinking+ , grImage = Nothing+ , grLogprobs = Nothing+ , grCompleted = Nothing+ , grTotal = Nothing+ }++instance Arbitrary WebSearchRequest where+ arbitrary = WebSearchRequest <$> genNonEmptyText <*> arbitrary++instance Arbitrary SearchResult where+ arbitrary = SearchResult <$> genNonEmptyText <*> genNonEmptyText <*> genNonEmptyText++instance Arbitrary WebSearchResponse where+ arbitrary = WebSearchResponse <$> arbitrary++instance Arbitrary WebFetchRequest where+ arbitrary = WebFetchRequest <$> genNonEmptyText++instance Arbitrary WebFetchResponse where+ arbitrary = WebFetchResponse <$> genNonEmptyText <*> genNonEmptyText++instance Arbitrary ModelDetails where+ arbitrary = do+ parent <- oneof [pure Nothing, Just <$> genNonEmptyText]+ fmt <- genNonEmptyText+ fam <- genNonEmptyText+ fams <- listOf genNonEmptyText+ paramSize <- genNonEmptyText+ ModelDetails parent fmt fam fams paramSize <$> genNonEmptyText++instance Arbitrary RunningModel where+ arbitrary = do+ name <- arbitrary+ model <- arbitrary+ size <- arbitrary+ digest <- arbitrary+ details <- arbitrary+ expiresAt <- arbitrary+ RunningModel name model size digest details expiresAt <$> arbitrary++instance Arbitrary RunningModelsResponse where+ arbitrary = RunningModelsResponse <$> arbitrary++instance (Arbitrary a) => Arbitrary (StructuredResponse a) where+ arbitrary = StructuredResponse <$> arbitrary <*> arbitrary
+ test/Test/Ollama/Property/ModelLifecycle.hs view
@@ -0,0 +1,36 @@+module Test.Ollama.Property.ModelLifecycle (tests) where++import Data.Aeson (decode, encode)+import Data.Text qualified as T+import Ollama+import Test.Ollama.Property.Arbitrary ()+import Test.Tasty+import Test.Tasty.QuickCheck++tests :: TestTree+tests =+ testGroup+ "Model Lifecycle Property & Algebraic Law Tests"+ [ testProperty "RunningModelsResponse JSON roundtrip: ∀ x. decode (encode x) == Just x" $+ \(resp :: RunningModelsResponse) ->+ decode (encode resp) === Just resp+ , testProperty+ "findRunningModel soundness: ∀ ms target rm. findRunningModel target ms == Just rm ==> matchesRunningModel target rm"+ $ \(models :: [RunningModel]) (target :: ModelName) ->+ case findRunningModel target models of+ Nothing -> property True+ Just rm -> matchesRunningModel target rm === True+ , testProperty "matchesRunningModel reflexivity: ∀ rm. matchesRunningModel (rmName rm) rm" $+ \(rm :: RunningModel) ->+ matchesRunningModel (rmName rm) rm === True+ , testProperty+ "Tag equivalence law: ∀ base models. without colon ==> find (ModelName base) == find (ModelName (base <> \":latest\"))"+ $ \(models :: [RunningModel]) (target :: ModelName) ->+ let cleanBase = T.filter (/= ':') (unModelName target)+ in not (T.null cleanBase) ==>+ let mUntagged = ModelName cleanBase+ mTagged = ModelName (cleanBase <> ":latest")+ foundUntagged = rmName <$> findRunningModel mUntagged models+ foundTagged = rmName <$> findRunningModel mTagged models+ in foundUntagged === foundTagged+ ]
+ test/Test/Ollama/Property/Streaming.hs view
@@ -0,0 +1,49 @@+module Test.Ollama.Property.Streaming (tests) where++import Data.Maybe (fromMaybe)+import Ollama+import Test.Ollama.Property.Arbitrary ()+import Test.Tasty+import Test.Tasty.QuickCheck++tests :: TestTree+tests =+ testGroup+ "Streaming Property & Algebraic Law Tests"+ [ testProperty+ "accumulateChat associativity: ∀ a b c. accumulateChat (accumulateChat a b) c == accumulateChat a (accumulateChat b c)"+ $ \(a :: ChatResponse) (b :: ChatResponse) (c :: ChatResponse) ->+ let lhs = accumulateChat (accumulateChat a b) c+ rhs = accumulateChat a (accumulateChat b c)+ -- Content check+ msgContent res = maybe "" messageContent (crMessage res)+ msgThinking res = fromMaybe "" (messageThinking =<< crMessage res)+ in (msgContent lhs === msgContent rhs)+ .&&. (msgThinking lhs === msgThinking rhs)+ .&&. (crDone lhs === crDone rhs)+ , testProperty+ "accumulateGenerate associativity: ∀ a b c. accumulateGenerate (accumulateGenerate a b) c == accumulateGenerate a (accumulateGenerate b c)"+ $ \(a :: GenerateResponse) (b :: GenerateResponse) (c :: GenerateResponse) ->+ let lhs = accumulateGenerate (accumulateGenerate a b) c+ rhs = accumulateGenerate a (accumulateGenerate b c)+ genThinking res = fromMaybe "" (grThinking res)+ in (grResponse lhs === grResponse rhs)+ .&&. (genThinking lhs === genThinking rhs)+ .&&. (grDone lhs === grDone rhs)+ , testProperty+ "accumulateChatChunks content conservation: ∀ c1 c2. content (acc [c1, c2]) == content c1 <> content c2"+ $ \(c1 :: ChatResponse) (c2 :: ChatResponse) ->+ case accumulateChatChunks [c1, c2] of+ Left _ -> property False+ Right acc ->+ let expected = maybe "" messageContent (crMessage c1) <> maybe "" messageContent (crMessage c2)+ actual = maybe "" messageContent (crMessage acc)+ in actual === expected+ , testProperty+ "accumulateGenerateChunks content conservation: ∀ g1 g2. response (acc [g1, g2]) == response g1 <> response g2"+ $ \(g1 :: GenerateResponse) (g2 :: GenerateResponse) ->+ case accumulateGenerateChunks [g1, g2] of+ Left _ -> property False+ Right acc ->+ grResponse acc === (grResponse g1 <> grResponse g2)+ ]
+ test/Test/Ollama/Property/StructuredAndTools.hs view
@@ -0,0 +1,59 @@+module Test.Ollama.Property.StructuredAndTools (tests) where++import Data.Aeson (FromJSON, ToJSON, decode, encode)+import Data.Map.Strict qualified as Map+import Data.Text (Text)+import GHC.Generics (Generic)+import Ollama+import Ollama.Types.Message qualified as M+import Test.Ollama.Property.Arbitrary ()+import Test.Tasty+import Test.Tasty.QuickCheck++data SampleRecord = SampleRecord+ { sampleKey :: !Text+ , sampleNum :: !Int+ }+ deriving stock (Eq, Show, Generic)+ deriving anyclass (FromJSON, ToJSON, ToSchema)++instance Arbitrary SampleRecord where+ arbitrary = (SampleRecord . unModelName <$> arbitrary) <*> arbitrary++tests :: TestTree+tests =+ testGroup+ "Structured Outputs & Tools Property Tests"+ [ testProperty "StructuredResponse JSON roundtrip: ∀ x. decode (encode x) == Just x" $+ \(sr :: StructuredResponse SampleRecord) ->+ decode (encode sr) === Just sr+ , testProperty "formatFor produces SchemaFormat with properties" $+ case formatFor @SampleRecord of+ SchemaFormat s ->+ property+ ( not (Map.null (schemaProperties s))+ && not (null (schemaRequired s))+ )+ JsonFormat -> property False+ , testProperty "toolResultMessageWithId correlation invariant" $+ \(c :: ModelName) (t :: ModelName) (cid :: ModelName) ->+ let content = unModelName c+ toolName = unModelName t+ callId = unModelName cid+ msg = toolResultMessageWithId content toolName callId+ in (messageRole msg === M.Tool)+ .&&. (messageContent msg === content)+ .&&. (messageToolName msg === Just toolName)+ .&&. (messageToolCallId msg === Just callId)+ , testProperty "toolResultMessage correlation invariant" $+ \(c :: ModelName) (t :: ModelName) ->+ let content = unModelName c+ toolName = unModelName t+ msg = toolResultMessage content toolName+ in (messageRole msg === M.Tool)+ .&&. (messageContent msg === content)+ .&&. (messageToolName msg === Just toolName)+ .&&. (messageToolCallId msg === Nothing)+ , testProperty "defaultToolLoopConfig positive max turns invariant" $+ property (tlcMaxTurns defaultToolLoopConfig > 0)+ ]
+ test/Test/Ollama/Property/WebSearch.hs view
@@ -0,0 +1,23 @@+module Test.Ollama.Property.WebSearch (tests) where++import Data.Aeson (decode, encode)+import Ollama+import Test.Ollama.Property.Arbitrary ()+import Test.Tasty+import Test.Tasty.QuickCheck++tests :: TestTree+tests =+ testGroup+ "WebSearch Property & Roundtrip QuickCheck Tests"+ [ testProperty "WebSearchRequest JSON roundtrip: ∀ x. decode (encode x) == Just x" $+ \(req :: WebSearchRequest) -> decode (encode req) === Just req+ , testProperty "SearchResult JSON roundtrip: ∀ x. decode (encode x) == Just x" $+ \(res :: SearchResult) -> decode (encode res) === Just res+ , testProperty "WebSearchResponse JSON roundtrip: ∀ x. decode (encode x) == Just x" $+ \(resp :: WebSearchResponse) -> decode (encode resp) === Just resp+ , testProperty "WebFetchRequest JSON roundtrip: ∀ x. decode (encode x) == Just x" $+ \(req :: WebFetchRequest) -> decode (encode req) === Just req+ , testProperty "WebFetchResponse JSON roundtrip: ∀ x. decode (encode x) == Just x" $+ \(resp :: WebFetchResponse) -> decode (encode resp) === Just resp+ ]
+ test/Test/Ollama/Unit/ModelLifecycle.hs view
@@ -0,0 +1,92 @@+module Test.Ollama.Unit.ModelLifecycle (tests) where++import Data.Aeson (encode)+import Data.ByteString qualified as BS+import Data.ByteString.Lazy qualified as BSL+import Ollama+import Ollama.Testing+import Test.Tasty+import Test.Tasty.HUnit++tests :: TestTree+tests =+ testGroup+ "Unit Model Lifecycle & GPU VRAM Management Tests"+ [ testCase "unloadModel sends non-streaming generate request with keep_alive 0" $ do+ (client, getReqBytes) <- newMockClientRecording "{}"+ res <- unloadModel client "llama3.2"+ assertEqual "Unload returns Right ()" (Right ()) res+ reqBytes <- getReqBytes+ assertBool "Contains keep_alive 0" ("\"keep_alive\":\"0\"" `BS.isInfixOf` reqBytes)+ assertBool "Contains empty prompt" ("\"prompt\":\"\"" `BS.isInfixOf` reqBytes)+ assertBool "Contains model name" ("\"model\":\"llama3.2\"" `BS.isInfixOf` reqBytes)+ assertBool "Contains stream false" ("\"stream\":false" `BS.isInfixOf` reqBytes)+ , testCase "unloadModel succeeds on empty response body" $ do+ (client, _) <- newMockClientRecording ""+ res <- unloadModel client "llama3.2"+ assertEqual "Unload returns Right () on empty response" (Right ()) res+ , testCase "preloadModel with Nothing defaults keep_alive to 5m" $ do+ (client, getReqBytes) <- newMockClientRecording "{}"+ res <- preloadModel client "qwen2.5" Nothing+ assertEqual "Preload returns Right ()" (Right ()) res+ reqBytes <- getReqBytes+ assertBool "Contains keep_alive 5m" ("\"keep_alive\":\"5m\"" `BS.isInfixOf` reqBytes)+ assertBool "Contains empty prompt" ("\"prompt\":\"\"" `BS.isInfixOf` reqBytes)+ assertBool "Contains model name" ("\"model\":\"qwen2.5\"" `BS.isInfixOf` reqBytes)+ assertBool "Contains stream false" ("\"stream\":false" `BS.isInfixOf` reqBytes)+ , testCase "preloadModel with Duration formats duration in seconds" $ do+ (client, getReqBytes) <- newMockClientRecording "{}"+ res <- preloadModel client "qwen2.5" (Just (Duration 300000000000))+ assertEqual "Preload returns Right ()" (Right ()) res+ reqBytes <- getReqBytes+ assertBool "Contains keep_alive 300s" ("\"keep_alive\":\"300s\"" `BS.isInfixOf` reqBytes)+ , testCase "preloadModelWith with custom string sends specified keep_alive" $ do+ (client, getReqBytes) <- newMockClientRecording "{}"+ res <- preloadModelWith client "qwen2.5" (Just "10m")+ assertEqual "PreloadWith returns Right ()" (Right ()) res+ reqBytes <- getReqBytes+ assertBool "Contains keep_alive 10m" ("\"keep_alive\":\"10m\"" `BS.isInfixOf` reqBytes)+ , testCase "preloadModel and unloadModel propagate server errors" $ do+ client <- newMockClientWithStatus 500 "{\"error\":\"server failed to load model\"}"+ res <- unloadModel client "llama3.2"+ case res of+ Left (ApiError 500 _) -> pure ()+ other -> assertFailure $ "Expected ApiError 500, got: " <> show other+ , testCase "isModelRunning returns True when model is present in running list" $ do+ let mockData = mockRunningModelsResponse [(ModelName "llama3.2:latest", 4000000000)]+ client <- newMockClient (BSL.toStrict (encode mockData))+ res <- isModelRunning client (ModelName "llama3.2:latest")+ assertEqual "Model is running" (Right True) res+ , testCase "isModelRunning handles tag normalization (query llama3.2 matches llama3.2:latest)" $ do+ let mockData = mockRunningModelsResponse [(ModelName "llama3.2:latest", 4000000000)]+ client <- newMockClient (BSL.toStrict (encode mockData))+ res <- isModelRunning client (ModelName "llama3.2")+ assertEqual "Model without tag matches :latest" (Right True) res+ , testCase "isModelRunning handles reverse tag normalization (query llama3.2:latest matches llama3.2)" $ do+ let mockData = mockRunningModelsResponse [(ModelName "llama3.2", 4000000000)]+ client <- newMockClient (BSL.toStrict (encode mockData))+ res <- isModelRunning client (ModelName "llama3.2:latest")+ assertEqual "Model with :latest matches untagged" (Right True) res+ , testCase "isModelRunning returns False when model is absent" $ do+ let mockData = mockRunningModelsResponse [(ModelName "mistral:latest", 4000000000)]+ client <- newMockClient (BSL.toStrict (encode mockData))+ res <- isModelRunning client (ModelName "llama3.2")+ assertEqual "Model is not running" (Right False) res+ , testCase "getModelVramUsage returns Just bytes when model is running" $ do+ let mockData = mockRunningModelsResponse [(ModelName "llama3.2", 4294967296)]+ client <- newMockClient (BSL.toStrict (encode mockData))+ res <- getModelVramUsage client (ModelName "llama3.2")+ assertEqual "VRAM usage is Just 4GB" (Right (Just 4294967296)) res+ , testCase "getModelVramUsage returns Nothing when model is not running" $ do+ let mockData = mockRunningModelsResponse [(ModelName "mistral", 4294967296)]+ client <- newMockClient (BSL.toStrict (encode mockData))+ res <- getModelVramUsage client (ModelName "llama3.2")+ assertEqual "VRAM usage is Nothing" (Right Nothing) res+ , testCase "isModelRunning and getModelVramUsage propagate server errors" $ do+ client1 <- newMockClientWithStatus 500 "server ps failure"+ resPs <- isModelRunning client1 (ModelName "llama3.2")+ assertEqual "isModelRunning propagates 500" (Left (ApiError 500 "server ps failure")) resPs+ client2 <- newMockClientWithStatus 500 "server ps failure"+ resVram <- getModelVramUsage client2 (ModelName "llama3.2")+ assertEqual "getModelVramUsage propagates 500" (Left (ApiError 500 "server ps failure")) resVram+ ]
+ test/Test/Ollama/Unit/Streaming.hs view
@@ -0,0 +1,247 @@+module Test.Ollama.Unit.Streaming (tests) where++import Conduit (yield)+import Data.Aeson (encode)+import Data.ByteString.Lazy qualified as BSL+import Data.Time (UTCTime (..))+import Ollama+import Test.Tasty+import Test.Tasty.HUnit++fixedTime :: UTCTime+fixedTime = UTCTime (toEnum 59000) 0++tests :: TestTree+tests =+ testGroup+ "Unit Streaming Tests"+ [ testCase "decodeStreamLine on server error JSON raises ApiError 500" $ do+ let errJson = "{\"error\":\"model 'nonexistent' not found\"}"+ res = decodeStreamLine @ChatResponse errJson+ assertEqual+ "Decodes to ApiError 500"+ (Left (ApiError 500 "model 'nonexistent' not found"))+ res+ , testCase "decodeStreamLine on malformed JSON raises DecodeError" $ do+ let malformed = "{\"broken\": json"+ res = decodeStreamLine @ChatResponse malformed+ case res of+ Left (DecodeError _ _) -> pure ()+ other -> assertFailure $ "Expected DecodeError, got: " <> show other+ , testCase "decodeStreamLine on empty line yields Nothing" $ do+ let res = decodeStreamLine @ChatResponse ""+ assertEqual "Empty yields Nothing" (Right Nothing) res+ , testCase "decodeStreamLine on whitespace line yields Nothing" $ do+ let res = decodeStreamLine @ChatResponse " \r\n\t "+ assertEqual "Whitespace yields Nothing" (Right Nothing) res+ , testCase "decodeStreamLine on valid ChatResponse JSON chunk yields Just resp" $ do+ let chunk =+ ChatResponse+ { crModel = "llama3.2"+ , crCreatedAt = fixedTime+ , crMessage = Just (assistantMessage "Hello")+ , crDone = False+ , crDoneReason = Nothing+ , crTotalDuration = Nothing+ , crLoadDuration = Nothing+ , crPromptEvalCount = Nothing+ , crPromptEvalDuration = Nothing+ , crEvalCount = Nothing+ , crEvalDuration = Nothing+ , crLogprobs = Nothing+ }+ chunkJson = BSL.toStrict (encode chunk)+ res = decodeStreamLine @ChatResponse chunkJson+ assertEqual "Decodes valid chunk" (Right (Just chunk)) res+ , testCase "accumulateChatChunks combines streaming text tokens in order" $ do+ let c1 =+ ChatResponse+ { crModel = "llama3.2"+ , crCreatedAt = fixedTime+ , crMessage = Just (assistantMessage "The ")+ , crDone = False+ , crDoneReason = Nothing+ , crTotalDuration = Nothing+ , crLoadDuration = Nothing+ , crPromptEvalCount = Nothing+ , crPromptEvalDuration = Nothing+ , crEvalCount = Nothing+ , crEvalDuration = Nothing+ , crLogprobs = Nothing+ }+ c2 = c1 {crMessage = Just (assistantMessage "sky is ")}+ c3 =+ c1+ { crMessage = Just (assistantMessage "blue.")+ , crDone = True+ , crDoneReason = Just "stop"+ , crTotalDuration = Just (Duration 500000000)+ , crEvalCount = Just 4+ }+ case accumulateChatChunks [c1, c2, c3] of+ Left err -> assertFailure $ "Failed to accumulate chat chunks: " <> show err+ Right acc -> do+ assertEqual "Model matches" "llama3.2" (crModel acc)+ assertBool "Done is True" (crDone acc)+ assertEqual "Done reason matches" (Just "stop") (crDoneReason acc)+ assertEqual "Total duration captured" (Just (Duration 500000000)) (crTotalDuration acc)+ assertEqual "Eval count captured" (Just 4) (crEvalCount acc)+ case crMessage acc of+ Nothing -> assertFailure "Accumulated message is Nothing"+ Just msg -> do+ assertEqual "Role is Assistant" Assistant (messageRole msg)+ assertEqual "Content is concatenated" "The sky is blue." (messageContent msg)+ , testCase "accumulateChatChunks combines thinking tokens and tool calls" $ do+ let tc1 = toolCallWithId "call-1" (ToolCallFunction "get_weather" mempty)+ c1 =+ ChatResponse+ { crModel = "deepseek-r1"+ , crCreatedAt = fixedTime+ , crMessage =+ Just $+ (assistantMessage "")+ { messageThinking = Just "Thinking step 1... "+ }+ , crDone = False+ , crDoneReason = Nothing+ , crTotalDuration = Nothing+ , crLoadDuration = Nothing+ , crPromptEvalCount = Nothing+ , crPromptEvalDuration = Nothing+ , crEvalCount = Nothing+ , crEvalDuration = Nothing+ , crLogprobs = Nothing+ }+ c2 =+ ChatResponse+ { crModel = "deepseek-r1"+ , crCreatedAt = fixedTime+ , crMessage =+ Just $+ (assistantMessage "Result")+ { messageThinking = Just "Step 2 done."+ , messageToolCalls = Just [tc1]+ }+ , crDone = True+ , crDoneReason = Just "tool_calls"+ , crTotalDuration = Nothing+ , crLoadDuration = Nothing+ , crPromptEvalCount = Nothing+ , crPromptEvalDuration = Nothing+ , crEvalCount = Nothing+ , crEvalDuration = Nothing+ , crLogprobs = Nothing+ }+ case accumulateChatChunks [c1, c2] of+ Left err -> assertFailure $ "Failed to accumulate: " <> show err+ Right acc -> case crMessage acc of+ Nothing -> assertFailure "Expected Just message in accumulated ChatResponse"+ Just msg -> do+ assertEqual "Thinking concatenated" (Just "Thinking step 1... Step 2 done.") (messageThinking msg)+ assertEqual "Content preserved" "Result" (messageContent msg)+ assertEqual "Tool calls preserved" (Just [tc1]) (messageToolCalls msg)+ , testCase "accumulateChatChunks on empty list returns InvalidRequest" $ do+ case accumulateChatChunks [] of+ Left (InvalidRequest _) -> pure ()+ other -> assertFailure $ "Expected Left InvalidRequest, got: " <> show other+ , testCase "accumulateGenerateChunks combines response text and thinking" $ do+ let g1 =+ GenerateResponse+ { grModel = "qwen2.5"+ , grCreatedAt = fixedTime+ , grResponse = "Hello "+ , grDone = False+ , grDoneReason = Nothing+ , grContext = Nothing+ , grTotalDuration = Nothing+ , grLoadDuration = Nothing+ , grPromptEvalCount = Nothing+ , grPromptEvalDuration = Nothing+ , grEvalCount = Nothing+ , grEvalDuration = Nothing+ , grThinking = Just "thinking 1. "+ , grImage = Nothing+ , grLogprobs = Nothing+ , grCompleted = Nothing+ , grTotal = Nothing+ }+ g2 =+ g1+ { grResponse = "world!"+ , grThinking = Just "thinking 2."+ , grDone = True+ , grDoneReason = Just "stop"+ , grTotalDuration = Just (Duration 100000000)+ , grContext = Just [1, 2, 3]+ }+ case accumulateGenerateChunks [g1, g2] of+ Left err -> assertFailure $ "Failed to accumulate generate chunks: " <> show err+ Right acc -> do+ assertEqual "Model matches" "qwen2.5" (grModel acc)+ assertEqual "Response concatenated" "Hello world!" (grResponse acc)+ assertEqual "Thinking concatenated" (Just "thinking 1. thinking 2.") (grThinking acc)+ assertBool "Done is True" (grDone acc)+ assertEqual "Context captured" (Just [1, 2, 3]) (grContext acc)+ assertEqual "Total duration captured" (Just (Duration 100000000)) (grTotalDuration acc)+ , testCase "accumulateGenerateChunks on empty list returns InvalidRequest" $ do+ case accumulateGenerateChunks [] of+ Left (InvalidRequest _) -> pure ()+ other -> assertFailure $ "Expected Left InvalidRequest, got: " <> show other+ , testCase "accumulateChatStream Conduit folds stream of chunks" $ do+ let c1 =+ ChatResponse+ { crModel = "llama3.2"+ , crCreatedAt = fixedTime+ , crMessage = Just (assistantMessage "Stream ")+ , crDone = False+ , crDoneReason = Nothing+ , crTotalDuration = Nothing+ , crLoadDuration = Nothing+ , crPromptEvalCount = Nothing+ , crPromptEvalDuration = Nothing+ , crEvalCount = Nothing+ , crEvalDuration = Nothing+ , crLogprobs = Nothing+ }+ c2 = c1 {crMessage = Just (assistantMessage "test!"), crDone = True}+ stream = do+ yield c1+ yield c2+ res <- accumulateChatStream stream+ case res of+ Left err -> assertFailure $ "accumulateChatStream failed: " <> show err+ Right acc -> do+ assertEqual "Content concatenated" "Stream test!" (maybe "" messageContent (crMessage acc))+ assertBool "Done is True" (crDone acc)+ , testCase "accumulateGenerateStream Conduit folds stream of chunks" $ do+ let g1 =+ GenerateResponse+ { grModel = "llama3.2"+ , grCreatedAt = fixedTime+ , grResponse = "Gen "+ , grDone = False+ , grDoneReason = Nothing+ , grContext = Nothing+ , grTotalDuration = Nothing+ , grLoadDuration = Nothing+ , grPromptEvalCount = Nothing+ , grPromptEvalDuration = Nothing+ , grEvalCount = Nothing+ , grEvalDuration = Nothing+ , grThinking = Nothing+ , grImage = Nothing+ , grLogprobs = Nothing+ , grCompleted = Nothing+ , grTotal = Nothing+ }+ g2 = g1 {grResponse = "stream!", grDone = True}+ stream = do+ yield g1+ yield g2+ res <- accumulateGenerateStream stream+ case res of+ Left err -> assertFailure $ "accumulateGenerateStream failed: " <> show err+ Right acc -> do+ assertEqual "Response concatenated" "Gen stream!" (grResponse acc)+ assertBool "Done is True" (grDone acc)+ ]
+ test/Test/Ollama/Unit/StructuredAndTools.hs view
@@ -0,0 +1,237 @@+module Test.Ollama.Unit.StructuredAndTools (tests) where++import Data.Aeson (FromJSON, ToJSON, Value (..), encode)+import Data.ByteString qualified as BS+import Data.ByteString.Lazy qualified as BSL+import Data.IORef (modifyIORef', newIORef, readIORef)+import Data.List.NonEmpty (NonEmpty (..))+import Data.Map.Strict qualified as Map+import Data.Text (Text)+import Data.Text qualified as T+import GHC.Generics (Generic)+import Ollama+import Ollama.Testing+import Ollama.Types.Message qualified as M+import Test.Tasty+import Test.Tasty.HUnit++data Person = Person+ { personName :: !Text+ , personAge :: !Int+ }+ deriving stock (Eq, Show, Generic)+ deriving anyclass (FromJSON, ToJSON, ToSchema)++data TaskItem = TaskItem+ { taskTitle :: !Text+ , taskPriority :: !Int+ }+ deriving stock (Eq, Show, Generic)+ deriving anyclass (FromJSON, ToJSON, ToSchema)++tests :: TestTree+tests =+ testGroup+ "Unit Structured Outputs & Tool Calling Loop Tests"+ [ testCase "chatStructured parses valid JSON into typed StructuredResponse" $ do+ let rawMsg = "{\"personName\":\"Alice\",\"personAge\":30}"+ mockResp = mockChatResponse "llama3.2" rawMsg+ client <- newMockClient (BSL.toStrict (encode mockResp))+ let req = chatRequest "llama3.2" (userMessage "Generate person" :| [])+ res <- chatStructured @Person client req+ case res of+ Left err -> assertFailure $ "Expected Right, got: " <> show err+ Right sr -> do+ assertEqual "Parsed value matches" (Person "Alice" 30) (srValue sr)+ assertEqual "Model matches" "llama3.2" (crModel (srRawResponse sr))+ , testCase "chatStructured injects schema format into request wire bytes" $ do+ (client, getReqBytes) <- newMockClientRecording "{}"+ let req = chatRequest "llama3.2" (userMessage "Generate person" :| [])+ _ <- chatStructured @Person client req+ reqBytes <- getReqBytes+ assertBool "Contains format object" ("\"format\":" `BS.isInfixOf` reqBytes)+ assertBool "Contains schema type" ("\"type\":\"object\"" `BS.isInfixOf` reqBytes)+ assertBool "Contains personName property" ("\"personName\"" `BS.isInfixOf` reqBytes)+ assertBool "Contains personAge property" ("\"personAge\"" `BS.isInfixOf` reqBytes)+ , testCase "chatStructured returns DecodeError on malformed JSON payload" $ do+ let rawMsg = "{\"personName\": 123, broken json"+ mockResp = mockChatResponse "llama3.2" rawMsg+ client <- newMockClient (BSL.toStrict (encode mockResp))+ let req = chatRequest "llama3.2" (userMessage "Generate person" :| [])+ res <- chatStructured @Person client req+ case res of+ Left (DecodeError _ _) -> pure ()+ other -> assertFailure $ "Expected DecodeError, got: " <> show other+ , testCase "generateStructured parses valid JSON into tuple" $ do+ let rawMsg = "{\"taskTitle\":\"Write tests\",\"taskPriority\":1}"+ mockResp = mockGenerateResponse "llama3.2" rawMsg+ client <- newMockClient (BSL.toStrict (encode mockResp))+ let req = generateRequest "llama3.2" "Generate task"+ res <- generateStructured @TaskItem client req+ case res of+ Left err -> assertFailure $ "Expected Right, got: " <> show err+ Right (item, raw) -> do+ assertEqual "Parsed item matches" (TaskItem "Write tests" 1) item+ assertEqual "Raw model matches" "llama3.2" (grModel raw)+ , testCase "generateStructured injects schema format into request wire bytes" $ do+ (client, getReqBytes) <- newMockClientRecording "{}"+ let req = generateRequest "llama3.2" "Generate task"+ _ <- generateStructured @TaskItem client req+ reqBytes <- getReqBytes+ assertBool "Contains format in generate request" ("\"format\":" `BS.isInfixOf` reqBytes)+ assertBool "Contains taskTitle" ("\"taskTitle\"" `BS.isInfixOf` reqBytes)+ , testCase "generateStructured returns DecodeError on invalid schema match" $ do+ let rawMsg = "{\"unknown_field\": true}"+ mockResp = mockGenerateResponse "llama3.2" rawMsg+ client <- newMockClient (BSL.toStrict (encode mockResp))+ let req = generateRequest "llama3.2" "Generate task"+ res <- generateStructured @TaskItem client req+ case res of+ Left (DecodeError _ _) -> pure ()+ other -> assertFailure $ "Expected DecodeError, got: " <> show other+ , testCase "chatWithTools executes single tool call and reaches final answer" $ do+ let tc =+ toolCallWithId "call-1" (mkToolCallFunction "add" (Map.fromList [("a", Number 2), ("b", Number 3)]))+ turn1Msg = (assistantMessage "") {messageToolCalls = Just [tc]}+ turn1Resp = (mockChatResponse "qwen2.5" "") {crMessage = Just turn1Msg}+ turn2Msg = assistantMessage "The sum of 2 and 3 is 5."+ turn2Resp = (mockChatResponse "qwen2.5" "The sum of 2 and 3 is 5.") {crMessage = Just turn2Msg}+ client <- newMockClientSequence [BSL.toStrict (encode turn1Resp), BSL.toStrict (encode turn2Resp)]+ let addTool =+ RegisteredTool+ { rtTool =+ toolDef+ "add"+ "Add two numbers"+ (objectParams [("a", numberParam Nothing), ("b", numberParam Nothing)] ["a", "b"])+ , rtHandler = \args -> case (Map.lookup "a" args, Map.lookup "b" args) of+ (Just (Number a), Just (Number b)) -> pure $ Right (Number (a + b))+ _ -> pure $ Left "Invalid arguments"+ }+ req = chatRequest "qwen2.5" (userMessage "What is 2 + 3?" :| [])+ res <- chatWithTools client req [addTool] defaultToolLoopConfig+ case res of+ Left err -> assertFailure $ "chatWithTools failed: " <> show err+ Right (finalMsg, fullHistory) -> do+ assertEqual "Final answer matches" "The sum of 2 and 3 is 5." (messageContent finalMsg)+ assertEqual+ "Total messages: user + assistant_call + tool_result + final_assistant"+ 4+ (length fullHistory)+ let toolResult = fullHistory !! 2+ assertEqual "Tool result role is Tool" M.Tool (messageRole toolResult)+ assertEqual "Tool result content is 5" "5" (messageContent toolResult)+ assertEqual "Tool call id correlated" (Just "call-1") (messageToolCallId toolResult)+ , testCase "chatWithTools executes multiple parallel tool calls in one turn" $ do+ let tc1 =+ toolCallWithId+ "call-1"+ (mkToolCallFunction "city_weather" (Map.fromList [("city", String "Paris")]))+ tc2 =+ toolCallWithId+ "call-2"+ (mkToolCallFunction "city_weather" (Map.fromList [("city", String "London")]))+ turn1Msg = (assistantMessage "") {messageToolCalls = Just [tc1, tc2]}+ turn1Resp = (mockChatResponse "qwen2.5" "") {crMessage = Just turn1Msg}+ turn2Msg = assistantMessage "Paris is 20C and London is 15C."+ turn2Resp = (mockChatResponse "qwen2.5" "Paris is 20C and London is 15C.") {crMessage = Just turn2Msg}+ client <- newMockClientSequence [BSL.toStrict (encode turn1Resp), BSL.toStrict (encode turn2Resp)]+ let weatherTool =+ RegisteredTool+ { rtTool =+ toolDef "city_weather" "Get temperature" (objectParams [("city", stringParam Nothing)] ["city"])+ , rtHandler = \args -> case Map.lookup "city" args of+ Just (String "Paris") -> pure $ Right (String "20C sunny")+ Just (String "London") -> pure $ Right (String "15C rainy")+ _ -> pure $ Left "Unknown city"+ }+ req = chatRequest "qwen2.5" (userMessage "Weather in Paris and London?" :| [])+ res <- chatWithTools client req [weatherTool] defaultToolLoopConfig+ case res of+ Left err -> assertFailure $ "chatWithTools parallel failed: " <> show err+ Right (finalMsg, fullHistory) -> do+ assertEqual "Final answer content" "Paris is 20C and London is 15C." (messageContent finalMsg)+ -- 1 (user) + 1 (assistant 2 tools) + 2 (tool results) + 1 (final assistant) = 5+ assertEqual "Total messages is 5" 5 (length fullHistory)+ let resParis = fullHistory !! 2+ resLondon = fullHistory !! 3+ assertEqual "Paris id" (Just "call-1") (messageToolCallId resParis)+ assertEqual "London id" (Just "call-2") (messageToolCallId resLondon)+ , testCase "chatWithTools formats tool errors gracefully" $ do+ let tc =+ toolCallWithId+ "call-err"+ (mkToolCallFunction "divide" (Map.fromList [("a", Number 10), ("b", Number 0)]))+ turn1Msg = (assistantMessage "") {messageToolCalls = Just [tc]}+ turn1Resp = (mockChatResponse "qwen2.5" "") {crMessage = Just turn1Msg}+ turn2Msg = assistantMessage "Error handled: division by zero"+ turn2Resp = (mockChatResponse "qwen2.5" "Error handled") {crMessage = Just turn2Msg}+ client <- newMockClientSequence [BSL.toStrict (encode turn1Resp), BSL.toStrict (encode turn2Resp)]+ let divTool =+ RegisteredTool+ { rtTool = toolDef "divide" "Division" (objectParams [] [])+ , rtHandler = \_ -> pure $ Left "division by zero"+ }+ req = chatRequest "qwen2.5" (userMessage "Divide 10 by 0" :| [])+ res <- chatWithTools client req [divTool] defaultToolLoopConfig+ case res of+ Left err -> assertFailure $ "chatWithTools error handling failed: " <> show err+ Right (finalMsg, fullHistory) -> do+ assertEqual "Final answer" "Error handled: division by zero" (messageContent finalMsg)+ let toolRes = fullHistory !! 2+ assertEqual "Tool error prefixed" "Error: division by zero" (messageContent toolRes)+ , testCase "chatWithTools handles unregistered tool gracefully" $ do+ let tc = toolCallWithId "call-unk" (mkToolCallFunction "unknown_calc" Map.empty)+ turn1Msg = (assistantMessage "") {messageToolCalls = Just [tc]}+ turn1Resp = (mockChatResponse "qwen2.5" "") {crMessage = Just turn1Msg}+ turn2Msg = assistantMessage "Tool was not available"+ turn2Resp = (mockChatResponse "qwen2.5" "") {crMessage = Just turn2Msg}+ client <- newMockClientSequence [BSL.toStrict (encode turn1Resp), BSL.toStrict (encode turn2Resp)]+ let req = chatRequest "qwen2.5" (userMessage "Use unknown calc" :| [])+ res <- chatWithTools client req [] defaultToolLoopConfig+ case res of+ Left err -> assertFailure $ "chatWithTools unregistered tool failed: " <> show err+ Right (_, fullHistory) -> do+ let toolRes = fullHistory !! 2+ assertBool "Mentions tool not available" ("is not available" `T.isInfixOf` messageContent toolRes)+ , testCase "chatWithTools enforces max turns recursion limit" $ do+ let tc = toolCallWithId "call-inf" (mkToolCallFunction "ping" Map.empty)+ turnMsg = (assistantMessage "") {messageToolCalls = Just [tc]}+ turnResp = (mockChatResponse "qwen2.5" "") {crMessage = Just turnMsg}+ -- 5 turns of tool calls+ fiveResps = replicate 5 (BSL.toStrict (encode turnResp))+ client <- newMockClientSequence fiveResps+ let pingTool =+ RegisteredTool+ { rtTool = toolDef "ping" "Ping" (objectParams [] [])+ , rtHandler = \_ -> pure $ Right (String "pong")+ }+ req = chatRequest "qwen2.5" (userMessage "Start ping" :| [])+ cfg = defaultToolLoopConfig {tlcMaxTurns = 3}+ res <- chatWithTools client req [pingTool] cfg+ case res of+ Left (InvalidRequest msg) ->+ assertBool "Reports maximum turns exceeded" ("Maximum tool loop turns" `T.isInfixOf` msg)+ other -> assertFailure $ "Expected Left InvalidRequest, got: " <> show other+ , testCase "chatWithTools triggers onTurn callback" $ do+ turnsRef <- newIORef ([] :: [Int])+ let tc = toolCallWithId "call-1" (mkToolCallFunction "echo" (Map.fromList [("x", String "hi")]))+ turn1Msg = (assistantMessage "") {messageToolCalls = Just [tc]}+ turn1Resp = (mockChatResponse "qwen2.5" "") {crMessage = Just turn1Msg}+ turn2Msg = assistantMessage "Done"+ turn2Resp = (mockChatResponse "qwen2.5" "Done") {crMessage = Just turn2Msg}+ client <- newMockClientSequence [BSL.toStrict (encode turn1Resp), BSL.toStrict (encode turn2Resp)]+ let echoTool =+ RegisteredTool+ { rtTool = toolDef "echo" "Echo" (objectParams [] [])+ , rtHandler = \_ -> pure $ Right (String "hi")+ }+ req = chatRequest "qwen2.5" (userMessage "Echo" :| [])+ cfg =+ defaultToolLoopConfig+ { tlcOnTurn = Just $ \turn _msg -> modifyIORef' turnsRef (++ [turn])+ }+ _ <- chatWithTools client req [echoTool] cfg+ recordedTurns <- readIORef turnsRef+ assertEqual "Callback was invoked for turn 1 and turn 2" [1, 2] recordedTurns+ ]
+ test/Test/Ollama/Unit/WebSearch.hs view
@@ -0,0 +1,113 @@+module Test.Ollama.Unit.WebSearch (tests) where++import Data.Aeson (decode, encode)+import Data.Maybe (isJust)+import Ollama+import Test.Tasty+import Test.Tasty.HUnit++tests :: TestTree+tests =+ testGroup+ "Unit WebSearch & WebFetch Tests"+ [ testCase "WebSearchRequest serialization with max_results" $ do+ let req = WebSearchRequest "Haskell 2026" (Just 5)+ jsonBytes = encode req+ expected = "{\"max_results\":5,\"query\":\"Haskell 2026\"}"+ assertEqual "Serialized JSON match" expected jsonBytes+ , testCase "WebSearchRequest serialization without max_results" $ do+ let req = webSearchRequest "Haskell functional programming"+ jsonBytes = encode req+ expected = "{\"query\":\"Haskell functional programming\"}"+ assertEqual "Serialized JSON match" expected jsonBytes+ , testCase "WebSearchResponse roundtrip decode" $ do+ let rawJson =+ "{\"results\":[{\"title\":\"Haskell Org\",\"url\":\"https://www.haskell.org\",\"content\":\"An advanced purely functional programming language.\"}]}"+ case decode @WebSearchResponse rawJson of+ Nothing -> assertFailure "Failed to decode WebSearchResponse"+ Just resp ->+ case wsResults resp of+ [item] -> do+ assertEqual "Title match" "Haskell Org" (srTitle item)+ assertEqual "Url match" "https://www.haskell.org" (srUrl item)+ assertEqual "Content match" "An advanced purely functional programming language." (srContent item)+ other -> assertFailure $ "Expected 1 result, got: " <> show (length other)+ , testCase "WebFetchRequest serialization" $ do+ let req = webFetchRequest "https://ollama.com"+ jsonBytes = encode req+ expected = "{\"url\":\"https://ollama.com\"}"+ assertEqual "Serialized JSON match" expected jsonBytes+ , testCase "WebFetchResponse roundtrip decode" $ do+ let rawJson =+ "{\"title\":\"Ollama\",\"content\":\"Get up and running with large language models.\"}"+ case decode @WebFetchResponse rawJson of+ Nothing -> assertFailure "Failed to decode WebFetchResponse"+ Just resp -> do+ assertEqual "Title match" "Ollama" (wfrTitle resp)+ assertEqual "Content match" "Get up and running with large language models." (wfrContent resp)+ , testCase "webSearchTool produces valid Tool schema" $ do+ let tool = webSearchTool+ assertEqual "Tool type is function" "function" (toolType tool)+ let fn = toolFunction tool+ assertEqual "Function name is web_search" "web_search" (fnName fn)+ assertBool "Description present" (isJust (fnDescription fn))+ case fnParameters fn of+ Nothing -> assertFailure "Parameters missing"+ Just p -> do+ assertEqual "Parameter type object" "object" (fpType p)+ assertEqual "Required fields" (Just ["query"]) (fpRequired p)+ , testCase "webFetchTool produces valid Tool schema" $ do+ let tool = webFetchTool+ assertEqual "Tool type is function" "function" (toolType tool)+ let fn = toolFunction tool+ assertEqual "Function name is web_fetch" "web_fetch" (fnName fn)+ assertBool "Description present" (isJust (fnDescription fn))+ case fnParameters fn of+ Nothing -> assertFailure "Parameters missing"+ Just p -> do+ assertEqual "Parameter type object" "object" (fpType p)+ assertEqual "Required fields" (Just ["url"]) (fpRequired p)+ , testCase "webSearch fails with InvalidRequest if configApiKey is Nothing" $ do+ client <- defaultClient+ res <- webSearch client (webSearchRequest "test")+ case res of+ Left (InvalidRequest msg) ->+ assertEqual+ "API key error message"+ "Ollama API key required for web search. Set OLLAMA_API_KEY or configApiKey."+ msg+ other -> assertFailure $ "Expected Left InvalidRequest, got: " <> show other+ , testCase "webFetch fails with InvalidRequest if configApiKey is Nothing" $ do+ client <- defaultClient+ res <- webFetch client (webFetchRequest "https://example.com")+ case res of+ Left (InvalidRequest msg) ->+ assertEqual+ "API key error message"+ "Ollama API key required for web fetch. Set OLLAMA_API_KEY or configApiKey."+ msg+ other -> assertFailure $ "Expected Left InvalidRequest, got: " <> show other+ , testCase "webSearch with mock client and API key succeeds" $ do+ let mockPayload =+ "{\"results\":[{\"title\":\"Test Title\",\"url\":\"https://test.com\",\"content\":\"Test snippet\"}]}"+ cfg = defaultConfig {configBaseUrl = "http://mock-cloud", configApiKey = Just "test-key"}+ client <- newMockClientWithConfig cfg mockPayload+ res <- webSearch client (webSearchRequest "query")+ case res of+ Left err -> assertFailure $ "webSearch failed: " <> show err+ Right resp ->+ case wsResults resp of+ [item] -> assertEqual "Result title" "Test Title" (srTitle item)+ other -> assertFailure $ "Expected 1 result, got: " <> show (length other)+ , testCase "webFetch with mock client and API key succeeds" $ do+ let mockPayload =+ "{\"title\":\"Fetched Page\",\"content\":\"Page content text\"}"+ cfg = defaultConfig {configBaseUrl = "http://mock-cloud", configApiKey = Just "test-key"}+ client <- newMockClientWithConfig cfg mockPayload+ res <- webFetch client (webFetchRequest "https://test.com")+ case res of+ Left err -> assertFailure $ "webFetch failed: " <> show err+ Right resp -> do+ assertEqual "Title match" "Fetched Page" (wfrTitle resp)+ assertEqual "Content match" "Page content text" (wfrContent resp)+ ]