packages feed

shroom-baikai (empty) → 0.1.0.0

raw patch · 10 files changed

+1465/−0 lines, 10 filesdep +aesondep +baikaidep +baikai-claude

Dependencies added: aeson, baikai, baikai-claude, baikai-effectful, baikai-openai, base, bytestring, effectful, generics-sop, network, openapi3, shroom, shroom-baikai, tasty, tasty-hunit, text, time, vector

Files

+ CHANGELOG.md view
@@ -0,0 +1,6 @@+# Revision history for shroom-baikai++## 0.1.0.0 -- 2026-11-27++* First release. Runs a shroom program against Claude, any other Anthropic-compatible host, a local+  Ollama, or any OpenAI-compatible host, through the `baikai` libraries.
+ LICENSE view
@@ -0,0 +1,29 @@+Copyright (c) 2026, Manuel Bärenz+++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++    * Redistributions of source code must retain the above copyright+      notice, this list of conditions and the following disclaimer.++    * Redistributions in binary form must reproduce the above+      copyright notice, this list of conditions and the following+      disclaimer in the documentation and/or other materials provided+      with the distribution.++    * Neither the name of the copyright holder nor the names of its+      contributors may be used to endorse or promote products derived+      from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ app/Claude.hs view
@@ -0,0 +1,107 @@+{- | Live conference scheduling demo against the real Claude API.++Runs the conference chain against Claude, printing each prompt and response+as they arrive.++Usage:++  ANTHROPIC_API_KEY=sk-ant-... cabal run shroom-claude+-}+module Main (main) where++-- base+import System.Environment (lookupEnv)++-- text+import Data.Text (pack)+import Data.Text qualified as T+import Data.Text.IO qualified as TIO++-- time+import Data.Time (UTCTime, defaultTimeLocale, formatTime)++-- shroom+import Control.Monad.Prompt.Baikai (claudeBackend)+import Control.Monad.Prompt.Effect (PromptConfig (..), defaultPromptConfig, runPromptResultEff)+import Control.Monad.Prompt.Tool (runTool, toolBinding)+import Control.Monad.Prompt.Tool.Web (DuckDuckGoSearch, WikipediaSearch, duckDuckGoSearchHandler, wikipediaSearchHandler)++-- conference scenario+import ConferenceTypes (+  ConferenceSchedule (..),+  Slot (..),+  Speaker (..),+  SpeakerName (..),+  Speakers (..),+  Talk (..),+  conferenceChainWithTools,+ )++fmtTime :: UTCTime -> String+fmtTime = formatTime defaultTimeLocale "%Y-%m-%dT%H:%M:%SZ"++main :: IO ()+main = do+  mKey <- lookupEnv "ANTHROPIC_API_KEY"+  case mKey of+    Nothing -> putStrLn "ANTHROPIC_API_KEY not set — exiting."+    Just key -> run (pack key)++run :: T.Text -> IO ()+run apiKey = do+  backend <- claudeBackend apiKey+  let pcfg = defaultPromptConfig {debugLog = Just TIO.putStrLn, maxToolSteps = Just 2}+      bindings = [toolBinding @DuckDuckGoSearch, toolBinding @WikipediaSearch]+  result <-+    runPromptResultEff backend pcfg $+      runTool duckDuckGoSearchHandler $+        runTool wikipediaSearchHandler $+          conferenceChainWithTools bindings+  putStrLn ""+  case result of+    Left err ->+      putStrLn $ "ERROR: " <> T.unpack err+    Right (allSpeakers, talks, schedule) -> do+      putStrLn "\n=== RESULTS ==="+      putStrLn $ "Speakers: " <> show (length (speakers allSpeakers))+      mapM_+        ( \s ->+            let n = speakerName s+             in putStrLn $+                  "  - "+                    <> T.unpack (firstName n)+                    <> " "+                    <> T.unpack (lastName n)+                    <> " ("+                    <> T.unpack (speakerAffiliation s)+                    <> ")\nBio: "+                    <> T.unpack (speakerBio s)+        )+        (speakers allSpeakers)+      putStrLn $ "Talks:    " <> show (length talks)+      mapM_+        ( \t ->+            let n = talkSpeakerName t+             in putStrLn $+                  "  - \""+                    <> T.unpack (talkTitle t)+                    <> "\" by "+                    <> T.unpack (firstName n)+                    <> " "+                    <> T.unpack (lastName n)+        )+        talks+      putStrLn $ "Day:      " <> fmtTime (scheduleDay schedule)+      putStrLn $ "Slots:    " <> show (length (scheduleSlots schedule))+      mapM_+        ( \slot ->+            putStrLn $+              "  "+                <> fmtTime (slotStart slot)+                <> "-"+                <> fmtTime (slotEnd slot)+                <> ": \""+                <> T.unpack (talkTitle (slotTalk slot))+                <> "\""+        )+        (scheduleSlots schedule)
+ shroom-baikai.cabal view
@@ -0,0 +1,151 @@+cabal-version: 3.0+name: shroom-baikai+version: 0.1.0.0+synopsis: The baikai transport adapter for shroom+description:+  shroom-baikai implements the+  <https://hackage.haskell.org/package/shroom/docs/Control-Monad-Prompt-Backend.html#t:Backend Backend>+  interface of <https://hackage.haskell.org/package/shroom shroom> by+  interpreting the+  <https://hackage.haskell.org/package/baikai-effectful/docs/Baikai-Effectful.html#t:Baikai Baikai>+  effect of+  <https://hackage.haskell.org/package/baikai-effectful baikai-effectful>, so a+  shroom program runs unchanged against Claude+  (<https://hackage.haskell.org/package/baikai-claude baikai-claude>) or any+  OpenAI-compatible host, including a local Ollama+  (<https://hackage.haskell.org/package/baikai-openai baikai-openai>).+  Front-door constructors build a backend from an API key or a base URL and a+  model name; a program that needs a different transport interprets the effect+  itself. Use it with <https://hackage.haskell.org/package/shroom shroom>,+  which holds the prompt monad, and+  <https://hackage.haskell.org/package/shroom-class shroom-class>, which+  describes the types.++category: AI+license: BSD-3-Clause+license-file: LICENSE+author: Manuel Bärenz+maintainer: programming@manuelbaerenz.de+-- copyright:+build-type: Simple+extra-doc-files: CHANGELOG.md+-- extra-source-files:+tested-with:+  ghc ==9.12++flag anthropic+  description:+    Build shroom-test-integration-claude, which calls the real Anthropic+    API and needs ANTHROPIC_API_KEY.++  default: True+  manual: True++flag ollama+  description:+    Build shroom-test-integration-ollama, which needs a reachable Ollama+    server.++  default: True+  manual: True++flag online+  description:+    Master switch for the test suites that need network or an external+    service. Off under nix, where the sandbox has no network.++  default: True+  manual: True++common opts+  ghc-options:+    -Wall+    -haddock+    -Winvalid-haddock++  build-depends:+    aeson ^>=2.2,+    baikai >=0.7.0 && <0.12,+    baikai-claude >=0.7.0 && <0.8,+    baikai-effectful >=0.4.0 && <0.6,+    baikai-openai >=0.7.0 && <0.8,+    base >=4.20 && <4.22,+    effectful ^>=2.7,+    shroom ^>=0.1,+    text >=2.1.2 && <2.2,+    vector ^>=0.13,++  default-extensions:+    DefaultSignatures+    DerivingVia+    OverloadedLists+    OverloadedRecordDot+    OverloadedStrings+    TypeFamilies++library+  import: opts+  exposed-modules:+    Control.Monad.Prompt.Baikai++  hs-source-dirs: src+  default-language: GHC2024++common test-opts+  build-depends:+    generics-sop ^>=0.5.1,+    openapi3 ^>=3.2,+    shroom,+    shroom:test-utils,+    shroom-baikai,+    tasty >=1.4 && <1.6,+    tasty-hunit ^>=0.10,++test-suite shroom-test-integration-claude+  import: opts, test-opts+  default-language: GHC2024+  type: exitcode-stdio-1.0+  hs-source-dirs: test+  main-is: Integration/Claude.hs+  other-modules:+    Integration.Cases++  if !(flag(anthropic) && flag(online))+    buildable: False++test-suite shroom-test-integration-ollama+  import: opts, test-opts+  default-language: GHC2024+  type: exitcode-stdio-1.0+  hs-source-dirs: test+  main-is: Integration/Ollama.hs+  other-modules:+    Integration.Cases+    ScalarTypes++  if !(flag(ollama) && flag(online))+    buildable: False++executable shroom-conference-claude+  import: opts, test-opts+  default-language: GHC2024+  hs-source-dirs: app+  main-is: Claude.hs+  build-depends:+    time ^>=1.14++-- Offline: talks only to a localhost socket opened by the test itself, so+-- unlike the integration suites it is not behind the @online@ flag, and the+-- offline test gate runs it.+test-suite shroom-test-baikai-offline+  import: opts+  default-language: GHC2024+  type: exitcode-stdio-1.0+  hs-source-dirs: test/Offline+  main-is: Main.hs+  build-depends:+    bytestring >=0.12 && <0.13,+    network ^>=3.2,+    shroom-baikai,+    tasty >=1.4 && <1.6,+    tasty-hunit ^>=0.10,
+ src/Control/Monad/Prompt/Baikai.hs view
@@ -0,0 +1,431 @@+{-# LANGUAGE OverloadedRecordDot #-}++{- |+Module      : Control.Monad.Prompt.Baikai+Description : Backends for Claude, a local Ollama and other hosted models.++Builds the t'Control.Monad.Prompt.Backend.Backend' that sends a shroom program's+requests to a real model, through @baikai@. Pick the constructor for the host and+pass the result to 'Control.Monad.Prompt.Effect.runPromptResultEff'. The program+below asks Claude for a @Recipe@, a type of your own with a description, and prints+the answer. The description of @Recipe@ is read from the Haddock comments, so the+module that declares @Recipe@ needs the GHC flag @-haddock@ (see "Data.Shroom.Class.TH").++@+-- | A recipe for a dish.+data Recipe = Recipe+  { title :: Text+  -- ^ The name of the dish.+  , steps :: [Text]+  -- ^ The preparation steps, in order.+  }+  deriving stock (Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++\$(deriveDescribable ''Recipe)++instance Surveyable Recipe++instance Promptable Recipe++main :: IO ()+main = do+  backend <- claudeBackend apiKey+  result <- runPromptResultEff backend defaultPromptConfig $ do+    context \"I have eggs, flour and milk.\"+    prompt \@Recipe+  print result+@++The example needs the language GHC2021 or GHC2024 and the extensions @DeriveAnyClass@,+@DerivingStrategies@, @OverloadedStrings@ and @TemplateHaskell@. It needs the packages+@shroom-baikai@,+<https://hackage.haskell.org/package/shroom shroom>,+<https://hackage.haskell.org/package/shroom-class shroom-class>,+<https://hackage.haskell.org/package/aeson aeson>,+<https://hackage.haskell.org/package/generics-sop generics-sop>,+<https://hackage.haskell.org/package/openapi3 openapi3> and+<https://hackage.haskell.org/package/text text> in @build-depends@.+Its names come from these modules:++* 'claudeBackend' from this module.+* 'Control.Monad.Prompt.Effect.context', 'Control.Monad.Prompt.Effect.defaultPromptConfig'+  and 'Control.Monad.Prompt.Effect.runPromptResultEff' from "Control.Monad.Prompt.Effect".+* t'Control.Monad.Prompt.Promptable' and 'Control.Monad.Prompt.prompt' from "Control.Monad.Prompt".+* 'Data.Shroom.Class.TH.deriveDescribable' from "Data.Shroom.Class.TH" and+  t'Data.Shroom.Class.Surveyable' from "Data.Shroom.Class".+* t'Data.Text.Text' from "Data.Text" and t'GHC.Generics.Generic' from "GHC.Generics".+* t'Data.Aeson.ToJSON' and t'Data.Aeson.FromJSON' from "Data.Aeson", and+  t'Data.OpenApi.ToSchema' from "Data.OpenApi".+* <https://hackage.haskell.org/package/generics-sop/docs/Generics-SOP.html#t:Generic SOP.Generic> and+  <https://hackage.haskell.org/package/generics-sop/docs/Generics-SOP.html#t:HasDatatypeInfo SOP.HasDatatypeInfo>+  from "Generics.SOP", which the example imports qualified as @SOP@.++@apiKey@ is an Anthropic API key as t'Data.Text.Text'. For another host, replace 'claudeBackend':++* 'claudeBackend' is the Claude API.+* 'anthropicCompatBackend' is any other host that speaks the Anthropic Messages API.+* 'localOllamaBackend' is a local Ollama server.+* 'openAICompatBackend' is any other host that speaks the OpenAI Chat Completions API.++All four are built on 'baikaiBackend', which makes one request per+'Control.Monad.Prompt.Backend.runBackendChat'. Calling a tool the model asks for, and+sending the result back, is left to the caller as for every backend (see+'Control.Monad.Prompt.Effect.promptTools').++The four constructors have these in common:++* Each returns in 'IO' because it registers its @baikai@ provider ('localOllamaBackend'+  also reads @OLLAMA_HOST@). No request is made until the first prompt.+* A reply is limited to 4096 tokens. The context window and output limit set on the+  'Model' are the published ones for the model of 'claudeBackend', and the placeholders+  8192 and 4096 for the other constructors, whose model is not known; they do not+  limit a reply.++Note that other limits need 'baikaiBackend' with a 'Model' and 'Options' of your own.+-}+module Control.Monad.Prompt.Baikai (+  -- * Backends for common hosts+  claudeBackend,+  anthropicCompatBackend,+  localOllamaBackend,+  openAICompatBackend,++  -- * Custom backends+  baikaiBackend,+  contextItemsToBaikai,++  -- * Auxiliary definitions and utilities+  normaliseOllamaHost,+) where++-- base+import Control.Exception (SomeAsyncException, SomeException, fromException, tryJust)+import Control.Monad.IO.Class (MonadIO (..))+import Data.Foldable (toList)+import System.Environment (lookupEnv)++-- text+import Data.Text (Text)+import Data.Text qualified as T++-- vector+import Data.Vector qualified as V++-- effectful+import Effectful (runEff)++-- baikai+import Baikai.Api (Api (AnthropicMessages, OpenAIChatCompletions))+import Baikai.Auth (ApiKeySource (ApiKeyLiteral))+import Baikai.Compat (MaxTokensField (MaxTokensField), OpenAICompletionsCompat (maxTokensField), autoDetectOpenAICompletions, hostMatchesSuffix, urlHost)+import Baikai.Content (AssistantContent (AssistantToolCall))+import Baikai.Content qualified as BContent+import Baikai.Context (Context (messages, systemPrompt, tools), emptyContext)+import Baikai.Error (ErrorCategory (ContentFiltered))+import Baikai.Error qualified as BE+import Baikai.Message (AssistantPayload (..), Message, assistant, toolResultErrorText, toolResultMessage, toolResultText, user)+import Baikai.Message qualified as BMessage+import Baikai.Model (Compat (CompatNone, CompatOpenAICompletions), Model (..), mkModel)+import Baikai.Options (Options (..), emptyOptions)+import Baikai.Response (Response (..), flattenAssistantText, responseError)+import Baikai.ResponseFormat (JsonSchemaFormat (strict), ResponseFormat (JsonSchema), jsonSchemaFormat)+import Baikai.StopReason (StopReason (Length, ToolUse))+import Baikai.Tool (Tool, mkTool)+import Baikai.Usage (zeroUsage)++-- baikai-effectful+import Baikai.Effectful (complete, runBaikai)++-- baikai-claude+import Baikai.Provider.Claude.Api qualified as ClaudeProvider++-- baikai-openai+import Baikai.Provider.OpenAI.Api qualified as OpenAIProvider++-- shroom+import Control.Monad.Prompt.Backend (+  Backend (..),+  BackendError (..),+  BackendReply (..),+  ContextItem (..),+  ToolCall (..),+  ToolDef (..),+  ToolResult (..),+ )++-- * Converting shroom's context to baikai's++{- | Turn shroom's context items into the request 'Context' of baikai, for a hand-written t'Backend' built on baikai.++Its 'SystemMessage' items are joined with newlines into the one+'systemPrompt'. 'ToolCallMessage' becomes one assistant message with a tool-call+block per call, and 'ToolResultMessage' one tool-result message per result. The+'tools' field stays empty, for 'baikaiBackend' to set.+-}+contextItemsToBaikai ::+  -- | The conversation so far.+  [ContextItem] ->+  -- | The description of the expected result type, which becomes the final user turn.+  Text ->+  Context+contextItemsToBaikai items typeDesc =+  emptyContext+    { systemPrompt = case [t | SystemMessage t <- items] of+        [] -> Nothing+        ts -> Just (T.intercalate "\n" ts)+    , messages =+        V.fromList $+          concatMap toBaikaiMessages [item | item <- items, not (isSystemItem item)]+            <> [user typeDesc]+    }+  where+    isSystemItem (SystemMessage _) = True+    isSystemItem _ = False++toBaikaiMessages :: ContextItem -> [Message]+toBaikaiMessages (SystemMessage _) = []+toBaikaiMessages (UserMessage t) = [user t]+toBaikaiMessages (AssistantMessage t) = [assistant t]+toBaikaiMessages (ToolCallMessage calls) =+  [ BMessage.AssistantMessage+      AssistantPayload+        { content = V.fromList (AssistantToolCall . toBaikaiToolCall <$> calls)+        , usage = zeroUsage+        , stopReason = ToolUse+        , errorMessage = Nothing+        , timestamp = Nothing+        }+  ]+toBaikaiMessages (ToolResultMessage results) = fmap toBaikaiToolResultMessage results++toBaikaiToolCall :: ToolCall -> BContent.ToolCall+toBaikaiToolCall tc =+  BContent.ToolCall+    { BContent.id_ = tc.toolCallId+    , BContent.name = tc.toolCallName+    , BContent.arguments = tc.toolCallArguments+    }++toBaikaiToolResultMessage :: ToolResult -> Message+toBaikaiToolResultMessage tr =+  toolResultMessage tr.toolResultId tr.toolResultName (toBaikaiToolResult tr.toolResultOutcome)+  where+    toBaikaiToolResult :: Either Text Text -> BMessage.ToolResult+    toBaikaiToolResult (Left err) = toolResultErrorText err+    toBaikaiToolResult (Right txt) = toolResultText txt++{- | Convert a t'ToolDef' to a baikai 'Tool'. The schema is passed on unchanged as the+opaque t'Data.Aeson.Value' that the @parameters@ field of 'Tool' holds. It must+already be flat, without @$ref@; every schema a t'ToolDef' carries is.+-}+toBaikaiTool :: ToolDef -> Tool+toBaikaiTool td = mkTool td.toolDefName td.toolDefDescription td.toolDefSchema++-- * Reading baikai's response back++{- | Read a t'Response' as a 'BackendReply' or a 'BackendError'.++Failure is decided by baikai's 'responseError', not by 'errorInfo': it is 'Just'+exactly when the stop reason is an error, including an error stop with no classified+detail, which 'errorInfo' alone would read as a successful empty answer.++A 'ContentFiltered' error is a refusal and becomes 'BackendRefusal'. Its+'refusalCategory' is populated only on Anthropic's streaming path, so with the+non-streaming 'complete' it is 'Nothing'. Any other error is a transport failure+for the retry to handle: 'BackendTransportError'. A 'Length' stop is a reply cut off+by the token or context limit and becomes 'BackendTruncated'. Otherwise tool-call+blocks in the reply make 'BackendToolCalls', and none make a 'BackendAnswer'.+-}+interpretResponse :: Response -> Either BackendError BackendReply+interpretResponse resp = case responseError resp of+  Just err+    | BE.category err == ContentFiltered ->+        Left (BackendRefusal {refusalCategory = BE.refusalCategory err, refusalMessage = BE.message err})+    | otherwise -> Left (BackendTransportError (BE.message err))+  Nothing+    -- Cut off by the token or context limit: whatever arrived, text or+    -- tool-call arguments, is half a document.+    | resp.message.stopReason == Length ->+        Left (BackendTruncated (flattenAssistantText resp.message.content))+    | otherwise ->+        let calls = [tc | AssistantToolCall tc <- toList resp.message.content]+         in if null calls+              then Right (BackendAnswer (flattenAssistantText resp.message.content))+              else Right (BackendToolCalls (fmap fromBaikaiToolCall calls))++fromBaikaiToolCall :: BContent.ToolCall -> ToolCall+fromBaikaiToolCall bc =+  ToolCall+    { toolCallId = BContent.id_ bc+    , toolCallName = BContent.name bc+    , toolCallArguments = BContent.arguments bc+    }++-- * The adapter++{- | Build a t'Backend' that makes one @baikai-effectful@ 'complete' call per+'Control.Monad.Prompt.Backend.runBackendChat'. The four constructors of this module are built on it; use it+directly for another provider, or for 'Options' they do not set.++The schema of the requested type goes out as the structured-output format on every+call, with or without tools, and with the @strict@ field of t'JsonSchemaFormat' set to @True@: OpenAI enforces it, and the+schema shroom produces already fits OpenAI's strict subset. Anthropic's structured+outputs enforce the schema either way.++No /synchronous/ exception a 'complete' call throws escapes this function; it comes+back as 'BackendTransportError'. /Asynchronous/ exceptions+('SomeAsyncException': a 'System.Timeout.timeout', 'Control.Exception.ThreadKilled', an @async@+cancellation) propagate, so that a 'System.Timeout.timeout' around a hung call returns 'Nothing'+instead of being retried as a backend error.+-}+baikaiBackend ::+  (MonadIO m) =>+  -- | The model to call, which names the provider and the host.+  Model ->+  -- | The options of every call. The response format is set per call, to the schema of the requested type, and replaces one given here.+  Options ->+  Backend m+baikaiBackend model baseOpts =+  Backend $ \ctx typeDesc schema toolDefs -> liftIO $ do+    let bCtx = (contextItemsToBaikai ctx typeDesc) {tools = V.fromList (fmap toBaikaiTool toolDefs)}+        opts =+          baseOpts+            { responseFormat = Just (JsonSchema ((jsonSchemaFormat "response" schema) {strict = True}))+            }+    result <- tryJust synchronousOnly (runEff (runBaikai (complete model bCtx opts)))+    pure $ case result of+      Left ex -> Left (BackendTransportError (T.pack (show ex)))+      Right resp -> interpretResponse resp+  where+    -- 'Nothing' lets an asynchronous exception keep propagating; 'Just'+    -- catches the synchronous ones.+    synchronousOnly :: SomeException -> Maybe SomeException+    synchronousOnly ex = case fromException ex of+      Just (_ :: SomeAsyncException) -> Nothing+      Nothing -> Just ex++-- * Backends for common hosts++{- | The 'Model' for the Anthropic constructors, with @baikai@'s own zero limits for+the caller to fill in. Registers the @baikai-claude@ provider.+-}+anthropicModel :: Text -> Text -> IO Model+anthropicModel baseUrl modelId = do+  ClaudeProvider.register+  pure (mkModel AnthropicMessages modelId baseUrl)++{- | The Claude API at @api.anthropic.com@, via @baikai-claude@. The model is+@claude-haiku-4-5-20251001@, with its published limits (200000 tokens of context,+8192 of output) as the 'Model' limits. For another Claude model use+'anthropicCompatBackend' with the base URL @https:\/\/api.anthropic.com@.+-}+claudeBackend ::+  (MonadIO m) =>+  -- | The Anthropic API key.+  Text ->+  IO (Backend m)+claudeBackend apiKey = do+  model <- anthropicModel "https://api.anthropic.com" "claude-haiku-4-5-20251001"+  let model' = model {contextWindow = 200000, maxOutputTokens = 8192}+      opts = emptyOptions {apiKey = Just (ApiKeyLiteral apiKey), maxTokens = Just 4096}+  pure (baikaiBackend model' opts)++-- | Any host that speaks the Anthropic Messages API, via @baikai-claude@.+anthropicCompatBackend ::+  (MonadIO m) =>+  -- | The base URL of the host, such as @https:\/\/api.deepseek.com\/anthropic@, without @\/v1@.+  Text ->+  -- | The id of the model, as the host names it, such as @deepseek-v4-pro@.+  Text ->+  {- | The API key, passed on as it is. Unlike the key of 'openAICompatBackend', it is+  not a 'Maybe': a hosted Anthropic-compatible host checks a real key, and a local+  proxy that does not still needs a placeholder, which only the caller can choose.+  -}+  Text ->+  IO (Backend m)+anthropicCompatBackend baseUrl modelId apiKey = do+  model <- anthropicModel baseUrl modelId+  let model' = model {contextWindow = 8192, maxOutputTokens = 4096}+      opts = emptyOptions {apiKey = Just (ApiKeyLiteral apiKey), maxTokens = Just 4096}+  pure (baikaiBackend model' opts)++{- | A local Ollama server, through its OpenAI-compatible Chat Completions API, via+@baikai-openai@. Like 'openAICompatBackend' without an API key, for the server at+@OLLAMA_HOST@, read through 'normaliseOllamaHost'; without @OLLAMA_HOST@ it is+@http:\/\/127.0.0.1:11434@.+-}+localOllamaBackend ::+  (MonadIO m) =>+  -- | The id of the model, such as @llama3.2:1b@.+  Text ->+  IO (Backend m)+localOllamaBackend modelId = do+  mHost <- lookupEnv "OLLAMA_HOST"+  let baseUrl = maybe "http://127.0.0.1:11434" (normaliseOllamaHost . T.pack) mHost+  openAICompatBackend baseUrl modelId Nothing++{- | Add a scheme and a default port to an @OLLAMA_HOST@-style value that lacks them.++Ollama's convention is a bare @host@ or @host:port@. A value without+@\"scheme:\/\/\"@ gets @http:\/\/@ in front, and @:11434@ behind when it names no+port. A value with a scheme is returned as it is, port included, so that+@https:\/\/tunnel-host@ stays on port 443.++>>> normaliseOllamaHost "gpu-box"+"http://gpu-box:11434"+>>> normaliseOllamaHost "gpu-box:8080"+"http://gpu-box:8080"+>>> normaliseOllamaHost "https://tunnel-host"+"https://tunnel-host"+-}+normaliseOllamaHost :: Text -> Text+normaliseOllamaHost h+  | "://" `T.isInfixOf` h = h+  | ":" `T.isInfixOf` h = "http://" <> h+  | otherwise = "http://" <> h <> ":11434"++{- | Any host that speaks the OpenAI Chat Completions API, hosted or self-hosted (vLLM,+the llama.cpp server), via @baikai-openai@.++The token cap is sent as @max_tokens@, not as @max_completion_tokens@, which+@baikai-openai@ sends by default and Ollama ignores. The host's other auto-detected+quirks are kept. @api.openai.com@ itself keeps @max_completion_tokens@, because its+newer models reject @max_tokens@.+-}+openAICompatBackend ::+  (MonadIO m) =>+  -- | The base URL of the host, such as @https:\/\/api.openai.com@, without @\/v1@.+  Text ->+  -- | The id of the model, as the host names it, such as @gpt-4o-mini@.+  Text ->+  {- | The API key. 'Nothing' for a host that checks no credential, such as a bare+  Ollama or llama.cpp server, and 'Just' the key for a host that does.+  -}+  Maybe Text ->+  IO (Backend m)+openAICompatBackend baseUrl modelId mApiKey = do+  OpenAIProvider.register+  let model =+        (mkModel OpenAIChatCompletions modelId baseUrl)+          { contextWindow = 8192+          , maxOutputTokens = 4096+          , compat = legacyMaxTokensCompat baseUrl+          }+      opts =+        emptyOptions+          { apiKey = Just (maybe (ApiKeyLiteral "unused") ApiKeyLiteral mApiKey)+          , maxTokens = Just 4096+          }+  pure (baikaiBackend model opts)++{- | The 'Compat' for 'openAICompatBackend': the one @baikai-openai@ auto-detects from+the base URL, with the token cap named @max_tokens@. @api.openai.com@ is left to+auto-detection ('CompatNone').+-}+legacyMaxTokensCompat :: Text -> Compat+legacyMaxTokensCompat baseUrl+  | maybe False (`hostMatchesSuffix` "api.openai.com") (urlHost baseUrl) = CompatNone+  | otherwise =+      CompatOpenAICompletions+        (autoDetectOpenAICompletions baseUrl) {maxTokensField = MaxTokensField}
+ test/Integration/Cases.hs view
@@ -0,0 +1,183 @@+{- | The one shared list of backend-integration test cases: written once+against "Control.Monad.Prompt.Backend"'s interface, then run in+"Integration.Claude" (against 'Control.Monad.Prompt.Baikai.claudeBackend')+and twice more in "Integration.Ollama" — against+'Control.Monad.Prompt.Baikai.localOllamaBackend', and against+'Control.Monad.Prompt.Baikai.openAICompatBackend' itself, called with the+same base URL and an explicit placeholder key rather than+'localOllamaBackend'\'s own 'Nothing' — the front-door path a caller+supplying a real key would exercise. The three call sites differ only in+which 'Backend' they pass in, never in the cases themselves.++Covers at least the union of what "Integration.Claude" and+"Integration.Ollama" each covered before this module existed: a typed value+comes back ('User', 'Counter'), a property-validated chain runs end to end+('conferenceChain'), and a tool actually gets dispatched and its result read+back in ('conferenceChainWithTools'). Three further cases run+@deriving via Generically@ end to end, always through the class method+'Control.Monad.Prompt.Promptable.prompt', since the single-request+'Control.Monad.Prompt.Effect.promptSingle' would pass without running the strategy:+a bare 'Text', 'Int' and 'Double' (the non-object schema roots the strategy+sends for its fields and for the constructor choice, so a provider that+rejects one fails there first), then the record 'Musician' and the sum+'Fruit' from "GenericTypes". Each suite keeps whatever+provider-specific cases do not fit this shape (web-search-tool smoke tests+and failure reporting in "Integration.Claude"; 'celebrityChain' and the+non-object top-level response types in "Integration.Ollama") alongside a+call to 'backendIntegrationTests'.++These cases, and the non-object top-level ones in "Integration.Ollama",+assert shroom's plumbing, not the model's capability; this paragraph is the+one statement of that rule for both files. An+assertion stays if it is a property any correct provider must satisfy, or+evidence that shroom's own machinery worked (the response parsed into the+declared type, fields were mapped to the right names, a non-object top-level+type was round-tripped, a tool was dispatched and its result read+back in); it is dropped or weakened if passing it requires the model to be+/good/. Applied to the assertions here: the upper bound on speaker count+(@n <= 10@) encoded an assumption about a weak local model's typical output+size, so it is dropped rather than risking a spurious failure against a+provider that reasons about more speakers; the exact answers (the counter's+value being 42, the user's name being @"Alice"@) were the model's to get+right, so they are weakened to what the machinery is responsible for, namely+that a 'Counter' came back at all, and that the name and email fields hold+non-empty text with the \@ in the email field only. In "Integration.Ollama"+the same goes for the spider-legs answer and the first three integers:+only that a 'ScalarInt' and a 'ScalarIntList' came back is asserted, never+@8@ or @[1, 2, 3]@, since a small local model may get those wrong. The slot-continuity+check (each slot picks up exactly where the last one left off), the+speaker-count floor and @length talks == n@ (cross-field coherence) and the+tool-was-called check stay, being properties of a valid result regardless of+provider.+-}+module Integration.Cases (backendIntegrationTests, sharedPromptConfig) where++-- base+import Data.IORef++-- effectful+import Effectful (Eff, IOE)+import Effectful.Concurrent.Async (Concurrent)+import Effectful.Error.Static (Error)+import Effectful.State.Static.Local (State)++-- text+import Data.Text (Text)+import Data.Text qualified as T++-- tasty+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++-- shroom+import Control.Monad.Prompt.Backend (Backend, ContextItem)+import Control.Monad.Prompt.Effect (PromptConfig (..), defaultPromptConfig)+import Control.Monad.Prompt.Effect qualified as Effect+import Control.Monad.Prompt.Promptable qualified as Promptable+import Control.Monad.Prompt.Tool (ToolHandler (..), runTool, runToolHandler, toolBinding)+import Control.Monad.Prompt.Tool.Web (DuckDuckGoSearch, duckDuckGoSearchHandler)++-- test+import ConferenceTypes+import GenericTypes (Fruit, Musician, allPropertiesHold)+import Types++{- | Generous enough for the weakest provider exercised here (a small local+Ollama model) without weakening any assertion for a stronger one: more+retries and tool steps only widen the budget before a call is given up on,+they do not change what counts as success.+-}+sharedPromptConfig :: PromptConfig+sharedPromptConfig = defaultPromptConfig {maxRetries = 10, maxToolSteps = Just 10}++-- | The concrete effect stack every call site here runs its program through.+type BackendEs = Eff '[State [ContextItem], Error Text, Concurrent, IOE]++{- | Run the shared cases — a typed value, a property-validated chain, and a+tool-dispatch case proving the tool was actually invoked — against one+'Backend'.+-}+backendIntegrationTests :: Backend BackendEs -> TestTree+backendIntegrationTests backend =+  testGroup+    "backend integration cases"+    [ testCase "Promptable.prompt returns a bare Text, Int and Double" $ do+        -- Scalar roots, through the class method: the generic strategy sends+        -- them as fields and as the constructor-choice enum, so a provider+        -- that refuses one should fail here rather than inside 'Fruit'.+        result <- Effect.runPromptResultEff backend sharedPromptConfig $ do+          Effect.context "Give the name of one fruit."+          fruitName <- Promptable.prompt @Text+          Effect.context "Give the number of seeds in one apple."+          seeds <- Promptable.prompt @Int+          Effect.context "Give the weight of one apple, in grams."+          grams <- Promptable.prompt @Double+          pure (fruitName, seeds, grams)+        case result of+          Left err -> assertFailure (show err)+          -- Any 'Int' and 'Double' prove the scalar roots round-tripped.+          Right (fruitName, _, _) -> assertBool "text is non-empty" (not (T.null fruitName))+    , testCase "Promptable.prompt returns a Musician, field by field" $ do+        -- The class method, not 'Effect.promptSingle': that one sends a single request+        -- and would pass without running the generic strategy.+        result <- Effect.runPromptResultEff backend sharedPromptConfig $ do+          Effect.context "Make up a classical composer."+          Promptable.prompt @Musician+        case result of+          Left err -> assertFailure (show err)+          Right musician -> assertBool "the properties of the musician hold" (allPropertiesHold musician)+    , testCase "Promptable.prompt returns a Fruit, constructor first" $ do+        result <- Effect.runPromptResultEff backend sharedPromptConfig $ do+          Effect.context "Make up a fruit that a classical composer would eat for breakfast."+          Promptable.prompt @Fruit+        case result of+          Left err -> assertFailure (show err)+          Right fruit -> assertBool "the properties of the fruit hold" (allPropertiesHold fruit)+    , testCase "promptSingle returns a User" $ do+        result <- Effect.runPromptResultEff backend sharedPromptConfig $ do+          Effect.context "Return a JSON object for a user named Alice with email alice@example.com"+          Effect.promptSingle @User+        case result of+          Left err -> assertFailure (show err)+          Right user -> do+            assertBool "name is non-empty" (not (T.null (userName user)))+            assertBool "email is non-empty" (not (T.null (userEmail user)))+            assertBool "email field holds an address" ("@" `T.isInfixOf` userEmail user)+            assertBool "name field does not hold an address" (not ("@" `T.isInfixOf` userName user))+    , testCase "promptSingle returns a Counter" $ do+        result <- Effect.runPromptResultEff backend sharedPromptConfig $ do+          Effect.context "Return a JSON counter object with value 42."+          Effect.promptSingle @Counter+        case result of+          Left err -> assertFailure (show err)+          -- Any 'Int' proves the non-object top-level type round-tripped.+          Right (Counter _) -> pure ()+    , testCase "conferenceChain produces a valid schedule" $ do+        result <- Effect.runPromptResultEff backend sharedPromptConfig conferenceChain+        case result of+          Left err -> assertFailure (show err)+          Right (allSpeakers, talks, schedule) -> do+            let n = length (speakers allSpeakers)+            assertBool "at least 3 speakers" (n >= 3)+            length talks @?= n+            let slots = scheduleSlots schedule+            assertBool "at least one slot" (not (null slots))+            let pairs = zip slots (drop 1 slots)+            assertBool "each slot picks up where the last left off" (all (\(a, b) -> slotEnd a == slotStart b) pairs)+    , testCase "conferenceChainWithTools: web_search tool is invoked at least once" $ do+        callCount <- newIORef (0 :: Int)+        let countingHandler = ToolHandler $ \q -> do+              atomicModifyIORef' callCount (\n -> (n + 1, ()))+              runToolHandler duckDuckGoSearchHandler q+        result <-+          Effect.runPromptResultEff backend sharedPromptConfig $+            runTool countingHandler (conferenceChainWithTools [toolBinding @DuckDuckGoSearch])+        case result of+          Left err -> assertFailure (show err)+          Right (allSpeakers, talks, _schedule) -> do+            let n = length (speakers allSpeakers)+            assertBool "at least 3 speakers" (n >= 3)+            length talks @?= n+        n <- readIORef callCount+        assertBool "web_search tool was called at least once" (n > 0)+    ]
+ test/Integration/Claude.hs view
@@ -0,0 +1,112 @@+{-# LANGUAGE DeriveAnyClass #-}++module Main (main) where++-- base+import GHC.Generics (Generic)+import System.Environment (lookupEnv)+import System.Exit (die)++-- text+import Data.Text (Text, pack)+import Data.Text qualified as T++-- aeson+import Data.Aeson (FromJSON, ToJSON)++-- openapi3+import Data.OpenApi (ToSchema)++-- generics-sop+import Generics.SOP qualified as SOP++-- tasty+import Test.Tasty (TestTree, defaultMain, testGroup)+import Test.Tasty.HUnit (assertFailure, testCase)++-- shroom+import Control.Monad.Prompt (Promptable)+import Control.Monad.Prompt.Baikai (claudeBackend)+import Control.Monad.Prompt.Effect (PromptConfig (..), defaultPromptConfig)+import Control.Monad.Prompt.Effect qualified as Effect+import Control.Monad.Prompt.Tool (ToolHandler (..), Toolable (..), runTool)+import Control.Monad.Prompt.Tool.Web (+  DuckDuckGoSearch,+  WebFetch,+  WikipediaSearch,+  duckDuckGoSearchHandler,+  webFetchHandler,+  wikipediaSearchHandler,+ )++import Data.Shroom.Class (Describable (..), Surveyable (..))++-- test+import Integration.Cases (backendIntegrationTests)+import WebToolReport (toolResults, webToolReportChain)++-- * Fake broken tool for testing failure reporting++newtype FakeBrokenSearch = FakeBrokenSearch {brokenQuery :: Text}+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++instance Describable FakeBrokenSearch where+  describeType _ = "A search query that always fails with a 404 error."++instance Surveyable FakeBrokenSearch++instance Promptable FakeBrokenSearch++instance Toolable FakeBrokenSearch where+  toolDescription _ = Just "Always returns an HTTP 404 error."++fakeBrokenSearchHandler :: ToolHandler FakeBrokenSearch+fakeBrokenSearchHandler = ToolHandler $ \_ -> pure (Left "HTTP 404: not found")++main :: IO ()+main = do+  mKey <- lookupEnv "ANTHROPIC_API_KEY"+  case mKey of+    Nothing -> die "ANTHROPIC_API_KEY not set; the Claude integration suite needs it to run"+    Just key -> integrationTests (pack key) >>= defaultMain++integrationTests :: Text -> IO TestTree+integrationTests apiKey = do+  backend <- claudeBackend apiKey+  pure $+    testGroup+      "Claude API integration"+      [ backendIntegrationTests backend+      , testCase "web tools smoke test: all three tools work" $ do+          let pcfg = defaultPromptConfig {maxRetries = 3, maxToolSteps = Just 15, debugLog = Just (putStrLn . T.unpack)}+          result <-+            Effect.runPromptResultEff backend pcfg $+              runTool duckDuckGoSearchHandler $+                runTool wikipediaSearchHandler $+                  runTool webFetchHandler $+                    webToolReportChain @'[DuckDuckGoSearch, WikipediaSearch, WebFetch]+          case result of+            Left err -> assertFailure (T.unpack err)+            Right report ->+              -- "ok" means success; anything else is a reported failure+              mapM_+                ( \(tool, status) ->+                    if status == "ok"+                      then pure ()+                      else assertFailure ("Tool " <> T.unpack tool <> " failed: " <> T.unpack status)+                )+                (toolResults report)+      , testCase "web tools: broken tool failure is reported" $ do+          let pcfg = defaultPromptConfig {maxRetries = 3, maxToolSteps = Just 5, debugLog = Just (putStrLn . T.unpack)}+          result <-+            Effect.runPromptResultEff backend pcfg $+              runTool fakeBrokenSearchHandler (webToolReportChain @'[FakeBrokenSearch])+          case result of+            Left err -> assertFailure (T.unpack err)+            Right report ->+              case lookup "fake_broken_search" (toolResults report) of+                Nothing -> assertFailure "fake_broken_search missing from report"+                Just "ok" -> assertFailure "Expected fake_broken_search to be reported as failed, but got ok"+                Just _ -> pure () -- model correctly reported a non-ok status+      ]
+ test/Integration/Ollama.hs view
@@ -0,0 +1,140 @@+module Main (main) where++-- base+import System.Environment (lookupEnv)++-- aeson+import Data.Aeson (object)++-- text+import Data.Text (Text, pack)+import Data.Text qualified as T++-- tasty+import Test.Tasty (TestTree, defaultMain, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, testCaseSteps)++-- shroom+import Control.Monad.Prompt.Backend (BackendReply (..), ContextItem (..), runBackendChat)+import Control.Monad.Prompt.Baikai (anthropicCompatBackend, localOllamaBackend, normaliseOllamaHost, openAICompatBackend)+import Control.Monad.Prompt.Effect (PromptConfig (..), defaultPromptConfig)+import Control.Monad.Prompt.Effect qualified as Effect+import Control.Monad.Prompt.Tool (runTool, toolBinding)+import Control.Monad.Prompt.Tool.Web (DuckDuckGoSearch, WebFetch, duckDuckGoSearchHandler, webFetchHandler)++-- test+import CelebrityTypes+import Integration.Cases (backendIntegrationTests)+import ScalarTypes (ScalarInt (..), ScalarIntList (..), ScalarText (..))++main :: IO ()+main = do+  mModel <- lookupEnv "OLLAMA_MODEL"+  -- Falls back to the same tag 'nix/ollama-shroom.nix' pulls by default, so running+  -- this suite locally against a module-provisioned Ollama without setting+  -- OLLAMA_MODEL asks for a model that is actually there. Keep the two in agreement+  -- by hand; a Haskell test suite has no business parsing a nix file at runtime.+  let model = maybe "llama3.2:1b" pack mModel+  ollamaIntegrationTests model >>= defaultMain++{- | 'localOllamaBackend' honours @OLLAMA_HOST@ itself, so this suite does not+read it directly.++The second backend built here calls 'Control.Monad.Prompt.Baikai.openAICompatBackend'+itself, the front-door constructor, rather than going around it: the same+@OLLAMA_HOST@-derived base URL 'localOllamaBackend' passes through+underneath, but with an explicit placeholder key where 'localOllamaBackend'+always passes 'Nothing' — exercising the constructor's @Just@ branch, which+'localOllamaBackend' never reaches. Ollama itself checks no credential, so+the placeholder only has to be non-empty, never correct.++The third calls 'Control.Monad.Prompt.Baikai.anthropicCompatBackend' against the+same host, which Ollama also serves as an Anthropic Messages API (@\/v1\/messages@).+Its one case sends a plain request through 'runBackendChat' and asserts that a+reply came back and was parsed as an Anthropic message, so it covers the+Anthropic Messages wire format and @baikai-claude@'s envelope parsing through+shroom's adapter, without a paid key. It does /not/ run the shared typed+'backendIntegrationTests' cases: Ollama's @\/v1\/messages@ ignores the+structured-output schema and answers in prose, so typed prompting on the+Anthropic path is covered only by the local Claude suite ("Integration.Claude").+Nor does it cover 'Control.Monad.Prompt.Baikai.claudeBackend'\'s fixed+@api.anthropic.com@ URL.+-}+ollamaIntegrationTests :: Text -> IO TestTree+ollamaIntegrationTests model = do+  localBackend <- localOllamaBackend model+  mHost <- lookupEnv "OLLAMA_HOST"+  let baseUrl = maybe "http://127.0.0.1:11434" (normaliseOllamaHost . T.pack) mHost+  genericBackend <- openAICompatBackend baseUrl model (Just "unused-ollama-checks-no-credential")+  anthropicBackend <- anthropicCompatBackend baseUrl model "unused-ollama-checks-no-credential"+  pure $+    testGroup+      "Ollama integration"+      [ testGroup+          "localOllamaBackend"+          [ backendIntegrationTests localBackend+          , testCaseSteps "celebrityChain: chain completes successfully with tools available" $ \step -> do+              let pcfg =+                    defaultPromptConfig+                      { maxRetries = 5+                      , maxToolSteps = Just 10+                      , debugLog = Just (step . T.unpack)+                      }+              result <-+                Effect.runPromptResultEff localBackend pcfg $+                  runTool duckDuckGoSearchHandler $+                    runTool webFetchHandler $+                      celebrityChain [toolBinding @DuckDuckGoSearch, toolBinding @WebFetch]+              case result of+                Left err -> assertFailure (show err)+                Right fact -> do+                  assertBool "celebrity not empty" (not (T.null (celebrity fact)))+                  assertBool "trivia fact not empty" (not (T.null (triviaFact fact)))+          , testCase "promptSingle returns a non-object Int" $ do+              result <- Effect.runPromptResultEff localBackend (defaultPromptConfig {maxRetries = 10}) $ do+                Effect.context "How many legs does a spider have? Answer with just the number."+                Effect.promptSingle @ScalarInt+              case result of+                Left err -> assertFailure (show err)+                -- Any 'Int' proves the non-object top-level type round-tripped;+                -- see "Integration.Cases" for why the answer is not asserted.+                Right (ScalarInt _) -> pure ()+          , testCase "promptSingle returns a non-object Text" $ do+              result <- Effect.runPromptResultEff localBackend (defaultPromptConfig {maxRetries = 10}) $ do+                Effect.context "Return the word \"hello\" and nothing else."+                Effect.promptSingle @ScalarText+              case result of+                Left err -> assertFailure (show err)+                Right (ScalarText t) -> assertBool "non-empty" (not (T.null t))+          , testCase "promptSingle returns a non-object array of Int" $ do+              result <- Effect.runPromptResultEff localBackend (defaultPromptConfig {maxRetries = 10}) $ do+                Effect.context "Return the first three positive integers as a JSON array, in order."+                Effect.promptSingle @ScalarIntList+              case result of+                Left err -> assertFailure (show err)+                -- Any list of 'Int' proves the non-object array round-tripped;+                -- the values are the model's to get right, not shroom's.+                Right (ScalarIntList _) -> pure ()+          ]+      , testGroup+          "openAICompatBackend (explicit base URL, explicit key)"+          [backendIntegrationTests genericBackend]+      , testGroup+          "anthropicCompatBackend (Ollama's Anthropic Messages API)"+          [ testCase "a plain request comes back as a parsed Anthropic reply" $ do+              -- Transport only: Ollama's @\/v1\/messages@ ignores the schema, so+              -- all this asserts is that a reply arrived, was read as an+              -- Anthropic message and carries some text.+              result <-+                runBackendChat+                  anthropicBackend+                  [UserMessage "Say hello."]+                  "Reply with one short sentence."+                  (object [])+                  []+              case result of+                Left err -> assertFailure (show err)+                Right (BackendAnswer t) -> assertBool "non-empty reply" (not (T.null (T.strip t)))+                Right reply -> assertFailure ("expected an answer, got: " <> show reply)+          ]+      ]
+ test/Offline/Main.hs view
@@ -0,0 +1,231 @@+module Main (main) where++-- base+import Control.Concurrent (forkIO, killThread, newEmptyMVar, putMVar, takeMVar)+import Control.Exception (bracket, finally)+import Control.Monad (void)+import Data.Char (isAsciiUpper)+import GHC.Clock (getMonotonicTime)+import System.Environment (lookupEnv, setEnv, unsetEnv)+import System.Timeout (timeout)++-- bytestring+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS+import Data.ByteString.Char8 qualified as BC+import Data.ByteString.Lazy qualified as BL++-- aeson+import Data.Aeson (Value (Null, Number, Object), decodeStrict, encode, object, (.=))+import Data.Aeson.KeyMap qualified as KeyMap++-- text+import Data.Text qualified as T++-- network+import Network.Socket (+  Family (AF_INET),+  PortNumber,+  SockAddr (SockAddrInet),+  Socket,+  SocketType (Stream),+  accept,+  bind,+  close,+  defaultProtocol,+  getSocketName,+  listen,+  socket,+  tupleToHostAddress,+ )+import Network.Socket.ByteString (recv, sendAll)++-- tasty+import Test.Tasty (TestTree, defaultMain, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++-- shroom+import Control.Monad.Prompt.Backend (BackendError (..), runBackendChat)+import Control.Monad.Prompt.Baikai (localOllamaBackend, openAICompatBackend)++main :: IO ()+main = defaultMain tests++tests :: TestTree+tests =+  testGroup+    "shroom-baikai offline"+    [ testCase "timeout interrupts a baikaiBackend call against a server that never answers" $+        withSilentServer $ \port -> do+          backend <- openAICompatBackend ("http://127.0.0.1:" <> T.pack (show port)) "unused" (Just "unused")+          start <- getMonotonicTime+          -- If the adapter swallowed the 'timeout''s asynchronous exception it+          -- would hand back @Just (Left (BackendTransportError _))@ here+          -- instead of 'Nothing'.+          result <- timeout 1_000_000 (runBackendChat backend [] "a type" (object []) [])+          elapsed <- subtract start <$> getMonotonicTime+          case result of+            Nothing -> pure ()+            Just r -> assertFailure ("expected the timeout to fire, but the call returned: " <> show r)+          assertBool ("timeout took " <> show elapsed <> "s, expected well under 3s") (elapsed < 3)+    , testCase "openAICompatBackend caps the output with max_tokens, which Ollama honours" $+        withRecordingServer $ \port recorded -> do+          backend <- openAICompatBackend ("http://127.0.0.1:" <> T.pack (show port)) "unused" (Just "unused")+          void (timeout 5_000_000 (runBackendChat backend [] "a type" (object []) []))+          recorded >>= assertTokenCap+    , testCase "localOllamaBackend caps the output with max_tokens, which Ollama honours" $+        withRecordingServer $ \port recorded ->+          withEnv "OLLAMA_HOST" ("127.0.0.1:" <> show port) $ do+            backend <- localOllamaBackend "unused"+            void (timeout 5_000_000 (runBackendChat backend [] "a type" (object []) []))+            recorded >>= assertTokenCap+    , testCase "a finish_reason of length is a truncated reply, not an answer that fails to parse" $+        withLengthStopServer "{\"userName\":\"Ali" $ \port -> do+          backend <- openAICompatBackend ("http://127.0.0.1:" <> T.pack (show port)) "unused" (Just "unused")+          result <- timeout 5_000_000 (runBackendChat backend [] "a type" (object []) [])+          result @?= Just (Left (BackendTruncated "{\"userName\":\"Ali"))+    ]++{- | The request body names the cap @max_tokens@ — the only spelling Ollama's+OpenAI-compatible layer reads — and does not carry the+@max_completion_tokens@ it ignores.+-}+assertTokenCap :: ByteString -> IO ()+assertTokenCap body = case decodeStrict body of+  Just (Object o) -> do+    KeyMap.lookup "max_tokens" o @?= Just (Number 4096)+    KeyMap.lookup "max_completion_tokens" o @?= Nothing+  other -> assertFailure ("expected a JSON object request body, got: " <> show other <> " from " <> show body)++-- | Run an action with an environment variable set, restoring its old value (or absence) afterwards.+withEnv :: String -> String -> IO a -> IO a+withEnv name value act = do+  old <- lookupEnv name+  setEnv name value+  act `finally` maybe (unsetEnv name) (setEnv name) old++{- | Run an action against a localhost TCP listener on a free port. Binds port+0, so the OS picks a free one and parallel runs cannot collide; localhost+only, no external service.+-}+withListener :: (Socket -> PortNumber -> IO a) -> IO a+withListener act =+  bracket (socket AF_INET Stream defaultProtocol) close $ \listener -> do+    bind listener (SockAddrInet 0 (tupleToHostAddress (127, 0, 0, 1)))+    listen listener 1+    port <-+      getSocketName listener >>= \case+        SockAddrInet p _ -> pure p+        other -> fail ("unexpected listener address: " <> show other)+    act listener port++{- | Run an action against a localhost TCP listener that accepts a connection+and then never reads from it or writes to it.+-}+withSilentServer :: (PortNumber -> IO a) -> IO a+withSilentServer act =+  withListener $ \listener port -> do+    -- Hold the accepted connection open, silent, until the thread is killed.+    blocked <- newEmptyMVar @()+    bracket+      ( forkIO . void $ do+          (conn, _) <- accept listener+          bracket (pure conn) close (\_ -> takeMVar blocked)+      )+      killThread+      (\_ -> act port)++{- | Run an action against a localhost HTTP server that records the body of+the first request it receives and answers it with a 400, so the client+gives up at once instead of retrying. The action gets the port and an+action that waits (up to five seconds) for the recorded body.+-}+withRecordingServer :: (PortNumber -> IO ByteString -> IO a) -> IO a+withRecordingServer act =+  withListener $ \listener port -> do+    bodyVar <- newEmptyMVar+    bracket+      ( forkIO . void $ do+          (conn, _) <- accept listener+          bracket (pure conn) close $ \c -> do+            readRequestBody c >>= putMVar bodyVar+            let reply = "{\"error\":{\"message\":\"recording server\"}}"+            sendAll c $+              "HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\nConnection: close\r\nContent-Length: "+                <> BC.pack (show (BS.length reply))+                <> "\r\n\r\n"+                <> reply+      )+      killThread+      ( \_ ->+          act port $+            timeout 5_000_000 (takeMVar bodyVar)+              >>= maybe (assertFailure "the server never received a request") pure+      )++{- | Read one HTTP request off the socket and return its body, as framed by+@Content-Length@ (a chunked request would be reported as a failure rather+than mis-parsed).+-}+readRequestBody :: Socket -> IO ByteString+readRequestBody conn = go BS.empty+  where+    go acc = case BS.breakSubstring "\r\n\r\n" acc of+      (headers, rest)+        | not (BS.null rest) -> do+            let body = BS.drop 4 rest+            case contentLength headers of+              Nothing -> fail ("request without a Content-Length: " <> show headers)+              Just n -> readUpTo n body+      _ -> recv conn 4096 >>= \chunk -> if BS.null chunk then pure acc else go (acc <> chunk)+    readUpTo n body+      | BS.length body >= n = pure (BS.take n body)+      | otherwise = recv conn 4096 >>= \chunk -> if BS.null chunk then pure body else readUpTo n (body <> chunk)+    contentLength headers =+      case [v | l <- BC.lines headers, Just v <- [BS.stripPrefix "content-length:" (BC.map toLowerAscii l)]] of+        (v : _) -> fst <$> BC.readInt (BC.strip v)+        [] -> Nothing+    toLowerAscii c = if isAsciiUpper c then toEnum (fromEnum c + 32) else c++{- | Run an action against a localhost HTTP server that answers its first+request with a streamed (SSE) OpenAI chat-completions reply: the given text+as the content, then a final chunk with @finish_reason: "length"@, then the+usage chunk and @[DONE]@ — what a server does when the output hits the token+cap. The client's @stream: true@ request is why the answer is SSE.+-}+withLengthStopServer :: T.Text -> (PortNumber -> IO a) -> IO a+withLengthStopServer content act =+  withListener $ \listener port ->+    bracket+      ( forkIO . void $ do+          (conn, _) <- accept listener+          bracket (pure conn) close $ \c -> do+            void (readRequestBody c)+            sendAll c $+              "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n"+                <> sseEvent (chunk (object ["role" .= ("assistant" :: T.Text), "content" .= content]) Null)+                <> sseEvent (chunk (object []) "length")+                <> sseEvent+                  ( object+                      [ "id" .= ("chatcmpl-test" :: T.Text)+                      , "object" .= ("chat.completion.chunk" :: T.Text)+                      , "created" .= (0 :: Int)+                      , "model" .= ("unused" :: T.Text)+                      , "choices" .= ([] :: [Value])+                      , "usage" .= object ["prompt_tokens" .= (10 :: Int), "completion_tokens" .= (4096 :: Int), "total_tokens" .= (4106 :: Int)]+                      ]+                  )+                <> "data: [DONE]\n\n"+      )+      killThread+      (\_ -> act port)+  where+    chunk delta finish =+      object+        [ "id" .= ("chatcmpl-test" :: T.Text)+        , "object" .= ("chat.completion.chunk" :: T.Text)+        , "created" .= (0 :: Int)+        , "model" .= ("unused" :: T.Text)+        , "choices" .= ([object ["index" .= (0 :: Int), "delta" .= delta, "finish_reason" .= (finish :: Value)]] :: [Value])+        ]+    sseEvent v = "data: " <> BL.toStrict (encode v) <> "\n\n"
+ test/ScalarTypes.hs view
@@ -0,0 +1,75 @@+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DeriveGeneric #-}++{- | Non-object top-level response types, used only in "Integration.Ollama"+to prove that a bare scalar or array root schema round-trips through a real+local model unchanged: @baikai@\'s own+'Baikai.ResponseFormat.jsonSchemaFormat' passes the schema straight through+as a raw JSON 'Data.Aeson.Value', so the root needs no wrapper object.++Each is a thin newtype over the type it stands in for ('Int', 'Text',+@['Int']@) rather than an instance directly on that type, so the+'Describable'\/'Surveyable'\/'Promptable' instances live in the module that+defines the newtype and are not orphans. This changes nothing about the+wire shape: a single-constructor, single-field newtype with no record+selector derives 'Data.Aeson.ToJSON'\/'Data.OpenApi.ToSchema' identically to+its underlying type via @GHC.Generics@ — confirmed directly in+@cabal repl@, and already relied on by "Types"\'s own 'Types.Counter', which+this module otherwise mirrors.+-}+module ScalarTypes (ScalarInt (..), ScalarText (..), ScalarIntList (..)) where++-- base+import GHC.Generics (Generic)++-- text+import Data.Text (Text)++-- generics-sop+import Generics.SOP qualified as SOP++-- aeson+import Data.Aeson (FromJSON, ToJSON)++-- openapi3+import Data.OpenApi (ToSchema)++-- shroom+import Control.Monad.Prompt.Promptable (Promptable)+import Data.Shroom.Class (Describable (..), Surveyable)++-- | A bare top-level integer response.+newtype ScalarInt = ScalarInt Int+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++instance Describable ScalarInt where+  describeType _ = "An integer."++instance Surveyable ScalarInt++instance Promptable ScalarInt++-- | A bare top-level string response.+newtype ScalarText = ScalarText Text+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++instance Describable ScalarText where+  describeType _ = "A short string."++instance Surveyable ScalarText++instance Promptable ScalarText++-- | A bare top-level array-of-integers response.+newtype ScalarIntList = ScalarIntList [Int]+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++instance Describable ScalarIntList where+  describeType _ = "A JSON array of integers."++instance Surveyable ScalarIntList++instance Promptable ScalarIntList