distributor_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package middleware_test
  2. import (
  3. "encoding/json"
  4. "strings"
  5. "testing"
  6. jsoniter "github.com/json-iterator/go"
  7. "github.com/labring/aiproxy/core/middleware"
  8. )
  9. type ModelRequest struct {
  10. Model string `json:"model" form:"model"`
  11. }
  12. func StdGetModelFromJSON(body []byte) (string, error) {
  13. var modelRequest ModelRequest
  14. err := json.Unmarshal(body, &modelRequest)
  15. if err != nil {
  16. return "", err
  17. }
  18. return modelRequest.Model, nil
  19. }
  20. func JSONIterGetModelFromJSON(body []byte) (string, error) {
  21. return jsoniter.Get(body, "model").ToString(), nil
  22. }
  23. func BenchmarkCompareGetModelFromJSON(b *testing.B) {
  24. tests := []struct {
  25. name string
  26. json string
  27. }{
  28. {
  29. name: "ValidModel",
  30. json: `{"model": "gpt-4", "messages": [{"role": "user", "content": "Hello"}]}`,
  31. },
  32. {
  33. name: "NoModel",
  34. json: `{"messages": [{"role": "user", "content": "Hello"}]}`,
  35. },
  36. {
  37. name: "EmptyJSON",
  38. json: `{}`,
  39. },
  40. {
  41. name: "LargeJSON",
  42. json: `{"model": "gpt-4","messages": [{"role": "user", "content": "` + strings.Repeat(
  43. "x",
  44. 1000,
  45. ) + `"}]}`,
  46. },
  47. {
  48. name: "LargeJSON2",
  49. json: `{"messages": [{"role": "user", "content": "` + strings.Repeat(
  50. "x",
  51. 1000,
  52. ) + `"}],"model": "gpt-4"}`,
  53. },
  54. {
  55. name: "VeryLargeJSON",
  56. json: `{"model": "gpt-4","messages": [{"role": "user", "content": "` + strings.Repeat(
  57. "x",
  58. 10000,
  59. ) + `"}]}`,
  60. },
  61. {
  62. name: "VeryLargeJSON2",
  63. json: `{"messages": [{"role": "user", "content": "` + strings.Repeat(
  64. "x",
  65. 10000,
  66. ) + `"}],"model": "gpt-4"}`,
  67. },
  68. }
  69. for _, tt := range tests {
  70. jsonBytes := []byte(tt.json)
  71. b.Run(tt.name+"/Std", func(b *testing.B) {
  72. b.ResetTimer()
  73. for range b.N {
  74. _, _ = StdGetModelFromJSON(jsonBytes)
  75. }
  76. })
  77. b.Run(tt.name+"/JSONIter", func(b *testing.B) {
  78. b.ResetTimer()
  79. for range b.N {
  80. _, _ = JSONIterGetModelFromJSON(jsonBytes)
  81. }
  82. })
  83. b.Run(tt.name+"/Sonic", func(b *testing.B) {
  84. b.ResetTimer()
  85. for range b.N {
  86. _, _ = middleware.GetModelFromJSON(jsonBytes)
  87. }
  88. })
  89. }
  90. }