ticket.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package ticket
  2. import (
  3. _ "embed"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/google/uuid"
  7. "github.com/sashabaranov/go-openai"
  8. "google.golang.org/protobuf/encoding/protojson"
  9. "time"
  10. )
  11. func (t *Ticket) Marshal() ([]byte, error) {
  12. return protojson.Marshal(t)
  13. }
  14. func (t *Ticket) AddMessage(m *Message) error {
  15. if m == nil {
  16. return fmt.Errorf("illegal argument: Message must not be a nil")
  17. }
  18. if m.TicketId == "" {
  19. m.TicketId = t.Id
  20. }
  21. if m.Id == "" {
  22. m.Id = uuid.NewString()
  23. }
  24. if m.Date == 0 {
  25. m.Date = time.Now().UnixMilli()
  26. }
  27. t.Thread = append(t.Thread, m)
  28. return nil
  29. }
  30. func (t *Ticket) AddGPTResponseMessage(src *openai.ChatCompletionChoice) (*Message, error) {
  31. var (
  32. message = &Message{
  33. Id: uuid.NewString(),
  34. TicketId: t.Id,
  35. Provider: MessageProvider_GptMessageProvider,
  36. Body: src.Message.Content,
  37. Date: time.Now().UnixMilli(),
  38. }
  39. buf []byte
  40. err error
  41. )
  42. if buf, err = json.Marshal(src.Message); err != nil {
  43. return nil, err
  44. }
  45. message.Raw = string(buf)
  46. if err = t.AddMessage(message); err != nil {
  47. return nil, err
  48. }
  49. return message, nil
  50. }
  51. //goland:noinspection GoUnusedExportedFunction
  52. func Unmarshal(d []byte) (*Ticket, error) {
  53. t := &Ticket{}
  54. if err := protojson.Unmarshal(d, t); err != nil {
  55. return nil, err
  56. }
  57. return t, nil
  58. }