ticket.go 1.2 KB

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