"Objects provided via 'anyOf' must not share identical first keys" error in Structured Output

Our response model anticipates multiple entities: e.g. EntityA or EntityB:

{
   "$defs":{
      "GenerateResponse":{
         "items":{
            "anyOf":[
               {
                  "$ref":"#/$defs/EntityA",
                  "$ref":"#/$defs/EntityB"
               }
            ]
         },
         "title":"GenerateResponse",
         "type":"array"
      },
      "EntityA":{
         "properties":{
            "field_a":{
               "items":{
                  "type":"string"
               },
               "minItems":1,
               "maxItems":4,
               "title":"Field A",
               "type":"array"
            },
         },
         "required":[
            "field_a",
         ],
         "title":"EntityA",
         "type":"object"
      },
      "EntityB":{
         "properties":{
            "field_b":{
               "items":{
                  "type":"string"
               },
               "minItems":1,
               "maxItems":4,
               "title":"Field B",
               "type":"array"
            },
         },
   },
   "properties":{
      "entities":{
         "$ref":"#/$defs/GenerateResponse"
      }
   },
   "required":[
      "entities"
   ],
   "title":"GenerateOpenAiResponse",
   "type":"object"
}

When using gpt4o with structured output, we face “Objects provided via ‘anyOf’ must not share identical first keys. Consider adding a discriminator key or rearranging the properties to ensure the first key is unique.” error.

What would be an appropriate change to the model above to workaround this?

Thanks!

your anyOf part seem to be incorrect.
should be like this

"anyOf": [
          {
            "$ref": "#/$defs/EntityA"
          },
          {
            "$ref": "#/$defs/EntityB"
          }
        ]