packages feed

shroom (empty) → 0.1.0.0

raw patch · 28 files changed

+5643/−0 lines, 28 filesdep +aesondep +basedep +bytestring

Dependencies added: aeson, base, bytestring, containers, directory, effectful, filepath, generics-sop, http-client, modern-uri, network, openapi3, req, shroom, shroom-class, sop-core, tagsoup, tasty, tasty-hunit, template-haskell, text, time, universe-base, vector, witherable

Files

+ CHANGELOG.md view
@@ -0,0 +1,7 @@+# Revision history for shroom++## 0.1.0.0 -- 2026-11-27++* First release. Typed LLM prompting on `effectful`: a program written with `context` and `prompt`+  gets back a typed Haskell value, retried when a reply fails to parse or breaks a property, and+  may offer the model tools its type lists. Released on an unsuspecting world.
+ 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/Main.hs view
@@ -0,0 +1,81 @@+{- | Development executable for inspecting generated prompts.++Runs the conference scheduling prompt chain against the file-based mock+backend, printing each prompt to stdout before reading the response from+@dev\/mock-responses\/response-NNN.json@.++To use:++1. Run @cabal run shroom-dev@ to see the prompts and results.+2. Edit @dev\/mock-responses\/response-NNN.json@ to change what the mock LLM returns.+3. Iterate on prompt quality in @Data.Shroom.Class@ or @Control.Monad.Prompt@.+-}+module Main (main) where++-- text+import Data.Text qualified as T++-- time+import Data.Time (UTCTime, defaultTimeLocale, formatTime)++-- shroom+import Control.Monad.Prompt.Effect (defaultPromptConfig, runPromptResultEff)+import Control.Monad.Prompt.FileMock (defaultFileMockConfig, fileMockBackend)++-- conference scenario+import ConferenceTypes (ConferenceSchedule (..), Slot (..), Speaker (..), SpeakerName (..), Speakers (..), Talk (..), conferenceChain)++fmtTime :: UTCTime -> String+fmtTime = formatTime defaultTimeLocale "%Y-%m-%dT%H:%M:%SZ"++main :: IO ()+main = do+  cfg <- defaultFileMockConfig+  result <- runPromptResultEff (fileMockBackend cfg) defaultPromptConfig conferenceChain+  putStrLn ""+  case result of+    Left err ->+      putStrLn $ "ERROR: " <> T.unpack err+    Right (allSpeakers, talks, schedule) -> do+      putStrLn "=== 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)+                    <> ")"+        )+        (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)
+ dev/mock-responses/response-001.json view
@@ -0,0 +1,19 @@+{+  "speakers": [+    {+      "speakerName": { "firstName": "Ada", "lastName": "Lovelace" },+      "speakerAffiliation": "University of Cambridge",+      "speakerBio": "Ada Lovelace is widely considered the world's first computer programmer, known for her work on Charles Babbage's Analytical Engine."+    },+    {+      "speakerName": { "firstName": "Haskell", "lastName": "Curry" },+      "speakerAffiliation": "Penn State University",+      "speakerBio": "Haskell Curry was a mathematician and logician who made foundational contributions to combinatory logic and lambda calculus."+    },+    {+      "speakerName": { "firstName": "Simon", "lastName": "Peyton Jones" },+      "speakerAffiliation": "University of Glasgow",+      "speakerBio": "Simon Peyton Jones is the lead designer of the Haskell programming language and a key contributor to functional programming research."+    }+  ]+}
+ dev/mock-responses/response-002.json view
@@ -0,0 +1,6 @@+{+  "talkTitle": "Monads and Mechanical Minds: Functional Abstractions for Analytical Engines",+  "talkAbstract": "We explore how the monad abstraction maps onto sequential computation in historical mechanical computers, drawing parallels between Lovelace's algorithm notes and modern pure functional programming.",+  "talkSpeakerName": { "firstName": "Ada", "lastName": "Lovelace" },+  "talkExtensions": ["TypeFamilies"]+}
+ dev/mock-responses/response-003.json view
@@ -0,0 +1,6 @@+{+  "talkTitle": "Combinatory Logic as a Foundation for Functional Languages",+  "talkAbstract": "An exploration of how Curry's combinatory logic underpins modern functional languages, with examples from Haskell and the SKI combinator calculus.",+  "talkSpeakerName": { "firstName": "Haskell", "lastName": "Curry" },+  "talkExtensions": ["UndecidableInstances"]+}
+ dev/mock-responses/response-004.json view
@@ -0,0 +1,6 @@+{+  "talkTitle": "Lazy Evaluation and the Future of Pure Functional Programming",+  "talkAbstract": "Simon Peyton Jones reflects on the design decisions behind Haskell's lazy evaluation strategy, its trade-offs, and what it reveals about the nature of purity in functional languages.",+  "talkSpeakerName": { "firstName": "Simon", "lastName": "Peyton Jones" },+  "talkExtensions": ["LinearTypes"]+}
+ dev/mock-responses/response-005.json view
@@ -0,0 +1,35 @@+{+  "scheduleDay": "2027-06-11T00:00:00Z",+  "scheduleSlots": [+    {+      "slotStart": "2027-06-11T07:00:00Z",+      "slotEnd": "2027-06-11T07:45:00Z",+      "slotTalk": {+        "talkTitle": "Monads and Mechanical Minds: Functional Abstractions for Analytical Engines",+        "talkAbstract": "We explore how the monad abstraction maps onto sequential computation in historical mechanical computers, drawing parallels between Lovelace's algorithm notes and modern pure functional programming.",+        "talkSpeakerName": { "firstName": "Ada", "lastName": "Lovelace" },+        "talkExtensions": ["TypeFamilies"]+      }+    },+    {+      "slotStart": "2027-06-11T07:45:00Z",+      "slotEnd": "2027-06-11T08:30:00Z",+      "slotTalk": {+        "talkTitle": "Combinatory Logic as a Foundation for Functional Languages",+        "talkAbstract": "An exploration of how Curry's combinatory logic underpins modern functional languages, with examples from Haskell and the SKI combinator calculus.",+        "talkSpeakerName": { "firstName": "Haskell", "lastName": "Curry" },+        "talkExtensions": ["UndecidableInstances"]+      }+    },+    {+      "slotStart": "2027-06-11T08:30:00Z",+      "slotEnd": "2027-06-11T09:15:00Z",+      "slotTalk": {+        "talkTitle": "Lazy Evaluation and the Future of Pure Functional Programming",+        "talkAbstract": "Simon Peyton Jones reflects on the design decisions behind Haskell's lazy evaluation strategy, its trade-offs, and what it reveals about the nature of purity in functional languages.",+        "talkSpeakerName": { "firstName": "Simon", "lastName": "Peyton Jones" },+        "talkExtensions": ["LinearTypes"]+      }+    }+  ]+}
+ shroom.cabal view
@@ -0,0 +1,193 @@+cabal-version: 3.0+name: shroom+version: 0.1.0.0+synopsis: Type-safe structured LLM prompting for Haskell+description:+  LLMs hallucinate, but if you use shroom, it will at least be a well-typed+  hallucination!++  shroom lets an LLM understand the types you defined in Haskell and generate+  good values for them. A monadic program written+  with <https://hackage.haskell.org/package/shroom/docs/Control-Monad-Prompt-Effect.html#v:context context> and+  <https://hackage.haskell.org/package/shroom/docs/Control-Monad-Prompt-Promptable.html#v:prompt prompt> returns a typed+  Haskell value, or a descriptive error. The model learns a type from what a+  human reader sees already: its Haddocks and its type, constructor and field+  names. Properties written as pure Haskell functions, example values and+  documentation for the model alone guide it further. A response that fails to+  parse or breaks a property is retried. The package includes+  the prompt monad and its effect interface+  ("Control.Monad.Prompt.Effect"), deriving via+  <https://hackage.haskell.org/package/base/docs/GHC-Generics.html#t:Generically Generically>,+  tool calls ("Control.Monad.Prompt.Tool"), and a mock backend that reads+  responses from files ("Control.Monad.Prompt.FileMock"). The classes+  describing types live in+  <https://hackage.haskell.org/package/shroom-class shroom-class>, which this+  package re-exports.++  A tool call is like an effect that the model triggers. The program's type+  decides which tools the model may use, and the model decides when and how.++  shroom ships no backend for a real model.+  <https://hackage.haskell.org/package/shroom-baikai shroom-baikai> supplies+  one for Claude and for OpenAI-compatible hosts such as a local Ollama.++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+data-files:+  dev/mock-responses/*.json++-- extra-source-files:+tested-with:+  ghc ==9.12++flag web+  description:+    Build shroom-test-web-tools, which makes real calls to DuckDuckGo and+    Wikipedia.++  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,+    base >=4.20 && <4.22,+    bytestring ^>=0.12,+    containers >=0.6 && <0.8,+    directory ^>=1.3,+    effectful ^>=2.7,+    filepath ^>=1.5,+    generics-sop ^>=0.5.1,+    http-client ^>=0.7,+    modern-uri ^>=0.3,+    openapi3 ^>=3.2,+    req ^>=3.13,+    sop-core ^>=0.5,+    tagsoup ^>=0.14,+    template-haskell >=2.22 && <2.25,+    text >=2.1.2 && <2.2,+    time ^>=1.14,+    universe-base ^>=1.1,+    vector ^>=0.13,+    witherable ^>=0.5,++  default-extensions:+    DefaultSignatures+    DerivingVia+    OverloadedLists+    OverloadedRecordDot+    OverloadedStrings+    TypeFamilies++library+  import: opts+  exposed-modules:+    Control.Monad.Prompt+    Control.Monad.Prompt.Backend+    Control.Monad.Prompt.Effect+    Control.Monad.Prompt.FileMock+    Control.Monad.Prompt.Promptable+    Control.Monad.Prompt.Tool+    Control.Monad.Prompt.Tool.Web++  reexported-modules:+    Data.Shroom.Class,+    Data.Shroom.Class.TH,++  other-modules:+    Control.Monad.Prompt.Schema+    Paths_shroom++  autogen-modules:+    Paths_shroom++  hs-source-dirs: src+  build-depends:+    shroom-class ^>=0.1++  default-language: GHC2024++library test-utils+  import: opts+  visibility: public+  hs-source-dirs: test-utils+  default-language: GHC2024+  build-depends:+    shroom++  exposed-modules:+    CelebrityTypes+    ConferenceTypes+    GenericTypes+    TestUtils+    Types+    WebToolReport++common test-opts+  build-depends:+    shroom,+    tasty >=1.4 && <1.6,+    tasty-hunit ^>=0.10,+    test-utils,++test-suite shroom-test+  import: opts, test-opts+  default-language: GHC2024+  type: exitcode-stdio-1.0+  hs-source-dirs: test+  main-is: Main.hs+  other-modules: UnqualifiedImports+  build-depends:+    network ^>=3.2,+    time ^>=1.14,++test-suite shroom-test-conference+  import: opts, test-opts+  default-language: GHC2024+  type: exitcode-stdio-1.0+  hs-source-dirs: test+  main-is: ConferenceScenario.hs++test-suite shroom-test-celebrity+  import: opts, test-opts+  default-language: GHC2024+  type: exitcode-stdio-1.0+  hs-source-dirs: test+  main-is: CelebrityScenario.hs++test-suite shroom-test-web-tools+  import: opts, test-opts+  default-language: GHC2024+  type: exitcode-stdio-1.0+  hs-source-dirs: test+  main-is: WebToolsScenario.hs+  build-depends:+    text++  if !(flag(web) && flag(online))+    buildable: False++executable shroom-dev+  import: opts, test-opts+  default-language: GHC2024+  hs-source-dirs: app+  main-is: Main.hs
+ src/Control/Monad/Prompt.hs view
@@ -0,0 +1,73 @@+{- |+Module      : Control.Monad.Prompt+Description : Ask a language model for a typed Haskell value.++'prompt' asks a language model for a value of any 'Promptable' type. The model is+told the type's description, properties and examples (see "Data.Shroom.Class"), and+its answer is parsed and checked against them, with a retry when it fails.++Programs that chain requests, add context or offer tools are written in+"Control.Monad.Prompt.Effect". For example, the program below gives additional+context, asks for a user and then asks for a second user who differs from the+first. The description of @User@ is read from the+Haddock comments, so the module that declares @User@ needs the GHC flag+@-haddock@ (see "Data.Shroom.Class.TH").++@+-- | A user with a name and an email address.+data User = User+  { userName :: Text+  -- ^ The user's full name.+  , userEmail :: Text+  -- ^ The user's email address.+  }+  deriving stock (Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++\$(deriveDescribable ''User)++instance Surveyable User++instance Promptable User++signUpTwice :: (Prompt :> es, State [ContextItem] :> es) => Eff es (User, User)+signUpTwice = do+  context \"Alice Smith signed up with alice\@example.org.\"+  first <- prompt \@User+  context \$ \"A second user signed up, who is not \" <> userName first <> \".\"+  second <- prompt \@User+  pure (first, second)+@++The example needs the language GHC2021 or GHC2024 and the extensions @DeriveAnyClass@,+@DerivingStrategies@, @OverloadedStrings@ and @TemplateHaskell@. It needs the packages+@shroom@, <https://hackage.haskell.org/package/shroom-class shroom-class>,+<https://hackage.haskell.org/package/aeson aeson>,+<https://hackage.haskell.org/package/effectful effectful>,+<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:++* 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@.+* 'Data.Shroom.Class.TH.deriveDescribable' from "Data.Shroom.Class.TH" and+  t'Data.Shroom.Class.Surveyable' from "Data.Shroom.Class".+* t'Promptable' and 'prompt' from this module.+* t'Control.Monad.Prompt.Effect.Prompt' and 'Control.Monad.Prompt.Effect.context' from+  "Control.Monad.Prompt.Effect", and t'Control.Monad.Prompt.Backend.ContextItem' from+  "Control.Monad.Prompt.Backend".+* t'Effectful.Eff' and t'(Effectful.:>)' from "Effectful", and t'Effectful.State.Static.Local.State'+  from "Effectful.State.Static.Local".++To run the program against a backend, see "Control.Monad.Prompt.Backend" and the+<https://hackage.haskell.org/package/shroom-baikai shroom-baikai> package.+-}+module Control.Monad.Prompt (module Control.Monad.Prompt.Promptable) where++-- shroom+import Control.Monad.Prompt.Promptable
+ src/Control/Monad/Prompt/Backend.hs view
@@ -0,0 +1,177 @@+{- |+Module      : Control.Monad.Prompt.Backend+Description : The connection that runs a prompt program's chat calls on a language model host.++A shroom program says what to ask for.+'Control.Monad.Prompt.Effect.runPrompt' interprets it, turns each request into chat+calls with retries and tool rounds, and sends every chat call through a t'Backend'+to a language model host. A t'Backend' is the connection to that host. Use it to+run a program on a real model, or to plug in a transport of your own.++A t'Backend' makes one raw chat call. It takes the conversation so far, the+description and JSON schema of the expected result type and the tools on offer,+and returns a 'BackendReply' or a 'BackendError'. The retry and tool loop around+that call is in 'Control.Monad.Prompt.Effect.runPrompt'.++A t'Backend' is a plain newtype, not a type class, so building one needs no+instance and no dependency on shroom's other modules. An adapter can turn a+<https://hackage.haskell.org/package/openapi3/docs/Data-OpenApi-Internal-Schema.html#t:ToSchema ToSchema>+instance into the schema the call needs with 'schemaWithDefs'.+'Control.Monad.Prompt.FileMock.fileMockBackend' replays canned responses from+files; the @shroom-baikai@ package builds a t'Backend' for real models.++As a trivial example, this backend answers every request with the same text:++@+constantBackend :: (Applicative m) => Text -> Backend m+constantBackend answer = Backend $ \\_ _ _ _ -> pure $ Right $ BackendAnswer answer+@+-}+module Control.Monad.Prompt.Backend (+  -- * Backends+  Backend (..),+  runBackendChat,+  BackendReply (..),+  BackendError (..),++  -- * Conversation+  ContextItem (..),+  renderContextItems,++  -- * Tools+  ToolDef (..),+  ToolCall (..),+  ToolResult (..),++  -- * Schemas+  schemaWithDefs,+) where++-- text+import Data.Text (Text)+import Data.Text qualified as T++-- aeson+import Data.Aeson (Value)++-- shroom+import Control.Monad.Prompt.Schema (ToolDef (..), schemaWithDefs)++-- * Tool calls and results++{- | A tool call the model requested, either in a 'BackendToolCalls' reply or,+once dispatched, replayed in a 'ToolCallMessage'.+-}+data ToolCall = ToolCall+  { toolCallId :: Text+  {- ^ The provider's own id for this call, echoed back unchanged in the+  matching t'ToolResult' so the provider can link the two.+  -}+  , toolCallName :: Text+  , toolCallArguments :: Value+  }+  deriving (Eq, Show)++-- | The outcome of dispatching one t'ToolCall', linked to it by 'toolResultId'.+data ToolResult = ToolResult+  { toolResultId :: Text+  -- ^ Echoes the originating t'ToolCall'\'s 'toolCallId'.+  , toolResultName :: Text+  , toolResultOutcome :: Either Text Text+  {- ^ 'Left' — the tool failed, with a message for the model. 'Right' —+  the tool's own result text.+  -}+  }+  deriving (Eq, Show)++-- * Context items++{- | One item of the conversation history. A t'Backend' maps each item to the+message of its transport that has the matching role.+-}+data ContextItem+  = -- | Instructions or persona, sent before any user turns.+    SystemMessage Text+  | -- | A user turn in the conversation.+    UserMessage Text+  | {- | A previous model response. Appended after each successful request so+      that later prompts can refer to earlier answers.+    -}+    AssistantMessage Text+  | {- | The tool calls the model requested in one turn. Parallel calls travel+      together, so they replay as one assistant turn.+    -}+    ToolCallMessage [ToolCall]+  | {- | The results of dispatching the calls of a 'ToolCallMessage', one per+      call, each linked to its call by 'toolResultId'.+    -}+    ToolResultMessage [ToolResult]+  deriving (Eq, Show)++{- | Render a conversation as flat 'Text', joining the items with newlines and+prefixing each with its role, except user messages. For display, or for a backend+without structured message histories.+-}+renderContextItems :: [ContextItem] -> Text+renderContextItems = T.intercalate "\n" . fmap render+  where+    render (SystemMessage t) = "[system] " <> t+    render (UserMessage t) = t+    render (AssistantMessage t) = "[assistant] " <> t+    render (ToolCallMessage calls) = "[tool call] " <> T.intercalate ", " (fmap toolCallName calls)+    render (ToolResultMessage results) = "[tool result] " <> T.intercalate ", " (fmap toolResultName results)++{- | A chat backend, reduced to the one call every backend must make.++__Contract:__ an implementation must not throw IO exceptions; every failure+comes back as a 'BackendError'.+-}+newtype Backend m = Backend ([ContextItem] -> Text -> Value -> [ToolDef] -> m (Either BackendError BackendReply))++-- | Makes the one chat call of a t'Backend'.+runBackendChat ::+  Backend m ->+  -- | The conversation so far.+  [ContextItem] ->+  -- | The description of the expected result type, appended as the final turn.+  Text ->+  -- | The JSON schema the response must satisfy.+  Value ->+  -- | The tools on offer for this call. Empty means none.+  [ToolDef] ->+  m (Either BackendError BackendReply)+runBackendChat (Backend call) = call++{- | The reply of one t'Backend' call: the model's final answer, or the tool+calls it wants made before it answers. A backend without tools, such as a mock,+always returns 'BackendAnswer'.+-}+data BackendReply+  = -- | The model's final response text, still raw JSON.+    BackendAnswer Text+  | {- | The model wants these tool calls made before it will answer.+      More than one call means parallel tool calls: dispatch each, then+      send all the results back together on the next 'runBackendChat' call.+    -}+    BackendToolCalls [ToolCall]+  deriving (Eq, Show)++{- | Why a t'Backend' call failed. The three cases are handled differently when+retrying: a refusal is terminal, a truncated reply is retried with a request+for a shorter one, and a transport failure is retried unchanged.+-}+data BackendError+  = -- | The model declined to answer at all; no re-prompt fixes that.+    BackendRefusal+      { refusalCategory :: Maybe Text+      -- ^ The category the provider names for the refusal, if it names one.+      , refusalMessage :: Text+      -- ^ The provider's own message text, for logging.+      }+  | {- | The reply was cut off by a length limit and is, at best, half a JSON+    document. Carries the text that arrived, for logging only.+    -}+    BackendTruncated Text+  | -- | Anything else: an HTTP failure, a decode failure, a timeout.+    BackendTransportError Text+  deriving (Eq, Show)
+ src/Control/Monad/Prompt/Effect.hs view
@@ -0,0 +1,620 @@+{- |+Module      : Control.Monad.Prompt.Effect+Description : Programs that prompt a language model, built from @effectful@ effects.++A shroom program is an @'Eff' es@ computation with 'Prompt' in @es@, where+'Eff' is the monad of the <https://hackage.haskell.org/package/effectful effectful>+package. Context is plain state ('addContextItem', 'withContext'), failure is an+error ('failWith', 'orElse') and parallel requests use "Effectful.Concurrent.Async"+('promptPar'). 'runPromptResultEff' runs a program against a t'Backend'.++In ordinary code, request a value with 'Control.Monad.Prompt.Promptable.prompt',+which follows the type's t'Control.Monad.Prompt.Promptable.Promptable' strategy.+'promptSingle' is the single request that method defaults to, 'promptTools' offers+the model tools to call, and 'improve' asks it to correct a value.+-}+module Control.Monad.Prompt.Effect (+  -- * Requesting values+  Prompt,+  promptSingle,+  promptSingleWith,+  promptTools,+  improve,++  -- * Running a program+  runPromptResultEff,+  runPrompt,+  PromptConfig (..),+  defaultPromptConfig,++  -- * Context+  addContextItem,+  context,+  withContextItem,+  withContext,++  -- * Failure and fallback+  failWith,+  orElse,++  -- * Parallel requests+  promptPar,+  promptsParallel,+) where++-- base+import Control.Monad.IO.Class (liftIO)+import Data.Functor ((<&>))+import Data.Kind (Type)+import Data.Proxy (Proxy (..))++-- text+import Data.Text (Text, pack)+import Data.Text qualified as T++-- aeson+import Data.Aeson (FromJSON (..), Value, eitherDecodeStrictText, object, withObject, (.:), (.=))++-- openapi3+import Data.OpenApi (ToSchema)++-- universe-base+import Data.Universe.Class (universe)++-- effectful+import Effectful (Dispatch (Dynamic), DispatchOf, Eff, IOE, runEff, (:>))+import Effectful.Concurrent.Async (Concurrent, concurrently, mapConcurrently, runConcurrent)+import Effectful.Dispatch.Dynamic (interpret, localSeqUnlift, send)+import Effectful.Error.Static (Error, catchError, runErrorNoCallStack, throwError)+import Effectful.State.Static.Local (State, evalState, get, modify, put)++-- shroom+import Control.Monad.Prompt.Backend (+  Backend (..),+  BackendError (..),+  BackendReply (..),+  ContextItem (..),+  ToolCall (..),+  ToolResult (..),+  runBackendChat,+ )+import Control.Monad.Prompt.Schema (ToolDef, ToolDispatcher, encodeJson, schemaWithDefs)+import Control.Monad.Prompt.Tool (ToolBinding (..), dispatchBindings)+import Data.Shroom.Class (Surveyable, describeProperties, description, propertyHolds)++-- * The Prompt effect++{- | The effect signature of a shroom program: the operations it can perform+against a language model. Put @Prompt ':>' es@ in a program's constraints to let+it prompt. An interpreter such as 'runPrompt' handles the operations, with the+conversation held in the @'State' ['ContextItem']@ effect.++The signature offers three operations:++* Request a value of a type, sent by 'promptSingle' (and so by+  'Control.Monad.Prompt.Promptable.prompt', through its default).+* Request a value while the model may call tools, sent by 'promptTools'.+* Improve a value, sent by 'improve'.++For example, a program that requests a @User@ and lets the model correct it:++@+refinedUser :: ('Prompt' ':>' es) => 'Eff' es User+refinedUser = do+  user <- 'promptSingle'+  fromMaybe user \<$> 'improve' user+@+-}+data Prompt (m :: Type -> Type) (result :: Type) where+  RequestPrompt :: (Surveyable a, ToSchema a, FromJSON a) => Prompt m a+  RequestPromptTools ::+    (Surveyable a, ToSchema a, FromJSON a) =>+    [ToolBinding m] ->+    Prompt m a+  RequestImprove :: (Surveyable a, ToSchema a, FromJSON a) => a -> Prompt m (Maybe a)++type instance DispatchOf Prompt = Dynamic++{- | Request a value of type @a@ in a single request, one call to the backend for+the whole value: the prompt text is the type's 'description' and the schema its+'ToSchema'. The reply joins the context as an 'AssistantMessage'.++Note that this skips the type's t'Control.Monad.Prompt.Promptable.Promptable'+strategy, such as a @deriving via Generically@. It is the default of+'Control.Monad.Prompt.Promptable.prompt', which honours the strategy and is the+usual choice; call 'promptSingle' directly inside a strategy itself.+-}+promptSingle :: forall a es. (Prompt :> es, Surveyable a, ToSchema a, FromJSON a) => Eff es a+promptSingle = send RequestPrompt++{- | Like 'promptSingle', with an extra piece of context scoped to this request.+The strategy-aware counterpart is 'withContext' around 'Control.Monad.Prompt.Promptable.prompt'.+-}+promptSingleWith ::+  forall a es.+  (Prompt :> es, State [ContextItem] :> es, Surveyable a, ToSchema a, FromJSON a) =>+  -- | The context, a piece of user-turn text that this request sees and no other.+  Text ->+  Eff es a+promptSingleWith txt = withContext txt (promptSingle @a)++{- | Like 'promptSingle', but the model may call tools. 'maxToolSteps' limits the+number of tool rounds. See "Control.Monad.Prompt.Tool" for how to define and run tools.+-}+promptTools ::+  forall a es.+  (Prompt :> es, Surveyable a, ToSchema a, FromJSON a) =>+  {- | The tools the model may call. Build each t'ToolBinding' with+  'Control.Monad.Prompt.Tool.toolBinding', which needs the tool's+  t'Control.Monad.Prompt.Tool.Tool' effect in @es@: a program cannot offer a tool it+  was not given.+  -}+  [ToolBinding (Eff es)] ->+  Eff es a+promptTools bindings = send (RequestPromptTools bindings)++{- | Ask the model to improve a value it (or anyone) has already produced:+'Nothing' means the given value is a good value of its type and the model is+content with it, @'Just' v'@ means the model returned a corrected whole value+@v'@.++As for 'promptSingle', the reply is appended to the context as an 'AssistantMessage'.++The reply goes through the same retry path as any request. An @improved@ value+that fails to parse or violates a property is re-prompted; so is a @fine@+verdict when the value passed in violates a property. So 'Nothing' always means+that the original value satisfies every t'Data.Shroom.Class.Property' of @a@.+Only the properties 'Surveyable' checks in code are enforced, not informal ones+that only the model can judge.++Like 'promptSingle', 'improve' is a single request: it does not call the type's own+'Control.Monad.Prompt.Promptable.prompt', so a prompt strategy may call it+without recursing into itself.+-}+improve ::+  forall a es.+  (Prompt :> es, Surveyable a, ToSchema a, FromJSON a) =>+  -- | The value to improve. The model is shown it for this request only.+  a ->+  Eff es (Maybe a)+improve = send . RequestImprove++{- | The reply to an 'improve' request: the model's verdict on the value shown.+Internal; the wire form is one object, see 'improveSchema'.+-}+data Verdict a = VerdictFine | VerdictImproved a++{- | A @fine@ verdict ignores @value@ (present on the wire, see 'improveSchema',+but never parsed, so a @fine@ reply without one is accepted too); an+@improved@ one requires it.+-}+instance (FromJSON a) => FromJSON (Verdict a) where+  parseJSON = withObject "Verdict" $ \o -> do+    verdict <- o .: "verdict"+    case (verdict :: Text) of+      "fine" -> pure VerdictFine+      "improved" -> VerdictImproved <$> o .: "value"+      other -> fail ("verdict must be \"fine\" or \"improved\", not " <> show other)++{- | The wire schema of a 'Verdict' over @a@: a single object whose root is+built by hand, so that it is not an openapi3-derived sum (which would emit a+@oneOf@ at the root, which structured-output schemas handle unevenly).+@value@ is the (already flattened) schema of @a@ itself. Both @verdict@ and+@value@ are listed in @required@: strict structured-output modes (OpenAI's+@json_schema@ with @strict@) reject an object whose @properties@ are not all+required, and JSON Schema cannot make @value@ conditional on the verdict+without @if@\/@oneOf@. So the model always sends a @value@, and for @fine@ the+parser ignores it (see the 'FromJSON' instance of 'Verdict', which still accepts+a @fine@ reply without one, for backends that do not enforce @required@).+-}+improveSchema :: forall a. (ToSchema a) => Proxy a -> Value+improveSchema prx =+  object+    [ "type" .= ("object" :: Text)+    , "properties"+        .= object+          [ "verdict"+              .= object+                [ "type" .= ("string" :: Text)+                , "enum" .= (["fine", "improved"] :: [Text])+                , "description" .= ("\"fine\" if the given value is already good (then repeat it unchanged in \"value\"), \"improved\" if a corrected value follows in \"value\"." :: Text)+                ]+          , "value" .= schemaWithDefs prx+          ]+    , "required" .= (["verdict", "value"] :: [Text])+    , "additionalProperties" .= False+    ]++-- | The descriptions of the properties of @a@ that a value does not satisfy.+violatedProperties :: forall a. (Surveyable a) => a -> [Text]+violatedProperties v =+  [ desc+  | p <- universe+  , not (propertyHolds v p)+  , Just desc <- [describeProperties (Proxy @a) p]+  ]++{- | Run two programs concurrently via "Effectful.Concurrent.Async", returning+both results. Parallelism is an explicit call here, rather than hiding+inside the @('<*>')@ of an 'Applicative'.+-}+promptPar :: (Concurrent :> es) => Eff es a -> Eff es b -> Eff es (a, b)+promptPar = concurrently++-- | Run a list of programs concurrently, returning all results.+promptsParallel :: (Concurrent :> es) => [Eff es a] -> Eff es [a]+promptsParallel = mapConcurrently id++-- * Runner configuration++-- | Model-independent configuration for 'runPrompt' \/ 'runPromptResultEff'.+data PromptConfig = PromptConfig+  { maxRetries :: Int+  {- ^ Maximum number of re-prompts per request. A reply that fails to parse,+  a parsed value that violates a property, a 'BackendTruncated' reply and a+  'BackendTransportError' each spend one; a 'BackendRefusal' is terminal and+  spends none. Default: 3.+  -}+  , maxToolSteps :: Maybe Int+  {- ^ Maximum number of tool rounds per 'promptTools' call; 'Nothing' means no+  limit. A round costs one step only when at least one of its calls succeeds.+  Once the steps are spent, the model gets one last call without tools to answer+  with what it already has. Default: 10.+  -}+  , debugLog :: Maybe (Text -> IO ())+  {- ^ Optional logger called before each LLM call and after each response.+  Receives a human-readable 'Text' summary. Pass @'Just' 'Data.Text.IO.putStrLn'@+  for stdout, or @tasty-hunit@\'s @step@ callback in tests.+  Default: 'Nothing'.+  -}+  }++-- | Default t'PromptConfig': up to 3 retries, up to 10 tool steps, no debug logging.+defaultPromptConfig :: PromptConfig+defaultPromptConfig = PromptConfig {maxRetries = 3, maxToolSteps = Just 10, debugLog = Nothing}++-- * Context++-- | Append a 'ContextItem' for the remainder of the current computation.+addContextItem :: (State [ContextItem] :> es) => ContextItem -> Eff es ()+addContextItem item = modify (\ctx -> ctx <> [item] :: [ContextItem])++-- | Append a piece of user-turn text for the remainder of the current computation.+context :: (State [ContextItem] :> es) => Text -> Eff es ()+context = addContextItem . UserMessage++{- | Scope a 'ContextItem' to a computation: visible only within the given+computation, and not carried past it, including anything that computation itself+added.+-}+withContextItem :: (State [ContextItem] :> es) => ContextItem -> Eff es a -> Eff es a+withContextItem item act = do+  (saved :: [ContextItem]) <- get+  put (saved <> [item] :: [ContextItem])+  a <- act+  put saved+  pure a++-- | Scope a piece of user-turn text to a sub-computation.+withContext :: (State [ContextItem] :> es) => Text -> Eff es a -> Eff es a+withContext = withContextItem . UserMessage++-- * Failure and fallback++-- | Always fail with the given message.+failWith :: (Error Text :> es) => Text -> Eff es a+failWith = throwError++{- | Try one computation and, on failure, run another. The context is restored to+how it stood before the attempt, discarding anything the failing computation added,+and the other computation runs from there.+-}+orElse ::+  (Error Text :> es, State [ContextItem] :> es) =>+  -- | The computation to try first.+  Eff es a ->+  -- | The computation to run if the first fails.+  Eff es a ->+  Eff es a+orElse l r = do+  (saved :: [ContextItem]) <- get+  l `catchError` \_ (_ :: Text) -> put saved >> r++-- * Interpreter++{- | Interpret 'Prompt' against a t'Backend', threading context through+"Effectful.State.Static.Local" and surfacing failure via+"Effectful.Error.Static".++A request is retried up to 'maxRetries' times. After a parse failure or a+property violation, the retry appends the offending response (as an+'AssistantMessage') and a 'UserMessage' naming what went wrong. After a+'BackendTruncated' reply it appends only a 'UserMessage' saying the reply was+cut off, and a 'BackendTransportError' is retried with the context unchanged.+A 'BackendRefusal' is terminal and consumes no retry.++The t'Backend' makes one raw call at a time, so this function runs the tool+cycle of 'promptTools' itself: it dispatches the calls the model requests,+appends their results to the context and calls the t'Backend' again, within+'maxToolSteps'. 'debugLog' reports each call and its outcome.+-}+runPrompt ::+  forall es a.+  (IOE :> es, Error Text :> es, State [ContextItem] :> es) =>+  Backend (Eff es) ->+  PromptConfig ->+  Eff (Prompt : es) a ->+  Eff es a+runPrompt backend promptCfg = interpret $ \env (request :: Prompt (Eff localEs) b) -> case request of+  -- No tools for 'RequestPrompt'.+  RequestPrompt -> let (toolDefs, dispatch, maxSteps) = noTools in runRequest toolDefs dispatch maxSteps+  -- 'RequestPromptTools': build the dispatcher out of the bindings by+  -- unlifting each binding's call — which runs in the request's own local+  -- effect stack ('localEs') — into this interpreter's 'es'.+  RequestPromptTools bindings ->+    runRequest+      (fmap toolBindingDef bindings)+      (\name v -> localSeqUnlift env (\unlift -> unlift (dispatchBindings bindings name v)))+      (maxToolSteps promptCfg)+  RequestImprove original -> runImprove original+  where+    -- The tool setup of a single request: no tool definitions, a dispatcher+    -- that refuses every call, and zero tool steps. Shared by 'RequestPrompt'+    -- and 'RequestImprove'.+    noTools :: ([ToolDef], ToolDispatcher (Eff es), Maybe Int)+    noTools = ([], \_ _ -> pure (Left "no tools"), Just 0)++    -- 'RequestImprove': a single request, no tools, whose reply is a 'Verdict'.+    -- The scoped 'UserMessage' showing the value goes onto the context the+    -- backend sees but not the one left behind; only the raw reply is kept.+    -- A @fine@ verdict is judged by the properties of the value passed in,+    -- an @improved@ one by the properties of the value it carries.+    runImprove ::+      forall b.+      (Surveyable b, ToSchema b, FromJSON b) =>+      b ->+      Eff es (Maybe b)+    runImprove original = do+      ctx <- get+      let prx = Proxy @b+          shown = encodeJson original+          ask =+            UserMessage $+              "Here is a value of the type described below, as JSON:\n"+                <> shown+                <> "\n\nIs it a good value of that type, and does it satisfy every listed property? "+                <> "If it does, answer with verdict \"fine\" and return the value unchanged in \"value\". "+                <> "If it does not, answer with verdict \"improved\" and put a corrected whole value in \"value\"."+          typeDesc =+            description prx+              <> "\nAnswer with a single JSON object: {\"verdict\": \"fine\", \"value\": <the given value, unchanged>} for a good value as it stands, "+              <> "or {\"verdict\": \"improved\", \"value\": <the corrected whole value>}.\n"+          check VerdictFine = violatedProperties original+          check (VerdictImproved v) = violatedProperties v+      let (toolDefs, dispatch, maxSteps) = noTools+      (verdict, rawTxt) <-+        attemptLoop toolDefs dispatch maxSteps (ctx <> [ask]) typeDesc (improveSchema prx) check (maxRetries promptCfg) (maxRetries promptCfg)+      put (ctx <> [AssistantMessage rawTxt])+      pure $ case verdict of+        VerdictFine -> Nothing+        VerdictImproved v -> Just v++    runRequest ::+      forall b.+      (Surveyable b, ToSchema b, FromJSON b) =>+      [ToolDef] ->+      ToolDispatcher (Eff es) ->+      Maybe Int ->+      Eff es b+    runRequest toolDefs dispatch maxSteps = do+      ctx <- get+      let prx = Proxy @b+          typeDesc = description prx+          schema = schemaWithDefs prx+          checkProps = violatedProperties @b+      (a, rawTxt) <- attemptLoop toolDefs dispatch maxSteps ctx typeDesc schema checkProps (maxRetries promptCfg) (maxRetries promptCfg)+      put (ctx <> [AssistantMessage rawTxt])+      pure a++    logDebug :: Text -> Eff es ()+    logDebug msg = case promptCfg.debugLog of+      Nothing -> pure ()+      Just fn -> liftIO (fn msg)++    -- Returns both the parsed value and the raw response text (for+    -- AssistantMessage). totalRetries is the original maxRetries value+    -- (fixed); retriesLeft decrements on each retry.+    attemptLoop ::+      forall c.+      (FromJSON c) =>+      [ToolDef] ->+      ToolDispatcher (Eff es) ->+      Maybe Int ->+      [ContextItem] ->+      Text ->+      Value ->+      (c -> [Text]) ->+      Int ->+      Int ->+      Eff es (c, Text)+    attemptLoop toolDefs dispatch maxSteps ctx typeDesc schema checkProps totalRetries retriesLeft = do+      let attemptNum = totalRetries - retriesLeft + 1+          separator = T.replicate 60 "─"+          renderItem (SystemMessage t) = "[system]    " <> t+          renderItem (UserMessage t) = "[user]      " <> t+          renderItem (AssistantMessage t) = "[assistant] " <> t+          renderItem (ToolCallMessage calls) = "[tool call] " <> T.intercalate ", " (fmap toolCallName calls)+          renderItem (ToolResultMessage results) = "[tool result] " <> T.intercalate ", " (fmap toolResultName results)+      logDebug $+        T.unlines $+          [ separator+          , "LLM CALL  attempt "+              <> pack (show attemptNum)+              <> "/"+              <> pack (show (totalRetries + 1))+              <> "  →  "+              <> typeDesc+          ]+            <> fmap renderItem ctx+            <> [separator]+      result <- toolLoop toolDefs dispatch maxSteps ctx typeDesc schema+      let attemptsStr = "(" <> pack (show attemptNum) <> " attempt(s))"+          retry = attemptLoop toolDefs dispatch maxSteps+      case result of+        Left (BackendRefusal {refusalMessage}) -> do+          -- Terminal: a refusal is not something a re-prompt can fix.+          logDebug $ "✗ REFUSAL: " <> refusalMessage+          throwError $ refusalMessage <> "\n" <> attemptsStr+        Left (BackendTruncated partial) -> do+          -- Retried, but with a message that says what went wrong: a blind+          -- re-prompt would get the same overlong answer. The cut-off text+          -- stays out of the context; it is half a document.+          logDebug $ "✗ TRUNCATED: " <> partial+          if retriesLeft <= 0+            then throwError $ "The reply was cut off at the length limit.\n" <> attemptsStr+            else do+              let retryCtx =+                    ctx+                      <> [ UserMessage $+                             "IMPORTANT: Your previous response was cut off at the length limit, so it was incomplete.\n"+                               <> "Generate a new, shorter JSON response that matches the required schema exactly."+                         ]+              retry retryCtx typeDesc schema checkProps totalRetries (retriesLeft - 1)+        Left (BackendTransportError err) -> do+          logDebug $ "✗ ERROR: " <> err+          if retriesLeft <= 0+            then throwError $ err <> "\n" <> attemptsStr+            else retry ctx typeDesc schema checkProps totalRetries (retriesLeft - 1)+        Right rawTxt ->+          case eitherDecodeStrictText' rawTxt of+            Left parseErr -> do+              logDebug $ "✗ PARSE FAIL: " <> parseErr+              if retriesLeft <= 0+                then throwError $ parseErr <> "\n" <> attemptsStr+                else do+                  let retryCtx =+                        ctx+                          <> [ AssistantMessage rawTxt+                             , UserMessage $+                                 "IMPORTANT: Your previous response could not be parsed.\n"+                                   <> "Parse error:\n"+                                   <> parseErr+                                   <> "\n\nGenerate a new, corrected JSON response that matches the required schema exactly."+                             ]+                  retry retryCtx typeDesc schema checkProps totalRetries (retriesLeft - 1)+            Right a ->+              let failDescs = checkProps a+               in if null failDescs+                    then do+                      logDebug $ "✓ " <> rawTxt+                      pure (a, rawTxt)+                    else do+                      logDebug $ "✗ VALIDATION FAIL: " <> T.intercalate ", " failDescs+                      if retriesLeft <= 0+                        then+                          throwError $+                            "Property validation failed:\n"+                              <> T.intercalate "\n" (fmap ("- " <>) failDescs)+                              <> "\n"+                              <> attemptsStr+                        else do+                          let retryCtx =+                                ctx+                                  <> [ AssistantMessage rawTxt+                                     , UserMessage $+                                         "IMPORTANT: Your previous response was rejected because it violated required properties.\n"+                                           <> "Violated properties:\n"+                                           <> T.unlines (fmap ("- " <>) failDescs)+                                           <> "\nGenerate a new, corrected JSON response that satisfies ALL properties listed above."+                                     ]+                          retry retryCtx typeDesc schema checkProps totalRetries (retriesLeft - 1)++    eitherDecodeStrictText' :: forall c. (FromJSON c) => Text -> Either Text c+    eitherDecodeStrictText' t = case eitherDecodeStrictText t of+      Left err -> Left (mconcat ["JSON decode error: ", t, "\n", pack err])+      Right v -> Right v++    -- \| Drive one prompt request's worth of tool calling against 'backend',+    --    one 'runBackendChat' call at a time, until it answers or the step+    --    budget is spent.+    --+    --    Budget rules:+    --    a round costs one step only when at least one call succeeds, failed+    --    calls are free, each successful result is annotated with the remaining+    --    count, and exhaustion sends one final tool-free call so the model can+    --    still answer.+    --+    toolLoop ::+      [ToolDef] ->+      ToolDispatcher (Eff es) ->+      -- \| Steps remaining (@Nothing@ = unlimited)+      Maybe Int ->+      [ContextItem] ->+      Text ->+      Value ->+      Eff es (Either BackendError Text)+    toolLoop toolDefs dispatch stepsLeft ctx typeDesc schema = do+      result <- runBackendChat backend ctx typeDesc schema toolDefs+      case result of+        Left err -> pure (Left err)+        Right (BackendAnswer txt) -> pure (Right txt)+        Right (BackendToolCalls calls) ->+          case stepsLeft of+            -- Budget exhausted: inform the model, then call without tools.+            Just 0 -> do+              logDebug "[tool budget exhausted]"+              let exhausted = "Tool budget exhausted. No further tool calls will be processed. Please give your final answer using the information already available."+                  fakeResults = [ToolResult {toolResultId = tc.toolCallId, toolResultName = tc.toolCallName, toolResultOutcome = Right exhausted} | tc <- calls]+                  ctx' = ctx <> [ToolCallMessage calls, ToolResultMessage fakeResults]+              final <- runBackendChat backend ctx' typeDesc schema []+              pure $ case final of+                Left err -> Left err+                Right (BackendAnswer txt) -> Right txt+                Right (BackendToolCalls _) -> Left (BackendTransportError "backend requested tools on the tool-free exhaustion call")+            _ -> do+              tagged <-+                traverse+                  ( \tc -> do+                      logDebug $ ">>> TOOL CALL: " <> tc.toolCallName <> " " <> encodeJson tc.toolCallArguments+                      r <- dispatch tc.toolCallName tc.toolCallArguments+                      logDebug $ "<<< TOOL RESULT: " <> tc.toolCallName <> " " <> either ("ERROR: " <>) ("OK: " <>) r+                      pure (tc, r)+                  )+                  calls+              -- Count successes; only successful calls cost budget.+              let successCount = length [() | (_, Right _) <- tagged]+                  newStepsLeft = stepsLeft <&> \n -> n - (if successCount > 0 then 1 else 0)+                  -- Annotate each successful result with remaining budget.+                  annotate (tc, Right txt) =+                    let note = case newStepsLeft of+                          Nothing -> ""+                          Just n -> "\n[" <> T.pack (show n) <> " tool step(s) remaining]"+                     in ToolResult {toolResultId = tc.toolCallId, toolResultName = tc.toolCallName, toolResultOutcome = Right (txt <> note)}+                  annotate (tc, Left err) =+                    ToolResult {toolResultId = tc.toolCallId, toolResultName = tc.toolCallName, toolResultOutcome = Left err}+                  results = fmap annotate tagged+                  ctx' = ctx <> [ToolCallMessage calls, ToolResultMessage results]+              toolLoop toolDefs dispatch newStepsLeft ctx' typeDesc schema++{- | Run a 'Prompt' program against a t'Backend', starting from an empty context+and returning a failure as 'Left'. 'promptPar' and 'promptsParallel' run+their branches concurrently.+-}+runPromptResultEff ::+  {- | Where the requests go. Build it with, for example, the @shroom-baikai@ package's+  <https://hackage.haskell.org/package/shroom-baikai/docs/Control-Monad-Prompt-Baikai.html#v:claudeBackend claudeBackend>+  or 'Control.Monad.Prompt.FileMock.fileMockBackend'. Both build a @t'Backend' m@ for+  any @t'Control.Monad.IO.Class.MonadIO' m@, so the result fits here without an annotation.+  -}+  Backend (Eff '[State [ContextItem], Error Text, Concurrent, IOE]) ->+  -- | The retry and tool limits, and the debug log.+  PromptConfig ->+  -- | The program to run.+  Eff '[Prompt, State [ContextItem], Error Text, Concurrent, IOE] a ->+  IO (Either Text a)+runPromptResultEff backend promptCfg program =+  runEff+    . runConcurrent+    . runErrorNoCallStack+    . evalState ([] :: [ContextItem])+    $ runPrompt backend promptCfg program
+ src/Control/Monad/Prompt/FileMock.hs view
@@ -0,0 +1,89 @@+{- |+Module      : Control.Monad.Prompt.FileMock+Description : A backend that replies from files, to test a prompt program without a model.++To test a shroom program, or to write a golden test for it, you want no network,+no API key and the same replies on every run. 'fileMockBackend' is a t'Backend'+that gives you that. It answers each request with the next numbered JSON file+(@response-001.json@, @response-002.json@, …) instead of calling a model. It also+prints the prompt of each request, so you see exactly what is sent for each step,+and you can edit the replies to try other scenarios.++@+cfg <- defaultFileMockConfig+result <- runPromptResultEff (fileMockBackend cfg) defaultPromptConfig (prompt \@User)+@++Here @User@ is any t'Control.Monad.Prompt.Promptable.Promptable' type, for example the one in "Control.Monad.Prompt".+Each file holds the JSON that a model would answer with for that step.+-}+module Control.Monad.Prompt.FileMock (FileMockConfig (..), defaultFileMockConfig, fileMockBackend) where++-- base+import Control.Monad.IO.Class (MonadIO (..))+import Data.IORef+import System.Directory (doesFileExist)+import System.FilePath ((</>))+import Text.Printf (printf)++-- text+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.IO qualified as TIO++-- shroom+import Control.Monad.Prompt.Backend (Backend (..), BackendError (..), BackendReply (..), renderContextItems)+import Paths_shroom (getDataDir)++-- | Configuration for the file-based mock backend.+data FileMockConfig = FileMockConfig+  { responseDir :: FilePath+  {- ^ Directory holding the numbered response files. The default is+    @dev\/mock-responses\/@ in the data directory of @shroom@ (@getDataDir@ of the+    Cabal-generated @Paths_shroom@), so it does not depend on the current working+    directory. Set it to read your own files.+  -}+  , promptLogFn :: Text -> IO ()+  {- ^ Called before each reply with the full prompt text (context followed by the+    type description). The default prints it to stdout.+  -}+  , stepCounter :: IORef Int+  {- ^ Counts the replies given so far, so that the next request reads the next file.+    'defaultFileMockConfig' creates it at zero.+  -}+  }++{- | A t'FileMockConfig' that reads the files in @dev\/mock-responses\/@ of the @shroom@ data+directory and prints prompts to stdout.+-}+defaultFileMockConfig :: IO FileMockConfig+defaultFileMockConfig = do+  counter <- newIORef 0+  dataDir <- getDataDir+  pure+    FileMockConfig+      { responseDir = dataDir </> "dev/mock-responses"+      , promptLogFn = TIO.putStrLn+      , stepCounter = counter+      }++{- | The t'Backend' for a t'FileMockConfig'. It ignores the offered tools, so every reply+is a 'BackendAnswer', and it answers a missing response file with+'BackendTransportError'.+-}+fileMockBackend :: (MonadIO m) => FileMockConfig -> Backend m+fileMockBackend cfg =+  Backend $ \ctx typeDesc _schema _toolDefs -> liftIO $ do+    n <- atomicModifyIORef' cfg.stepCounter (\i -> (i + 1, i))+    let stepNum = n + 1 -- 1-indexed for humans+        filename = "response-" <> printf "%03d" stepNum <> ".json"+        path = cfg.responseDir </> filename+        header = "=== PROMPT (step " <> T.pack (show stepNum) <> ") ==="+        footer = T.replicate (T.length header) "="+    cfg.promptLogFn $ T.unlines [header, renderContextItems ctx <> "\n" <> typeDesc, footer]+    exists <- doesFileExist path+    if not exists+      then pure $ Left $ BackendTransportError $ "FileMock: missing response file: " <> T.pack path+      else do+        contents <- TIO.readFile path+        pure $ Right (BackendAnswer (T.strip contents))
+ src/Control/Monad/Prompt/Promptable.hs view
@@ -0,0 +1,534 @@+{-# LANGUAGE UndecidableInstances #-}+-- The orphan is 'ToSchema' for 'Generically', whose class and type are both elsewhere.+{-# OPTIONS_GHC -Wno-orphans #-}++{- |+Module      : Control.Monad.Prompt.Promptable+Description : Request a value of a type from a language model, with a default strategy.++Ask a language model for a value of one of your own types. You write the type+with Haddock comments on it and on its fields, derive the classes that describe+it in a few lines of boilerplate, and the type is ready to be prompted for. The+model is shown your Haddocks as the description of what to produce, and its+answer is parsed into your type and checked against the type's properties.++@+-- | A recipe for a dish.+data Recipe = Recipe+  { title :: 'Text'+  -- ^ The name of the dish.+  , servings :: 'Int'+  -- ^ How many people the recipe feeds.+  , steps :: ['Text']+  -- ^ The preparation steps, in order.+  }+  deriving stock (<https://hackage.haskell.org/package/base/docs/GHC-Generics.html#t:Generic Generic>)+  deriving anyclass ('ToJSON', 'FromJSON', 'ToSchema', <https://hackage.haskell.org/package/generics-sop/docs/Generics-SOP.html#t:Generic SOP.Generic>, <https://hackage.haskell.org/package/generics-sop/docs/Generics-SOP.html#t:HasDatatypeInfo SOP.HasDatatypeInfo>)++\$('Data.Shroom.Class.TH.deriveDescribable' ''Recipe)++instance 'Surveyable' Recipe++instance 'Promptable' Recipe+@++Here @SOP@ is "Generics.SOP". Running 'prompt' at the type @Recipe@ then requests+a recipe from the model. The classes this module builds on, 'Surveyable' and+'Describable', are in "Data.Shroom.Class" from @shroom-class@.++The deriving clause names the classes that the superclasses of 'Promptable' need.+It does not choose a prompting strategy, which <#partByPart Prompting part by part> describes.++* t'GHC.Generics.Generic' lets @aeson@ and @openapi3@ derive 'ToJSON', 'FromJSON'+  and 'ToSchema' for you.+* 'ToJSON' is a superclass of 'Describable', and 'FromJSON' and 'ToSchema' are+  superclasses of 'Promptable'.+* <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>+  serve the default of 'Surveyable',+  which checks the properties of every field of the record.++== Prompting part by part #partByPart#++Prompt a type part by part, after choosing its constructor if it has several,+by deriving 'Promptable' via t'Generically'.++A 'Promptable' that makes a single request asks for the whole value at once. The strategy here+instead asks for a record's fields one at a time, each seeing the earlier ones,+so that parts that must fit together are built in one train of thought. It then+asks the model to 'improve' the assembled value, in+case the parts do not fit after all.++=== An example++A musician has a name and a city they are from. A musician from a city that+they have nothing to do with is wrong, though each part alone looks fine. Here+is the type, derived part by part:++@+-- | The name of a city.+newtype City = City 'Text'+  deriving stock (<https://hackage.haskell.org/package/base/docs/GHC-Generics.html#t:Generic Generic>)+  deriving anyclass ('ToJSON', 'FromJSON', 'ToSchema', <https://hackage.haskell.org/package/generics-sop/docs/Generics-SOP.html#t:Generic SOP.Generic>, <https://hackage.haskell.org/package/generics-sop/docs/Generics-SOP.html#t:HasDatatypeInfo SOP.HasDatatypeInfo>)++\$('Data.Shroom.Class.TH.deriveDescribable' ''City)++instance 'Surveyable' City++-- A leaf takes a single request.+instance 'Promptable' City++-- | A musician.+data Musician = Musician+  { name :: 'Text'+  -- ^ The musician's full name.+  , city :: City+  -- ^ The city the musician is from.+  }+  deriving stock (<https://hackage.haskell.org/package/base/docs/GHC-Generics.html#t:Generic Generic>)+  deriving anyclass ('ToJSON', 'FromJSON', 'ToSchema', <https://hackage.haskell.org/package/generics-sop/docs/Generics-SOP.html#t:Generic SOP.Generic>, <https://hackage.haskell.org/package/generics-sop/docs/Generics-SOP.html#t:HasDatatypeInfo SOP.HasDatatypeInfo>)++\$('Data.Shroom.Class.TH.deriveDescribable' ''Musician)++instance 'Surveyable' Musician++deriving via t'Generically' Musician instance 'Promptable' Musician+@++The example needs the packages @shroom@, @generics-sop@, @aeson@, @openapi3@+and @text@, and the GHC flag @-haddock@ for the module that declares the types:+the descriptions are read from their Haddock comments (see "Data.Shroom.Class.TH").+A leaf type that a field uses is derived before the type that has the field.++A program asks for a musician with @'prompt' \@Musician@, as for any 'Promptable'+type. The request then goes through these steps:++1. Each part is requested on its own, and sees the description of a @Musician@+   and the parts before it. The name comes out as @\"Wolfgang Amadeus Mozart\"@.+   The city, though it sees the name, may come out as @City \"Eisenach\"@: a+   plausible city for a composer, but not Mozart's.+2. shroom assembles the parts into+   @Musician \"Wolfgang Amadeus Mozart\" (City \"Eisenach\")@.+3. The model is shown this assembled value and asked to improve it, which means+   either to keep it or to return a corrected one.+4. The model notices that the name and the city do not fit, since Bach was born+   in Eisenach and Mozart in Salzburg. It corrects the value to+   @Musician \"Johann Sebastian Bach\" (City \"Eisenach\")@ or to+   @Musician \"Wolfgang Amadeus Mozart\" (City \"Salzburg\")@.++Without the last two steps, the mismatch of step 2 would stay. That is why the+strategy ends with 'improve'.++A sum is derived the same way. Its strategy first asks which constructor to+build.++Only the class method 'prompt' runs the strategy, directly or through+the instance of a field. 'Control.Monad.Prompt.Effect.promptSingle' and+'improve' send one request for the whole value and+never run it.++=== The strategy++'prompt' for @t'Generically' a@ builds an @a@ in the following steps, all+inside one snapshot of the context:++1. The model is told it is about to build a value of @a@, described by+   'description'. A type with several constructors is then asked for a+   t'ConstructorChoice', an enum of the constructor names. A type whose only+   constructor has no fields skips this step.+2. For each field in order, a message names the field (a record's field name,+   otherwise the constructor's name and the field's position), and the field+   type's own 'prompt' is called. Its answer stays in the context, so+   each field sees the earlier ones. A constructor with no fields has none of+   these requests.+3. The fields are assembled into a draft and go through+   'improve', which checks it against the type's own+   'Property' (see 'Surveyable') and either keeps it or returns a corrected one.+4. The context is restored to the snapshot, and one 'AssistantMessage' holding the+   final value's JSON is appended, so of the steps above only that answer stays in the context.++Note that a field type whose own 'prompt' scopes its context leaves no answer+behind. The strategy then appends the answer, whenever the context did not grow+or does not end in an 'AssistantMessage'. It cannot tell whether a trailing+'AssistantMessage' really is the field's answer, so an override that drops its+answer yet appends some other 'AssistantMessage' last goes unnoticed.++=== Cost++A record with @n > 0@ fields costs @n + 1@ requests (fields, improve), where+a single request costs 1. The @Musician@ above costs 3. A constructor of a type with+several constructors costs one more for the choice, and one more for every retry.+Derive the leaves with single requests, with a bare @instance Promptable@, as asking for a scalar+part by part would pay an 'improve' for nothing. Use t'Generically' for+the records and sums whose parts must cohere.++=== The limits of the strategy++A field of a container type is prompted whole, in one+request for the container, and the properties of its elements are neither checked+nor told to the model, as for any container field (see "Data.Shroom.Class").+A recursive type needs the opt-out that "Data.Shroom.Class" describes. Anthropic's+structured outputs do not support recursive schemas, so such a type fails against+Claude even with it.++The schema that 'improve' sends for a sum is the one+'Control.Monad.Prompt.Backend.schemaWithDefs' builds from its 'ToSchema':+normalised for structured outputs, so that its @oneOf@ becomes @anyOf@, and+self-contained.+-}+module Control.Monad.Prompt.Promptable (+  -- * Promptable+  Promptable (..),++  -- * Answers to the strategy's requests+  ConstructorChoice,+) where++-- base+import Control.Monad (unless)+import Data.Int (Int64)+import Data.List.NonEmpty (NonEmpty)+import Data.Maybe (fromMaybe)+import Data.Proxy (Proxy (..))+import Data.Typeable (Typeable)+import Data.Void (Void)+import GHC.Generics (Generically (..))+import Numeric.Natural (Natural)++-- containers+import Data.Set (Set)++-- aeson+import Data.Aeson (FromJSON (..), ToJSON (..), Value (String), withText)++-- openapi3+import Data.OpenApi (NamedSchema (..), OpenApiType (..), Schema (..), ToSchema (..))++-- text+import Data.Text (Text)+import Data.Text qualified as T++-- time+import Data.Time (Day, UTCTime)++-- generics-sop+import Generics.SOP (All, All2, Code, ConstructorInfo, I (..), K (..), NP (..), NS (..), SList (..), SOP (..), constructorInfo, constructorName, datatypeInfo, datatypeName, sList, to)+import Generics.SOP qualified as SOP++-- effectful+import Effectful (Eff, (:>))+import Effectful.State.Static.Local (State, get, put)++-- shroom+import Control.Monad.Prompt.Backend (ContextItem (..))+import Control.Monad.Prompt.Effect (Prompt, addContextItem, improve)+import Control.Monad.Prompt.Effect qualified as Effect+import Control.Monad.Prompt.Schema (encodeJson)+import Data.Shroom.Class++{- | A class for types that you want to request from a language model.++An instance says that a value of the type can be asked for with 'prompt'. The+superclasses carry what the model needs. 'Surveyable' supplies the description,+properties and examples that the prompt is built from. 'ToSchema' supplies the+schema that the model's answer must follow, and 'FromJSON' parses the answer.++Most types need nothing more, and an empty instance is enough. The request+sends the type's 'description' to the 'Prompt' effect with+'Control.Monad.Prompt.Effect.promptSingle', and checks the answer against the+type's properties:++@+instance 'Promptable' Recipe+@++Override 'prompt' to change what a request for your type does. The override+below adds one line of context to the request, and keeps it out of every other+request:++@+instance 'Promptable' Recipe where+  prompt = 'Control.Monad.Prompt.Effect.withContext' "Always prefer metric units." 'Control.Monad.Prompt.Effect.promptSingle'+@++To prompt a record or a sum part by part instead, derive the instance via t'Generically'. See <#partByPart Prompting part by part>.+-}+class (Surveyable a, ToSchema a, FromJSON a) => Promptable a where+  {- | Request a value of type @a@ from the model.++  An override can also add fallbacks or run sub-prompts in parallel. Its+  @'State' ['ContextItem']@ constraint is the state that+  'Control.Monad.Prompt.Effect.context' adds to, so an override can scope context+  with 'Control.Monad.Prompt.Effect.withContext'.+  -}+  prompt :: forall es. (Prompt :> es, State [ContextItem] :> es) => Eff es a+  prompt = Effect.promptSingle++-- | Default prompt.+instance Promptable Text++-- | Default prompt.+instance Promptable Int++-- | Default prompt.+instance Promptable Integer++-- | Default prompt.+instance Promptable Int64++-- | Default prompt.+instance Promptable Word++-- | Default prompt.+instance Promptable Natural++-- | Default prompt.+instance Promptable Double++-- | Default prompt.+instance Promptable Float++-- | Default prompt.+instance Promptable Bool++-- | Default prompt.+instance Promptable Char++-- | Default prompt.+instance Promptable UTCTime++-- | Default prompt.+instance Promptable Day++-- | Default prompt, for a list of values described by @a@.+instance (Describable a, ToSchema a, FromJSON a) => Promptable [a]++-- | Default prompt, for a non-empty list of values described by @a@.+instance (Describable a, ToSchema a, FromJSON a) => Promptable (NonEmpty a)++-- | Default prompt, for a set of values described by @a@.+instance (Describable a, ToSchema a, FromJSON a, Ord a) => Promptable (Set a)++-- | Default prompt, for an optional value described by @a@.+instance (Describable a, ToSchema a, FromJSON a) => Promptable (Maybe a)++-- * The constructor choice++{- | The constructor of an @a@ to build, one of the constructors of @a@. When building+an @a@ part by part, the model is asked for it first, and only for a type with several+constructors.++On the wire it is a string, one of the constructor names, and nothing else is+accepted; its schema is a string enum named after @a@, so the choices of two+sum types do not collide.+-}+newtype ConstructorChoice a = ConstructorChoice (NS (K ()) (Code a))++-- | The names of the constructors of @a@, in order.+constructorNames :: forall a. (SOP.HasDatatypeInfo a) => Proxy a -> [Text]+constructorNames prx = go (constructorInfo (datatypeInfo prx))+  where+    go :: NP ConstructorInfo xss -> [Text]+    go Nil = []+    go (c :* cs) = T.pack (constructorName c) : go cs++-- | The name of the chosen constructor.+choiceName :: NP ConstructorInfo xss -> NS (K ()) xss -> Text+choiceName (c :* _) (Z _) = T.pack (constructorName c)+choiceName (_ :* cs) (S choice) = choiceName cs choice+choiceName Nil choice = case choice of {}++-- | The choice naming a constructor, if there is one of that name.+choiceFromName :: NP ConstructorInfo xss -> Text -> Maybe (NS (K ()) xss)+choiceFromName Nil _ = Nothing+choiceFromName (c :* cs) name+  | T.pack (constructorName c) == name = Just (Z (K ()))+  | otherwise = S <$> choiceFromName cs name++instance (SOP.HasDatatypeInfo a) => ToJSON (ConstructorChoice a) where+  toJSON (ConstructorChoice choice) = String (choiceName (constructorInfo (datatypeInfo (Proxy @a))) choice)++instance (SOP.HasDatatypeInfo a) => FromJSON (ConstructorChoice a) where+  parseJSON = withText "ConstructorChoice" $ \name ->+    case choiceFromName (constructorInfo (datatypeInfo (Proxy @a))) name of+      Just choice -> pure (ConstructorChoice choice)+      Nothing -> fail ("not the name of a constructor: " <> T.unpack name <> ", expected one of " <> T.unpack (T.intercalate ", " (constructorNames (Proxy @a))))++instance (Typeable a, SOP.HasDatatypeInfo a) => ToSchema (ConstructorChoice a) where+  declareNamedSchema _ =+    pure $+      NamedSchema+        (Just (T.pack (datatypeName (datatypeInfo (Proxy @a))) <> "Choice"))+        mempty+          { _schemaType = Just OpenApiString+          , _schemaEnum = Just (String <$> constructorNames (Proxy @a))+          }++instance (SOP.HasDatatypeInfo a, Describable a) => Describable (ConstructorChoice a) where+  describeType _ =+    "A choice of which kind of the type described below to build, made by naming one of its constructors, exactly as written.\n"+      <> describeType (Proxy @a)++instance (SOP.HasDatatypeInfo a, Describable a) => Surveyable (ConstructorChoice a) where+  type Property (ConstructorChoice a) = Void++instance (Typeable a, SOP.HasDatatypeInfo a, Describable a) => Promptable (ConstructorChoice a)++-- * The strategy++{- | Build an @a@ part by part: choose its constructor if it has several, then+prompt its fields in order and improve the assembled draft. The context ends as+the caller's plus the final value. The 'Promptable' instance for t'Generically'+wraps it.+-}+promptGeneric ::+  forall a es.+  ( Prompt :> es+  , State [ContextItem] :> es+  , Surveyable a+  , ToSchema a+  , FromJSON a+  , SOP.Generic a+  , SOP.HasDatatypeInfo a+  , All2 Promptable (Code a)+  ) =>+  Eff es a+promptGeneric = do+  (saved :: [ContextItem]) <- get+  let parent = description (Proxy @a)+      choose = (\(ConstructorChoice choice) -> choice) <$> prompt @(ConstructorChoice a)+  built <- promptConstructors parent choose (constructorInfo (datatypeInfo (Proxy @a)))+  let draft = to (SOP built)+  final <- fromMaybe draft <$> improve draft+  put (saved <> [AssistantMessage (encodeJson final)])+  pure final++{- | Build the fields of one of the constructors. A single constructor is the+type itself and needs no choice; with several, the model is first told what is+being built and asked which constructor (the action @choose@ does the asking), and+then the fields of that constructor are built. @parent@ is the description of the+whole type.+-}+promptConstructors ::+  forall xss es.+  (Prompt :> es, State [ContextItem] :> es, All2 Promptable xss) =>+  Text ->+  Eff es (NS (K ()) xss) ->+  NP ConstructorInfo xss ->+  Eff es (NS (NP I) xss)+promptConstructors parent choose constructors = case constructors of+  constructor :* Nil -> Z <$> promptConstructor parent False constructor+  _ -> do+    -- Persistent context, not 'withContext': that would drop every answer.+    addContextItem $+      UserMessage $+        "You are about to build a value of the type described below. First choose which of its constructors to build it with; then its fields are built one by one.\n"+          <> parent+    choice <- choose+    promptChosen parent constructors choice++-- | Build the fields of the chosen one of several constructors.+promptChosen ::+  forall xss es.+  (Prompt :> es, State [ContextItem] :> es, All2 Promptable xss) =>+  Text ->+  NP ConstructorInfo xss ->+  NS (K ()) xss ->+  Eff es (NS (NP I) xss)+promptChosen parent (constructor :* _) (Z _) = Z <$> promptConstructor parent True constructor+promptChosen parent (_ :* constructors) (S choice) = S <$> promptChosen parent constructors choice+promptChosen _ Nil choice = case choice of {}++{- | The product strategy for one constructor: a message saying what is being+built, then its fields. A constructor without fields is built at once. The flag+says whether the constructor was chosen among several, which the messages then say.+-}+promptConstructor ::+  forall xs es.+  (Prompt :> es, State [ContextItem] :> es, All Promptable xs) =>+  Text ->+  Bool ->+  ConstructorInfo xs ->+  Eff es (NP I xs)+promptConstructor parent chosen constructor = case sList :: SList xs of+  SNil -> pure Nil+  SCons -> do+    addContextItem $+      UserMessage $+        if chosen+          then "You chose the constructor " <> T.pack (constructorName constructor) <> ". Its fields are built one by one."+          else+            "You are about to build a value of the type described below, field by field.\n"+              <> parent+    promptFields (fieldLabel chosen constructor) 0++{- | Prompt each field of one constructor in order, each through its own type's+'prompt', after a message naming it. The label function says how to+name the field at a (zero-based) position.+-}+promptFields ::+  forall xs es.+  (Prompt :> es, State [ContextItem] :> es, All Promptable xs) =>+  (Int -> Text) ->+  Int ->+  Eff es (NP I xs)+promptFields label i = case sList :: SList xs of+  SNil -> pure Nil+  SCons -> do+    addContextItem (UserMessage ("Next, produce " <> label i <> " of the value."))+    (before :: [ContextItem]) <- get+    value <- prompt+    (after :: [ContextItem]) <- get+    -- A field whose own @prompt@ scopes its context leaves no answer behind;+    -- later fields must still see it. An answer is taken to be a context that+    -- grew and ends in an 'AssistantMessage'.+    unless (length after > length before && endsInAssistantMessage after) $+      addContextItem (AssistantMessage (encodeJson value))+    rest <- promptFields label (i + 1)+    pure (I value :* rest)++-- | Whether the last item of a context is an 'AssistantMessage'.+endsInAssistantMessage :: [ContextItem] -> Bool+endsInAssistantMessage ctx = case reverse ctx of+  AssistantMessage _ : _ -> True+  _ -> False++{- | The name of the field at a position: the record field's, else the+constructor's and the position. When the constructor was chosen among several,+a record field's name is followed by the constructor's as well.+-}+fieldLabel :: Bool -> ConstructorInfo xs -> Int -> Text+fieldLabel chosen constructor i = case fieldNameAt i constructor of+  Just name+    | chosen -> "the field " <> name <> " of constructor " <> conName+    | otherwise -> "the field " <> name+  Nothing -> "field " <> T.pack (show (i + 1)) <> " of constructor " <> conName+  where+    conName = T.pack (constructorName constructor)++-- * The instances++{- | A schema for t'Generically' that is the schema of @a@. It exists so that+@deriving via Generically@ meets the superclass of 'Promptable'. You neither write+nor call it.+-}+instance (ToSchema a) => ToSchema (Generically a) where+  declareNamedSchema _ = declareNamedSchema (Proxy @a)++{- | Prompt a record or sum type part by part, so that its parts fit together,+by deriving 'Promptable' via t'Generically'. See <#partByPart Prompting part by part>+for the steps and what they cost.+-}+instance+  ( Surveyable a+  , ToSchema a+  , FromJSON a+  , ToJSON (Generically a)+  , FromJSON (Generically a)+  , SOP.Generic a+  , SOP.HasDatatypeInfo a+  , All2 Promptable (Code a)+  ) =>+  Promptable (Generically a)+  where+  prompt = Generically <$> promptGeneric @a
+ src/Control/Monad/Prompt/Schema.hs view
@@ -0,0 +1,207 @@+{- | Internal schema utilities shared by 'Control.Monad.Prompt' and+'Control.Monad.Prompt.Tool'.  Not part of the public API.+-}+module Control.Monad.Prompt.Schema (encodeJson, schemaWithDefs, normalizeSchemaForStructuredOutput, inlineSchema, ToolDef (..), ToolDispatcher) where++-- base+import Data.Foldable (toList)+import Data.Maybe (catMaybes)+import Data.Proxy (Proxy)++-- text+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Lazy (toStrict)++-- aeson+import Data.Aeson (ToJSON, Value (..), toJSON)+import Data.Aeson.Key qualified as Key+import Data.Aeson.KeyMap qualified as KM+import Data.Aeson.Text (encodeToLazyText)++-- vector+import Data.Vector qualified as V++-- openapi3+import Data.OpenApi (Referenced (..), ToSchema, declareSchemaRef, getReference)+import Data.OpenApi.Declare (runDeclare)++-- | Encode a value as compact JSON text.+encodeJson :: (ToJSON v) => v -> Text+encodeJson = toStrict . encodeToLazyText++-- | A backend-agnostic tool definition passed to LLM backends.+data ToolDef = ToolDef+  { toolDefName :: Text+  -- ^ Identifier sent to the LLM.  Must match @[a-zA-Z0-9_-]+@.+  , toolDefDescription :: Text+  -- ^ Human-readable description sent alongside the name and schema.+  , toolDefSchema :: Value+  -- ^ OpenAPI JSON schema for the tool's input type.+  }++{- | A runtime tool dispatcher: given @(tool_name, input_value)@ returns a+result text or an error.+-}+type ToolDispatcher m = Text -> Value -> m (Either Text Text)++{- | Build the JSON schema of type @a@, self-contained with no @$ref@ or @$defs@+left in it. It takes the schema @openapi3@ derives, normalises it for+structured-output use and then inlines every reference.++A backend uses it to describe the expected result type and a tool's input to+the model.+-}+schemaWithDefs :: forall a. (ToSchema a) => Proxy a -> Value+schemaWithDefs prx =+  let (defs, ref) = runDeclare (declareSchemaRef prx) mempty+      rootSchema = case ref of+        Inline s -> toJSON s+        Ref r -> Object (KM.singleton "$ref" (String ("#/$defs/" <> getReference r)))+      defsJson = toJSON defs+      normalized = case defsJson of+        Object defsKm | not (KM.null defsKm) ->+          case rootSchema of+            Object rootKm -> normalizeSchemaForStructuredOutput (Object (KM.insert "$defs" (Object defsKm) rootKm))+            _ -> normalizeSchemaForStructuredOutput rootSchema+        _ -> normalizeSchemaForStructuredOutput rootSchema+   in inlineSchema normalized++{- | Normalise a JSON schema 'Value' for use as a structured-output (or+strict tool) schema:++* Adds @"additionalProperties": false@ to every @"type": "object"@ node.+* Rewrites @$ref@ values from @#\/components\/schemas\/X@ (openapi3's+  default) to @#\/$defs\/X@.+* Folds @"minimum"@\/@"maximum"@ on every @"type": "integer"@ node into that+  field's @"description"@ and removes the keywords, so the model still hears+  the constraint. @openapi3@'s true\/false @"exclusiveMinimum"@\/@"exclusiveMaximum"@+  is folded with them.+* Rewrites @"oneOf"@ to @"anyOf"@, the form structured-output schemas support.+  The alternatives that @openapi3@ generates for a+  sum are told apart by their tag, so \"at least one\" accepts what \"exactly+  one\" did. A node that already has an @anyOf@ keeps it, and its @oneOf@ moves+  into an extra @allOf@ entry so that both constraints still apply.++* Keeps a string node's @"format"@ only where structured outputs support it.+  @openapi3@'s format for @UTCTime@ becomes @date-time@, which @aeson@'s+  encoding of a @UTCTime@ satisfies. Any other unsupported format moves into+  the node's @"description"@, so the model still hears it.++Whether a host enforces a supported format varies; the properties of+@Surveyable@ in "Data.Shroom.Class" check in code what the schema does not+enforce.+-}+normalizeSchemaForStructuredOutput :: Value -> Value+normalizeSchemaForStructuredOutput (Object km) =+  let km1 = case KM.lookup "$ref" km of+        Just (String ref) -> KM.insert "$ref" (String (T.replace "#/components/schemas/" "#/$defs/" ref)) km+        _ -> km+      km2 = KM.map normalizeSchemaForStructuredOutput km1+      km' = case KM.lookup "oneOf" km2 of+        -- Only an array is the keyword; an object under that key is a property named @oneOf@.+        Just alternatives@(Array _) -> case KM.lookup "anyOf" km2 of+          Nothing -> KM.insert "anyOf" alternatives (KM.delete "oneOf" km2)+          Just _ ->+            let existing = case KM.lookup "allOf" km2 of+                  Just (Array vs) -> toList vs+                  _ -> []+             in KM.insert "allOf" (Array (V.fromList (existing <> [Object (KM.singleton "anyOf" alternatives)]))) (KM.delete "oneOf" km2)+        _ -> km2+   in Object $ case KM.lookup "type" km' of+        Just (String "object") -> KM.insert "additionalProperties" (Bool False) km'+        Just (String "integer") -> foldBoundsIntoDescription km'+        Just (String "string") -> normalizeStringFormat km'+        _ -> km'+normalizeSchemaForStructuredOutput (Array vs) = Array (fmap normalizeSchemaForStructuredOutput vs)+normalizeSchemaForStructuredOutput v = v++{- | Fold @"minimum"@\/@"maximum"@, with a true\/false+@"exclusiveMinimum"@\/@"exclusiveMaximum"@, into @"description"@ on a schema+node, then drop those keywords. Appends to an existing description rather than+replacing it.+-}+foldBoundsIntoDescription :: KM.KeyMap Value -> KM.KeyMap Value+foldBoundsIntoDescription km =+  let bound key exclusiveKey = (,KM.lookup exclusiveKey km == Just (Bool True)) <$> KM.lookup key km+      -- Only openapi3's true/false form of the exclusive keywords is removed; a numeric one is a bound of its own.+      dropFlag key m = case KM.lookup key m of+        Just (Bool _) -> KM.delete key m+        _ -> m+      stripped = dropFlag "exclusiveMinimum" $ dropFlag "exclusiveMaximum" $ KM.delete "minimum" $ KM.delete "maximum" km+   in case (bound "minimum" "exclusiveMinimum", bound "maximum" "exclusiveMaximum") of+        (Nothing, Nothing) -> stripped+        (lower, upper) -> appendToDescription (boundsSentence lower upper) stripped++{- | Keep a string node's @"format"@ if structured outputs support it, rename+@openapi3@'s @UTCTime@ format to @date-time@, and fold any other format into+@"description"@.+-}+normalizeStringFormat :: KM.KeyMap Value -> KM.KeyMap Value+normalizeStringFormat km = case KM.lookup "format" km of+  Just (String "yyyy-mm-ddThh:MM:ssZ") -> KM.insert "format" (String "date-time") km+  Just (String format)+    | format `notElem` supportedStringFormats ->+        appendToDescription ("Format: " <> format <> ".") (KM.delete "format" km)+  _ -> km++-- | The string formats that structured-output schemas accept.+supportedStringFormats :: [Text]+supportedStringFormats = ["date-time", "date", "time", "duration", "email", "hostname", "uri", "ipv4", "ipv6", "uuid"]++-- | Append a sentence to a schema node's @"description"@, or make it the description if there is none.+appendToDescription :: Text -> KM.KeyMap Value -> KM.KeyMap Value+appendToDescription sentence km =+  let newDescription = case KM.lookup "description" km of+        Just (String d) | not (T.null d) -> d <> " " <> sentence+        _ -> sentence+   in KM.insert "description" (String newDescription) km++-- | Render a lower and an upper bound, each with whether it is exclusive, as a sentence.+boundsSentence :: Maybe (Value, Bool) -> Maybe (Value, Bool) -> Text+boundsSentence Nothing Nothing = ""+boundsSentence (Just (mn, False)) (Just (mx, False)) = "Must be between " <> renderNum mn <> " and " <> renderNum mx <> " (inclusive)."+boundsSentence lower upper = "Must be " <> T.intercalate " and " (catMaybes [lowerPhrase <$> lower, upperPhrase <$> upper]) <> "."+  where+    lowerPhrase (n, exclusive) = (if exclusive then "greater than " else "at least ") <> renderNum n+    upperPhrase (n, exclusive) = (if exclusive then "less than " else "at most ") <> renderNum n++-- | Render a numeric schema bound (assumed integral) without a trailing @.0@.+renderNum :: Value -> Text+renderNum (Number n) = T.pack (show (round n :: Integer))+renderNum v = T.pack (show v)++{- | Inline all @$ref@ pointers in a schema against its @$defs@ section,+producing a flat schema with no @$ref@ or @$defs@.++Recursion is capped at 20 levels: a self-referential type has no finite fully+inlined form, so past the cap whatever is left is not descended into.+-}+inlineSchema :: Value -> Value+inlineSchema root = go 20 startVal+  where+    defs = case root of+      Object km -> case KM.lookup "$defs" km of+        Just (Object d) -> d+        _ -> KM.empty+      _ -> KM.empty++    startVal = case root of+      Object km -> case KM.lookup "$ref" km of+        Just (String ref) -> resolve 19 ref+        _ -> root+      _ -> root++    resolve n ref =+      let name = T.replace "#/$defs/" "" ref+       in case KM.lookup (Key.fromText name) defs of+            Just v -> go n v+            Nothing -> Object KM.empty++    go :: Int -> Value -> Value+    go 0 v = v+    go n (Object o) = case KM.lookup "$ref" o of+      Just (String ref) -> go (n - 1) (resolve (n - 1) ref)+      _ -> Object (KM.map (go (n - 1)) (KM.delete "$defs" o))+    go n (Array vs) = Array (fmap (go (n - 1)) vs)+    go _ v = v
+ src/Control/Monad/Prompt/Tool.hs view
@@ -0,0 +1,241 @@+{-# LANGUAGE AllowAmbiguousTypes #-}++{- |+Module      : Control.Monad.Prompt.Tool+Description : Tools a language model can call, as effectful effects.++To complete an answer, a model may want to call a tool, for example a web+search with t'Control.Monad.Prompt.Tool.Web.DuckDuckGoSearch' or a lookup in your own+data. Tools run right here in your program, so a tool is an effect that the+model triggers: the program decides what a tool may do, and the model decides+when to call it. shroom gives the same grip on tools as on any other effect. A+program can only offer a tool whose @'Tool' t@ effect is in its effect row, and+the compiler checks that.++A tool is a Haskell type that the model fills in, together with a t'ToolHandler'+that runs it. The type is documented with a Haddock comment, which becomes the+description the model reads. A program lists the tools it may call in its+constraints, @'Tool' MySearch ':>' es@, offers them to the model with+'toolBinding' and 'Control.Monad.Prompt.Effect.promptTools', and is run with+'runTool' supplying the handler:++@+-- | A web search query.+data MySearch = MySearch { query :: Text }+  deriving (Generic, ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++\$(deriveDescribable ''MySearch)+instance Surveyable MySearch++instance Toolable MySearch where+  toolDescription _ = Just "Returns results from the search API."++mySearchHandler :: ToolHandler MySearch+mySearchHandler = ToolHandler $ \\(MySearch q) -> callSearchAPI q++myProgram :: (Tool MySearch ':>' es, Prompt ':>' es) => Eff es Result+myProgram = promptTools [toolBinding \@MySearch]++result <- runPromptResultEff backend defaultPromptConfig (runTool mySearchHandler myProgram)+@++"Control.Monad.Prompt.Tool.Web" provides ready-made tools for fetching pages and searching.+-}+module Control.Monad.Prompt.Tool (+  -- * Defining a tool+  Toolable (..),+  toolName,++  -- * Handling a tool+  ToolHandler (..),+  toolDefsRaw,++  -- * Tools as effects+  Tool (..),+  callTool,+  runTool,++  -- * Offering tools to the model+  ToolBinding (..),+  toolBinding,+  dispatchBindings,+) where++-- base+import Control.Monad.IO.Class (MonadIO (..))+import Data.Char (isUpper, toLower)+import Data.List (intercalate)+import Data.Proxy (Proxy (..))+import Data.Typeable (Typeable, tyConName, typeRep, typeRepTyCon)++-- text+import Data.Text (Text)+import Data.Text qualified as T++-- aeson+import Data.Aeson (FromJSON, Result (..), Value (..), fromJSON)++-- openapi3+import Data.OpenApi (ToSchema)++-- sop-core+import Data.SOP (All, K (..), NP (..), SListI, hcmap, hcollapse)+import Data.SOP.NP ()++-- SListI instances++-- effectful+import Effectful (Dispatch (Dynamic), DispatchOf, Eff, Effect, IOE, (:>))+import Effectful.Dispatch.Dynamic (interpret, send)++-- shroom++import Control.Monad.Prompt.Schema (ToolDef (..), schemaWithDefs)+import Data.Shroom.Class (Surveyable, describeType)++-- * Tool typeclass++{- | A class for the types whose values the model supplies as the input of a tool+call.++The model is told the tool's name ('toolName'), a description made of+'describeType' followed by 'toolDescription', and the JSON schema of @t@.+When it calls the tool, the input is parsed as @t@ and passed to a t'ToolHandler',+whose result is sent back to the model.+-}+class (Surveyable t, ToSchema t, FromJSON t, Typeable t) => Toolable t where+  {- | Text appended to 'describeType' in the tool's description, for details+  the type does not show, such as rate limits or the format of the result.+  'Nothing' adds nothing.+  -}+  toolDescription :: Proxy t -> Maybe Text+  toolDescription _ = Nothing++{- | The name the model calls tool @t@ by: the type's name in snake case, so+@WebSearch@ becomes @"web_search"@.+-}+toolName :: forall t. (Typeable t) => Proxy t -> Text+toolName p =+  let name = tyConName (typeRepTyCon (typeRep p))+   in T.pack $ fmap toLower $ intercalate "_" $ splitCamel name+  where+    splitCamel [] = []+    splitCamel (c : cs) =+      let (word, rest) = break isUpper cs+       in (c : word) : splitCamel rest++-- * Tool handler++{- | The code that runs tool @t@: it receives the parsed input and returns+'Left' with a failure message or 'Right' with a result, either of which is+sent back to the model. A failure does __not__ count against the limit on tool rounds.+-}+newtype ToolHandler t = ToolHandler+  { runToolHandler :: t -> IO (Either Text Text)+  -- ^ Run the tool on one input.+  }++-- * Tool metadata++{- | The t'ToolDef' of every tool in a list of handlers, for a backend to+register with the model's API.+-}+toolDefsRaw ::+  forall tools.+  (SListI tools, All Toolable tools) =>+  NP ToolHandler tools ->+  [ToolDef]+toolDefsRaw = hcollapse . hcmap (Proxy @Toolable) extract+  where+    extract :: forall t. (Toolable t) => ToolHandler t -> K ToolDef t+    extract _ =+      K+        ToolDef+          { toolDefName = toolName p+          , toolDefDescription = describeType p <> maybe "" (" " <>) (toolDescription p)+          , toolDefSchema = schemaWithDefs p+          }+      where+        p = Proxy @t++-- * Tools as effects++{- | The effect of calling tool @t@.++A program that calls a tool has @'Tool' t ':>' es@ in its constraints, and+calling it without that constraint does not type-check. A sub-program that+needs only some tools runs unchanged inside a program that has more.+'runTool' interprets the effect with a t'ToolHandler'.+-}+data Tool t :: Effect where+  -- | Call the tool with the given input.+  CallTool :: t -> Tool t m (Either Text Text)++type instance DispatchOf (Tool t) = Dynamic++-- | Call tool @t@ and return its result, or the failure message of its handler.+callTool :: forall t es. (Tool t :> es) => t -> Eff es (Either Text Text)+callTool = send . CallTool++-- | Interpret @'Tool' t@ with a t'ToolHandler', running the handler in 'IO'.+runTool :: forall t es a. (IOE :> es) => ToolHandler t -> Eff (Tool t : es) a -> Eff es a+runTool (ToolHandler run) = interpret $ \_ (CallTool t) -> liftIO (run t)++-- * Offering tools to the model++{- | A tool offered to one prompt call: its t'ToolDef' paired with the action+that calls it. Build one with 'toolBinding'.+-}+data ToolBinding m = ToolBinding+  { toolBindingDef :: ToolDef+  -- ^ The name, description and schema the model is sent.+  , toolBindingCall :: Value -> m (Either Text Text)+  -- ^ Parse the model's input and call the tool; a parse failure is a 'Left'.+  }++{- | Offer tool @t@ to a prompt call. It needs @'Tool' t ':>' es@, so a program+can only offer a tool it has been given. The name and description are those+of 'toolDefsRaw'.+-}+toolBinding :: forall t es. (Toolable t, Tool t :> es) => ToolBinding (Eff es)+toolBinding =+  ToolBinding+    { toolBindingDef =+        ToolDef+          { toolDefName = toolName p+          , toolDefDescription = describeType p <> maybe "" (" " <>) (toolDescription p)+          , toolDefSchema = schemaWithDefs p+          }+    , toolBindingCall = \v -> case fromJSON v of+        Error e -> pure (Left ("Tool input parse error for " <> toolName p <> ": " <> T.pack e))+        Success (t :: t) -> callTool t+    }+  where+    p = Proxy @t++{- | Call the tool that the model named, on the input it sent.++The lookup by name happens at run time, since the model sends only a name.+-}+dispatchBindings ::+  (Applicative m) =>+  -- | The tools on offer.+  [ToolBinding m] ->+  {- | The name of the tool, as the model sent it. An unknown name gives a 'Left' that+  lists the available tools.+  -}+  Text ->+  -- | The input of the tool, as the model sent it.+  Value ->+  m (Either Text Text)+dispatchBindings bindings name v =+  case [call | ToolBinding {toolBindingDef, toolBindingCall = call} <- bindings, toolDefName toolBindingDef == name] of+    (call : _) -> call v+    [] ->+      pure $+        Left+          ( "Unknown tool: "+              <> name+              <> ". Available tools: "+              <> T.intercalate ", " (fmap (toolDefName . toolBindingDef) bindings)+          )
+ src/Control/Monad/Prompt/Tool/Web.hs view
@@ -0,0 +1,364 @@+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE TemplateHaskell #-}++{- |+Module      : Control.Monad.Prompt.Tool.Web+Description : Ready-made tools that let a model fetch a web page or search the web.++Three tools, each a 'Toolable' type with a t'ToolHandler' to run it:++* 'webFetchHandler' runs t'WebFetch': an HTTP GET whose HTML is stripped and+  whose text is cut to 2000 characters.+* 'duckDuckGoSearchHandler' runs t'DuckDuckGoSearch', the DuckDuckGo Instant+  Answer API. It suits named entities (people, places, concepts) that have a+  Wikipedia article, and returns a short abstract with a URL.+* 'wikipediaSearchHandler' runs t'WikipediaSearch', the Wikipedia OpenSearch API.+  It returns up to 5 article titles and URLs for any query.++A program that offers these tools has them in its constraints and is run with+one 'Control.Monad.Prompt.Tool.runTool' per handler. See "Control.Monad.Prompt.Tool"+for 'Control.Monad.Prompt.Tool.toolBinding', which offers a tool to the model:++@+result <- runPromptResultEff backend defaultPromptConfig $+  runTool webFetchHandler $+    runTool duckDuckGoSearchHandler $+      runTool wikipediaSearchHandler+        myProgram+@+-}+module Control.Monad.Prompt.Tool.Web (+  -- * Fetching a page+  WebFetch (..),+  WebFetchProperty (..),+  webFetchHandler,++  -- * Searching with DuckDuckGo+  DuckDuckGoSearch (..),+  DuckDuckGoSearchProperty (..),+  duckDuckGoSearchHandler,++  -- * Searching Wikipedia+  WikipediaSearch (..),+  WikipediaSearchProperty (..),+  wikipediaSearchHandler,+) where++-- base+import Control.Exception (SomeAsyncException, SomeException, fromException, tryJust)+import Data.Char (isAlphaNum)++-- text+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Encoding qualified as TE++-- aeson+import Data.Aeson (FromJSON, ToJSON, withObject, (.:?))+import Data.Aeson qualified as Aeson+import GHC.Generics (Generic)++-- vector+import Data.Vector qualified as V++-- containers+import Data.Set qualified as S++-- openapi3+import Data.OpenApi (ToSchema)++-- tagsoup+import Text.HTML.TagSoup (Tag, innerText, parseTags)++-- modern-uri+import Text.URI (mkURI)++-- req+import Network.HTTP.Req (+  GET (..),+  NoReqBody (..),+  bsResponse,+  defaultHttpConfig,+  https,+  req,+  responseBody,+  runReq,+  useHttpURI,+  useHttpsURI,+  (/:),+ )+import Network.HTTP.Req qualified as Req++-- universe-base+import Data.Universe.Class (Universe)++-- shroom++import Control.Monad.Prompt.Promptable (Promptable)+import Control.Monad.Prompt.Tool (ToolHandler (..), Toolable (..))+import Data.Shroom.Class (Surveyable (..))+import Data.Shroom.Class.TH (deriveDescribable)++-- * WebFetch++{- | A request to fetch a URL via HTTP GET.+The LLM provides the URL; the handler returns the page text.+-}+newtype WebFetch = WebFetch+  { fetchUrl :: Text+  -- ^ The URL to fetch.+  }+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema)++-- | The properties of a t'WebFetch', for 'propertyHolds'.+data WebFetchProperty+  = -- | Must start with @http:\/\/@ or @https:\/\/@+    WebFetchUrlScheme+  | -- | Must contain only URL-safe characters+    WebFetchUrlSafeChars+  deriving (Bounded, Enum, Universe, Eq, Ord, Show)++$(deriveDescribable ''WebFetch)++instance Surveyable WebFetch where+  type Property WebFetch = WebFetchProperty+  describeProperties _ WebFetchUrlScheme =+    Just "The URL must start with \"https://\" or \"http://\"."+  describeProperties _ WebFetchUrlSafeChars =+    Just "The URL must contain only URL-safe characters: alphanumerics and \"-._~:/?#[]@!$&'()*+,;=%\". No spaces, no angle brackets, no backslash, no shell special characters."+  propertyHolds (WebFetch url) WebFetchUrlScheme =+    "https://" `T.isPrefixOf` url || "http://" `T.isPrefixOf` url+  propertyHolds (WebFetch url) WebFetchUrlSafeChars =+    T.all (\c -> isAlphaNum c || c `elem` ("-._~:/?#[]@!$&'()*+,;=%" :: String)) url+  examples _ =+    S.fromList+      [ WebFetch "https://example.com"+      , WebFetch "https://en.wikipedia.org/wiki/Haskell_%28programming_language%29"+      ]++instance Promptable WebFetch++instance Toolable WebFetch where+  toolDescription _ = Just "Returns up to 2000 characters of the page body."++-- The User-Agent header that every web handler sends.+userAgentHeader :: Req.Option scheme+userAgentHeader = Req.header "User-Agent" "shroom/0.1 (https://github.com/turion/shroom)"++-- Run an action, catching synchronous exceptions only: a failed request+-- becomes a result, while an asynchronous exception (a timeout, a cancellation)+-- propagates to the caller.+trySynchronous :: IO a -> IO (Either SomeException a)+trySynchronous = tryJust synchronousOnly+  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++{- | Fetch a URL with an HTTP GET, strip the HTML tags and return the first 2000+characters of the text.+-}+webFetchHandler :: ToolHandler WebFetch+webFetchHandler = ToolHandler $ \(WebFetch url) -> do+  result <- trySynchronous $ runReq defaultHttpConfig $ do+    uri <- mkURI url+    case useHttpsURI uri of+      Just (u, opts) -> do+        r <- req GET u NoReqBody bsResponse (opts <> userAgentHeader)+        pure $ Right (responseBody r)+      Nothing ->+        case useHttpURI uri of+          Just (u, opts) -> do+            r <- req GET u NoReqBody bsResponse (opts <> userAgentHeader)+            pure $ Right (responseBody r)+          Nothing -> pure $ Left ("WebFetch: could not parse URL: " <> url)+  case result of+    Left ex -> pure $ Left ("WebFetch error: " <> T.pack (show ex))+    Right (Left e) -> pure $ Left e+    Right (Right bs) ->+      let txt = TE.decodeUtf8Lenient bs+          -- Strip HTML tags using tagsoup+          stripped = innerText (parseTags txt :: [Tag Text])+          -- Collapse whitespace+          cleaned = T.unwords . filter (not . T.null) . T.words $ stripped+       in pure $ Right (T.take 2000 cleaned)++-- * DuckDuckGoSearch++{- | A DuckDuckGo Instant Answer search query.++__Limitations__: This uses the DuckDuckGo Instant Answer API, which only returns+results for well-known named entities (people, places, concepts) that have a+dedicated Wikipedia article. Vague or multi-word queries (e.g. @\"celebrity names\"@,+@\"Haskell conference speakers\"@) will return @\"No result found\"@.+For general search use the Wikipedia search tool instead.+-}+newtype DuckDuckGoSearch = DuckDuckGoSearch+  { searchQuery :: Text+  -- ^ The search query string.+  }+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema)++$(deriveDescribable ''DuckDuckGoSearch)++-- | The properties of a t'DuckDuckGoSearch', for 'propertyHolds'.+data DuckDuckGoSearchProperty+  = -- | Must not be empty+    DuckDuckGoSearchQueryNotEmpty+  | -- | Only alphanumerics, spaces, basic punctuation+    DuckDuckGoSearchQuerySafeChars+  deriving (Bounded, Enum, Universe, Eq, Ord, Show)++instance Surveyable DuckDuckGoSearch where+  type Property DuckDuckGoSearch = DuckDuckGoSearchProperty+  describeProperties _ DuckDuckGoSearchQueryNotEmpty =+    Just "The search query must not be empty."+  describeProperties _ DuckDuckGoSearchQuerySafeChars =+    Just "The search query must contain only alphanumerics, spaces, and basic punctuation (\".,'-\"). No newlines, no HTML, no shell special characters."+  propertyHolds (DuckDuckGoSearch q) DuckDuckGoSearchQueryNotEmpty = not (T.null q)+  propertyHolds (DuckDuckGoSearch q) DuckDuckGoSearchQuerySafeChars =+    T.all (\c -> isAlphaNum c || c `elem` (" .,'-" :: String)) q+  examples _ =+    S.fromList+      [ DuckDuckGoSearch "Haskell programming language"+      , DuckDuckGoSearch "Simon Peyton Jones"+      ]++instance Promptable DuckDuckGoSearch++instance Toolable DuckDuckGoSearch where+  toolDescription _ = Just "DuckDuckGo Instant Answer: returns a short abstract for well-known named entities (people, places) that have a Wikipedia article. Returns no result for vague or multi-word queries — use wikipedia_search instead."++-- The fields of the DuckDuckGo Instant Answer API response that the handler reads.+data DDGResponse = DDGResponse+  { abstractText :: Maybe Text+  , abstractURL :: Maybe Text+  , heading :: Maybe Text+  , answer :: Maybe Text+  }++instance Aeson.FromJSON DDGResponse where+  parseJSON = withObject "DDGResponse" $ \o ->+    DDGResponse+      <$> o .:? "AbstractText"+      <*> o .:? "AbstractURL"+      <*> o .:? "Heading"+      <*> o .:? "Answer"++-- | Query the DuckDuckGo Instant Answer API and return its answer, or its abstract with a URL.+duckDuckGoSearchHandler :: ToolHandler DuckDuckGoSearch+duckDuckGoSearchHandler = ToolHandler $ \(DuckDuckGoSearch q) -> do+  result <- trySynchronous $ runReq defaultHttpConfig $ do+    r <-+      req+        GET+        (https "api.duckduckgo.com")+        NoReqBody+        bsResponse+        ( Req.queryParam "q" (Just q)+            <> Req.queryParam "format" (Just ("json" :: Text))+            <> Req.queryParam "no_html" (Just ("1" :: Text))+            <> Req.queryParam "skip_disambig" (Just ("1" :: Text))+            <> userAgentHeader+        )+    pure $ responseBody r+  case result of+    Left ex -> pure $ Left ("DuckDuckGoSearch error: " <> T.pack (show ex))+    Right bs ->+      case Aeson.decodeStrict bs of+        Nothing -> pure $ Right "DuckDuckGoSearch: could not parse response"+        Just ddg ->+          pure $ Right $ case answer ddg of+            Just a | not (T.null a) -> a+            _ -> case abstractText ddg of+              Just t+                | not (T.null t) ->+                    let url = maybe "" ("\nURL: " <>) (abstractURL ddg)+                     in T.take 500 t <> url+              _ -> case heading ddg of+                Just h | not (T.null h) -> "Search result: " <> h+                _ -> "No result found for: " <> q++-- * WikipediaSearch++-- | A Wikipedia article search query.+newtype WikipediaSearch = WikipediaSearch+  { wikiQuery :: Text+  -- ^ The search query string.+  }+  deriving stock (Eq, Ord, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema)++-- | The properties of a t'WikipediaSearch', for 'propertyHolds'.+data WikipediaSearchProperty+  = -- | Must not be empty+    WikipediaSearchQueryNotEmpty+  | -- | Only alphanumerics, spaces, basic punctuation+    WikipediaSearchQuerySafeChars+  deriving (Bounded, Enum, Universe, Eq, Ord, Show)++$(deriveDescribable ''WikipediaSearch)++instance Surveyable WikipediaSearch where+  type Property WikipediaSearch = WikipediaSearchProperty+  describeProperties _ WikipediaSearchQueryNotEmpty =+    Just "The search query must not be empty."+  describeProperties _ WikipediaSearchQuerySafeChars =+    Just "The search query must contain only alphanumerics, spaces, and basic punctuation (\".,'-\"). No newlines, no HTML, no shell special characters."+  propertyHolds (WikipediaSearch q) WikipediaSearchQueryNotEmpty = not (T.null q)+  propertyHolds (WikipediaSearch q) WikipediaSearchQuerySafeChars =+    T.all (\c -> isAlphaNum c || c `elem` (" .,'-" :: String)) q+  examples _ =+    S.fromList+      [ WikipediaSearch "Haskell monad tutorial"+      , WikipediaSearch "functional programming"+      ]++instance Promptable WikipediaSearch++instance Toolable WikipediaSearch where+  toolDescription _ = Just "Returns up to 5 Wikipedia article titles and URLs matching the query."++{- | Query the Wikipedia OpenSearch API, return article titles and URLs.+Works for any query; use 'webFetchHandler' to read a returned URL.+-}+wikipediaSearchHandler :: ToolHandler WikipediaSearch+wikipediaSearchHandler = ToolHandler $ \(WikipediaSearch q) -> do+  result <- trySynchronous $ runReq defaultHttpConfig $ do+    r <-+      req+        GET+        (https "en.wikipedia.org" /: "w" /: "api.php")+        NoReqBody+        bsResponse+        ( Req.queryParam "action" (Just ("opensearch" :: Text))+            <> Req.queryParam "search" (Just q)+            <> Req.queryParam "limit" (Just ("5" :: Text))+            <> Req.queryParam "format" (Just ("json" :: Text))+            <> userAgentHeader+        )+    pure $ responseBody r+  case result of+    Left ex -> pure $ Left ("WikipediaSearch error: " <> T.pack (show ex))+    Right bs ->+      -- OpenSearch response: [query, [titles], [descriptions], [urls]]+      case Aeson.decodeStrict bs of+        Just (Aeson.Array arr)+          | length arr == 4+          , Just titles <- decodeTexts (arr V.! 1)+          , Just urls <- decodeTexts (arr V.! 3)+          , not (null titles) ->+              pure $+                Right $+                  T.intercalate+                    "\n"+                    [t <> " — " <> u | (t, u) <- zip titles urls]+        _ -> pure $ Right ("No Wikipedia results for: " <> q)+  where+    decodeTexts (Aeson.Array v) = Just [t | Aeson.String t <- V.toList v]+    decodeTexts _ = Nothing
+ test-utils/CelebrityTypes.hs view
@@ -0,0 +1,133 @@+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE DerivingStrategies #-}+{-# LANGUAGE TemplateHaskell #-}+{-# OPTIONS_HADDOCK hide #-}++{- |+Module      : CelebrityTypes+Description : Types and prompt chain for a celebrity trivia scenario.++The chain has two steps:++1. Ask the LLM to produce a list of exactly 3 celebrities.+2. Pick one deterministically, then ask the LLM to look up a Wikipedia+   article via web search + web fetch and return one surprising trivia fact.+-}+module CelebrityTypes (+  CelebrityList (..),+  CelebrityListProperty (..),+  CelebrityFact (..),+  CelebrityFactProperty (..),+  celebrityChain,+) where++-- base+import GHC.Generics (Generic)++-- text+import Data.Text (Text)+import Data.Text qualified as T++-- aeson+import Data.Aeson (FromJSON, ToJSON)++-- openapi3+import Data.OpenApi (ToSchema)++-- universe-base+import Data.Universe.Class (Universe)++-- effectful+import Effectful (Eff, (:>))+import Effectful.State.Static.Local (State)++-- shroom+import Control.Monad.Prompt+import Control.Monad.Prompt.Backend (ContextItem)+import Control.Monad.Prompt.Effect (Prompt, context)+import Control.Monad.Prompt.Effect qualified as Effect+import Control.Monad.Prompt.Tool (ToolBinding)+import Data.Shroom.Class+import Data.Shroom.Class.TH (deriveDescribable)++-- * Types++-- | A list of exactly 3 celebrity names.+newtype CelebrityList = CelebrityList+  { celebrities :: [Text]+  -- ^ Exactly 3 celebrity names (first and last name).+  }+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema)++-- | A property of a t'CelebrityList' that should hold.+data CelebrityListProperty = CelebrityListHasThree+  deriving (Bounded, Enum, Universe, Eq, Ord, Show)++-- | A single celebrity trivia fact.+data CelebrityFact = CelebrityFact+  { celebrity :: Text+  -- ^ The full name of the celebrity.+  , triviaFact :: Text+  -- ^ One surprising trivia fact about this celebrity.+  }+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema)++-- | A property of a t'CelebrityFact' that should hold.+data CelebrityFactProperty+  = CelebrityFactNameNotEmpty+  | CelebrityFactTriviaNotEmpty+  deriving (Bounded, Enum, Universe, Eq, Ord, Show)++$(deriveDescribable ''CelebrityList)++instance Surveyable CelebrityList where+  type Property CelebrityList = CelebrityListProperty+  describeProperties _ CelebrityListHasThree = Just "The list must contain exactly 3 celebrity names."+  propertyHolds cl CelebrityListHasThree = length cl.celebrities == 3++instance Promptable CelebrityList++$(deriveDescribable ''CelebrityFact)++instance Surveyable CelebrityFact where+  type Property CelebrityFact = CelebrityFactProperty+  describeProperties _ CelebrityFactNameNotEmpty = Just "The celebrity name must not be empty."+  describeProperties _ CelebrityFactTriviaNotEmpty = Just "The trivia fact must not be empty."+  propertyHolds cf CelebrityFactNameNotEmpty = not (T.null cf.celebrity)+  propertyHolds cf CelebrityFactTriviaNotEmpty = not (T.null cf.triviaFact)++instance Promptable CelebrityFact++-- * Prompt chain++{- | A two-step prompt chain for celebrity trivia.++1. Generate a list of exactly 3 celebrities.+2. Pick one (deterministically), look up their Wikipedia page using+   @web_search@ and @web_fetch@, and return one surprising trivia fact.++The tools ('Control.Monad.Prompt.Tool.Web.duckDuckGoSearchHandler',+'Control.Monad.Prompt.Tool.Web.wikipediaSearchHandler',+'Control.Monad.Prompt.Tool.Web.webFetchHandler') are offered only at the second step, via the+@bindings@ this takes — build each with+'Control.Monad.Prompt.Tool.toolBinding' and interpret with+'Control.Monad.Prompt.Tool.runTool'.+-}+celebrityChain ::+  (Prompt :> es, State [ContextItem] :> es) =>+  [ToolBinding (Eff es)] ->+  Eff es CelebrityFact+celebrityChain bindings = do+  context "You are a trivia assistant. You MUST use your tools to look up information — do not answer from memory."+  CelebrityList names <- prompt @CelebrityList+  let chosen = names !! (length names `mod` 3)+  Effect.withContext+    ( "You MUST use your tools to look up "+        <> chosen+        <> ". First search the web to find their Wikipedia page URL, then fetch that URL."+        <> " Do not answer from memory. Return one surprising trivia fact found in the fetched page."+    )+    (Effect.promptTools @CelebrityFact bindings)
+ test-utils/ConferenceTypes.hs view
@@ -0,0 +1,415 @@+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE DerivingStrategies #-}+{-# LANGUAGE TemplateHaskell #-}+{-# OPTIONS_HADDOCK hide #-}++{- |+Module      : ConferenceTypes+Description : Types for a multi-step conference scheduling scenario.++The prompt chain has three steps, each depending on the previous:++1. t'Speakers' — who is presenting? A list of t'Speaker' values.+2. t'Talk' — what are they presenting? One per speaker, referencing the speaker.+3. t'ConferenceSchedule' — the full day's schedule, containing the talks.+-}+module ConferenceTypes (+  SpeakerName (..),+  Speaker (..),+  SpeakerProperty (..),+  Speakers (..),+  SpeakersProperty (..),+  GhcExtension (..),+  Talk (..),+  TalkProperty (..),+  Slot (..),+  SlotProperty (..),+  ConferenceSchedule (..),+  ScheduleProperty (..),+  conferenceChain,+  SpeakerLookup (..),+  fakeSpeakerLookupHandler,+  conferenceChainWithTools,+) where++-- base+import Data.List (nub)+import Data.Proxy (Proxy (..))+import GHC.Generics (Generic)++-- text+import Data.Text (Text)+import Data.Text qualified as T++-- time+import Data.Time (UTCTime, secondsToDiffTime, utctDayTime)++-- aeson+import Data.Aeson (FromJSON, ToJSON)++-- openapi3+import Data.OpenApi (ToSchema)++-- generics-sop+import Generics.SOP qualified as SOP++-- universe-base+import Data.Universe.Class (Universe)++-- effectful+import Effectful (Eff, (:>))+import Effectful.Error.Static (Error)+import Effectful.State.Static.Local (State)++-- shroom+import Control.Monad.Prompt+import Control.Monad.Prompt.Backend (ContextItem)+import Control.Monad.Prompt.Effect (Prompt, context, orElse, promptSingleWith, withContext)+import Control.Monad.Prompt.Effect qualified as Effect+import Control.Monad.Prompt.Tool (ToolBinding, ToolHandler (..), Toolable (..))+import Data.Shroom.Class+import Data.Shroom.Class.TH (deriveDescribable)++-- * Types++-- | The full name of a person.+data SpeakerName = SpeakerName+  { firstName :: Text+  -- ^ The person's given name, e.g. "Simon".+  , lastName :: Text+  -- ^ The person's family name, e.g. "Peyton Jones".+  }+  deriving (Eq, Ord, Show, Generic, ToJSON, FromJSON, ToSchema)+  deriving anyclass (SOP.Generic, SOP.HasDatatypeInfo)++-- | A speaker at ZuriHac, identified by name, affiliation, and a short bio.+data Speaker = Speaker+  { speakerName :: SpeakerName+  -- ^ The speaker's name.+  , speakerAffiliation :: Text+  -- ^ The speaker's institutional affiliation, e.g. "University of Cambridge".+  , speakerBio :: Text+  -- ^ A one-paragraph biography of the speaker.+  }+  deriving (Eq, Show, Generic, ToJSON, FromJSON, ToSchema)++-- | A property of a speaker that should hold.+data SpeakerProperty+  = SpeakerFirstNameNotEmpty+  | SpeakerLastNameNotEmpty+  | SpeakerAffiliationNotEmpty+  deriving (Bounded, Enum, Universe, Eq, Ord, Show)++-- | A list of speakers at the conference. Must contain between 3 and 10 speakers.+newtype Speakers = Speakers+  { speakers :: [Speaker]+  }+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema)++-- | A property of a speakers list that should hold.+data SpeakersProperty = SpeakersBetween3And10+  deriving (Bounded, Enum, Universe, Eq, Ord, Show)++{- | A GHC language extension that may be required to understand or appreciate a talk.+If your talk requires all of these, please also bring a whiteboard.+-}+data GhcExtension+  = -- | For when you want your types to have a family reunion nobody asked for.+    TypeFamilies+  | -- | The extension that says "I trust you" while slowly backing away.+    UndecidableInstances+  | -- | Finally, the extension for types that can't make up their mind.+    ImpredicativeTypes+  | -- | Use each value exactly once. No, you can't have it back.+    LinearTypes+  deriving (Bounded, Enum, Universe, Eq, Ord, Show, Generic, ToJSON, FromJSON, ToSchema)++-- | A talk submitted to a conference session, with title, abstract, speaker, and required GHC extensions.+data Talk = Talk+  { talkTitle :: Text+  -- ^ The title of the talk.+  , talkAbstract :: Text+  -- ^ A brief abstract describing the talk's content (1-3 sentences).+  , talkSpeakerName :: SpeakerName+  -- ^ The name of the presenting speaker. Must exactly match a known speaker's name.+  , talkExtensions :: [GhcExtension]+  -- ^ GHC language extensions that attendees should know to fully appreciate this talk.+  }+  deriving (Eq, Show, Generic, ToJSON, FromJSON, ToSchema)++-- | A property of a talk that should hold.+data TalkProperty+  = TalkTitleNotEmpty+  | TalkSpeakerNameNotEmpty+  deriving (Bounded, Enum, Universe, Eq, Ord, Show)++-- | A timetable slot at the conference, containing a single talk with its start and end time.+data Slot = Slot+  { slotStart :: UTCTime+  -- ^ The start time of the slot (ISO 8601), e.g. "2027-06-11T09:00:00Z".+  , slotEnd :: UTCTime+  -- ^ The end time of the slot (ISO 8601), e.g. "2027-06-11T09:45:00Z".+  , slotTalk :: Talk+  -- ^ The talk presented in this slot.+  }+  deriving (Eq, Show, Generic, ToJSON, FromJSON, ToSchema)++-- | A property of a slot that should hold.+data SlotProperty+  = SlotStartBeforeEnd+  deriving (Bounded, Enum, Universe, Eq, Ord, Show)++-- | A full day's schedule for the conference, listing all timetable slots in order.+data ConferenceSchedule = ConferenceSchedule+  { scheduleDay :: UTCTime+  -- ^ The date of this conference day (ISO 8601), e.g. "2027-06-11T00:00:00Z".+  , scheduleSlots :: [Slot]+  {- ^ The ordered list of timetable slots for the day. Must contain at least one slot,+    one per speaker, and slots must be contiguous (each slot's end time equals the next slot's start time).+  -}+  }+  deriving (Eq, Show, Generic, ToJSON, FromJSON, ToSchema)++-- | A property of a schedule that should hold.+data ScheduleProperty+  = ScheduleHasAtLeastOneSlot+  | ScheduleSlotsAreContiguous+  | ScheduleEachTalkOccursOnce+  | ScheduleStartsAtNine+  deriving (Bounded, Enum, Universe, Eq, Ord, Show)++$(deriveDescribable ''SpeakerName)++instance Surveyable SpeakerName++instance Promptable SpeakerName++$(deriveDescribable ''Speaker)++instance Surveyable Speaker where+  type Property Speaker = SpeakerProperty+  describeProperties _ SpeakerFirstNameNotEmpty = Just "The speaker's first name must not be empty."+  describeProperties _ SpeakerLastNameNotEmpty = Just "The speaker's last name must not be empty."+  describeProperties _ SpeakerAffiliationNotEmpty = Just "The speaker's affiliation must not be empty."+  propertyHolds s SpeakerLastNameNotEmpty = not (T.null (lastName (speakerName s)))+  propertyHolds s SpeakerFirstNameNotEmpty = not (T.null (firstName (speakerName s)))+  propertyHolds s SpeakerAffiliationNotEmpty = not (T.null (speakerAffiliation s))++instance Promptable Speaker++$(deriveDescribable ''Speakers)++instance Surveyable Speakers where+  type Property Speakers = Either SpeakersProperty SpeakerProperty+  describeProperties _ (Left SpeakersBetween3And10) = Just "The list must contain between 3 and 10 speakers (inclusive)."+  describeProperties _ (Right p) = describeEvery "Every speaker" (Proxy @Speaker) p+  propertyHolds s (Left SpeakersBetween3And10) = let n = length (speakers s) in n >= 3 && n <= 10+  propertyHolds s (Right p) = everyHolds (speakers s) p++instance Promptable Speakers++$(deriveDescribable ''GhcExtension)++$(deriveDescribable ''Talk)++instance Surveyable Talk where+  type Property Talk = TalkProperty+  describeProperties _ TalkTitleNotEmpty = Just "The talk title must not be empty."+  describeProperties _ TalkSpeakerNameNotEmpty = Just "The speaker's first and last name must not be empty."+  propertyHolds t TalkTitleNotEmpty = not (T.null (talkTitle t))+  propertyHolds t TalkSpeakerNameNotEmpty = not (T.null (firstName (talkSpeakerName t))) && not (T.null (lastName (talkSpeakerName t)))++instance Promptable Talk++$(deriveDescribable ''Slot)++instance Surveyable Slot where+  type Property Slot = SlotProperty+  describeProperties _ SlotStartBeforeEnd = Just "The slot's start time must be strictly before its end time."+  propertyHolds s SlotStartBeforeEnd = slotStart s < slotEnd s++instance Promptable Slot++$(deriveDescribable ''ConferenceSchedule)++instance Surveyable ConferenceSchedule where+  type Property ConferenceSchedule = Either ScheduleProperty SlotProperty+  describeProperties _ (Left ScheduleHasAtLeastOneSlot) = Just "The schedule must contain at least one slot."+  describeProperties _ (Left ScheduleSlotsAreContiguous) = Just "Slots must be contiguous: each slot's end time must equal the next slot's start time."+  describeProperties _ (Left ScheduleEachTalkOccursOnce) = Just "Each talk must appear in exactly one slot (no duplicate talks)."+  describeProperties _ (Left ScheduleStartsAtNine) = Just "ZuriHac always starts at 09:00 local time (07:00 UTC in June). The first slot must start then."+  describeProperties _ (Right p) = describeEvery "Every slot" (Proxy @Slot) p+  propertyHolds s (Left ScheduleHasAtLeastOneSlot) = not (null (scheduleSlots s))+  propertyHolds s (Left ScheduleSlotsAreContiguous) =+    let slots = scheduleSlots s+        pairs = zip slots (drop 1 slots)+     in all (\(a, b) -> slotEnd a == slotStart b) pairs+  propertyHolds s (Left ScheduleEachTalkOccursOnce) =+    let titles = fmap (talkTitle . slotTalk) (scheduleSlots s)+     in length titles == length (nub titles)+  propertyHolds s (Left ScheduleStartsAtNine) =+    case scheduleSlots s of+      [] -> False+      (first : _) -> utctDayTime (slotStart first) == secondsToDiffTime (7 * 3600)+  propertyHolds s (Right p) = everyHolds (scheduleSlots s) p++instance Promptable ConferenceSchedule++-- * Prompt chain++{- | A multi-step prompt chain that builds a ZuriHac 2027 conference schedule from scratch.++Each step uses the output of earlier steps to constrain later prompts,+demonstrating prompt chaining with cross-step dependencies.++Steps:++1. t'Speakers' — generate 3-10 speakers+2. One t'Talk' per speaker (each speaker gives exactly one talk)+3. t'ConferenceSchedule' — the full day's schedule+-}+conferenceChain ::+  (Prompt :> es, State [ContextItem] :> es, Error Text :> es) =>+  Eff es (Speakers, [Talk], ConferenceSchedule)+conferenceChain = do+  context "You are helping to schedule ZuriHac 2027, a Haskell community conference at OST Rapperswil-Jona, Switzerland, right next to a beautiful lake."+  context "The conference focuses on Haskell, functional programming, and type theory -- or as we call it, 'a weekend of explaining monads to lake ducks'."++  allSpeakers <- prompt @Speakers++  context $+    "The confirmed speakers are: "+      <> T.intercalate+        ", "+        ( fmap+            ( \s ->+                firstName (speakerName s)+                  <> " "+                  <> lastName (speakerName s)+                  <> " ("+                  <> speakerAffiliation s+                  <> ")"+            )+            (speakers allSpeakers)+        )++  talks <-+    mapM+      ( \speaker -> do+          promptSingleWith @Talk $+            "The talk must be presented by "+              <> firstName (speakerName speaker)+              <> " "+              <> lastName (speakerName speaker)+              <> ". "+              <> "Invent a talk that fits their background."+      )+      (speakers allSpeakers)++  context $+    "The talks are: "+      <> T.intercalate+        ", "+        ( fmap+            ( \t ->+                "\""+                  <> talkTitle t+                  <> "\" by "+                  <> firstName (talkSpeakerName t)+                  <> " "+                  <> lastName (talkSpeakerName t)+            )+            talks+        )++  -- Try a short prompt first (cheap); if the model can't satisfy the type properties+  -- after retries, fall back to the detailed prompt that explicitly spells them out.+  schedule <-+    promptSingleWith @ConferenceSchedule+      "Create a schedule for Friday 11 June 2027 with one slot per talk. Include every talk."+      `orElse` promptSingleWith @ConferenceSchedule+        ( "Create a schedule for Friday 11 June 2027 as an ordered list of timetable slots, one per talk. "+            <> "Each slot must have a start time and end time in ISO 8601 UTC format (e.g. \"2027-06-11T07:00:00Z\", \"2027-06-11T07:45:00Z\"), and slots must be contiguous. "+            <> "The first slot must start at 07:00:00 UTC (09:00 Zurich local time). "+            <> "Include every talk exactly once."+        )++  pure (allSpeakers, talks, schedule)++-- * Tool: SpeakerLookup++-- | A request to look up background info about a conference speaker by name.+newtype SpeakerLookup = SpeakerLookup+  { speakerLookupName :: Text+  -- ^ The full name of the speaker to look up.+  }+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++$(deriveDescribable ''SpeakerLookup)++instance Surveyable SpeakerLookup++instance Promptable SpeakerLookup++instance Toolable SpeakerLookup where+  toolDescription _ = Just "Look up a speaker's background, research interests, and past talks."++-- | Canned handler: returns one of 3 bios based on name length mod 3.+fakeSpeakerLookupHandler :: ToolHandler SpeakerLookup+fakeSpeakerLookupHandler = ToolHandler $ \(SpeakerLookup name) ->+  pure $ Right $ case T.length name `mod` 3 of+    0 -> name <> " is known for pioneering work on dependent types and proof assistants."+    1 -> name <> " is a compiler engineer specializing in GHC optimizations and LLVM backends."+    _ -> name <> " researches distributed systems and formal verification of consensus protocols."++{- | Conference chain that instructs the LLM to search the web for speaker+info. Unlike 'conferenceChain', this takes the tool @bindings@ to offer —+only the per-speaker t'Talk' step gets them, matching the instruction text+below; build each binding with 'Control.Monad.Prompt.Tool.toolBinding' and+interpret with 'Control.Monad.Prompt.Tool.runTool'.+-}+conferenceChainWithTools ::+  (Prompt :> es, State [ContextItem] :> es, Error Text :> es) =>+  [ToolBinding (Eff es)] ->+  Eff es (Speakers, [Talk], ConferenceSchedule)+conferenceChainWithTools bindings = do+  context "You are helping to schedule ZuriHac 2027, a Haskell community conference at OST Rapperswil-Jona, Switzerland, right next to a beautiful lake."+  context "The conference focuses on Haskell, functional programming, and type theory."+  allSpeakers <- prompt @Speakers+  context $+    "The confirmed speakers are: "+      <> T.intercalate+        ", "+        ( fmap+            ( \s ->+                firstName (speakerName s)+                  <> " "+                  <> lastName (speakerName s)+            )+            (speakers allSpeakers)+        )+  talks <-+    mapM+      ( \speaker ->+          withContext+            ( "The talk must be presented by "+                <> firstName (speakerName speaker)+                <> " "+                <> lastName (speakerName speaker)+                <> ". You may search the web once to look up their background. Then write the abstract — do not search again."+            )+            (Effect.promptTools @Talk bindings)+      )+      (speakers allSpeakers)+  context $+    "The talks are: "+      <> T.intercalate ", " (fmap talkTitle talks)+  schedule <-+    promptSingleWith @ConferenceSchedule+      "Create a schedule for Friday 11 June 2027 with one slot per talk. Include every talk."+      `orElse` promptSingleWith @ConferenceSchedule+        "Create a schedule for Friday 11 June 2027. First slot starts at 07:00:00 UTC. Slots must be contiguous."+  pure (allSpeakers, talks, schedule)
+ test-utils/GenericTypes.hs view
@@ -0,0 +1,155 @@+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE StandaloneDeriving #-}+{-# LANGUAGE TemplateHaskell #-}+{-# OPTIONS_HADDOCK hide #-}++{- |+Module      : GenericTypes+Description : The two examples of @deriving via Generically@, a record and a sum.++Both are written the way a user would write them, and shared by the+integration cases of @shroom-baikai@, so a failure of the strategy against a+real provider has a minimal reproduction.++The composite types, t'Musician' and t'Fruit', derive 'Promptable' via+the t'Generically' wrapper, so a prompt of one builds its parts one request at a time and+makes them cohere. Their leaves, t'Name', t'City', t'Apple' and t'Banana', each make a single request,+as the guide in "Control.Monad.Prompt.Promptable" advises.+-}+module GenericTypes (+  Musician (..),+  Name (..),+  NameProperty (..),+  City (..),+  Fruit (..),+  Apple (..),+  Banana (..),+  allPropertiesHold,+) where++-- base+import GHC.Generics (Generic, Generically (..))++-- text+import Data.Text (Text)+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++-- universe-base+import Data.Universe.Class (Universe, universe)++-- shroom+import Control.Monad.Prompt.Promptable (Promptable)+import Data.Shroom.Class+import Data.Shroom.Class.TH (deriveDescribable)++-- | A musician, with a name and the city they are from.+data Musician = Musician+  { name :: Name+  -- ^ The musician's full name.+  , city :: City+  -- ^ The city the musician is from.+  }+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++-- | The full name of a person.+newtype Name = Name Text+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++-- | The name of a city.+newtype City = City Text+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++-- | A fruit, either an apple or a banana.+data Fruit+  = -- | An apple.+    FruitApple Apple+  | -- | A banana.+    FruitBanana Banana+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++-- | An apple, counted by its kernels.+newtype Apple = Apple+  { kernels :: Int+  -- ^ The number of kernels in the apple.+  }+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++{- | A banana, measured by its length.++The field is called @lengthCm@ rather than @length@: the unit belongs in the+name, as the model sees it, and a field @length@ would clash with+'Prelude.length' in every module that imports this one unqualified.+-}+newtype Banana = Banana+  { lengthCm :: Double+  -- ^ The length of the banana, in centimetres.+  }+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++-- | A property of a name that should hold.+data NameProperty = NameNotEmpty+  deriving stock (Eq, Ord, Show, Bounded, Enum)+  deriving anyclass (Universe)++$(deriveDescribable ''Name)++$(deriveDescribable ''City)++$(deriveDescribable ''Musician)++$(deriveDescribable ''Apple)++$(deriveDescribable ''Banana)++$(deriveDescribable ''Fruit)++-- A property for the structural default of 'Musician' to find.+instance Surveyable Name where+  type Property Name = NameProperty+  describeProperties _ NameNotEmpty = Just "The name is not empty."+  propertyHolds (Name t) NameNotEmpty = not (T.null t)++instance Surveyable City++instance Surveyable Apple++instance Surveyable Banana++-- No @Property@, no methods: the properties of the fields, 'Name''s included.+instance Surveyable Musician++instance Surveyable Fruit++-- Leaves make a single request each.+instance Promptable Name++instance Promptable City++instance Promptable Apple++instance Promptable Banana++-- Composites are prompted part by part, see "Control.Monad.Prompt.Promptable".+deriving via Generically Musician instance Promptable Musician++deriving via Generically Fruit instance Promptable Fruit++-- | Whether every property of a value holds.+allPropertiesHold :: (Surveyable a) => a -> Bool+allPropertiesHold x = all (propertyHolds x) universe
+ test-utils/TestUtils.hs view
@@ -0,0 +1,90 @@+{-# LANGUAGE LambdaCase #-}+{-# OPTIONS_HADDOCK hide #-}++{- |+Module      : TestUtils+Description : Mock backends and assertion helpers for the offline tests.+-}+module TestUtils (+  MockConfig (..),+  SeqMockConfig (..),+  InjectFailConfig (..),+  mockBackend,+  seqMockBackend,+  injectFailBackend,+  assertContains,+  assertNotContains,+  textIsInfixOf,+) where++-- base++import Control.Monad.IO.Class (MonadIO, liftIO)+import Data.IORef++-- aeson+import Data.Aeson (encode)++-- text+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Lazy (toStrict)+import Data.Text.Lazy.Encoding (decodeUtf8)++-- shroom+import Control.Monad.Prompt.Backend (Backend (..), BackendError (..), BackendReply (..), renderContextItems)++-- * Mock backends++{- | A mock t'Backend' that records the context passed to each call (as flat+text via 'renderContextItems') and always returns @0@ (encoded as JSON)+for a t'Types.Counter'. No tool concept: the offered tools are ignored and every+reply is a 'BackendAnswer'.+-}+newtype MockConfig = MockConfig (IORef [Text])++mockBackend :: (MonadIO m) => MockConfig -> Backend m+mockBackend (MockConfig ref) =+  Backend $ \ctx _typeDesc _schema _toolDefs -> liftIO $ do+    atomicModifyIORef' ref (\xs -> (xs <> [renderContextItems ctx], ()))+    -- Return a valid Counter JSON (the newtype wraps an Int)+    pure $ Right (BackendAnswer (toStrict (decodeUtf8 (encode (0 :: Int)))))++{- | A mock t'Backend' that returns responses from a list in order, repeating+the last one when the list is exhausted. Records contexts as flat text via+'renderContextItems'. No tool concept: the offered tools are ignored and+every reply is a 'BackendAnswer'.+-}+data SeqMockConfig = SeqMockConfig (IORef [Text]) (IORef [Text])++seqMockBackend :: (MonadIO m) => SeqMockConfig -> Backend m+seqMockBackend (SeqMockConfig responses seenCtxs) =+  Backend $ \ctx _typeDesc _schema _toolDefs -> liftIO $ do+    atomicModifyIORef' seenCtxs (\xs -> (xs <> [renderContextItems ctx], ()))+    atomicModifyIORef' responses $ \case+      [] -> ([], Left (BackendTransportError "SeqMockConfig: no more responses"))+      [x] -> ([x], Right (BackendAnswer x))+      (x : rest) -> (rest, Right (BackendAnswer x))++-- * Helpers++assertContains :: Text -> Text -> IO ()+assertContains needle haystack+  | needle `textIsInfixOf` haystack = pure ()+  | otherwise = fail $ "Expected " <> show needle <> " in:\n" <> show haystack++assertNotContains :: Text -> Text -> IO ()+assertNotContains needle haystack+  | needle `textIsInfixOf` haystack =+      fail $ "Expected " <> show needle <> " to NOT be in:\n" <> show haystack+  | otherwise = pure ()++textIsInfixOf :: Text -> Text -> Bool+textIsInfixOf = T.isInfixOf++-- | A marker config for a mock t'Backend' that always returns a backend-level error.+data InjectFailConfig = InjectFailConfig++-- | t'Backend' for t'InjectFailConfig': always fails, unconditionally.+injectFailBackend :: (Applicative m) => InjectFailConfig -> Backend m+injectFailBackend _ = Backend $ \_ _ _ _ -> pure (Left (BackendTransportError "injected failure"))
+ test-utils/Types.hs view
@@ -0,0 +1,90 @@+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE TemplateHaskell #-}+{-# OPTIONS_HADDOCK hide #-}++{- |+Module      : Types+Description : Small example types for the offline tests.+-}+module Types where++-- base+import GHC.Generics (Generic)++-- text+import Data.Text (Text)+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++-- containers+import Data.Set qualified as S++-- universe-base+import Data.Universe.Class (Universe)++-- shroom++import Control.Monad.Prompt.Promptable (Promptable)+import Data.Shroom.Class+import Data.Shroom.Class.TH (deriveDescribable)++-- | A user with a name and an email address.+data User = User+  { userName :: Text+  -- ^ The user's full name.+  , userEmail :: Text+  -- ^ The user's email address.+  }+  deriving (Eq, Show, Generic, ToJSON, FromJSON, ToSchema)++-- | An integer counter that keeps track of how many times an event has occurred.+newtype Counter = Counter Int+  deriving stock (Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++-- | A geographic coordinate expressed as a latitude\/longitude pair.+data Coordinate = Coordinate+  { latitude :: Double+  -- ^ The latitude in degrees.+  , longitude :: Double+  -- ^ The longitude in degrees.+  }+  deriving (Generic, ToJSON, FromJSON, ToSchema)+  deriving anyclass (SOP.Generic, SOP.HasDatatypeInfo)++-- | A property of a user that should hold.+data UserProperty = UserEmailNotEmpty | UserEmailHasAtSign+  deriving (Bounded, Enum, Universe, Eq, Ord, Show)++$(deriveDescribable ''User)++instance Surveyable User where+  type Property User = UserProperty+  describeProperties _ UserEmailNotEmpty = Just "The email address is not empty."+  describeProperties _ UserEmailHasAtSign = Just "The email address must contain an '@' character."+  propertyHolds user UserEmailNotEmpty = not (T.null (userEmail user))+  propertyHolds user UserEmailHasAtSign = T.elem '@' (userEmail user)++instance Promptable User++$(deriveDescribable ''Counter)++instance Surveyable Counter where+  examples _ = S.singleton (Counter 0)++instance Promptable Counter++$(deriveDescribable ''Coordinate)++instance Surveyable Coordinate++instance Promptable Coordinate
+ test-utils/WebToolReport.hs view
@@ -0,0 +1,172 @@+{-# LANGUAGE AllowAmbiguousTypes #-}+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DerivingStrategies #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE UndecidableInstances #-}+{-# OPTIONS_HADDOCK hide #-}++{- |+Module      : WebToolReport+Description : A tool-testing report type parametrised by the list of tools under test.++'WebToolReport tools' holds a list of t'ToolResult' records, one per tool,+recording success (no error) or failure (error message).+-}+module WebToolReport (+  WebToolReport (..),+  ToolResult (..),+  expectedNames,+  toolResults,+  webToolReportChain,+) where++-- base+import Data.Kind (Type)+import Data.Proxy (Proxy (..))+import Data.Typeable (Typeable)+import GHC.Generics (Generic)++-- text+import Data.Text (Text)+import Data.Text qualified as T++-- aeson+import Data.Aeson (FromJSON, ToJSON)++-- openapi3+import Data.OpenApi (ToSchema)++-- sop-core+import Data.SOP (All, K (..), NP, SListI, hcollapse, hcpure)++-- universe-base+import Data.Universe.Class (Universe)++-- effectful+import Effectful (Eff, (:>))+import Effectful.State.Static.Local (State)++-- shroom+import Control.Monad.Prompt (Promptable)+import Control.Monad.Prompt.Backend (ContextItem)+import Control.Monad.Prompt.Effect (Prompt, context)+import Control.Monad.Prompt.Effect qualified as Effect+import Control.Monad.Prompt.Tool (Tool, ToolBinding, Toolable, toolBinding, toolName)+import Data.Shroom.Class (Describable (..), Surveyable (..))++-- * Types++-- | The result of testing one tool.+data ToolResult = ToolResult+  { resultToolName :: Text+  -- ^ The snake_case name of the tool that was tested.+  , resultStatus :: Text+  {- ^ Either @"ok"@ if the tool returned any content, or an error message+  string if the tool call failed with an exception or HTTP error.+  -}+  }+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema)++{- | A report of tool tests.++A list of one t'ToolResult' per available tool.+-}+newtype WebToolReport (tools :: [Type]) = WebToolReport+  { results :: [ToolResult]+  -- ^ One entry per tool tested.+  }+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema)++{- | Extract results as a list of @(toolName, status)@ pairs.+Status is @"ok"@ for success or an error string for failure.+-}+toolResults :: WebToolReport tools -> [(Text, Text)]+toolResults r = (\tr -> (resultToolName tr, resultStatus tr)) <$> results r++-- | The only enforced property: every expected tool must appear in the results.+data AllToolsTested = AllToolsTested+  deriving stock (Bounded, Enum, Eq, Ord, Show)+  deriving anyclass (Universe)++instance (SListI tools, All Toolable tools, Typeable tools) => Describable (WebToolReport tools) where+  describeType _ =+    "A report of tool tests. "+      <> "Call each available tool with a reasonable test input. "+      <> "For each tool: set resultStatus to the string \"ok\" if the tool returned any content, "+      <> "or set resultStatus to the error message if the tool call failed with an exception or HTTP error. "+      <> "The tools to test are: "+      <> T.intercalate ", " (expectedNames @tools)+      <> ". Example of all tools succeeding: {\"results\": ["+      <> T.intercalate ", " (fmap (\k -> "{\"resultToolName\": \"" <> k <> "\", \"resultStatus\": \"ok\"}") (expectedNames @tools))+      <> "]}. "+      <> "Example with one failure: {\"results\": [{\"resultToolName\": \"some_tool\", \"resultStatus\": \"HTTP 404: not found\"}]}"++instance (SListI tools, All Toolable tools, Typeable tools) => Surveyable (WebToolReport tools) where+  type Property (WebToolReport tools) = AllToolsTested++  describeProperties _ AllToolsTested =+    Just $+      "The results list must contain exactly one entry per tool: "+        <> T.intercalate ", " (expectedNames @tools)++  propertyHolds r AllToolsTested =+    let names = fmap resultToolName (results r)+     in all (`elem` names) (expectedNames @tools)++instance (SListI tools, All Toolable tools, Typeable tools) => Promptable (WebToolReport tools)++-- | Extract the tool names for a type-level list of 'Toolable' types.+expectedNames ::+  forall tools.+  (SListI tools, All Toolable tools) =>+  [Text]+expectedNames =+  hcollapse (hcpure (Proxy @Toolable) nameK :: NP (K Text) tools)+  where+    nameK :: forall t. (Toolable t) => K Text t+    nameK = K (toolName (Proxy @t))++{- | A tool type that is both 'Toolable' and offered in @es@ — the two+constraints 'toolBindingsFor' needs to build a 'ToolBinding' for it. A+separate, named class rather than a bare tuple constraint because+'hcpure' needs one t'Proxy'-able class to instantiate at each element of+@tools@.+-}+class (Toolable t, Tool t :> es) => ToolableIn es t++instance (Toolable t, Tool t :> es) => ToolableIn es t++{- | Build one 'ToolBinding' per tool in @tools@, generically — the+type-level-list analogue of writing out @[toolBinding \@T1, toolBinding+\@T2, ...]@ by hand.+-}+toolBindingsFor ::+  forall tools es.+  (SListI tools, All (ToolableIn es) tools) =>+  [ToolBinding (Eff es)]+toolBindingsFor =+  hcollapse (hcpure (Proxy @(ToolableIn es)) bindingK :: NP (K (ToolBinding (Eff es))) tools)+  where+    bindingK :: forall t. (ToolableIn es t) => K (ToolBinding (Eff es)) t+    bindingK = K (toolBinding @t)++-- * Chain++{- | A prompt chain that asks the model to test every available tool and+return a t'WebToolReport'.  The type description already instructs the model+to record success\/failure per tool, so no extra context is needed. Every+tool named in @tools@ must also be in @es@ (via 'Tool'), which is what lets+'toolBindingsFor' build a binding for each of them.+-}+webToolReportChain ::+  forall tools es.+  (Prompt :> es, State [ContextItem] :> es, SListI tools, All Toolable tools, All (ToolableIn es) tools, Typeable tools) =>+  Eff es (WebToolReport tools)+webToolReportChain = do+  context "You are a tool-testing assistant. Your job is to call each available tool exactly once with a reasonable test input, observe the result, then return a JSON report."+  context $ "Step 1: call each of these tools once: " <> T.intercalate ", " (expectedNames @tools) <> "."+  context $ "Step 2: return a JSON object with a \"results\" array. Each entry must have \"resultToolName\" and \"resultStatus\". Set resultStatus to \"ok\" if the tool returned any content. Set resultStatus to the error message if the tool result started with 'Error:'. Tools: " <> T.intercalate ", " (expectedNames @tools) <> "."+  Effect.promptTools @(WebToolReport tools) (toolBindingsFor @tools @es)
+ test/CelebrityScenario.hs view
@@ -0,0 +1,102 @@+module Main (main) where++-- base+import Control.Monad (void)+import Data.IORef++-- text+import Data.Text (Text)+import Data.Text qualified as T++-- tasty+import Test.Tasty (defaultMain, testGroup)+import Test.Tasty.HUnit (testCase, (@?=))++-- shroom+import Control.Monad.Prompt.Effect (PromptConfig (..), defaultPromptConfig)+import Control.Monad.Prompt.Effect qualified as Effect++-- test+import CelebrityTypes+import TestUtils++-- | A valid CelebrityList JSON with exactly 3 celebrities.+listJson :: Text+listJson =+  "{\"celebrities\":[\"Albert Einstein\",\"Marie Curie\",\"Nikola Tesla\"]}"++-- | A valid CelebrityFact JSON.+factJson :: Text+factJson =+  "{\"celebrity\":\"Marie Curie\",\"triviaFact\":\"She was the first woman to win a Nobel Prize, and the only person to win Nobel Prizes in two different sciences (Physics and Chemistry).\"}"++defaultResponses :: [Text]+defaultResponses = [listJson, factJson]++-- | Run celebrityChain with the given canned responses; return (result, seen contexts).+runCelebrity :: PromptConfig -> [Text] -> IO (Either Text CelebrityFact, [Text])+runCelebrity cfg responseList = do+  responses <- newIORef responseList+  seenCtxs <- newIORef []+  result <- Effect.runPromptResultEff (seqMockBackend (SeqMockConfig responses seenCtxs)) cfg (celebrityChain [])+  seen <- readIORef seenCtxs+  pure (result, seen)++-- | Like 'runCelebrity' but fails the test on 'Left'.+runCelebrityOk :: PromptConfig -> [Text] -> IO (CelebrityFact, [Text])+runCelebrityOk cfg responseList = do+  (result, seen) <- runCelebrity cfg responseList+  case result of+    Left err -> fail $ "Expected Right but got Left: " <> T.unpack err+    Right x -> pure (x, seen)++main :: IO ()+main =+  defaultMain $+    testGroup+      "celebrity scenario"+      [ testCase "chain completes successfully" $ do+          void $ runCelebrityOk defaultPromptConfig defaultResponses+      , testCase "returned celebrity name is non-empty" $ do+          (fact, _) <- runCelebrityOk defaultPromptConfig defaultResponses+          not (T.null (celebrity fact)) @?= True+      , testCase "returned trivia fact is non-empty" $ do+          (fact, _) <- runCelebrityOk defaultPromptConfig defaultResponses+          not (T.null (triviaFact fact)) @?= True+      , testCase "exactly 2 LLM calls are made (1 list + 1 fact)" $ do+          (_, seen) <- runCelebrity defaultPromptConfig defaultResponses+          length seen @?= 2+      , testCase "second call context includes the chosen celebrity name" $ do+          (_, seen) <- runCelebrity defaultPromptConfig defaultResponses+          -- The chosen celebrity is names !! (3 `mod` 3) = names !! 0 = "Albert Einstein"+          assertContains "Albert Einstein" (seen !! 1)+      , testCase "empty trivia fact triggers retry" $ do+          let badFact = "{\"celebrity\":\"Marie Curie\",\"triviaFact\":\"\"}"+          responses <- newIORef [listJson, badFact, factJson]+          seenCtxs <- newIORef ([] :: [Text])+          let cfg = SeqMockConfig responses seenCtxs+          result <-+            Effect.runPromptResultEff (seqMockBackend cfg) (defaultPromptConfig {maxRetries = 2}) (celebrityChain [])+          case result of+            Left err -> fail $ "Expected Right but got Left: " <> T.unpack err+            Right fact -> not (T.null (triviaFact fact)) @?= True+          seen <- readIORef seenCtxs+          -- 1 list + 1 bad fact + 1 retry fact = 3 calls+          length seen @?= 3+          assertContains "IMPORTANT" (seen !! 2)+      , testCase "list with wrong count triggers retry" $ do+          let badList = "{\"celebrities\":[\"Only One Celebrity\"]}"+          responses <- newIORef [badList, listJson, factJson]+          seenCtxs <- newIORef ([] :: [Text])+          let cfg = SeqMockConfig responses seenCtxs+          result <-+            Effect.runPromptResultEff (seqMockBackend cfg) (defaultPromptConfig {maxRetries = 2}) (celebrityChain [])+          case result of+            Left err -> fail $ "Expected Right but got Left: " <> T.unpack err+            Right _ -> pure ()+          seen <- readIORef seenCtxs+          -- 1 bad list + 1 good list + 1 fact = 3 calls+          length seen @?= 3+          assertContains "IMPORTANT" (seen !! 1)+          assertContains "exactly 3" (seen !! 1)+      ]
+ test/ConferenceScenario.hs view
@@ -0,0 +1,265 @@+module Main (main) where++-- base+import Control.Monad (void)+import Data.IORef+import Data.List (nub)+import Data.Proxy (Proxy (..))++-- text+import Data.Text (Text)+import Data.Text qualified as T++-- time+import Data.Time (UTCTime (..), fromGregorian, secondsToDiffTime)++-- tasty+import Test.Tasty (defaultMain, testGroup)+import Test.Tasty.HUnit (testCase, (@?=))++-- shroom+import Control.Monad.Prompt.Effect (PromptConfig (..), defaultPromptConfig)+import Control.Monad.Prompt.Effect qualified as Effect+import Control.Monad.Prompt.Tool (runTool, toolBinding)+import Data.Shroom.Class (description, propertyHolds)++-- test+import ConferenceTypes+import TestUtils++-- Canned responses matching the new chain:+--   1. Speakers (3 speakers)+--   2. Talk for speaker 1+--   3. Talk for speaker 2+--   4. Talk for speaker 3+--   5. ConferenceSchedule (3 contiguous slots, starting at 07:00 UTC)++speakersJson :: Text+speakersJson =+  "{\"speakers\":["+    <> "{\"speakerName\":{\"firstName\":\"Grace\",\"lastName\":\"Hopper\"},\"speakerAffiliation\":\"Yale University\",\"speakerBio\":\"Pioneer of compiler design.\"},"+    <> "{\"speakerName\":{\"firstName\":\"Alan\",\"lastName\":\"Turing\"},\"speakerAffiliation\":\"University of Manchester\",\"speakerBio\":\"Father of theoretical computer science.\"},"+    <> "{\"speakerName\":{\"firstName\":\"John\",\"lastName\":\"McCarthy\"},\"speakerAffiliation\":\"Stanford University\",\"speakerBio\":\"Creator of Lisp and coiner of AI.\"}"+    <> "]}"++talk1Json :: Text+talk1Json = "{\"talkTitle\":\"Compilers Are For Everyone\",\"talkAbstract\":\"A history of the compiler.\",\"talkSpeakerName\":{\"firstName\":\"Grace\",\"lastName\":\"Hopper\"},\"talkExtensions\":[\"TypeFamilies\"]}"++talk2Json :: Text+talk2Json = "{\"talkTitle\":\"Computability and the Halting Problem\",\"talkAbstract\":\"On undecidability and limits of computation.\",\"talkSpeakerName\":{\"firstName\":\"Alan\",\"lastName\":\"Turing\"},\"talkExtensions\":[\"UndecidableInstances\"]}"++talk3Json :: Text+talk3Json = "{\"talkTitle\":\"The Birth of Lisp\",\"talkAbstract\":\"How symbolic computation changed programming.\",\"talkSpeakerName\":{\"firstName\":\"John\",\"lastName\":\"McCarthy\"},\"talkExtensions\":[]}"++scheduleJson :: Text+scheduleJson =+  "{\"scheduleDay\":\"2027-06-11T00:00:00Z\",\"scheduleSlots\":["+    <> "{\"slotStart\":\"2027-06-11T07:00:00Z\",\"slotEnd\":\"2027-06-11T07:45:00Z\",\"slotTalk\":"+    <> talk1Json+    <> "},"+    <> "{\"slotStart\":\"2027-06-11T07:45:00Z\",\"slotEnd\":\"2027-06-11T08:30:00Z\",\"slotTalk\":"+    <> talk2Json+    <> "},"+    <> "{\"slotStart\":\"2027-06-11T08:30:00Z\",\"slotEnd\":\"2027-06-11T09:15:00Z\",\"slotTalk\":"+    <> talk3Json+    <> "}"+    <> "]}"++defaultResponses :: [Text]+defaultResponses = [speakersJson, talk1Json, talk2Json, talk3Json, scheduleJson]++-- | Run conferenceChain with given responses; return (result, seen contexts).+runConference :: PromptConfig -> [Text] -> IO (Either Text (Speakers, [Talk], ConferenceSchedule), [Text])+runConference cfg responseList = do+  responses <- newIORef responseList+  seenCtxs <- newIORef []+  result <- Effect.runPromptResultEff (seqMockBackend (SeqMockConfig responses seenCtxs)) cfg conferenceChain+  seen <- readIORef seenCtxs+  pure (result, seen)++-- | Like 'runConference' but fails the test on 'Left'.+runConferenceOk :: PromptConfig -> [Text] -> IO ((Speakers, [Talk], ConferenceSchedule), [Text])+runConferenceOk cfg responseList = do+  (result, seen) <- runConference cfg responseList+  case result of+    Left err -> fail $ "Expected Right but got Left: " <> T.unpack err+    Right x -> pure (x, seen)++main :: IO ()+main =+  defaultMain $+    testGroup+      "conference scenario"+      [ testCase "chain completes successfully" $ do+          void $ runConferenceOk defaultPromptConfig defaultResponses+      , testCase "3 speakers are returned" $ do+          ((allSpeakers, _, _), _) <- runConferenceOk defaultPromptConfig defaultResponses+          length (speakers allSpeakers) @?= 3+      , testCase "one talk per speaker, speaker names match" $ do+          ((allSpeakers, talks, _), _) <- runConferenceOk defaultPromptConfig defaultResponses+          length talks @?= length (speakers allSpeakers)+          mapM_+            (\(speaker, talk) -> talkSpeakerName talk @?= speakerName speaker)+            (zip (speakers allSpeakers) talks)+      , testCase "schedule has at least one slot" $ do+          ((_, _, schedule), _) <- runConferenceOk defaultPromptConfig defaultResponses+          not (null (scheduleSlots schedule)) @?= True+      , testCase "schedule slots are contiguous" $ do+          ((_, _, schedule), _) <- runConferenceOk defaultPromptConfig defaultResponses+          let slots = scheduleSlots schedule+              pairs = zip slots (drop 1 slots)+          all (\(a, b) -> slotEnd a == slotStart b) pairs @?= True+      , testCase "schedule starts at 07:00 UTC (09:00 Zurich)" $ do+          ((_, _, schedule), _) <- runConferenceOk defaultPromptConfig defaultResponses+          case scheduleSlots schedule of+            [] -> fail "No slots"+            (first : _) -> slotStart first @?= read "2027-06-11 07:00:00 UTC"+      , testCase "step 2 context includes all speaker names" $ do+          (_, seen) <- runConference defaultPromptConfig defaultResponses+          -- Step 2 (index 1) should contain the speaker names injected into context+          assertContains "Hopper" (seen !! 1)+          assertContains "Turing" (seen !! 1)+          assertContains "McCarthy" (seen !! 1)+      , testCase "last context includes all talk titles" $ do+          (_, seen) <- runConference defaultPromptConfig defaultResponses+          -- Step 5 (index 4) should contain all talk titles injected into context+          assertContains "Compilers Are For Everyone" (seen !! 4)+          assertContains "Computability and the Halting" (seen !! 4)+          assertContains "The Birth of Lisp" (seen !! 4)+      , testCase "exactly 5 LLM calls are made (1 speakers + 3 talks + 1 schedule)" $ do+          (_, seen) <- runConference defaultPromptConfig defaultResponses+          length seen @?= 5+      , testCase "duplicate talk in schedule triggers retry" $ do+          -- First schedule has talk1 in two slots (fails ScheduleEachTalkOccursOnce)+          -- Second schedule is valid+          let dupScheduleJson =+                "{\"scheduleDay\":\"2027-06-11T00:00:00Z\",\"scheduleSlots\":["+                  <> "{\"slotStart\":\"2027-06-11T07:00:00Z\",\"slotEnd\":\"2027-06-11T07:45:00Z\",\"slotTalk\":"+                  <> talk1Json+                  <> "},"+                  <> "{\"slotStart\":\"2027-06-11T07:45:00Z\",\"slotEnd\":\"2027-06-11T08:30:00Z\",\"slotTalk\":"+                  <> talk1Json+                  <> "},"+                  <> "{\"slotStart\":\"2027-06-11T08:30:00Z\",\"slotEnd\":\"2027-06-11T09:15:00Z\",\"slotTalk\":"+                  <> talk3Json+                  <> "}"+                  <> "]}"+          responses <- newIORef [speakersJson, talk1Json, talk2Json, talk3Json, dupScheduleJson, scheduleJson]+          seenCtxs <- newIORef ([] :: [Text])+          let cfg = SeqMockConfig responses seenCtxs+          result <- Effect.runPromptResultEff (seqMockBackend cfg) (defaultPromptConfig {maxRetries = 2}) conferenceChain+          case result of+            Left err -> fail $ "Expected Right but got Left: " <> T.unpack err+            Right (_, _, schedule) -> do+              let titles = fmap (talkTitle . slotTalk) (scheduleSlots schedule)+              length titles @?= length (nub titles)+          seen <- readIORef seenCtxs+          -- 5 normal calls + 1 retry for schedule = 6 total+          length seen @?= 6+          -- Retry context should mention the violated property+          assertContains "IMPORTANT" (seen !! 5)+          assertContains "duplicate" (seen !! 5)+      , testCase "non-contiguous slots in schedule triggers retry" $ do+          -- First schedule has a gap between slots (fails ScheduleSlotsAreContiguous)+          let gapScheduleJson =+                "{\"scheduleDay\":\"2027-06-11T00:00:00Z\",\"scheduleSlots\":["+                  <> "{\"slotStart\":\"2027-06-11T07:00:00Z\",\"slotEnd\":\"2027-06-11T07:45:00Z\",\"slotTalk\":"+                  <> talk1Json+                  <> "},"+                  <> "{\"slotStart\":\"2027-06-11T08:00:00Z\",\"slotEnd\":\"2027-06-11T08:45:00Z\",\"slotTalk\":"+                  <> talk2Json+                  <> "},"+                  <> "{\"slotStart\":\"2027-06-11T08:45:00Z\",\"slotEnd\":\"2027-06-11T09:30:00Z\",\"slotTalk\":"+                  <> talk3Json+                  <> "}"+                  <> "]}"+          responses <- newIORef [speakersJson, talk1Json, talk2Json, talk3Json, gapScheduleJson, scheduleJson]+          seenCtxs <- newIORef ([] :: [Text])+          let cfg = SeqMockConfig responses seenCtxs+          result <- Effect.runPromptResultEff (seqMockBackend cfg) (defaultPromptConfig {maxRetries = 2}) conferenceChain+          case result of+            Left err -> fail $ "Expected Right but got Left: " <> T.unpack err+            Right (_, _, schedule) -> do+              let slots = scheduleSlots schedule+                  pairs = zip slots (drop 1 slots)+              all (\(a, b) -> slotEnd a == slotStart b) pairs @?= True+          seen <- readIORef seenCtxs+          length seen @?= 6+          assertContains "IMPORTANT" (seen !! 5)+          assertContains "contiguous" (seen !! 5)+      , testCase "speakers property validation: too few speakers triggers retry" $ do+          -- First response has only 2 speakers (fails SpeakersBetween3And10)+          -- Second response has 3 speakers (valid)+          let badSpeakers =+                "{\"speakers\":["+                  <> "{\"speakerName\":{\"firstName\":\"A\",\"lastName\":\"B\"},\"speakerAffiliation\":\"X\",\"speakerBio\":\".\"},"+                  <> "{\"speakerName\":{\"firstName\":\"C\",\"lastName\":\"D\"},\"speakerAffiliation\":\"Y\",\"speakerBio\":\".\"}"+                  <> "]}"+          responses <- newIORef [badSpeakers, speakersJson, talk1Json, talk2Json, talk3Json, scheduleJson]+          seenCtxs <- newIORef ([] :: [Text])+          let cfg = SeqMockConfig responses seenCtxs+          result <- Effect.runPromptResultEff (seqMockBackend cfg) (defaultPromptConfig {maxRetries = 2}) conferenceChain+          case result of+            Left err -> fail $ "Expected Right but got Left: " <> T.unpack err+            Right (allSpeakers, _, _) ->+              length (speakers allSpeakers) @?= 3+          seen <- readIORef seenCtxs+          -- 1 bad speakers + 1 good speakers + 3 talks + 1 schedule = 6 calls+          length seen @?= 6+          -- Retry context should explain the violated property+          assertContains "IMPORTANT" (seen !! 1)+          assertContains "between 3 and 10" (seen !! 1)+      , testCase "speaker element property: empty last name inside Speakers triggers retry" $ do+          -- First response has 3 speakers, one with an empty lastName: the+          -- element property is lifted into Speakers, so it is checked and retried.+          let emptyLastName =+                "{\"speakers\":["+                  <> "{\"speakerName\":{\"firstName\":\"Grace\",\"lastName\":\"Hopper\"},\"speakerAffiliation\":\"Yale University\",\"speakerBio\":\".\"},"+                  <> "{\"speakerName\":{\"firstName\":\"Alan\",\"lastName\":\"\"},\"speakerAffiliation\":\"University of Manchester\",\"speakerBio\":\".\"},"+                  <> "{\"speakerName\":{\"firstName\":\"John\",\"lastName\":\"McCarthy\"},\"speakerAffiliation\":\"Stanford University\",\"speakerBio\":\".\"}"+                  <> "]}"+          responses <- newIORef [emptyLastName, speakersJson, talk1Json, talk2Json, talk3Json, scheduleJson]+          seenCtxs <- newIORef ([] :: [Text])+          let cfg = SeqMockConfig responses seenCtxs+          result <- Effect.runPromptResultEff (seqMockBackend cfg) (defaultPromptConfig {maxRetries = 2}) conferenceChain+          case result of+            Left err -> fail $ "Expected Right but got Left: " <> T.unpack err+            Right (allSpeakers, _, _) ->+              not (any (T.null . lastName . speakerName) (speakers allSpeakers)) @?= True+          seen <- readIORef seenCtxs+          -- 1 bad speakers + 1 good speakers + 3 talks + 1 schedule = 6 calls+          length seen @?= 6+          assertContains "IMPORTANT" (seen !! 1)+          assertContains "Every speaker: The speaker's last name must not be empty." (seen !! 1)+      , testCase "Speakers lifts Speaker's properties: an empty lastName violates the Right property" $ do+          let speaker ln = Speaker (SpeakerName "A" ln) "X" "."+              ok = Speakers [speaker "B", speaker "C", speaker "D"]+              bad = Speakers [speaker "B", speaker "", speaker "D"]+          propertyHolds ok (Right SpeakerLastNameNotEmpty) @?= True+          propertyHolds bad (Right SpeakerLastNameNotEmpty) @?= False+          propertyHolds bad (Left SpeakersBetween3And10) @?= True+      , testCase "description of Speakers mentions the lifted last-name rule" $+          assertContains "Every speaker: The speaker's last name must not be empty." (description (Proxy @Speakers))+      , testCase "ConferenceSchedule lifts Slot's properties: a slot ending before it starts is rejected" $ do+          let t h = UTCTime (fromGregorian 2027 6 11) (secondsToDiffTime (h * 3600))+              talk = Talk "T" "A" (SpeakerName "A" "B") []+              good = ConferenceSchedule (t 0) [Slot (t 7) (t 8) talk]+              bad = ConferenceSchedule (t 0) [Slot (t 8) (t 7) talk]+          propertyHolds good (Right SlotStartBeforeEnd) @?= True+          propertyHolds bad (Right SlotStartBeforeEnd) @?= False+          assertContains "Every slot: The slot's start time must be strictly before its end time." (description (Proxy @ConferenceSchedule))+      , testCase "conferenceChainWithTools: chain runs successfully (mock ignores tools)" $ do+          -- Verify that passing a real tool binding and dispatcher compiles+          -- and produces the correct result even when the backend doesn't invoke tools.+          responses <- newIORef defaultResponses+          seenCtxs <- newIORef ([] :: [Text])+          let cfg = SeqMockConfig responses seenCtxs+          result <-+            Effect.runPromptResultEff (seqMockBackend cfg) defaultPromptConfig $+              runTool fakeSpeakerLookupHandler (conferenceChainWithTools [toolBinding @SpeakerLookup])+          case result of+            Left err -> fail $ "Expected Right but got Left: " <> T.unpack err+            Right (allSpeakers, talks, _schedule) -> do+              length (speakers allSpeakers) @?= 3+              length talks @?= 3+      ]
+ test/Main.hs view
@@ -0,0 +1,1414 @@+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE TemplateHaskell #-}++module Main (main) where++-- base+import Control.Concurrent (forkIO, killThread, newEmptyMVar, takeMVar, threadDelay)+import Control.Concurrent.MVar (MVar, modifyMVar_, newMVar, readMVar)+import Control.Exception (bracket)+import Control.Monad (forM_, void)+import Control.Monad.IO.Class (MonadIO, liftIO)+import Data.IORef+import Data.Int (Int64)+import Data.Proxy (Proxy (..))+import Data.Void (Void)+import GHC.Clock (getMonotonicTime)+import Numeric.Natural (Natural)+import System.Timeout (timeout)++-- containers+import Data.Set (Set)+import Data.Set qualified as Set++-- aeson+import Data.Aeson (FromJSON, ToJSON, Value (..), toJSON)+import Data.Aeson.KeyMap qualified as KM+import Data.Aeson.Text (encodeToLazyText)++-- text+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Lazy qualified as TL++-- time+import Data.Time (TimeOfDay, UTCTime)++-- GHC.Generics+import GHC.Generics (Generic, Generically (..))++-- network+import Network.Socket (+  Family (AF_INET),+  PortNumber,+  SockAddr (SockAddrInet),+  SocketType (Stream),+  accept,+  bind,+  close,+  defaultProtocol,+  getSocketName,+  listen,+  socket,+  tupleToHostAddress,+ )++-- openapi3+import Data.OpenApi (ToSchema, toSchema)++-- universe-base+import Data.Universe.Class (Universe)++-- sop-core+import Data.SOP (NP (..))++-- generics-sop+import Generics.SOP qualified as SOP++-- tasty+import Test.Tasty (defaultMain, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++-- effectful+import Effectful (Eff, IOE, (:>))+import Effectful.Concurrent.Async (Concurrent)+import Effectful.Error.Static (Error)+import Effectful.State.Static.Local (State, get)++-- shroom+import Control.Monad.Prompt.Backend (Backend (..), BackendError (..), BackendReply (..), ContextItem (..), ToolCall (..), ToolDef (..), renderContextItems, schemaWithDefs)+import Control.Monad.Prompt.Effect (PromptConfig (..), defaultPromptConfig)+import Control.Monad.Prompt.Effect qualified as Eff+import Control.Monad.Prompt.Promptable (Promptable)+import Control.Monad.Prompt.Promptable qualified as Promptable+import Control.Monad.Prompt.Tool (Tool, ToolHandler (..), Toolable, runTool, toolBinding, toolDefsRaw, toolName)+import Control.Monad.Prompt.Tool.Web+import Data.Shroom.Class (Describable (..), Surveyable (..), description, reach)+import Data.Shroom.Class.TH (deriveDescribable)++-- test+import TestUtils+import Types+import UnqualifiedImports qualified++-- * Mock backends++{- | A mock 'Backend' that blocks every call until @expected@ calls have+all entered, then lets them all through together.++This proves genuine concurrency without a timing assertion: if the calling+branches ran one after another rather than concurrently, the first call+would still be blocked waiting for a second call that has not even started+yet, so the whole computation hangs until the test's outer 'timeout' kills+it. There is no race window to get unlucky on — under real concurrency the+wait resolves as soon as the last branch starts; under sequential+execution it never resolves at all.+-}+barrierBackend :: (MonadIO m) => MVar Int -> Int -> Backend m+barrierBackend entered expected =+  Backend $ \_ctx _typeDesc _schema _toolDefs -> liftIO $ do+    modifyMVar_ entered (pure . (+ 1))+    let waitForAll = do+          n <- readMVar entered+          if n >= expected then pure () else threadDelay 1000 >> waitForAll+    waitForAll+    pure (Right (BackendAnswer "0"))++{- | A mock 'Backend' whose first @n@ calls come back 'BackendTruncated' (with+a half-finished JSON document as the partial text) and whose later calls+answer with @answer@, recording each call's context as one rendered text.+-}+truncatedBackend :: (MonadIO m) => Int -> Text -> IORef Int -> IORef [Text] -> Backend m+truncatedBackend n answer callRef seenCtxs =+  Backend $ \ctx _typeDesc _schema _toolDefs -> liftIO $ do+    atomicModifyIORef' seenCtxs (\xs -> (xs <> [renderContextItems ctx], ()))+    call <- atomicModifyIORef' callRef (\k -> (k + 1, k))+    pure $+      if call < n+        then Left (BackendTruncated "{\"userName\":\"Ali")+        else Right (BackendAnswer answer)++{- | A mock 'Backend' that requests the given tool call once, then answers+@"0"@ (a valid 'Counter') once the conversation shows a tool result. Proves+a tool result actually reaches its registered handler through+"Control.Monad.Prompt.Effect"\'s own tool loop, without needing a real+backend's wire-level tool_use protocol.+-}+toolCallBackend :: (MonadIO m) => Text -> Value -> Backend m+toolCallBackend name inputVal =+  Backend $ \ctx _typeDesc _schema _toolDefs ->+    pure $+      Right $+        if any isToolResult ctx+          then BackendAnswer "0"+          else BackendToolCalls [ToolCall {toolCallId = "call-id", toolCallName = name, toolCallArguments = inputVal}]+  where+    isToolResult (ToolResultMessage _) = True+    isToolResult _ = False++{- | A mock 'Backend' that requests the given tool for the first @n@ rounds,+then answers directly — exercising "Control.Monad.Prompt.Effect"\'s own+tool loop's budget rules (a round costs a step only on success, failed+calls are free) rather than re-testing them against a loop in isolation.++Honours the same "empty @toolDefs@ means no tools are being offered"+contract 'Control.Monad.Prompt.Backend.Backend' documents: called with no+tools (the exhaustion path's own tool-free call), it always answers+straight away rather than consulting the round counter, exactly as the+pre-'Backend'-adapter mock's separate @callModelNoTools@ field always did.+Without this, the round counter alone would keep offering tool calls past+the caller's own step budget, and the tool-free call would look like a+backend that ignored being asked not to.+-}+roundBasedToolBackend :: (MonadIO m) => Text -> Int -> IORef Int -> Backend m+roundBasedToolBackend name wantRounds roundRef =+  Backend $ \_ctx _typeDesc _schema toolDefs ->+    if null toolDefs+      then pure (Right (BackendAnswer "0"))+      else liftIO $ do+        n <- readIORef roundRef+        modifyIORef' roundRef (+ 1)+        pure $+          Right $+            if n < wantRounds+              then BackendToolCalls [ToolCall {toolCallId = "call-id", toolCallName = name, toolCallArguments = toJSON (DuckDuckGoSearch "budget-test")}]+              else BackendAnswer "0"++{- | The effect stack every mock test below runs its program through, once+its own tools have been peeled off the front by 'runTool' — exactly what+'Eff.runPromptResultEff' expects.+-}+type BaseEs = '[Eff.Prompt, State [ContextItem], Error Text, Concurrent, IOE]++{- | Demonstrates "a sub-program can be run with a strict subset of its+caller's tools": this needs only 'DuckDuckGoSearch', not 'WikipediaSearch'.+-}+subProgram :: (Tool DuckDuckGoSearch :> es, Eff.Prompt :> es) => Eff es Counter+subProgram = Eff.promptTools [toolBinding @DuckDuckGoSearch]++{- | A caller with a wider tool surface than 'subProgram' needs. Delegating+to it type-checks for free, because its @es@ is a strict superset of+'subProgram'\'s.+-}+callerProgram :: Eff (Tool DuckDuckGoSearch : Tool WikipediaSearch : BaseEs) Counter+callerProgram = subProgram++-- * A nested array-of-records type, for 'schemaWithDefs' regression coverage++{- | A record two named-schema hops away from a would-be top level — the+shape 'Quexnorbs' below needs, and the shape the existing suite never had:+a nested array of records referencing another record. Field names are+deliberately made up so a passing test can only mean the schema carried them,+never that a model guessed something plausible.+-}+data Zblorf = Zblorf+  { zblorfSnorkfirst :: Text+  , zblorfSnorklast :: Text+  }+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++-- | A record containing 'Zblorf' — one named-schema hop further in.+data Quexnorb = Quexnorb+  { quexnorbVintquark :: Zblorf+  , quexnorbLabel :: Text+  }+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++{- | The actual type under test: an array of 'Quexnorb', itself referencing+'Zblorf'. This is what 'ConferenceTypes.Speakers' looks like structurally+(a list of records, each holding another record) without depending on+that module, so this test stays a fast, hermetic unit test rather than a+live-model integration one.+-}+newtype Quexnorbs = Quexnorbs {quexnorbs :: [Quexnorb]}+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++instance Describable Zblorf where describeType _ = "A record with two unguessable-name fields."+instance Surveyable Zblorf+instance Promptable Zblorf++instance Describable Quexnorb where describeType _ = "A record containing another record."+instance Surveyable Quexnorb+instance Promptable Quexnorb++instance Describable Quexnorbs where describeType _ = "A list of records, each containing another record."+instance Surveyable Quexnorbs+instance Promptable Quexnorbs++instance Toolable Quexnorbs++-- * A bare instance over a field that carries properties++{- | A guest: a label and a registered user. The bare 'Surveyable' instance below+surveys the fields, so the 'User''s email properties are properties of the guest.+-}+data Guest = Guest+  { guestLabel :: Text+  , guestUser :: User+  }+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++instance Describable Guest where describeType _ = "A guest with a label and a registered user."+instance Surveyable Guest+instance Promptable Guest++-- * An override that scopes context++{- | A value whose 'Promptable' instance overrides 'prompt' to scope a piece of+context around the default request, which the class method's @State+[ContextItem]@ constraint makes possible.+-}+newtype Metric = Metric {metricText :: Text}+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++instance Describable Metric where describeType _ = "A measurement written out in text."+instance Surveyable Metric+instance Promptable Metric where+  prompt = Eff.withContext "Always prefer metric units." Eff.promptSingle++-- * Types prompted field by field++-- | A band: a name and a head count. Prompted field by field.+data Band = Band+  { bandName :: Text+  , bandSize :: Int+  }+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++instance Describable Band where describeType _ = "A band with a name and a head count."+instance Surveyable Band+deriving via Generically Band instance Promptable Band++-- | A property of a 'Profile' that should hold.+data ProfileProperty = ProfileEmailNotEmpty+  deriving stock (Bounded, Enum, Eq, Show)+  deriving anyclass (Universe)++-- | A profile with a name and an email address, whose email must not be empty.+data Profile = Profile+  { profileName :: Text+  , profileEmail :: Text+  }+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++instance Describable Profile where describeType _ = "A profile with a name and an email address."+instance Surveyable Profile where+  type Property Profile = ProfileProperty+  propertyHolds p ProfileEmailNotEmpty = not (T.null (profileEmail p))+  describeProperties _ ProfileEmailNotEmpty = Just "The email address is not empty."+deriving via Generically Profile instance Promptable Profile++-- | A measurement whose length field has its own scoped 'prompt' (see 'Metric').+data Measurement = Measurement+  { measurementLength :: Metric+  , measurementNote :: Text+  }+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++instance Describable Measurement where describeType _ = "A measured length with a note."+instance Surveyable Measurement+deriving via Generically Measurement instance Promptable Measurement++-- | A pair with positional fields.+data Pair = Pair Text Int+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++instance Describable Pair where describeType _ = "A text and a number."+instance Surveyable Pair+deriving via Generically Pair instance Promptable Pair++-- | A gig: a band, which is itself prompted field by field, and a venue.+data Gig = Gig+  { gigBand :: Band+  , gigVenue :: Text+  }+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++instance Describable Gig where describeType _ = "A gig at a venue."+instance Surveyable Gig+deriving via Generically Gig instance Promptable Gig++-- | A treat on offer.+data Treat+  = -- | A cake, in a given flavour.+    Cake+      { cakeFlavour :: Text+      -- ^ What the cake tastes of.+      }+  | -- | A biscuit, with a kind and a count.+    Biscuit Text Int+  | -- | No treat at all.+    NoTreat+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++-- The constructors' Haddock comes from the splice, so the description is not written by hand.+$(deriveDescribable ''Treat)++instance Surveyable Treat+deriving via Generically Treat instance Promptable Treat++-- * Reachable types through 'Generically'++-- | An inner record, reachable from 'Outer'.+data Inner = Inner {innerNote :: Text}+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++-- | An outer record that refers to 'Inner', and is prompted for with a bare instance.+data Outer = Outer+  { outerInner :: Inner+  , outerCount :: Int+  , outerTags :: [Text]+  }+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++instance Describable Inner where describeType _ = "An inner record."+instance Surveyable Inner++instance Describable Outer where+  describeType _ = "An outer record."+  referencedTypes _ = reach @Inner <> reach @Int <> reach @[Text]++instance Surveyable Outer+instance Promptable Outer++-- | A chain of links, each holding the next: a recursive type promoted through 'Generically'.+data Chain = Chain+  { chainInner :: Inner+  -- ^ What this link holds.+  , chainNext :: Maybe Chain+  -- ^ The next link, if any.+  }+  deriving stock (Eq, Show, Generic)+  deriving anyclass (ToJSON, FromJSON, ToSchema, SOP.Generic, SOP.HasDatatypeInfo)++$(deriveDescribable ''Chain)++instance Surveyable Chain where type Property Chain = Void++{- | A mock 'Backend' that answers from a list in order (repeating the last+reply once the list runs out, like 'seqMockBackend') and records, for every+call, the rendered context, the type description and the schema it was sent —+which 'seqMockBackend' does not keep.+-}+recordingBackend :: (MonadIO m) => IORef [Text] -> IORef [(Text, Text, Value)] -> Backend m+recordingBackend responses seen =+  Backend $ \ctx typeDesc schema _toolDefs -> liftIO $ do+    atomicModifyIORef' seen (\xs -> (xs <> [(renderContextItems ctx, typeDesc, schema)], ()))+    atomicModifyIORef' responses $ \case+      [] -> ([], Left (BackendTransportError "recordingBackend: no more responses"))+      [x] -> ([x], Right (BackendAnswer x))+      (x : rest) -> (rest, Right (BackendAnswer x))++{- | Run a program against 'recordingBackend' with the given replies and retry+budget, returning the result and every call's (context, type description,+schema).+-}+runRecording :: [Text] -> Int -> Eff BaseEs a -> IO (Either Text a, [(Text, Text, Value)])+runRecording replies retries program = do+  responses <- newIORef replies+  seen <- newIORef []+  result <- Eff.runPromptResultEff (recordingBackend responses seen) (defaultPromptConfig {maxRetries = retries}) program+  calls <- readIORef seen+  pure (result, calls)++-- | The rendered context of the n-th recorded call.+callCtx :: [(Text, Text, Value)] -> Int -> Text+callCtx calls n = case calls !! n of (ctx, _, _) -> ctx++-- | The type description of the n-th recorded call.+callDesc :: [(Text, Text, Value)] -> Int -> Text+callDesc calls n = case calls !! n of (_, desc, _) -> desc++-- | The schema sent with the n-th recorded call.+callSchema :: [(Text, Text, Value)] -> Int -> Value+callSchema calls n = case calls !! n of (_, _, schema) -> schema++{- | Run an action against a localhost TCP listener that accepts a connection+and then never reads from it or writes to it. Binds port 0, so the OS picks a+free one and parallel runs cannot collide; localhost only, no external+service.+-}+withSilentServer :: (PortNumber -> IO a) -> IO a+withSilentServer 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)+    -- 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)++-- * Tests++main :: IO ()+main =+  defaultMain $+    testGroup+      "shroom"+      [ UnqualifiedImports.tests+      , testGroup+          "deriveDescribeType"+          [ testCase "User description comes from Haddock comment" $+              describeType (Proxy @User)+                @?= "A user with a name and an email address.\n"+                  <> "- userName: The user's full name.\n"+                  <> "- userEmail: The user's email address.\n"+          , testCase "Counter description comes from Haddock comment" $+              describeType (Proxy @Counter)+                @?= "An integer counter that keeps track of how many times an event has occurred.\n"+          , testCase "Coordinate description comes from Haddock comment" $+              describeType (Proxy @Coordinate)+                @?= "A geographic coordinate expressed as a latitude/longitude pair.\n"+                  <> "- latitude: The latitude in degrees.\n"+                  <> "- longitude: The longitude in degrees.\n"+          , testCase "describeProperties works for UserEmailNotEmpty" $+              describeProperties (Proxy @User) UserEmailNotEmpty+                @?= Just "The email address is not empty."+          , testCase "propertyHolds catches empty email" $+              propertyHolds (User "Alice" "") UserEmailNotEmpty @?= False+          , testCase "propertyHolds passes non-empty email" $+              propertyHolds (User "Alice" "alice@example.com") UserEmailNotEmpty @?= True+          ]+      , testGroup+          "description output"+          [ testCase "no properties section when Property a = () (Counter)" $ do+              let d = description (Proxy @Counter)+              -- Should contain type description+              assertContains "Produce a value of the following type:" d+              -- Should NOT contain the properties header+              assertNotContains "The following properties MUST hold in your response:" d+              -- Should contain the example+              assertContains "Example valid JSON responses:" d+          , testCase "properties section present when Property a has constructors (User)" $ do+              let d = description (Proxy @User)+              assertContains "The following properties MUST hold in your response:" d+              assertContains "The email address is not empty." d+          , testCase "a bare instance describes the properties of its fields (Guest)" $ do+              let d = description (Proxy @Guest)+              assertContains "The following properties MUST hold in your response:" d+              assertContains "- Field guestUser: The email address is not empty." d+              assertContains "- Field guestUser: The email address must contain an '@' character." d+          ]+      , testGroup+          "structured-output schema (Control.Monad.Prompt.Schema.schemaWithDefs, via toolDefsRaw)"+          [ testCase "a nested array-of-records type carries no unresolved $ref/$defs, and keeps its field names" $ do+              let dummyHandler = ToolHandler $ \_ -> pure (Right "")+              -- The bug this guards against: a live Ollama resolves one+              -- '$ref' hop correctly but silently stops enforcing the schema at a+              -- second one — exactly what a nested array-of-records type produces+              -- unless the schema handed to the wire is fully self-contained.+              case toolDefsRaw (dummyHandler :* Nil :: NP ToolHandler '[Quexnorbs]) of+                [toolDef] -> do+                  let schemaText = TL.toStrict (encodeToLazyText (toolDefSchema toolDef))+                  assertNotContains "$ref" schemaText+                  assertNotContains "$defs" schemaText+                  assertContains "quexnorbVintquark" schemaText+                  assertContains "zblorfSnorkfirst" schemaText+                  assertContains "zblorfSnorklast" schemaText+                defs -> assertFailure ("expected exactly one ToolDef, got " <> show (length defs))+          ]+      , testGroup+          "multi-prompt context preservation"+          [ testCase "global context is visible to all prompts" $ do+              -- A mock backend that records contexts it receives+              seenContexts <- newIORef ([] :: [Text])+              let mockCfg = MockConfig seenContexts++              _ <- Eff.runPromptResultEff (mockBackend mockCfg) defaultPromptConfig $ do+                Eff.context "global info"+                _ <- Eff.promptSingle @Counter+                _ <- Eff.promptSingle @Counter+                pure ()++              seen <- readIORef seenContexts+              -- Both calls should have seen the global context+              length seen @?= 2+              all (\c -> "global info" `textIsInfixOf` c) seen @?= True+          , testCase "promptSingleWith local context not carried forward" $ do+              seenContexts <- newIORef ([] :: [Text])+              let mockCfg = MockConfig seenContexts++              _ <- Eff.runPromptResultEff (mockBackend mockCfg) defaultPromptConfig $ do+                Eff.context "global"+                _ <- Eff.promptSingleWith @Counter "local only"+                _ <- Eff.promptSingle @Counter+                pure ()++              seen <- readIORef seenContexts+              case seen of+                [firstCall, secondCall] -> do+                  -- First call: has both global and local+                  "local only" `textIsInfixOf` firstCall @?= True+                  -- Second call: only global, no local+                  "local only" `textIsInfixOf` secondCall @?= False+                _ -> assertFailure "Unexpected number of seen contexts"+          ]+      , testGroup+          "parallel prompts"+          [ testCase "promptPar makes two LLM calls" $ do+              seenContexts <- newIORef ([] :: [Text])+              let mockCfg = MockConfig seenContexts+              result <-+                Eff.runPromptResultEff (mockBackend mockCfg) defaultPromptConfig $+                  Eff.promptPar (Eff.promptSingle @Counter) (Eff.promptSingle @Counter)+              case result of+                Left err -> fail (show err)+                Right _ -> pure ()+              seen <- readIORef seenContexts+              length seen @?= 2+          , testCase "promptPar branches both see global context" $ do+              seenContexts <- newIORef ([] :: [Text])+              let mockCfg = MockConfig seenContexts+              _ <- Eff.runPromptResultEff (mockBackend mockCfg) defaultPromptConfig $ do+                Eff.context "shared global"+                Eff.promptPar (Eff.promptSingle @Counter) (Eff.promptSingle @Counter)+              seen <- readIORef seenContexts+              all ("shared global" `textIsInfixOf`) seen @?= True+          , testCase "context inside promptPar branch does not leak to sibling" $ do+              seenContexts <- newIORef ([] :: [Text])+              let mockCfg = MockConfig seenContexts+              _ <-+                Eff.runPromptResultEff (mockBackend mockCfg) defaultPromptConfig $+                  Eff.promptPar+                    (Eff.context "branch-local" >> Eff.promptSingle @Counter)+                    (Eff.promptSingle @Counter)+              seen <- readIORef seenContexts+              -- exactly one branch should have seen "branch-local"+              length (filter ("branch-local" `textIsInfixOf`) seen) @?= 1+          , testCase "context inside promptPar branch does not leak to subsequent sequential prompt" $ do+              seenContexts <- newIORef ([] :: [Text])+              let mockCfg = MockConfig seenContexts+              _ <- Eff.runPromptResultEff (mockBackend mockCfg) defaultPromptConfig $ do+                _ <-+                  Eff.promptPar+                    (Eff.context "branch-local" >> Eff.promptSingle @Counter)+                    (Eff.promptSingle @Counter)+                Eff.promptSingle @Counter+              seen <- readIORef seenContexts+              -- last (3rd) call must not contain "branch-local"+              "branch-local" `textIsInfixOf` (seen !! 2) @?= False+          , testCase "promptsParallel makes one call per element" $ do+              seenContexts <- newIORef ([] :: [Text])+              let mockCfg = MockConfig seenContexts+              result <-+                Eff.runPromptResultEff (mockBackend mockCfg) defaultPromptConfig $+                  Eff.promptsParallel (replicate 3 (Eff.promptSingle @Counter))+              case result of+                Left err -> fail (show err)+                Right xs -> length xs @?= 3+              seen <- readIORef seenContexts+              length seen @?= 3+          ]+      , testGroup+          "failure and fallback"+          [ testCase "failWith propagates the message" $ do+              let cfg = MockConfig (error "not implemented")+              result <-+                Eff.runPromptResultEff (mockBackend cfg) defaultPromptConfig (Eff.failWith "the reason" :: Eff BaseEs Counter)+              case result of+                Left err -> assertContains "the reason" err+                Right _ -> fail "Expected Left"+          , testCase "succeeding first branch returned, fallback not run" $ do+              let cfg = MockConfig (error "not implemented")+              result <-+                Eff.runPromptResultEff (mockBackend cfg) defaultPromptConfig $+                  pure (Counter 42) `Eff.orElse` Eff.failWith "should not reach"+              case result of+                Right (Counter 42) -> pure ()+                _ -> fail "Expected Right (Counter 42)"+          , testCase "failing first branch falls back to second" $ do+              let cfg = MockConfig (error "not implemented")+              result <-+                Eff.runPromptResultEff (mockBackend cfg) defaultPromptConfig $+                  Eff.failWith "x" `Eff.orElse` pure (Counter 42)+              case result of+                Right (Counter 42) -> pure ()+                _ -> fail "Expected Right (Counter 42)"+          , testCase "both branches fail — second error propagates" $ do+              let cfg = MockConfig (error "not implemented")+              result <-+                Eff.runPromptResultEff (mockBackend cfg) defaultPromptConfig $+                  Eff.failWith "first" `Eff.orElse` (Eff.failWith "second" :: Eff BaseEs Counter)+              case result of+                Left err -> assertContains "second" err+                Right _ -> fail "Expected Left"+          , testCase "backend error triggers fallback" $ do+              result <-+                Eff.runPromptResultEff (injectFailBackend InjectFailConfig) defaultPromptConfig $+                  Eff.promptSingle @Counter `Eff.orElse` pure (Counter 0)+              case result of+                Right (Counter 0) -> pure ()+                _ -> fail "Expected Right (Counter 0)"+          , testCase "context from failing branch does not persist" $ do+              seenContexts <- newIORef ([] :: [Text])+              let cfg = MockConfig seenContexts+              _ <-+                Eff.runPromptResultEff (mockBackend cfg) defaultPromptConfig $+                  (Eff.context "leaked" >> Eff.failWith "x") `Eff.orElse` Eff.promptSingle @Counter+              seen <- readIORef seenContexts+              length seen @?= 1+              forM_ seen $ assertNotContains "leaked"+          , testCase "context from winning branch persists to next prompt" $ do+              seenContexts <- newIORef ([] :: [Text])+              let cfg = MockConfig seenContexts+              _ <- Eff.runPromptResultEff (mockBackend cfg) defaultPromptConfig $ do+                _ <- (Eff.context "kept" >> Eff.promptSingle @Counter) `Eff.orElse` Eff.failWith "x"+                Eff.promptSingle @Counter+              seen <- readIORef seenContexts+              length seen @?= 2+              assertContains "kept" (seen !! 1)+          ]+      , testGroup+          "web tool security properties"+          [ -- WebFetch URL scheme+            testCase "valid https URL passes scheme check" $+              propertyHolds (WebFetch "https://example.com") WebFetchUrlScheme @?= True+          , testCase "valid http URL passes scheme check" $+              propertyHolds (WebFetch "http://example.com") WebFetchUrlScheme @?= True+          , testCase "file:// URL fails scheme check" $+              propertyHolds (WebFetch "file:///etc/passwd") WebFetchUrlScheme @?= False+          , testCase "empty string fails scheme check" $+              propertyHolds (WebFetch "") WebFetchUrlScheme @?= False+          , -- WebFetch safe chars+            testCase "clean URL passes safe-char check" $+              propertyHolds (WebFetch "https://example.com/path?q=1&x=2") WebFetchUrlSafeChars @?= True+          , testCase "URL with space fails safe-char check" $+              propertyHolds (WebFetch "https://example.com/bad url") WebFetchUrlSafeChars @?= False+          , testCase "URL with backtick injection fails safe-char check" $+              propertyHolds (WebFetch "https://example.com/`rm -rf /`") WebFetchUrlSafeChars @?= False+          , testCase "URL with angle bracket fails safe-char check" $+              propertyHolds (WebFetch "https://evil.com/<script>") WebFetchUrlSafeChars @?= False+          , -- DuckDuckGoSearch not-empty+            testCase "non-empty DDG query passes not-empty check" $+              propertyHolds (DuckDuckGoSearch "Haskell") DuckDuckGoSearchQueryNotEmpty @?= True+          , testCase "empty DDG query fails not-empty check" $+              propertyHolds (DuckDuckGoSearch "") DuckDuckGoSearchQueryNotEmpty @?= False+          , -- DuckDuckGoSearch safe chars+            testCase "plain DDG query passes safe-char check" $+              propertyHolds (DuckDuckGoSearch "Simon Peyton Jones") DuckDuckGoSearchQuerySafeChars @?= True+          , testCase "DDG query with newline fails safe-char check" $+              propertyHolds (DuckDuckGoSearch "foo\nbar") DuckDuckGoSearchQuerySafeChars @?= False+          , testCase "DDG query with angle bracket fails safe-char check" $+              propertyHolds (DuckDuckGoSearch "foo <script>") DuckDuckGoSearchQuerySafeChars @?= False+          , testCase "DDG query with semicolon fails safe-char check" $+              propertyHolds (DuckDuckGoSearch "foo; rm -rf /") DuckDuckGoSearchQuerySafeChars @?= False+          , -- WikipediaSearch safe chars+            testCase "plain Wikipedia query passes safe-char check" $+              propertyHolds (WikipediaSearch "functional programming") WikipediaSearchQuerySafeChars @?= True+          , testCase "Wikipedia query with newline fails safe-char check" $+              propertyHolds (WikipediaSearch "foo\nbar") WikipediaSearchQuerySafeChars @?= False+          , testCase "empty Wikipedia query fails not-empty check" $+              propertyHolds (WikipediaSearch "") WikipediaSearchQueryNotEmpty @?= False+          ]+      , testGroup+          "Prompt effect (effectful)"+          [ testGroup+              "improve"+              [ testCase "a fine reply about a valid value yields Nothing, and the request carries the value, the description and a flat verdict schema" $ do+                  responses <-+                    newIORef+                      (["{\"verdict\":\"fine\",\"value\":{\"userName\":\"Alice\",\"userEmail\":\"alice@example.com\"}}"] :: [Text])+                  seen <- newIORef ([] :: [(Text, Text, Value)])+                  result <-+                    Eff.runPromptResultEff (recordingBackend responses seen) (defaultPromptConfig {maxRetries = 2}) $+                      Eff.improve (User "Alice" "alice@example.com")+                  result @?= Right Nothing+                  calls <- readIORef seen+                  length calls @?= 1+                  let (ctxTxt, typeDesc, schema) = calls !! 0+                  assertContains "\"userName\":\"Alice\"" ctxTxt+                  assertContains "\"userEmail\":\"alice@example.com\"" ctxTxt+                  assertContains (description (Proxy @User)) typeDesc+                  case schema of+                    Object root -> do+                      KM.lookup "type" root @?= Just (String "object")+                      assertBool "no oneOf at the root" (not (KM.member "oneOf" root))+                      assertBool "no $ref at the root" (not (KM.member "$ref" root))+                      -- strict structured-output modes need every property required+                      KM.lookup "required" root @?= Just (toJSON (["verdict", "value"] :: [Text]))+                      case KM.lookup "properties" root of+                        Just (Object props) -> do+                          assertBool "verdict property" (KM.member "verdict" props)+                          assertBool "value property" (KM.member "value" props)+                        other -> assertFailure ("expected a properties object, got " <> show other)+                    other -> assertFailure ("expected an object schema root, got " <> show other)+              , testCase "a fine reply without a value is still accepted for a valid original" $ do+                  responses <- newIORef (["{\"verdict\":\"fine\"}"] :: [Text])+                  seen <- newIORef ([] :: [(Text, Text, Value)])+                  result <-+                    Eff.runPromptResultEff (recordingBackend responses seen) (defaultPromptConfig {maxRetries = 2}) $+                      Eff.improve (User "Alice" "alice@example.com")+                  result @?= Right Nothing+                  readIORef seen >>= (@?= 1) . length+              , testCase "a fine reply's value is ignored, even when it differs from the original and violates properties" $ do+                  responses <-+                    newIORef+                      (["{\"verdict\":\"fine\",\"value\":{\"userName\":\"Someone else\",\"userEmail\":\"\"}}"] :: [Text])+                  seen <- newIORef ([] :: [(Text, Text, Value)])+                  result <-+                    Eff.runPromptResultEff (recordingBackend responses seen) (defaultPromptConfig {maxRetries = 2}) $+                      Eff.improve (User "Alice" "alice@example.com")+                  result @?= Right Nothing+                  readIORef seen >>= (@?= 1) . length+              , testCase "an improved reply yields Just the parsed value" $ do+                  responses <-+                    newIORef+                      (["{\"verdict\":\"improved\",\"value\":{\"userName\":\"Alicia\",\"userEmail\":\"alice@example.com\"}}"] :: [Text])+                  seen <- newIORef ([] :: [(Text, Text, Value)])+                  result <-+                    Eff.runPromptResultEff (recordingBackend responses seen) (defaultPromptConfig {maxRetries = 2}) $+                      Eff.improve (User "Alice" "alice@example.com")+                  result @?= Right (Just (User "Alicia" "alice@example.com"))+                  readIORef seen >>= (@?= 1) . length+              , testCase "an improved value violating a property is retried with a correction naming it" $ do+                  responses <-+                    newIORef+                      ( [ "{\"verdict\":\"improved\",\"value\":{\"userName\":\"Alicia\",\"userEmail\":\"\"}}"+                        , "{\"verdict\":\"improved\",\"value\":{\"userName\":\"Alicia\",\"userEmail\":\"alicia@example.com\"}}"+                        ] ::+                          [Text]+                      )+                  seen <- newIORef ([] :: [(Text, Text, Value)])+                  result <-+                    Eff.runPromptResultEff (recordingBackend responses seen) (defaultPromptConfig {maxRetries = 2}) $+                      Eff.improve (User "Alice" "alice@example.com")+                  result @?= Right (Just (User "Alicia" "alicia@example.com"))+                  calls <- readIORef seen+                  length calls @?= 2+                  let (ctx1, _, _) = calls !! 1+                  assertContains "Violated properties:" ctx1+                  assertContains "The email address is not empty." ctx1+              , testCase "a fine reply about a violating value is retried until the result satisfies the property" $ do+                  responses <-+                    newIORef+                      ( [ "{\"verdict\":\"fine\",\"value\":{\"userName\":\"Alice\",\"userEmail\":\"\"}}"+                        , "{\"verdict\":\"improved\",\"value\":{\"userName\":\"Alice\",\"userEmail\":\"alice@example.com\"}}"+                        ] ::+                          [Text]+                      )+                  seen <- newIORef ([] :: [(Text, Text, Value)])+                  result <-+                    Eff.runPromptResultEff (recordingBackend responses seen) (defaultPromptConfig {maxRetries = 2}) $+                      Eff.improve (User "Alice" "")+                  result @?= Right (Just (User "Alice" "alice@example.com"))+                  calls <- readIORef seen+                  length calls @?= 2+                  let (ctx0, _, _) = calls !! 0+                      (ctx1, _, _) = calls !! 1+                  assertNotContains "Violated properties" ctx0+                  assertContains "Violated properties:" ctx1+                  assertContains "The email address is not empty." ctx1+              , testCase "a fine reply about a violating value is an error once retries run out" $ do+                  responses <- newIORef (["{\"verdict\":\"fine\"}"] :: [Text])+                  seen <- newIORef ([] :: [(Text, Text, Value)])+                  result <-+                    Eff.runPromptResultEff (recordingBackend responses seen) (defaultPromptConfig {maxRetries = 1}) $+                      Eff.improve (User "Alice" "")+                  case result of+                    Left err -> assertContains "The email address is not empty." err+                    Right r -> assertFailure ("expected a failure, got " <> show r)+                  readIORef seen >>= (@?= 2) . length+              , testCase "the scoped message is not persisted; the raw reply is" $ do+                  responses <-+                    newIORef+                      (["{\"verdict\":\"fine\"}", "{\"userName\":\"Bob\",\"userEmail\":\"bob@example.com\"}"] :: [Text])+                  seen <- newIORef ([] :: [(Text, Text, Value)])+                  result <-+                    Eff.runPromptResultEff (recordingBackend responses seen) defaultPromptConfig $ do+                      _ <- Eff.improve (User "Alice" "alice@example.com")+                      Eff.promptSingle @User+                  result @?= Right (User "Bob" "bob@example.com")+                  calls <- readIORef seen+                  length calls @?= 2+                  let (ctx0, _, _) = calls !! 0+                      (ctx1, _, _) = calls !! 1+                  assertContains "Here is a value of the type described below" ctx0+                  assertNotContains "Here is a value of the type described below" ctx1+                  assertContains "[assistant] {\"verdict\":\"fine\"}" ctx1+              ]+          , testGroup+              "Generically (products)"+              [ testCase "a two-field record prompts field 1, field 2, improve, each field seeing what came before" $ do+                  (result, calls) <-+                    runRecording+                      ["\"The Quarks\"", "4", "{\"verdict\":\"fine\"}"]+                      2+                      (Promptable.prompt @Band)+                  -- a fine verdict keeps the draft+                  result @?= Right (Band "The Quarks" 4)+                  length calls @?= 3+                  let parent = description (Proxy @Band)+                  assertContains "A piece of text." (callDesc calls 0)+                  assertContains "A whole number." (callDesc calls 1)+                  assertContains parent (callDesc calls 2)+                  assertContains parent (callCtx calls 0)+                  assertContains "the field bandName" (callCtx calls 0)+                  assertNotContains "the field bandSize" (callCtx calls 0)+                  assertContains parent (callCtx calls 1)+                  assertContains "the field bandSize" (callCtx calls 1)+                  assertContains "[assistant] \"The Quarks\"" (callCtx calls 1)+                  assertContains "\"bandName\":\"The Quarks\"" (callCtx calls 2)+                  assertContains "\"bandSize\":4" (callCtx calls 2)+              , testCase "an improved verdict replaces the draft" $ do+                  (result, calls) <-+                    runRecording+                      [ "\"The Quarks\""+                      , "4"+                      , "{\"verdict\":\"improved\",\"value\":{\"bandName\":\"The Quarks\",\"bandSize\":5}}"+                      ]+                      2+                      (Promptable.prompt @Band)+                  result @?= Right (Band "The Quarks" 5)+                  length calls @?= 3+              , testCase "a violating draft is not returned on a fine verdict" $ do+                  (result, calls) <-+                    runRecording+                      [ "\"Alice\""+                      , "\"\""+                      , "{\"verdict\":\"fine\"}"+                      , "{\"verdict\":\"improved\",\"value\":{\"profileName\":\"Alice\",\"profileEmail\":\"alice@example.com\"}}"+                      ]+                      2+                      (Promptable.prompt @Profile)+                  result @?= Right (Profile "Alice" "alice@example.com")+                  length calls @?= 4+                  assertContains "Violated properties:" (callCtx calls 3)+                  case result of+                    Right p -> propertyHolds p ProfileEmailNotEmpty @?= True+                    Left err -> assertFailure ("expected a value, got " <> show err)+              , testCase "the caller's context ends as what it was plus one AssistantMessage with the final value's JSON" $ do+                  (result, _) <-+                    runRecording+                      ["\"The Quarks\"", "4", "{\"verdict\":\"fine\"}"]+                      2+                      $ do+                        Eff.context "Hello."+                        band <- Promptable.prompt @Band+                        (ctx :: [ContextItem]) <- get+                        pure (band, ctx)+                  result+                    @?= Right+                      ( Band "The Quarks" 4+                      , [UserMessage "Hello.", AssistantMessage (TL.toStrict (encodeToLazyText (Band "The Quarks" 4)))]+                      )+              , testCase "the flat Effect.promptSingle stays flat for a type that derives Generically" $ do+                  (result, calls) <-+                    runRecording+                      ["{\"bandName\":\"The Quarks\",\"bandSize\":4}"]+                      2+                      (Eff.promptSingle @Band)+                  result @?= Right (Band "The Quarks" 4)+                  length calls @?= 1+              , testCase "a field with its own prompt override is prompted through it, and its answer stays visible" $ do+                  (result, calls) <-+                    runRecording+                      ["{\"metricText\":\"3 km\"}", "\"a long road\"", "{\"verdict\":\"fine\"}"]+                      2+                      (Promptable.prompt @Measurement)+                  result @?= Right (Measurement (Metric "3 km") "a long road")+                  length calls @?= 3+                  assertContains "Always prefer metric units." (callCtx calls 0)+                  assertNotContains "Always prefer metric units." (callCtx calls 1)+                  -- the override scoped its own answer away; the strategy put it back+                  assertContains "[assistant] {\"metricText\":\"3 km\"}" (callCtx calls 1)+              , testCase "a positional constructor's fields are named by constructor and position" $ do+                  (result, calls) <-+                    runRecording+                      ["\"x\"", "1", "{\"verdict\":\"fine\"}"]+                      2+                      (Promptable.prompt @Pair)+                  result @?= Right (Pair "x" 1)+                  assertContains "field 1 of constructor Pair" (callCtx calls 0)+                  assertContains "field 2 of constructor Pair" (callCtx calls 1)+              , testCase "a field that is itself generic is built the same way and leaves one message behind" $ do+                  (result, calls) <-+                    runRecording+                      [ "\"The Quarks\""+                      , "4"+                      , "{\"verdict\":\"fine\"}"+                      , "\"The Pub\""+                      , "{\"verdict\":\"fine\"}"+                      ]+                      2+                      (Promptable.prompt @Gig)+                  result @?= Right (Gig (Band "The Quarks" 4) "The Pub")+                  length calls @?= 5+                  -- the venue request sees the finished band as one message, not its parts+                  assertContains "[assistant] {\"bandName\":\"The Quarks\",\"bandSize\":4}" (callCtx calls 3)+                  assertNotContains "the field bandName" (callCtx calls 3)+              ]+          , testGroup+              "Generically (sums)"+              [ testCase "a record constructor prompts choice, its fields, improve" $ do+                  (result, calls) <-+                    runRecording+                      ["\"Cake\"", "\"lemon\"", "{\"verdict\":\"fine\"}"]+                      2+                      (Promptable.prompt @Treat)+                  result @?= Right (Cake "lemon")+                  length calls @?= 3+                  let parent = description (Proxy @Treat)+                  -- the choice: asked about the type, with the parent in its context+                  assertContains "which kind of the type described below" (callDesc calls 0)+                  assertContains parent (callCtx calls 0)+                  assertContains "First choose which of its constructors" (callCtx calls 0)+                  -- the field: names the constructor, sees the choice's reply+                  assertContains "A piece of text." (callDesc calls 1)+                  assertContains "You chose the constructor Cake" (callCtx calls 1)+                  assertContains "the field cakeFlavour of constructor Cake" (callCtx calls 1)+                  assertContains "[assistant] \"Cake\"" (callCtx calls 1)+                  -- the improve request is about the whole value+                  assertContains parent (callDesc calls 2)+                  assertContains "\"cakeFlavour\":\"lemon\"" (callCtx calls 2)+              , testCase "a positional constructor's fields are named by constructor and position" $ do+                  (result, calls) <-+                    runRecording+                      ["\"Biscuit\"", "\"digestive\"", "12", "{\"verdict\":\"fine\"}"]+                      2+                      (Promptable.prompt @Treat)+                  result @?= Right (Biscuit "digestive" 12)+                  length calls @?= 4+                  assertContains "You chose the constructor Biscuit" (callCtx calls 1)+                  assertContains "field 1 of constructor Biscuit" (callCtx calls 1)+                  assertContains "field 2 of constructor Biscuit" (callCtx calls 2)+                  assertContains "[assistant] \"digestive\"" (callCtx calls 2)+              , testCase "a constructor without fields is assembled without field prompts, then improved" $ do+                  (result, calls) <-+                    runRecording+                      ["\"NoTreat\"", "{\"verdict\":\"fine\"}"]+                      2+                      (Promptable.prompt @Treat)+                  result @?= Right NoTreat+                  length calls @?= 2+                  assertContains "[assistant] \"NoTreat\"" (callCtx calls 1)+                  assertNotContains "Next, produce" (callCtx calls 1)+                  assertContains "\"verdict\"" (callDesc calls 1)+              , testCase "an improved verdict replaces the draft" $ do+                  (result, calls) <-+                    runRecording+                      [ "\"Cake\""+                      , "\"lemon\""+                      , "{\"verdict\":\"improved\",\"value\":{\"tag\":\"Cake\",\"cakeFlavour\":\"chocolate\"}}"+                      ]+                      2+                      (Promptable.prompt @Treat)+                  result @?= Right (Cake "chocolate")+                  length calls @?= 3+                  -- the improve request's own schema carries the sum, as anyOf+                  let improveSchema = TL.toStrict (encodeToLazyText (callSchema calls 2))+                  assertContains "anyOf" improveSchema+                  assertNotContains "oneOf" improveSchema+              , testCase "the constructor choice's schema is an enum of exactly the constructor names, and its description has their Haddock" $ do+                  (_, calls) <-+                    runRecording+                      ["\"NoTreat\"", "{\"verdict\":\"fine\"}"]+                      2+                      (Promptable.prompt @Treat)+                  case callSchema calls 0 of+                    Object schema -> do+                      KM.lookup "type" schema @?= Just (String "string")+                      KM.lookup "enum" schema @?= Just (toJSON (["Cake", "Biscuit", "NoTreat"] :: [Text]))+                    other -> assertFailure ("expected a schema object, got " <> show other)+                  assertContains "A treat on offer." (callDesc calls 0)+                  assertContains "A cake, in a given flavour." (callDesc calls 0)+                  assertContains "A biscuit, with a kind and a count." (callDesc calls 0)+                  assertContains "No treat at all." (callDesc calls 0)+              , testCase "a name that is not a constructor is rejected and retried" $ do+                  (result, calls) <-+                    runRecording+                      ["\"Pancake\"", "\"NoTreat\"", "{\"verdict\":\"fine\"}"]+                      2+                      (Promptable.prompt @Treat)+                  result @?= Right NoTreat+                  length calls @?= 3+                  assertContains "not the name of a constructor: Pancake" (callCtx calls 1)+              , testCase "the caller's context ends as what it was plus one AssistantMessage with the final value's JSON" $ do+                  (result, _) <-+                    runRecording+                      ["\"Cake\"", "\"lemon\"", "{\"verdict\":\"fine\"}"]+                      2+                      $ do+                        Eff.context "Hello."+                        treat <- Promptable.prompt @Treat+                        (ctx :: [ContextItem]) <- get+                        pure (treat, ctx)+                  result+                    @?= Right+                      ( Cake "lemon"+                      , [UserMessage "Hello.", AssistantMessage (TL.toStrict (encodeToLazyText (Cake "lemon")))]+                      )+              , testCase "a sum type's wire schema says anyOf where openapi3 says oneOf" $ do+                  let rendered :: (ToJSON v) => v -> Text+                      rendered = TL.toStrict . encodeToLazyText+                  -- the premise: openapi3 itself renders this sum as a oneOf+                  assertContains "oneOf" (rendered (toSchema (Proxy @Treat)))+                  assertNotContains "oneOf" (rendered (schemaWithDefs (Proxy @Treat)))+                  assertContains "anyOf" (rendered (schemaWithDefs (Proxy @Treat)))+              , testCase "a UTCTime's wire schema has the format date-time" $ do+                  let field key = case schemaWithDefs $ Proxy @UTCTime of+                        Object km -> KM.lookup key km+                        _ -> Nothing+                  field "format" @?= Just (String "date-time")+              , testCase "a TimeOfDay's unsupported format moves into its description" $ do+                  let field key = case schemaWithDefs $ Proxy @TimeOfDay of+                        Object km -> KM.lookup key km+                        _ -> Nothing+                  field "format" @?= Nothing+                  field "description" @?= Just (String "Format: hh:MM:ss.")+              , testCase "a Natural's wire schema keeps its bound in the description and sends no exclusiveMinimum" $ do+                  let field key = case schemaWithDefs $ Proxy @Natural of+                        Object km -> KM.lookup key km+                        _ -> Nothing+                  field "exclusiveMinimum" @?= Nothing+                  field "minimum" @?= Nothing+                  field "description" @?= Just (String "Must be at least 0.")+              ]+          , testGroup+              "retry loop"+              [ testCase "validation passes immediately — no retry" $ do+                  responses <- newIORef ["{\"userName\":\"Alice\",\"userEmail\":\"alice@example.com\"}"]+                  seenContexts <- newIORef ([] :: [Text])+                  let cfg = SeqMockConfig responses seenContexts+                  result <-+                    Eff.runPromptResultEff (seqMockBackend cfg) (defaultPromptConfig {maxRetries = 2}) $+                      Eff.promptSingle @User+                  result @?= Right (User "Alice" "alice@example.com")+                  seen <- readIORef seenContexts+                  length seen @?= 1+              , testCase "validation fails then passes — retry succeeds" $ do+                  responses <-+                    newIORef+                      [ "{\"userName\":\"Alice\",\"userEmail\":\"\"}"+                      , "{\"userName\":\"Alice\",\"userEmail\":\"alice@example.com\"}"+                      ]+                  seenContexts <- newIORef ([] :: [Text])+                  let cfg = SeqMockConfig responses seenContexts+                  result <-+                    Eff.runPromptResultEff (seqMockBackend cfg) (defaultPromptConfig {maxRetries = 2}) $+                      Eff.promptSingle @User+                  result @?= Right (User "Alice" "alice@example.com")+                  seen <- readIORef seenContexts+                  length seen @?= 2+              , testCase "retry context includes the property-violation description" $ do+                  responses <-+                    newIORef+                      [ "{\"userName\":\"Alice\",\"userEmail\":\"\"}"+                      , "{\"userName\":\"Alice\",\"userEmail\":\"alice@example.com\"}"+                      ]+                  seenContexts <- newIORef ([] :: [Text])+                  let cfg = SeqMockConfig responses seenContexts+                  _ <-+                    Eff.runPromptResultEff (seqMockBackend cfg) (defaultPromptConfig {maxRetries = 2}) $+                      Eff.promptSingle @User+                  seen <- readIORef seenContexts+                  assertContains "The email address is not empty." (seen !! 1)+                  assertContains "Generate a new, corrected JSON response" (seen !! 1)+              , testCase "a field's violated property is rejected and named in the correction (bare instance)" $ do+                  responses <-+                    newIORef+                      [ "{\"guestLabel\":\"vip\",\"guestUser\":{\"userName\":\"Alice\",\"userEmail\":\"\"}}"+                      , "{\"guestLabel\":\"vip\",\"guestUser\":{\"userName\":\"Alice\",\"userEmail\":\"alice@example.com\"}}"+                      ]+                  seenContexts <- newIORef ([] :: [Text])+                  let cfg = SeqMockConfig responses seenContexts+                  result <-+                    Eff.runPromptResultEff (seqMockBackend cfg) (defaultPromptConfig {maxRetries = 2}) $+                      Eff.promptSingle @Guest+                  result @?= Right (Guest "vip" (User "Alice" "alice@example.com"))+                  seen <- readIORef seenContexts+                  length seen @?= 2+                  assertNotContains "Violated properties" (seen !! 0)+                  assertContains "Violated properties:" (seen !! 1)+                  assertContains "- Field guestUser: The email address is not empty." (seen !! 1)+              , testCase "the class method prompts a bare Text and a [Int]" $ do+                  textResponses <- newIORef ["\"hello\""]+                  textSeen <- newIORef ([] :: [Text])+                  textResult <-+                    Eff.runPromptResultEff (seqMockBackend (SeqMockConfig textResponses textSeen)) (defaultPromptConfig {maxRetries = 0}) $+                      Promptable.prompt @Text+                  textResult @?= Right "hello"+                  readIORef textSeen >>= (@?= 1) . length+                  intsResponses <- newIORef ["[1,2,3]"]+                  intsSeen <- newIORef ([] :: [Text])+                  intsResult <-+                    Eff.runPromptResultEff (seqMockBackend (SeqMockConfig intsResponses intsSeen)) (defaultPromptConfig {maxRetries = 0}) $+                      Promptable.prompt @[Int]+                  intsResult @?= Right [1, 2, 3 :: Int]+                  readIORef intsSeen >>= (@?= 1) . length+              , testCase "the class method prompts a bare Int64, Word and Set Int" $ do+                  let checkPrompt response program expected = do+                        (result, calls) <- runRecording [response] 0 program+                        result @?= Right expected+                        length calls @?= 1+                        pure calls+                  _ <- checkPrompt "42" (Promptable.prompt @Int64) 42+                  _ <- checkPrompt "7" (Promptable.prompt @Word) 7+                  setCalls <- checkPrompt "[3,1,2,3]" (Promptable.prompt @(Set Int)) (Set.fromList [1, 2, 3])+                  assertContains "A set of distinct values of the following type: A whole number." (callDesc setCalls 0)+              , testCase "a prompt override scopes its context to its own request" $ do+                  responses <- newIORef ["{\"metricText\":\"3 km\"}", "{\"metricText\":\"4 km\"}"]+                  seenContexts <- newIORef ([] :: [Text])+                  let cfg = SeqMockConfig responses seenContexts+                  result <-+                    Eff.runPromptResultEff (seqMockBackend cfg) (defaultPromptConfig {maxRetries = 0}) $ do+                      m <- Promptable.prompt @Metric+                      _ <- Eff.promptSingle @Metric+                      pure m+                  result @?= Right (Metric "3 km")+                  seen <- readIORef seenContexts+                  length seen @?= 2+                  assertContains "Always prefer metric units." (seen !! 0)+                  assertNotContains "Always prefer metric units." (seen !! 1)+              , testCase "JSON decode error triggers retry — distinct wording from a property violation" $ do+                  responses <-+                    newIORef+                      [ "not valid json"+                      , "{\"userName\":\"Alice\",\"userEmail\":\"alice@example.com\"}"+                      ]+                  seenContexts <- newIORef ([] :: [Text])+                  let cfg = SeqMockConfig responses seenContexts+                  result <-+                    Eff.runPromptResultEff (seqMockBackend cfg) (defaultPromptConfig {maxRetries = 2}) $+                      Eff.promptSingle @User+                  result @?= Right (User "Alice" "alice@example.com")+                  seen <- readIORef seenContexts+                  length seen @?= 2+                  assertContains "IMPORTANT: Your previous response could not be parsed" (seen !! 1)+                  assertNotContains "violated required properties" (seen !! 1)+              , testCase "JSON decode error exhausts retries" $ do+                  responses <- newIORef (repeat "not valid json")+                  seenContexts <- newIORef ([] :: [Text])+                  let cfg = SeqMockConfig responses seenContexts+                  result <-+                    Eff.runPromptResultEff (seqMockBackend cfg) (defaultPromptConfig {maxRetries = 1}) $+                      Eff.promptSingle @User+                  case result of+                    Left err -> assertContains "JSON decode error" err+                    Right _ -> fail "Expected Left but got Right"+                  seen <- readIORef seenContexts+                  -- 1 original + 1 retry = 2 total calls+                  length seen @?= 2+              , testCase "validation always fails — error after retries exhausted (1 + maxRetries calls)" $ do+                  responses <- newIORef (repeat "{\"userName\":\"Alice\",\"userEmail\":\"\"}")+                  seenContexts <- newIORef ([] :: [Text])+                  let cfg = SeqMockConfig responses seenContexts+                  result <-+                    Eff.runPromptResultEff (seqMockBackend cfg) (defaultPromptConfig {maxRetries = 2}) $+                      Eff.promptSingle @User+                  case result of+                    Left err -> assertContains "The email address is not empty." err+                    Right _ -> assertFailure "Expected Left but got Right"+                  seen <- readIORef seenContexts+                  length seen @?= 3+              , testCase "a truncated reply is retried with a message saying so, not a parse error" $ do+                  callRef <- newIORef 0+                  seenContexts <- newIORef ([] :: [Text])+                  let backend = truncatedBackend 1 "{\"userName\":\"Alice\",\"userEmail\":\"alice@example.com\"}" callRef seenContexts+                  result <-+                    Eff.runPromptResultEff backend (defaultPromptConfig {maxRetries = 2}) $+                      Eff.promptSingle @User+                  result @?= Right (User "Alice" "alice@example.com")+                  seen <- readIORef seenContexts+                  length seen @?= 2+                  assertContains "IMPORTANT: Your previous response was cut off at the length limit" (seen !! 1)+                  assertContains "shorter" (seen !! 1)+                  assertNotContains "could not be parsed" (seen !! 1)+                  -- The half-finished text is not replayed into the context.+                  assertNotContains "Ali\"" (seen !! 1)+              , testCase "a truncated reply that keeps recurring ends in a length error, not a JSON decode error" $ do+                  callRef <- newIORef 0+                  seenContexts <- newIORef ([] :: [Text])+                  let backend = truncatedBackend maxBound "unused" callRef seenContexts+                  result <-+                    Eff.runPromptResultEff backend (defaultPromptConfig {maxRetries = 1}) $+                      Eff.promptSingle @User+                  case result of+                    Left err -> do+                      assertContains "cut off at the length limit" err+                      assertNotContains "JSON decode error" err+                    Right _ -> assertFailure "Expected Left but got Right"+                  seen <- readIORef seenContexts+                  -- 1 original + 1 retry = 2 total calls+                  length seen @?= 2+              ]+          , testGroup+              "promptPar / promptsParallel genuinely run concurrently"+              [ testCase "promptPar: two branches meet at a barrier — sequential execution would deadlock" $ do+                  entered <- newMVar (0 :: Int)+                  outcome <-+                    timeout (5 * 1000 * 1000) $+                      Eff.runPromptResultEff (barrierBackend entered 2) defaultPromptConfig $+                        Eff.promptPar (Eff.promptSingle @Counter) (Eff.promptSingle @Counter)+                  case outcome of+                    Nothing ->+                      assertFailure+                        "promptPar branches never both entered the backend within 5s: they did not run concurrently"+                    Just (Left err) -> assertFailure (show err)+                    Just (Right _) -> pure ()+              , testCase "promptsParallel: three branches meet at a barrier" $ do+                  entered <- newMVar (0 :: Int)+                  outcome <-+                    timeout (5 * 1000 * 1000) $+                      Eff.runPromptResultEff (barrierBackend entered 3) defaultPromptConfig $+                        Eff.promptsParallel (replicate 3 (Eff.promptSingle @Counter))+                  case outcome of+                    Nothing ->+                      assertFailure+                        "promptsParallel branches never all entered the backend within 5s: they did not run concurrently"+                    Just (Left err) -> assertFailure (show err)+                    Just (Right xs) -> length xs @?= 3+              ]+          ]+      , testGroup+          "Tools as effects"+          [ testCase "toolBinding + promptTools + runTool: dispatch reaches the registered handler" $ do+              seenInput <- newIORef Nothing+              let handler = ToolHandler $ \q -> do+                    writeIORef seenInput (Just q)+                    pure (Right "fetched page text")+                  program :: Eff (Tool WebFetch : BaseEs) Counter+                  program = Eff.promptTools [toolBinding @WebFetch]+              result <-+                Eff.runPromptResultEff+                  (toolCallBackend (toolName (Proxy @WebFetch)) (toJSON (WebFetch "https://example.com")))+                  defaultPromptConfig+                  (runTool handler program)+              case result of+                Right (Counter 0) -> pure ()+                Right (Counter n) -> assertFailure ("Expected Counter 0, got Counter " <> show n)+                Left err -> assertFailure (show err)+              seen <- readIORef seenInput+              seen @?= Just (WebFetch "https://example.com")+          , testCase "sub-program runs with a strict subset of the caller's tools" $ do+              let ddgHandler = ToolHandler $ \_ -> pure (Right "ddg result")+                  wikiHandler = ToolHandler $ \_ -> pure (Right "wiki result")+              result <-+                Eff.runPromptResultEff+                  (toolCallBackend (toolName (Proxy @DuckDuckGoSearch)) (toJSON (DuckDuckGoSearch "x")))+                  defaultPromptConfig+                  (runTool wikiHandler (runTool ddgHandler callerProgram))+              case result of+                Right (Counter 0) -> pure ()+                Right (Counter n) -> assertFailure ("Expected Counter 0, got Counter " <> show n)+                Left err -> assertFailure (show err)+          , testCase "tool budget: successful calls cost exactly the budget, then one final tool-free call" $ do+              callCount <- newIORef (0 :: Int)+              roundRef <- newIORef (0 :: Int)+              let handler = ToolHandler $ \_ -> do+                    modifyIORef' callCount (+ 1)+                    pure (Right "ok")+                  program :: Eff (Tool DuckDuckGoSearch : BaseEs) Counter+                  program = Eff.promptTools [toolBinding @DuckDuckGoSearch]+              result <-+                Eff.runPromptResultEff+                  (roundBasedToolBackend (toolName (Proxy @DuckDuckGoSearch)) 5 roundRef)+                  (defaultPromptConfig {maxToolSteps = Just 2})+                  (runTool handler program)+              case result of+                Right (Counter 0) -> pure ()+                Right (Counter n) -> assertFailure ("Expected Counter 0, got Counter " <> show n)+                Left err -> assertFailure (show err)+              n <- readIORef callCount+              n @?= 2+          , testCase "tool budget: failed calls are free and do not consume it" $ do+              roundRef <- newIORef (0 :: Int)+              let handler = ToolHandler $ \_ -> pure (Left "nope")+                  program :: Eff (Tool DuckDuckGoSearch : BaseEs) Counter+                  program = Eff.promptTools [toolBinding @DuckDuckGoSearch]+              result <-+                Eff.runPromptResultEff+                  (roundBasedToolBackend (toolName (Proxy @DuckDuckGoSearch)) 3 roundRef)+                  (defaultPromptConfig {maxToolSteps = Just 1})+                  (runTool handler program)+              case result of+                Right (Counter 0) -> pure ()+                Right (Counter n) -> assertFailure ("Expected Counter 0, got Counter " <> show n)+                Left err ->+                  assertFailure+                    ( "Expected the natural finish after 3 failed calls on a budget of 1, but got: "+                        <> show err+                    )+              {- 'roundBasedToolBackend' bumps 'roundRef' once per+              'runBackendChat' call regardless of outcome, so its count is+              the tell: with the budget never actually spent, all 3+              attempted (and failed) rounds plus the final answer round+              reach 'runBackendChat', for 4 in total. Were failed calls to+              consume budget instead, a budget of 1 would trip the+              exhaustion branch after round 2, and 'runBackendChat' would+              never be reached again — this assertion is what would catch+              that, since both paths otherwise settle on the same+              'Counter 0'.+              -}+              n <- readIORef roundRef+              n @?= 4+          ]+      , testGroup+          "reachable types"+          [ testCase "a type promoted through Generically renders the same reachable sections as its own description" $ do+              let own = description (Proxy @Outer)+              assertContains "The types above refer to the following types:\n\nInner:\nAn inner record.\n" own+              description (Proxy @(Generically Outer)) @?= own+          , testCase "a recursive type promoted through Generically is not listed under itself" $ do+              let sectionHeaders = filter (`elem` (["Chain:", "Inner:"] :: [Text])) . T.lines+                  own = description (Proxy @Chain)+                  promoted = description (Proxy @(Generically Chain))+              sectionHeaders own @?= ["Inner:"]+              sectionHeaders promoted @?= ["Inner:"]+              promoted @?= own+          , testCase "prompt @Outer sends the reachable sections" $ do+              (result, calls) <-+                runRecording+                  ["{\"outerInner\":{\"innerNote\":\"hi\"},\"outerCount\":1,\"outerTags\":[]}"]+                  0+                  (Promptable.prompt @Outer)+              result @?= Right (Outer (Inner "hi") 1 [])+              assertContains (description (Proxy @Outer)) (callDesc calls 0)+          ]+      , testGroup+          "Web tools"+          [ testCase "webFetchHandler: timeout interrupts a request to a server that never answers" $+              withSilentServer $ \port -> do+                let ToolHandler fetch = webFetchHandler+                start <- getMonotonicTime+                -- If the handler swallowed the 'timeout''s asynchronous+                -- exception it would hand back @Just (Left "WebFetch error:+                -- ...")@ here instead of 'Nothing'.+                result <- timeout 1_000_000 (fetch (WebFetch ("http://127.0.0.1:" <> T.pack (show port))))+                elapsed <- subtract start <$> getMonotonicTime+                case result of+                  Nothing -> pure ()+                  Just r -> assertFailure ("expected the timeout to fire, but the handler returned: " <> show r)+                assertBool ("timeout took " <> show elapsed <> "s, expected well under 3s") (elapsed < 3)+          , testCase "webFetchHandler: a synchronous HTTP failure still comes back as a tool error" $ do+              -- The listener is gone once 'withSilentServer' returns, so+              -- its port refuses connections.+              port <- withSilentServer pure+              let ToolHandler fetch = webFetchHandler+              result <- timeout 5_000_000 (fetch (WebFetch ("http://127.0.0.1:" <> T.pack (show port))))+              case result of+                Just (Left err) -> assertBool ("unexpected error text: " <> show err) ("WebFetch error: " `T.isPrefixOf` err)+                other -> assertFailure ("expected a WebFetch tool error, got: " <> show other)+          ]+      ]
+ test/UnqualifiedImports.hs view
@@ -0,0 +1,40 @@+{- | "Control.Monad.Prompt" and "Control.Monad.Prompt.Effect" imported+unqualified, side by side, the way a user's program does. @prompt@ is the class method alone, and the+one-request prompt is 'promptSingle', so the two do not clash.+-}+module UnqualifiedImports (tests) where++-- base+import Data.IORef (newIORef, readIORef)++-- text+import Data.Text (Text)+import Data.Text qualified as T++-- tasty+import Test.Tasty (TestTree)+import Test.Tasty.HUnit (assertFailure, testCase, (@?=))++-- shroom+import Control.Monad.Prompt+import Control.Monad.Prompt.Effect++-- test+import TestUtils (MockConfig (..), mockBackend)+import Types (Counter (..))++tests :: TestTree+tests =+  testCase "prompt is unambiguous next to Effect's promptSingle and promptSingleWith" $ do+    seen <- newIORef ([] :: [Text])+    result <- runPromptResultEff (mockBackend (MockConfig seen)) defaultPromptConfig $ do+      context "unqualified"+      viaClass <- prompt @Counter+      single <- promptSingle @Counter+      singleWith <- promptSingleWith @Counter "local only"+      pure (viaClass, single, singleWith)+    case result of+      Left err -> assertFailure (T.unpack err)+      Right (Counter a, Counter b, Counter c) -> (a, b, c) @?= (0, 0, 0)+    calls <- readIORef seen+    length calls @?= 3
+ test/WebToolsScenario.hs view
@@ -0,0 +1,80 @@+module Main (main) where++-- text+import Data.Text qualified as T++-- tasty+import Test.Tasty (defaultMain, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase)++-- shroom+import Control.Monad.Prompt.Tool (runToolHandler)+import Control.Monad.Prompt.Tool.Web (+  DuckDuckGoSearch (..),+  WebFetch (..),+  WikipediaSearch (..),+  duckDuckGoSearchHandler,+  webFetchHandler,+  wikipediaSearchHandler,+ )++main :: IO ()+main =+  defaultMain $+    testGroup+      "web tools"+      [ testGroup+          "duckDuckGoSearch"+          [ testCase "named entity returns a non-empty result" $ do+              result <- runToolHandler duckDuckGoSearchHandler (DuckDuckGoSearch "Marie Curie")+              case result of+                Left err -> assertFailure ("Expected Right but got Left: " <> T.unpack err)+                Right txt -> assertBool "result should be non-empty" (not (T.null txt))+          , testCase "named entity result includes URL" $ do+              result <- runToolHandler duckDuckGoSearchHandler (DuckDuckGoSearch "Marie Curie")+              case result of+                Left err -> assertFailure ("Expected Right but got Left: " <> T.unpack err)+                Right txt -> assertBool "result should contain a URL" ("URL: " `T.isInfixOf` txt)+          , testCase "vague query returns 'No result found'" $ do+              result <- runToolHandler duckDuckGoSearchHandler (DuckDuckGoSearch "xyzzy frob quux 12345")+              case result of+                Left err -> assertFailure ("Expected Right but got Left: " <> T.unpack err)+                Right txt -> assertBool "vague query should say No result found" ("No result found" `T.isInfixOf` txt)+          ]+      , testGroup+          "wikipediaSearch"+          [ testCase "query returns non-empty results" $ do+              result <- runToolHandler wikipediaSearchHandler (WikipediaSearch "Marie Curie")+              case result of+                Left err -> assertFailure ("Expected Right but got Left: " <> T.unpack err)+                Right txt -> assertBool "result should be non-empty" (not (T.null txt))+          , testCase "result contains Wikipedia URL" $ do+              result <- runToolHandler wikipediaSearchHandler (WikipediaSearch "Marie Curie")+              case result of+                Left err -> assertFailure ("Expected Right but got Left: " <> T.unpack err)+                Right txt -> assertBool "result should contain wikipedia.org URL" ("wikipedia.org" `T.isInfixOf` txt)+          , testCase "vague query still returns results (Wikipedia is broad)" $ do+              result <- runToolHandler wikipediaSearchHandler (WikipediaSearch "celebrity trivia")+              case result of+                Left err -> assertFailure ("Expected Right but got Left: " <> T.unpack err)+                Right txt -> assertBool "Wikipedia should find something" (not (T.null txt))+          ]+      , testGroup+          "webFetch"+          [ testCase "fetching a known URL returns non-empty text" $ do+              result <- runToolHandler webFetchHandler (WebFetch "https://en.wikipedia.org/wiki/Marie_Curie")+              case result of+                Left err -> assertFailure ("Expected Right but got Left: " <> T.unpack err)+                Right txt -> assertBool "fetched content should be non-empty" (not (T.null txt))+          , testCase "fetched content is truncated to 2000 chars" $ do+              result <- runToolHandler webFetchHandler (WebFetch "https://en.wikipedia.org/wiki/Marie_Curie")+              case result of+                Left err -> assertFailure ("Expected Right but got Left: " <> T.unpack err)+                Right txt -> assertBool "content should be at most 2000 chars" (T.length txt <= 2000)+          , testCase "invalid URL returns Left" $ do+              result <- runToolHandler webFetchHandler (WebFetch "not-a-url")+              case result of+                Left _ -> pure ()+                Right _ -> assertFailure "Expected Left for invalid URL"+          ]+      ]