|
| 1 | +{-# LANGUAGE DuplicateRecordFields #-} |
| 2 | +{-# LANGUAGE OverloadedRecordDot #-} |
| 3 | + |
| 4 | +import Control.Monad.IO.Class (liftIO) |
| 5 | +import System.Environment (getArgs) |
| 6 | +import qualified Data.Aeson as Aeson |
| 7 | +import Data.Aeson (FromJSON, ToJSON) |
| 8 | +import GHC.Generics |
| 9 | +import Network.HTTP.Client (newManager, httpLbs, parseRequest, Request(..), RequestBody(..), responseBody, responseStatus, defaultManagerSettings) |
| 10 | +import Network.HTTP.Types.Status (statusCode) |
| 11 | +--import qualified Data.Text as T |
| 12 | +--import Data.Text.Encoding (encodeUtf8) |
| 13 | + |
| 14 | +data OllamaRequest = OllamaRequest |
| 15 | + { model :: String |
| 16 | + , prompt :: String |
| 17 | + , stream :: Bool |
| 18 | + } deriving (Show, Generic, ToJSON) |
| 19 | + |
| 20 | +data OllamaResponse = OllamaResponse |
| 21 | + { model :: String |
| 22 | + , created_at :: String |
| 23 | + , response :: String -- This matches the actual field name in the JSON |
| 24 | + , done :: Bool |
| 25 | + , done_reason :: String |
| 26 | + } deriving (Show, Generic, FromJSON) |
| 27 | + |
| 28 | +main :: IO () |
| 29 | +main = do |
| 30 | + args <- getArgs |
| 31 | + case args of |
| 32 | + [] -> putStrLn "Error: Please provide a prompt as a command-line argument." |
| 33 | + (arg:_) -> do |
| 34 | + manager <- newManager defaultManagerSettings |
| 35 | + |
| 36 | + initialRequest <- parseRequest "http://localhost:11434/api/generate" |
| 37 | + |
| 38 | + let ollamaRequestBody = OllamaRequest |
| 39 | + { model = "llama3.2:latest" -- You can change this to your preferred model |
| 40 | + , prompt = arg |
| 41 | + , stream = False |
| 42 | + } |
| 43 | + |
| 44 | + let request = initialRequest |
| 45 | + { requestHeaders = [("Content-Type", "application/json")] |
| 46 | + , method = "POST" |
| 47 | + , requestBody = RequestBodyLBS $ Aeson.encode ollamaRequestBody |
| 48 | + } |
| 49 | + |
| 50 | + httpResponse <- httpLbs request manager |
| 51 | +-- liftIO $ putStrLn $ "httpResponse:" ++ show httpResponse -- debug |
| 52 | + |
| 53 | + let responseStatus' = responseStatus httpResponse |
| 54 | + |
| 55 | + if statusCode responseStatus' == 200 |
| 56 | + then do |
| 57 | + let maybeOllamaResponse = |
| 58 | + Aeson.decode (responseBody httpResponse) :: Maybe OllamaResponse |
| 59 | + case maybeOllamaResponse of |
| 60 | + Just ollamaResponse -> do |
| 61 | + liftIO $ putStrLn $ "Response:\n\n" ++ ollamaResponse.response |
| 62 | + Nothing -> do |
| 63 | + liftIO $ putStrLn "Error: Failed to parse response" |
| 64 | + else do |
| 65 | + putStrLn $ "Error: " ++ show responseStatus' |
0 commit comments