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.

chatglm.go 1.8 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. "time"
  21. "github.com/leverly/ChatGLM/client"
  22. )
  23. type ChatGLMModelProvider struct {
  24. subType string
  25. clientSecret string
  26. }
  27. func NewChatGLMModelProvider(subType string, clientSecret string) (*ChatGLMModelProvider, error) {
  28. return &ChatGLMModelProvider{subType: subType, clientSecret: clientSecret}, nil
  29. }
  30. func (p *ChatGLMModelProvider) QueryText(question string, writer io.Writer, builder *strings.Builder) error {
  31. proxy := client.NewChatGLMClient(p.clientSecret, 30*time.Second)
  32. prompt := []client.Message{{Role: "user", Content: question}}
  33. taskId, err := proxy.AsyncInvoke(p.subType, 0.2, prompt)
  34. if err != nil {
  35. return err
  36. }
  37. flusher, ok := writer.(http.Flusher)
  38. if !ok {
  39. return fmt.Errorf("writer does not implement http.Flusher")
  40. }
  41. flushData := func(data string) error {
  42. if _, err := fmt.Fprintf(writer, "event: message\ndata: %s\n\n", data); err != nil {
  43. return err
  44. }
  45. flusher.Flush()
  46. builder.WriteString(data)
  47. return nil
  48. }
  49. response, err := proxy.AsyncInvokeTask(p.subType, taskId)
  50. if err != nil {
  51. return err
  52. }
  53. content := (*response.Choices)[0].Content
  54. err = flushData(content)
  55. if err != nil {
  56. return err
  57. }
  58. return nil
  59. }