packages feed

shroom-baikai-0.1.0.0: test/Integration/Cases.hs

{- | 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)
    ]