response_format.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package apicompat
  2. import "encoding/json"
  3. func chatResponseFormatToResponsesTextFormat(raw json.RawMessage) json.RawMessage {
  4. raw = normalizedRawJSON(raw)
  5. if len(raw) == 0 {
  6. return nil
  7. }
  8. obj, ok := rawJSONObject(raw)
  9. if !ok || rawString(obj["type"]) != "json_schema" {
  10. return raw
  11. }
  12. schemaRaw := normalizedRawJSON(obj["json_schema"])
  13. if len(schemaRaw) == 0 {
  14. return raw
  15. }
  16. var schema map[string]json.RawMessage
  17. if err := json.Unmarshal(schemaRaw, &schema); err != nil {
  18. return raw
  19. }
  20. schema["type"] = rawJSONString("json_schema")
  21. out, err := json.Marshal(schema)
  22. if err != nil {
  23. return raw
  24. }
  25. return out
  26. }
  27. func responsesTextFormatToChatResponseFormat(raw json.RawMessage) json.RawMessage {
  28. raw = normalizedRawJSON(raw)
  29. if len(raw) == 0 {
  30. return nil
  31. }
  32. obj, ok := rawJSONObject(raw)
  33. if !ok || rawString(obj["type"]) != "json_schema" {
  34. return raw
  35. }
  36. if _, alreadyChatShape := obj["json_schema"]; alreadyChatShape {
  37. return raw
  38. }
  39. schema := make(map[string]json.RawMessage, len(obj))
  40. for key, value := range obj {
  41. if key == "type" {
  42. continue
  43. }
  44. schema[key] = value
  45. }
  46. if len(schema) == 0 {
  47. return raw
  48. }
  49. schemaRaw, err := json.Marshal(schema)
  50. if err != nil {
  51. return raw
  52. }
  53. out, err := json.Marshal(map[string]json.RawMessage{
  54. "type": rawJSONString("json_schema"),
  55. "json_schema": schemaRaw,
  56. })
  57. if err != nil {
  58. return raw
  59. }
  60. return out
  61. }
  62. func normalizedRawJSON(raw json.RawMessage) json.RawMessage {
  63. raw = bytesTrimSpace(raw)
  64. if len(raw) == 0 || string(raw) == "null" {
  65. return nil
  66. }
  67. return append(json.RawMessage(nil), raw...)
  68. }
  69. func rawJSONObject(raw json.RawMessage) (map[string]json.RawMessage, bool) {
  70. var obj map[string]json.RawMessage
  71. if err := json.Unmarshal(raw, &obj); err != nil {
  72. return nil, false
  73. }
  74. return obj, true
  75. }
  76. func rawJSONString(value string) json.RawMessage {
  77. data, _ := json.Marshal(value)
  78. return data
  79. }