openai.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. package openai
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "fmt"
  6. "github.com/0xJacky/Nginx-UI/api"
  7. "github.com/0xJacky/Nginx-UI/settings"
  8. "github.com/gin-gonic/gin"
  9. "github.com/pkg/errors"
  10. "github.com/sashabaranov/go-openai"
  11. "io"
  12. "net/http"
  13. "net/url"
  14. "os"
  15. )
  16. const ChatGPTInitPrompt = "You are a assistant who can help users write and optimise the configurations of Nginx, the first user message contains the content of the configuration file which is currently opened by the user and the current language code(CLC). You suppose to use the language corresponding to the CLC to give the first reply. Later the language environment depends on the user message. The first reply should involve the key information of the file and ask user what can you help them."
  17. func MakeChatCompletionRequest(c *gin.Context) {
  18. var json struct {
  19. Messages []openai.ChatCompletionMessage `json:"messages"`
  20. }
  21. if !api.BindAndValid(c, &json) {
  22. return
  23. }
  24. messages := []openai.ChatCompletionMessage{
  25. {
  26. Role: openai.ChatMessageRoleSystem,
  27. Content: ChatGPTInitPrompt,
  28. },
  29. }
  30. messages = append(messages, json.Messages...)
  31. // sse server
  32. c.Writer.Header().Set("Content-Type", "text/event-stream; charset=utf-8")
  33. c.Writer.Header().Set("Cache-Control", "no-cache")
  34. c.Writer.Header().Set("Connection", "keep-alive")
  35. c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
  36. config := openai.DefaultConfig(settings.OpenAISettings.Token)
  37. if settings.OpenAISettings.Proxy != "" {
  38. proxyUrl, err := url.Parse(settings.OpenAISettings.Proxy)
  39. if err != nil {
  40. c.Stream(func(w io.Writer) bool {
  41. c.SSEvent("message", gin.H{
  42. "type": "error",
  43. "content": err.Error(),
  44. })
  45. return false
  46. })
  47. return
  48. }
  49. transport := &http.Transport{
  50. Proxy: http.ProxyURL(proxyUrl),
  51. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  52. }
  53. config.HTTPClient = &http.Client{
  54. Transport: transport,
  55. }
  56. }
  57. if settings.OpenAISettings.BaseUrl != "" {
  58. config.BaseURL = settings.OpenAISettings.BaseUrl
  59. }
  60. openaiClient := openai.NewClientWithConfig(config)
  61. ctx := context.Background()
  62. req := openai.ChatCompletionRequest{
  63. Model: settings.OpenAISettings.Model,
  64. Messages: messages,
  65. Stream: true,
  66. }
  67. stream, err := openaiClient.CreateChatCompletionStream(ctx, req)
  68. if err != nil {
  69. fmt.Printf("CompletionStream error: %v\n", err)
  70. c.Stream(func(w io.Writer) bool {
  71. c.SSEvent("message", gin.H{
  72. "type": "error",
  73. "content": err.Error(),
  74. })
  75. return false
  76. })
  77. return
  78. }
  79. defer stream.Close()
  80. msgChan := make(chan string)
  81. go func() {
  82. defer close(msgChan)
  83. for {
  84. response, err := stream.Recv()
  85. if errors.Is(err, io.EOF) {
  86. fmt.Println()
  87. return
  88. }
  89. if err != nil {
  90. fmt.Printf("Stream error: %v\n", err)
  91. return
  92. }
  93. message := fmt.Sprintf("%s", response.Choices[0].Delta.Content)
  94. fmt.Printf("%s", message)
  95. _ = os.Stdout.Sync()
  96. msgChan <- message
  97. }
  98. }()
  99. c.Stream(func(w io.Writer) bool {
  100. if m, ok := <-msgChan; ok {
  101. c.SSEvent("message", gin.H{
  102. "type": "message",
  103. "content": m,
  104. })
  105. return true
  106. }
  107. return false
  108. })
  109. }