Skip to content

Commit b1ebcff

Browse files
committed
not in book: trying Alexander Thiemann's library for OpenAI
1 parent 3d63525 commit b1ebcff

File tree

4 files changed

+75
-0
lines changed

4 files changed

+75
-0
lines changed

OpenAiApiClient/GenText.hs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
-- Example from https://github.com/agrafix/openai-hs/tree/main/openai-hs
2+
-- code by Alexander Thiemann
3+
4+
{-# LANGUAGE OverloadedStrings #-}
5+
import OpenAI.Client
6+
7+
import Network.HTTP.Client
8+
import Network.HTTP.Client.TLS
9+
import System.Environment (getEnv)
10+
import qualified Data.Text as T
11+
12+
request :: ChatCompletionRequest
13+
request = ChatCompletionRequest
14+
{ chcrModel = ModelId "gpt-3.5-turbo"
15+
, chcrMessages =
16+
[ChatMessage { chmContent = "Write a hello world program in Haskell"
17+
, chmRole = "user"
18+
}
19+
]
20+
, chcrTemperature = Nothing
21+
, chcrTopP = Nothing
22+
, chcrN = Nothing
23+
, chcrStream = Nothing
24+
, chcrStop = Nothing
25+
, chcrMaxTokens = Nothing
26+
, chcrPresencePenalty = Nothing
27+
, chcrFrequencyPenalty = Nothing
28+
, chcrLogitBias = Nothing
29+
, chcrUser = Nothing
30+
}
31+
32+
main :: IO ()
33+
main =
34+
do manager <- newManager tlsManagerSettings
35+
apiKey <- T.pack <$> getEnv "OPENAI_KEY"
36+
-- create a openai client that automatically retries up to 4 times on network
37+
-- errors
38+
let client = makeOpenAIClient apiKey manager 4
39+
result <- completeChat client request
40+
case result of
41+
Left failure -> print failure
42+
Right success -> print $ chrChoices success

OpenAiApiClient/OpenAiApiClient.cabal

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
name: OpenAiApiClient
2+
version: 0.1.0.0
3+
synopsis: Simple project template from stack
4+
description: Please see README.md
5+
homepage: https://github.com/mark-watson/haskell_tutorial_cookbook_examples
6+
license: Apache-2.0
7+
license-file: ../APACHE_LICENSE-2.0.txt
8+
author: Mark watson
9+
copyright: 2023 Mark Watson
10+
category: Web
11+
build-type: Simple
12+
cabal-version: >=1.10
13+
14+
executable GenText
15+
hs-source-dirs: .
16+
main-is: GenText.hs
17+
default-language: Haskell2010
18+
build-depends: base >= 4.7 && < 5, mtl >= 2.2.2, text
19+

OpenAiApiClient/README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# OpenAI APIs
2+
3+
I am using the library written by Alexander Thiemann at:
4+
5+
https://github.com/agrafix/openai-hs/tree/main/openai-hs

OpenAiApiClient/stack.yaml

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
resolver: lts-21.4
2+
3+
# flags:
4+
extra-package-dbs: []
5+
packages:
6+
- '.'
7+
extra-deps:
8+
- openai-hs
9+

0 commit comments

Comments
 (0)