never executed always true always false
1 module PureClaw.Tools.Registry
2 ( -- * Tool execution
3 ToolHandler (..)
4 , ToolRegistry
5 -- * Registry operations
6 , emptyRegistry
7 , registerTool
8 , registryDefinitions
9 , executeTool
10 ) where
11
12 import Data.Aeson (Value)
13 import Data.Map.Strict (Map)
14 import Data.Map.Strict qualified as Map
15 import Data.Text (Text)
16
17 import PureClaw.Providers.Class
18
19 -- | A tool handler: given JSON input, produce a text result.
20 -- The Bool in the result indicates whether the result is an error.
21 newtype ToolHandler = ToolHandler
22 { runTool :: Value -> IO (Text, Bool)
23 }
24
25 -- | Registry of available tools. Maps tool names to their definitions
26 -- and handlers.
27 newtype ToolRegistry = ToolRegistry
28 { _tr_tools :: Map Text (ToolDefinition, ToolHandler)
29 }
30
31 -- | Empty registry with no tools.
32 emptyRegistry :: ToolRegistry
33 emptyRegistry = ToolRegistry Map.empty
34
35 -- | Register a tool with its definition and handler.
36 registerTool :: ToolDefinition -> ToolHandler -> ToolRegistry -> ToolRegistry
37 registerTool def handler reg = reg
38 { _tr_tools = Map.insert (_td_name def) (def, handler) (_tr_tools reg)
39 }
40
41 -- | Get all tool definitions for sending to the provider.
42 registryDefinitions :: ToolRegistry -> [ToolDefinition]
43 registryDefinitions = map fst . Map.elems . _tr_tools
44
45 -- | Execute a tool by name. Returns Nothing if the tool is not found.
46 executeTool :: ToolRegistry -> Text -> Value -> IO (Maybe (Text, Bool))
47 executeTool reg name input =
48 case Map.lookup name (_tr_tools reg) of
49 Nothing -> pure Nothing
50 Just (_, handler) -> Just <$> runTool handler input