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.

iflytek.go 2.2 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. "fmt"
  17. "io"
  18. "net/http"
  19. "strings"
  20. iflytek "github.com/vogo/xfspark/chat"
  21. )
  22. type iFlytekModelProvider struct {
  23. subType string
  24. appID string
  25. apiKey string
  26. secretKey string
  27. temperature string
  28. topK int
  29. }
  30. func NewiFlytekModelProvider(subType string, secretKey string, temperature float32, topK int) (*iFlytekModelProvider, error) {
  31. p := &iFlytekModelProvider{
  32. subType: subType,
  33. appID: "",
  34. apiKey: "",
  35. secretKey: secretKey,
  36. temperature: fmt.Sprintf("%f", temperature),
  37. topK: topK,
  38. }
  39. return p, nil
  40. }
  41. func (p *iFlytekModelProvider) QueryText(question string, writer io.Writer, builder *strings.Builder) error {
  42. client := iflytek.NewServer(p.appID, p.apiKey, p.secretKey)
  43. flusher, ok := writer.(http.Flusher)
  44. if !ok {
  45. return fmt.Errorf("writer does not implement http.Flusher")
  46. }
  47. session, err := client.GetSession("1")
  48. if err != nil {
  49. return fmt.Errorf("iflytek get session error: %v", err)
  50. }
  51. if session == nil {
  52. return fmt.Errorf("iflytek get session error: session is nil")
  53. }
  54. session.Req.Parameter.Chat.Temperature = p.temperature
  55. session.Req.Parameter.Chat.TopK = p.topK
  56. response, err := session.Send(question)
  57. if err != nil {
  58. return fmt.Errorf("iflytek send error: %v", err)
  59. }
  60. flushData := func(data string) error {
  61. if _, err := fmt.Fprintf(writer, "event: message\ndata: %s\n\n", data); err != nil {
  62. return err
  63. }
  64. flusher.Flush()
  65. builder.WriteString(data)
  66. return nil
  67. }
  68. err = flushData(response)
  69. if err != nil {
  70. return err
  71. }
  72. return nil
  73. }