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.

query.go 1.8 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 model
  15. import (
  16. "context"
  17. "fmt"
  18. "strings"
  19. "time"
  20. "github.com/sashabaranov/go-openai"
  21. )
  22. func queryAnswer(authToken string, question string, timeout int) (string, error) {
  23. // fmt.Printf("Question: %s\n", question)
  24. client := getProxyClientFromToken(authToken)
  25. ctx, cancel := context.WithTimeout(context.Background(), time.Duration(2+timeout*2)*time.Second)
  26. defer cancel()
  27. resp, err := client.CreateChatCompletion(
  28. ctx,
  29. openai.ChatCompletionRequest{
  30. Model: openai.GPT3Dot5Turbo,
  31. Messages: []openai.ChatCompletionMessage{
  32. {
  33. Role: openai.ChatMessageRoleUser,
  34. Content: question,
  35. },
  36. },
  37. },
  38. )
  39. if err != nil {
  40. return "", err
  41. }
  42. res := resp.Choices[0].Message.Content
  43. res = strings.Trim(res, "\n")
  44. // fmt.Printf("Answer: %s\n\n", res)
  45. return res, nil
  46. }
  47. func QueryAnswerSafe(authToken string, question string) string {
  48. var res string
  49. var err error
  50. for i := 0; i < 10; i++ {
  51. res, err = queryAnswer(authToken, question, i)
  52. if err != nil {
  53. if i > 0 {
  54. fmt.Printf("\tFailed (%d): %s\n", i+1, err.Error())
  55. }
  56. } else {
  57. break
  58. }
  59. }
  60. if err != nil {
  61. panic(err)
  62. }
  63. return res
  64. }