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

ai.go 3.8 kB

2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. // Copyright 2023 The casbin Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package ai
  15. import (
  16. "context"
  17. "fmt"
  18. "io"
  19. "net/http"
  20. "strings"
  21. "time"
  22. "github.com/sashabaranov/go-openai"
  23. )
  24. func queryAnswer(authToken string, question string, timeout int) (string, error) {
  25. // fmt.Printf("Question: %s\n", question)
  26. client := getProxyClientFromToken(authToken)
  27. ctx, cancel := context.WithTimeout(context.Background(), time.Duration(2+timeout*2)*time.Second)
  28. defer cancel()
  29. resp, err := client.CreateChatCompletion(
  30. ctx,
  31. openai.ChatCompletionRequest{
  32. Model: openai.GPT3Dot5Turbo,
  33. Messages: []openai.ChatCompletionMessage{
  34. {
  35. Role: openai.ChatMessageRoleUser,
  36. Content: question,
  37. },
  38. },
  39. },
  40. )
  41. if err != nil {
  42. return "", err
  43. }
  44. res := resp.Choices[0].Message.Content
  45. res = strings.Trim(res, "\n")
  46. // fmt.Printf("Answer: %s\n\n", res)
  47. return res, nil
  48. }
  49. func QueryAnswerSafe(authToken string, question string) string {
  50. var res string
  51. var err error
  52. for i := 0; i < 10; i++ {
  53. res, err = queryAnswer(authToken, question, i)
  54. if err != nil {
  55. if i > 0 {
  56. fmt.Printf("\tFailed (%d): %s\n", i+1, err.Error())
  57. }
  58. } else {
  59. break
  60. }
  61. }
  62. if err != nil {
  63. panic(err)
  64. }
  65. return res
  66. }
  67. func QueryAnswerStream(authToken string, question string, writer io.Writer, builder *strings.Builder) error {
  68. client := getProxyClientFromToken(authToken)
  69. ctx := context.Background()
  70. flusher, ok := writer.(http.Flusher)
  71. if !ok {
  72. return fmt.Errorf("writer does not implement http.Flusher")
  73. }
  74. // https://platform.openai.com/tokenizer
  75. // https://github.com/pkoukk/tiktoken-go#available-encodings
  76. promptTokens, err := GetTokenSize(openai.GPT3TextDavinci003, question)
  77. if err != nil {
  78. return err
  79. }
  80. // https://platform.openai.com/docs/models/gpt-3-5
  81. maxTokens := 4097 - promptTokens
  82. respStream, err := client.CreateCompletionStream(
  83. ctx,
  84. openai.CompletionRequest{
  85. Model: openai.GPT3TextDavinci003,
  86. Prompt: question,
  87. MaxTokens: maxTokens,
  88. Stream: true,
  89. },
  90. )
  91. if err != nil {
  92. return err
  93. }
  94. defer respStream.Close()
  95. isLeadingReturn := true
  96. for {
  97. completion, streamErr := respStream.Recv()
  98. if streamErr != nil {
  99. if streamErr == io.EOF {
  100. break
  101. }
  102. return streamErr
  103. }
  104. data := completion.Choices[0].Text
  105. if isLeadingReturn && len(data) != 0 {
  106. if strings.Count(data, "\n") == len(data) {
  107. continue
  108. } else {
  109. isLeadingReturn = false
  110. }
  111. }
  112. fmt.Printf("%s", data)
  113. // Write the streamed data as Server-Sent Events
  114. if _, err = fmt.Fprintf(writer, "event: message\ndata: %s\n\n", data); err != nil {
  115. return err
  116. }
  117. flusher.Flush()
  118. // Append the response to the strings.Builder
  119. builder.WriteString(data)
  120. }
  121. return nil
  122. }
  123. func GetQuestionWithKnowledge(knowledge string, question string) string {
  124. return fmt.Sprintf(`paragraph: %s
  125. You are a reading comprehension expert. Please answer the following questions based on the provided content. The content may be in a different language from the questions, so you need to understand the content according to the language of the questions and ensure that your answers are translated into the same language as the questions:
  126. Q1: %s`, knowledge, question)
  127. }