1
- -- Example from https://github.com/agrafix/openai-hs/tree/main/openai-hs
2
- -- code by Alexander Thiemann
3
-
4
1
{-# LANGUAGE OverloadedStrings #-}
5
2
import OpenAI.Client
6
3
7
4
import Network.HTTP.Client
8
-
9
5
import Network.HTTP.Client.TLS
10
6
import System.Environment (getEnv )
11
7
import qualified Data.Text as T
12
8
import Data.Maybe (fromMaybe )
13
9
14
- request :: ChatCompletionRequest
15
- request = ChatCompletionRequest
16
- { chcrModel = ModelId " gpt-4o"
17
- , chcrMessages =
18
- [ChatMessage { chmContent = Just " Write a hello world program in Haskell"
19
- , chmRole = " user"
20
- , chmFunctionCall = Nothing
21
- , chmName = Nothing
22
- }
23
- ]
24
- , chcrFunctions = Nothing
25
- , chcrTemperature = Nothing
26
- , chcrTopP = Nothing
27
- , chcrN = Nothing
28
- , chcrStream = Nothing
29
- , chcrStop = Nothing
30
- , chcrMaxTokens = Nothing
31
- , chcrPresencePenalty = Nothing
32
- , chcrFrequencyPenalty = Nothing
33
- , chcrLogitBias = Nothing
34
- , chcrUser = Nothing
35
- }
10
+ completionRequestToString :: String -> IO String
11
+ completionRequestToString prompt = do
12
+ manager <- newManager tlsManagerSettings
13
+ apiKey <- T. pack <$> getEnv " OPENAI_KEY"
14
+ let client = makeOpenAIClient apiKey manager 4
15
+ let request = ChatCompletionRequest
16
+ { chcrModel = ModelId " gpt-4o"
17
+ , chcrMessages =
18
+ [ ChatMessage
19
+ { chmContent = Just (T. pack prompt)
20
+ , chmRole = " user"
21
+ , chmFunctionCall = Nothing
22
+ , chmName = Nothing
23
+ }
24
+ ]
25
+ , chcrFunctions = Nothing
26
+ , chcrTemperature = Nothing
27
+ , chcrTopP = Nothing
28
+ , chcrN = Nothing
29
+ , chcrStream = Nothing
30
+ , chcrStop = Nothing
31
+ , chcrMaxTokens = Nothing
32
+ , chcrPresencePenalty = Nothing
33
+ , chcrFrequencyPenalty = Nothing
34
+ , chcrLogitBias = Nothing
35
+ , chcrUser = Nothing
36
+ }
37
+ result <- completeChat client request
38
+ case result of
39
+ Left failure -> return (show failure)
40
+ Right success ->
41
+ case chrChoices success of
42
+ (ChatChoice {chchMessage = ChatMessage {chmContent = content}} : _) ->
43
+ return $ fromMaybe " No content" $ T. unpack <$> content
44
+ _ -> return " No choices returned"
36
45
37
46
main :: IO ()
38
47
main = do
39
- manager <- newManager tlsManagerSettings
40
- apiKey <- T. pack <$> (getEnv " OPENAI_KEY" )
41
- -- create a openai client that automatically retries up to 4 times on network
42
- -- errors
43
- let client = makeOpenAIClient apiKey manager 4
44
- result <- completeChat client request
45
- case result of
46
- Left failure -> print failure
47
- Right success -> -- print $ chrChoices success
48
- case chrChoices success of
49
- (ChatChoice {chchMessage = ChatMessage {chmContent = content}}: _) ->
50
- putStrLn $ fromMaybe " No content" $ T. unpack <$> content
51
- _ -> putStrLn " No choices returned"
48
+ response <- completionRequestToString " Write a hello world program in Haskell"
49
+ putStrLn response
0 commit comments