summaryrefslogtreecommitdiff
path: root/Omni/Agent/Tools/Python.hs
blob: 99f3f7d2781326fe999d3af1f00c9c1bf08f9ca5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoImplicitPrelude #-}

-- | Python execution tool for agent use.
--
-- Executes Python snippets via subprocess with timeout support.
-- Writes code to temp file, executes with python3, cleans up after.
--
-- Available stdlib: requests, json, csv, re, datetime, urllib
--
-- : out omni-agent-tools-python
-- : dep aeson
-- : dep process
-- : dep directory
-- : dep temporary
module Omni.Agent.Tools.Python
  ( pythonExecTool,
    PythonExecArgs (..),
    PythonResult (..),
    main,
    test,
  )
where

import Alpha
import Data.Aeson ((.:), (.:?), (.=))
import qualified Data.Aeson as Aeson
import qualified Data.Text as Text
import qualified Data.Text.IO as TextIO
import qualified Omni.Agent.Engine as Engine
import qualified Omni.Test as Test
import qualified System.Directory as Directory
import qualified System.Exit as Exit
import qualified System.Process as Process
import System.Timeout (timeout)

main :: IO ()
main = Test.run test

test :: Test.Tree
test =
  Test.group
    "Omni.Agent.Tools.Python"
    [ Test.unit "pythonExecTool has correct name" <| do
        Engine.toolName pythonExecTool Test.@=? "python_exec",
      Test.unit "pythonExecTool schema is valid" <| do
        let schema = Engine.toolJsonSchema pythonExecTool
        case schema of
          Aeson.Object _ -> pure ()
          _ -> Test.assertFailure "Schema should be an object",
      Test.unit "PythonExecArgs parses correctly" <| do
        let json = Aeson.object ["code" .= ("print('hello')" :: Text)]
        case Aeson.fromJSON json of
          Aeson.Success (args :: PythonExecArgs) -> pythonCode args Test.@=? "print('hello')"
          Aeson.Error e -> Test.assertFailure e,
      Test.unit "PythonExecArgs parses with timeout" <| do
        let json = Aeson.object ["code" .= ("x = 1" :: Text), "timeout" .= (10 :: Int)]
        case Aeson.fromJSON json of
          Aeson.Success (args :: PythonExecArgs) -> do
            pythonCode args Test.@=? "x = 1"
            pythonTimeout args Test.@=? Just 10
          Aeson.Error e -> Test.assertFailure e,
      Test.unit "simple print statement" <| do
        let args = Aeson.object ["code" .= ("print('hello world')" :: Text)]
        result <- Engine.toolExecute pythonExecTool args
        case Aeson.fromJSON result of
          Aeson.Success (r :: PythonResult) -> do
            pythonResultExitCode r Test.@=? 0
            ("hello world" `Text.isInfixOf` pythonResultStdout r) Test.@=? True
          Aeson.Error e -> Test.assertFailure e,
      Test.unit "syntax error handling" <| do
        let args = Aeson.object ["code" .= ("def broken(" :: Text)]
        result <- Engine.toolExecute pythonExecTool args
        case Aeson.fromJSON result of
          Aeson.Success (r :: PythonResult) -> do
            (pythonResultExitCode r /= 0) Test.@=? True
            not (Text.null (pythonResultStderr r)) Test.@=? True
          Aeson.Error e -> Test.assertFailure e,
      Test.unit "import json works" <| do
        let code = "import json\nprint(json.dumps({'a': 1}))"
            args = Aeson.object ["code" .= (code :: Text)]
        result <- Engine.toolExecute pythonExecTool args
        case Aeson.fromJSON result of
          Aeson.Success (r :: PythonResult) -> do
            pythonResultExitCode r Test.@=? 0
            ("{\"a\": 1}" `Text.isInfixOf` pythonResultStdout r) Test.@=? True
          Aeson.Error e -> Test.assertFailure e,
      Test.unit "timeout handling" <| do
        let code = "import time\ntime.sleep(5)"
            args = Aeson.object ["code" .= (code :: Text), "timeout" .= (1 :: Int)]
        result <- Engine.toolExecute pythonExecTool args
        case Aeson.fromJSON result of
          Aeson.Success (r :: PythonResult) -> do
            pythonResultExitCode r Test.@=? (-1)
            ("timeout" `Text.isInfixOf` Text.toLower (pythonResultStderr r)) Test.@=? True
          Aeson.Error e -> Test.assertFailure e
    ]

data PythonExecArgs = PythonExecArgs
  { pythonCode :: Text,
    pythonTimeout :: Maybe Int
  }
  deriving (Show, Eq, Generic)

instance Aeson.FromJSON PythonExecArgs where
  parseJSON =
    Aeson.withObject "PythonExecArgs" <| \v ->
      (PythonExecArgs </ (v .: "code"))
        <*> (v .:? "timeout")

data PythonResult = PythonResult
  { pythonResultStdout :: Text,
    pythonResultStderr :: Text,
    pythonResultExitCode :: Int
  }
  deriving (Show, Eq, Generic)

instance Aeson.ToJSON PythonResult where
  toJSON r =
    Aeson.object
      [ "stdout" .= pythonResultStdout r,
        "stderr" .= pythonResultStderr r,
        "exit_code" .= pythonResultExitCode r
      ]

instance Aeson.FromJSON PythonResult where
  parseJSON =
    Aeson.withObject "PythonResult" <| \v ->
      (PythonResult </ (v .: "stdout"))
        <*> (v .: "stderr")
        <*> (v .: "exit_code")

pythonExecTool :: Engine.Tool
pythonExecTool =
  Engine.Tool
    { Engine.toolName = "python_exec",
      Engine.toolDescription =
        "Execute Python code and return the output. "
          <> "Use for data processing, API calls, calculations, or any task requiring Python. "
          <> "Available libraries: requests, json, csv, re, datetime, urllib. "
          <> "Code runs in a subprocess with a 30 second default timeout.",
      Engine.toolJsonSchema =
        Aeson.object
          [ "type" .= ("object" :: Text),
            "properties"
              .= Aeson.object
                [ "code"
                    .= Aeson.object
                      [ "type" .= ("string" :: Text),
                        "description" .= ("Python code to execute" :: Text)
                      ],
                  "timeout"
                    .= Aeson.object
                      [ "type" .= ("integer" :: Text),
                        "description" .= ("Timeout in seconds (default: 30)" :: Text)
                      ]
                ],
            "required" .= (["code"] :: [Text])
          ],
      Engine.toolExecute = executePythonExec
    }

executePythonExec :: Aeson.Value -> IO Aeson.Value
executePythonExec v =
  case Aeson.fromJSON v of
    Aeson.Error e -> pure <| mkError ("Invalid arguments: " <> Text.pack e)
    Aeson.Success args -> do
      let code = pythonCode args
          timeoutSecs = fromMaybe 30 (pythonTimeout args)
          timeoutMicros = timeoutSecs * 1000000
      tmpDir <- Directory.getTemporaryDirectory
      let tmpFile = tmpDir <> "/python_exec_" <> show (codeHash code) <> ".py"
      result <-
        try <| do
          TextIO.writeFile tmpFile code
          let proc = Process.proc "python3" [tmpFile]
          mResult <- timeout timeoutMicros <| Process.readCreateProcessWithExitCode proc ""
          Directory.removeFile tmpFile
          pure mResult
      case result of
        Left (e :: SomeException) -> do
          _ <- try @SomeException <| Directory.removeFile tmpFile
          pure <| mkError ("Execution failed: " <> tshow e)
        Right Nothing -> do
          _ <- try @SomeException <| Directory.removeFile tmpFile
          pure
            <| Aeson.toJSON
            <| PythonResult
              { pythonResultStdout = "",
                pythonResultStderr = "Timeout: execution exceeded " <> tshow timeoutSecs <> " seconds",
                pythonResultExitCode = -1
              }
        Right (Just (exitCode, stdoutStr, stderrStr)) ->
          pure
            <| Aeson.toJSON
            <| PythonResult
              { pythonResultStdout = Text.pack stdoutStr,
                pythonResultStderr = Text.pack stderrStr,
                pythonResultExitCode = exitCodeToInt exitCode
              }

exitCodeToInt :: Exit.ExitCode -> Int
exitCodeToInt Exit.ExitSuccess = 0
exitCodeToInt (Exit.ExitFailure n) = n

mkError :: Text -> Aeson.Value
mkError err =
  Aeson.toJSON
    <| PythonResult
      { pythonResultStdout = "",
        pythonResultStderr = err,
        pythonResultExitCode = -1
      }

codeHash :: Text -> Int
codeHash = Text.foldl' (\h c -> 31 * h + fromEnum c) 0