1
0

openai.go 2.7 KB

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