go-chatgpt
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 6.2 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. # Go OpenAI
  2. [![GoDoc](http://img.shields.io/badge/GoDoc-Reference-blue.svg)](https://godoc.org/github.com/sashabaranov/go-gogpt)
  3. [![Go Report Card](https://goreportcard.com/badge/github.com/sashabaranov/go-gogpt)](https://goreportcard.com/report/github.com/sashabaranov/go-gogpt)
  4. [![codecov](https://codecov.io/gh/sashabaranov/go-gogpt/branch/master/graph/badge.svg?token=bCbIfHLIsW)](https://codecov.io/gh/sashabaranov/go-gogpt)
  5. > **Note**: the repository was recently renamed from `go-gpt3` to `go-gogpt`
  6. This library provides Go clients for [OpenAI API](https://platform.gogpt.com/). We support:
  7. * ChatGPT
  8. * GPT-3, GPT-4
  9. * DALL·E 2
  10. * Whisper
  11. Installation:
  12. ```
  13. go get github.com/sashabaranov/go-gogpt
  14. ```
  15. ChatGPT example usage:
  16. ```go
  17. package main
  18. import (
  19. "context"
  20. "fmt"
  21. gogpt "github.com/sashabaranov/go-gogpt"
  22. )
  23. func main() {
  24. client := gogpt.NewClient("your token")
  25. resp, err := client.CreateChatCompletion(
  26. context.Background(),
  27. gogpt.ChatCompletionRequest{
  28. Model: gogpt.GPT3Dot5Turbo,
  29. Messages: []gogpt.ChatCompletionMessage{
  30. {
  31. Role: gogpt.ChatMessageRoleUser,
  32. Content: "Hello!",
  33. },
  34. },
  35. },
  36. )
  37. if err != nil {
  38. fmt.Printf("ChatCompletion error: %v\n", err)
  39. return
  40. }
  41. fmt.Println(resp.Choices[0].Message.Content)
  42. }
  43. ```
  44. Other examples:
  45. <details>
  46. <summary>GPT-3 completion</summary>
  47. ```go
  48. package main
  49. import (
  50. "context"
  51. "fmt"
  52. gogpt "github.com/sashabaranov/go-gogpt"
  53. )
  54. func main() {
  55. c := gogpt.NewClient("your token")
  56. ctx := context.Background()
  57. req := gogpt.CompletionRequest{
  58. Model: gogpt.GPT3Ada,
  59. MaxTokens: 5,
  60. Prompt: "Lorem ipsum",
  61. }
  62. resp, err := c.CreateCompletion(ctx, req)
  63. if err != nil {
  64. fmt.Printf("Completion error: %v\n", err)
  65. return
  66. }
  67. fmt.Println(resp.Choices[0].Text)
  68. }
  69. ```
  70. </details>
  71. <details>
  72. <summary>GPT-3 streaming completion</summary>
  73. ```go
  74. package main
  75. import (
  76. "errors"
  77. "context"
  78. "fmt"
  79. "io"
  80. gogpt "github.com/sashabaranov/go-gogpt"
  81. )
  82. func main() {
  83. c := gogpt.NewClient("your token")
  84. ctx := context.Background()
  85. req := gogpt.CompletionRequest{
  86. Model: gogpt.GPT3Ada,
  87. MaxTokens: 5,
  88. Prompt: "Lorem ipsum",
  89. Stream: true,
  90. }
  91. stream, err := c.CreateCompletionStream(ctx, req)
  92. if err != nil {
  93. fmt.Printf("CompletionStream error: %v\n", err)
  94. return
  95. }
  96. defer stream.Close()
  97. for {
  98. response, err := stream.Recv()
  99. if errors.Is(err, io.EOF) {
  100. fmt.Println("Stream finished")
  101. return
  102. }
  103. if err != nil {
  104. fmt.Printf("Stream error: %v\n", err)
  105. return
  106. }
  107. fmt.Printf("Stream response: %v\n", response)
  108. }
  109. }
  110. ```
  111. </details>
  112. <details>
  113. <summary>Audio Speech-To-Text</summary>
  114. ```go
  115. package main
  116. import (
  117. "context"
  118. "fmt"
  119. gogpt "github.com/sashabaranov/go-gogpt"
  120. )
  121. func main() {
  122. c := gogpt.NewClient("your token")
  123. ctx := context.Background()
  124. req := gogpt.AudioRequest{
  125. Model: gogpt.Whisper1,
  126. FilePath: "recording.mp3",
  127. }
  128. resp, err := c.CreateTranscription(ctx, req)
  129. if err != nil {
  130. fmt.Printf("Transcription error: %v\n", err)
  131. return
  132. }
  133. fmt.Println(resp.Text)
  134. }
  135. ```
  136. </details>
  137. <details>
  138. <summary>DALL-E 2 image generation</summary>
  139. ```go
  140. package main
  141. import (
  142. "bytes"
  143. "context"
  144. "encoding/base64"
  145. "fmt"
  146. gogpt "github.com/sashabaranov/go-gogpt"
  147. "image/png"
  148. "os"
  149. )
  150. func main() {
  151. c := gogpt.NewClient("your token")
  152. ctx := context.Background()
  153. // Sample image by link
  154. reqUrl := gogpt.ImageRequest{
  155. Prompt: "Parrot on a skateboard performs a trick, cartoon style, natural light, high detail",
  156. Size: gogpt.CreateImageSize256x256,
  157. ResponseFormat: gogpt.CreateImageResponseFormatURL,
  158. N: 1,
  159. }
  160. respUrl, err := c.CreateImage(ctx, reqUrl)
  161. if err != nil {
  162. fmt.Printf("Image creation error: %v\n", err)
  163. return
  164. }
  165. fmt.Println(respUrl.Data[0].URL)
  166. // Example image as base64
  167. reqBase64 := gogpt.ImageRequest{
  168. Prompt: "Portrait of a humanoid parrot in a classic costume, high detail, realistic light, unreal engine",
  169. Size: gogpt.CreateImageSize256x256,
  170. ResponseFormat: gogpt.CreateImageResponseFormatB64JSON,
  171. N: 1,
  172. }
  173. respBase64, err := c.CreateImage(ctx, reqBase64)
  174. if err != nil {
  175. fmt.Printf("Image creation error: %v\n", err)
  176. return
  177. }
  178. imgBytes, err := base64.StdEncoding.DecodeString(respBase64.Data[0].B64JSON)
  179. if err != nil {
  180. fmt.Printf("Base64 decode error: %v\n", err)
  181. return
  182. }
  183. r := bytes.NewReader(imgBytes)
  184. imgData, err := png.Decode(r)
  185. if err != nil {
  186. fmt.Printf("PNG decode error: %v\n", err)
  187. return
  188. }
  189. file, err := os.Create("image.png")
  190. if err != nil {
  191. fmt.Printf("File creation error: %v\n", err)
  192. return
  193. }
  194. defer file.Close()
  195. if err := png.Encode(file, imgData); err != nil {
  196. fmt.Printf("PNG encode error: %v\n", err)
  197. return
  198. }
  199. fmt.Println("The image was saved as example.png")
  200. }
  201. ```
  202. </details>
  203. <details>
  204. <summary>Configuring proxy</summary>
  205. ```go
  206. config := gogpt.DefaultConfig("token")
  207. proxyUrl, err := url.Parse("http://localhost:{port}")
  208. if err != nil {
  209. panic(err)
  210. }
  211. transport := &http.Transport{
  212. Proxy: http.ProxyURL(proxyUrl),
  213. }
  214. config.HTTPClient = &http.Client{
  215. Transport: transport,
  216. }
  217. c := gogpt.NewClientWithConfig(config)
  218. ```
  219. See also: https://pkg.go.dev/github.com/sashabaranov/go-gogpt#ClientConfig
  220. </details>
  221. <details>
  222. <summary>ChatGPT support context</summary>
  223. ```go
  224. package main
  225. import (
  226. "bufio"
  227. "context"
  228. "fmt"
  229. "os"
  230. "strings"
  231. "github.com/sashabaranov/go-gogpt"
  232. )
  233. func main() {
  234. client := gogpt.NewClient("your token")
  235. messages := make([]gogpt.ChatCompletionMessage, 0)
  236. reader := bufio.NewReader(os.Stdin)
  237. fmt.Println("Conversation")
  238. fmt.Println("---------------------")
  239. for {
  240. fmt.Print("-> ")
  241. text, _ := reader.ReadString('\n')
  242. // convert CRLF to LF
  243. text = strings.Replace(text, "\n", "", -1)
  244. messages = append(messages, gogpt.ChatCompletionMessage{
  245. Role: gogpt.ChatMessageRoleUser,
  246. Content: text,
  247. })
  248. resp, err := client.CreateChatCompletion(
  249. context.Background(),
  250. gogpt.ChatCompletionRequest{
  251. Model: gogpt.GPT3Dot5Turbo,
  252. Messages: messages,
  253. },
  254. )
  255. if err != nil {
  256. fmt.Printf("ChatCompletion error: %v\n", err)
  257. continue
  258. }
  259. content := resp.Choices[0].Message.Content
  260. messages = append(messages, gogpt.ChatCompletionMessage{
  261. Role: gogpt.ChatMessageRoleAssistant,
  262. Content: content,
  263. })
  264. fmt.Println(content)
  265. }
  266. }
  267. ```
  268. </details>