def recursive_resolve(obj, current_doc, seen_refs=None):
      """Recursively resolves references, handling circularity.

      Args:
          obj: The object to traverse.
          current_doc:  Document to search for refs.
          seen_refs: A set to track already-visited references (for circularity
            detection).

      Returns:
          The resolved object.
      """
      if seen_refs is None:
        seen_refs = set()  # Initialize the set if it's the first call

      if isinstance(obj, dict):
        if "$ref" in obj and isinstance(obj["$ref"], str):
          ref_string = obj["$ref"]

          # Check for circularity
          if ref_string in seen_refs and ref_string not in resolved_cache:
            # Circular reference detected! Return a *copy* of the object,
            # but *without* the $ref.  This breaks the cycle while
            # still maintaining the overall structure.
            return {k: v for k, v in obj.items() if k != "$ref"}

          seen_refs.add(ref_string)  # Add the reference to the set

          # Check if we have a cached resolved value
          if ref_string in resolved_cache:
            return copy.deepcopy(resolved_cache[ref_string])

          resolved_value = resolve_ref(ref_string, current_doc)
          if resolved_value is not None:
            # Recursively resolve the *resolved* value,
            # passing along the 'seen_refs' set
            resolved_value = recursive_resolve(
                resolved_value, current_doc, seen_refs
            )
            resolved_cache[ref_string] = resolved_value
            return copy.deepcopy(resolved_value)  # return the cached result
          else:
            return obj  # return original if no resolved value.

        else:
          new_dict = {}
          for key, value in obj.items():
            new_dict[key] = recursive_resolve(value, current_doc, seen_refs)
          return new_dict

      elif isinstance(obj, list):
        return [recursive_resolve(item, current_doc, seen_refs) for item in obj]
      else:
        return obj
Recursively resolves references, handling circularity.

      Args:
          obj: The object to traverse.
          current_doc:  Document to search for refs.
          seen_refs: A set to track already-visited references (for circularity
            detection).

      Returns:
          The resolved object.
      
src/google/adk/tools/openapi_tool/openapi_spec_parser/openapi_spec_parser.py