Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | """OpenAPI helpers.""" |
| 2 | |
| 3 | import inspect |
| 4 | import typing as t |
| 5 | |
| 6 | from composio.exceptions import InvalidSchemaError |
| 7 | |
| 8 | OPENAPI_TO_PYTHON = { |
| 9 | "null": None, |
| 10 | "number": float, |
| 11 | "integer": int, |
| 12 | "boolean": bool, |
| 13 | "string": str, |
| 14 | } |
| 15 | |
| 16 | # Tool schemas come from the backend and may be arbitrarily deeply nested. |
| 17 | _MAX_SCHEMA_DEPTH = 64 |
| 18 | # Bounds the schemas converted for one parameter: a schema that branches at |
| 19 | # every level costs exponential work well within the depth bound. |
| 20 | _MAX_SCHEMA_NODES = 2_000 |
| 21 | |
| 22 | |
| 23 | class _Budget: |
| 24 | """Schema conversions left for one parameter; past it, a schema is `Any`.""" |
| 25 | |
| 26 | def __init__(self) -> None: |
| 27 | self.nodes = _MAX_SCHEMA_NODES |
| 28 | |
| 29 | |
| 30 | # pylint: disable=unused-argument |
| 31 | def _handle_object_type(schema: t.Dict) -> t.Type: |
| 32 | # Nested objects are not supported ATM |
| 33 | return t.Dict[str, t.Any] |
| 34 | |
| 35 | |
| 36 | def _handle_array_type( |
| 37 | schema: t.Dict, *, _depth: int = 0, _budget: t.Optional[_Budget] = None |
| 38 | ) -> t.Any: |
| 39 | # This discards the nested objects |
| 40 | SubT = _type_to_parameter( |
| 41 | schema=schema.get("items", {}), _depth=_depth + 1, _budget=_budget |
| 42 | ) |
| 43 | return t.List[SubT] # type: ignore |
| 44 | |
| 45 | |
| 46 | def _handle_enum_type(schema: t.Dict) -> t.Any: |
| 47 | return t.Literal[tuple(schema["enum"])] |
| 48 | |
| 49 | |
| 50 | def _type_to_parameter( |
| 51 | schema: t.Dict[str, t.Any], |
| 52 | *, |
| 53 | _depth: int = 0, |
| 54 | _budget: t.Optional[_Budget] = None, |
| 55 | ) -> t.Any: |
| 56 | if _budget is None: |
| 57 | _budget = _Budget() |
| 58 | if _depth >= _MAX_SCHEMA_DEPTH or _budget.nodes <= 0: |
| 59 | return t.Any |
| 60 | _budget.nodes -= 1 |
| 61 | if "enum" in schema: |
| 62 | return _handle_enum_type(schema=schema) |
| 63 | |
| 64 | p_type = schema.get("type") |
| 65 | # Preserve the existing enum/type precedence for already-typed schemas. |
| 66 | if p_type is None: |
| 67 | if "oneOf" in schema: |
| 68 | return _one_of_to_parameter(schema=schema, _depth=_depth, _budget=_budget) |
| 69 | if "anyOf" in schema: |
| 70 | return _any_of_to_parameter(schema=schema, _depth=_depth, _budget=_budget) |
| 71 | if "allOf" in schema: |
| 72 | return _all_of_to_parameter(schema=schema, _depth=_depth, _budget=_budget) |
| 73 | if isinstance(p_type, list): |
| 74 | # JSON Schema Draft 2020-12 / OpenAPI 3.1 express a nullable field as a |
| 75 | # list of types, e.g. {"type": ["string", "null"]}, rather than an anyOf. |
| 76 | if not p_type: |
| 77 | return t.Any |
| 78 | members = [] |
| 79 | for member in p_type: |
| 80 | # Each member copies the whole schema, so stop once nothing is left |
| 81 | # to convert it with. |
| 82 | if _budget.nodes <= 0: |
| 83 | members.append(t.Any) |
| 84 | break |
| 85 | members.append( |
| 86 | _type_to_parameter( |
| 87 | schema={**schema, "type": member}, |
| 88 | _depth=_depth + 1, |
| 89 | _budget=_budget, |
| 90 | ) |
| 91 | ) |
| 92 | return t.Union[tuple(members)] |
| 93 | |
| 94 | if p_type in OPENAPI_TO_PYTHON: |
| 95 | return OPENAPI_TO_PYTHON[p_type] |
| 96 | |
| 97 | if p_type == "object": |
| 98 | return _handle_object_type(schema=schema) |
| 99 | |
| 100 | if p_type == "array": |
| 101 | return _handle_array_type(schema=schema, _depth=_depth, _budget=_budget) |
| 102 | |
| 103 | if p_type is None: |
| 104 | # No type specified (e.g. a combiner option that is description-only or |
| 105 | # an explicit Any), mirroring the top-level fallback below. |
| 106 | return t.Any |
| 107 | |
| 108 | raise InvalidSchemaError(f"Invalid property type {p_type}: {schema!r}") |
| 109 | |
| 110 | |
| 111 | def _handle_composite_type( |
| 112 | schemas: t.List[t.Dict], |
| 113 | *, |
| 114 | _depth: int = 0, |
| 115 | _budget: t.Optional[_Budget] = None, |
| 116 | ) -> t.Any: |
| 117 | if not schemas: |
| 118 | # An empty oneOf/anyOf has no options to union; fall back to Any. |
| 119 | return t.Any |
| 120 | if _budget is None: |
| 121 | _budget = _Budget() |
| 122 | return t.Union[ |
| 123 | tuple( |
| 124 | _type_to_parameter(schema=schema, _depth=_depth + 1, _budget=_budget) |
| 125 | for schema in schemas |
| 126 | ) |
| 127 | ] |
| 128 | |
| 129 | |
| 130 | def _one_of_to_parameter( |
| 131 | schema: t.Dict[str, t.Any], |
| 132 | *, |
| 133 | _depth: int = 0, |
| 134 | _budget: t.Optional[_Budget] = None, |
| 135 | ) -> t.Any: |
| 136 | return _handle_composite_type( |
| 137 | schemas=schema["oneOf"], _depth=_depth, _budget=_budget |
| 138 | ) |
| 139 | |
| 140 | |
| 141 | def _any_of_to_parameter( |
| 142 | schema: t.Dict[str, t.Any], |
| 143 | *, |
| 144 | _depth: int = 0, |
| 145 | _budget: t.Optional[_Budget] = None, |
| 146 | ) -> t.Any: |
| 147 | return _handle_composite_type( |
| 148 | schemas=schema["anyOf"], _depth=_depth, _budget=_budget |
| 149 | ) |
| 150 | |
| 151 | |
| 152 | def _all_of_to_parameter( |
| 153 | schema: t.Dict[str, t.Any], |
| 154 | *, |
| 155 | _depth: int = 0, |
| 156 | _budget: t.Optional[_Budget] = None, |
| 157 | ) -> t.Type: |
| 158 | composite = {} |
| 159 | for subschema in schema["allOf"]: |
| 160 | composite.update(subschema) |
| 161 | return _type_to_parameter(schema=composite, _depth=_depth + 1, _budget=_budget) |
| 162 | |
| 163 | |
| 164 | def function_signature_from_jsonschema( |
| 165 | schema: t.Dict[str, t.Any], |
| 166 | skip_default: bool = False, |
| 167 | ) -> t.List[inspect.Parameter]: |
| 168 | """Convert json schema to a list of parameters (`inspect.Parameter`).""" |
| 169 | parameters = [] |
| 170 | required = set(schema.get("required", [])) |
| 171 | for p_name, p_schema in schema.get("properties", {}).items(): |
| 172 | if "oneOf" in p_schema: |
| 173 | p_type = _one_of_to_parameter(schema=p_schema) |
| 174 | elif "anyOf" in p_schema: |
| 175 | p_type = _any_of_to_parameter(schema=p_schema) |
| 176 | elif "allOf" in p_schema: |
| 177 | p_type = _all_of_to_parameter(schema=p_schema) |
| 178 | elif "type" in p_schema: |
| 179 | p_type = _type_to_parameter(schema=p_schema) |
| 180 | else: |
| 181 | # Handle cases where no type is specified (e.g., Pydantic's Any type) |
| 182 | # This typically happens when using typing.Any in Pydantic models, |
| 183 | # which intentionally omits the 'type' field in JSON schema |
| 184 | p_type = t.Any |
| 185 | |
| 186 | p_val = p_schema.get("default", None) |
| 187 | if p_name in required or p_schema.get("required", False) or skip_default: |
| 188 | p_val = inspect.Parameter.empty |
| 189 | |
| 190 | parameters.append( |
| 191 | inspect.Parameter( |
| 192 | name=p_name, |
| 193 | annotation=p_type, |
| 194 | default=p_val, |
| 195 | kind=inspect.Parameter.POSITIONAL_OR_KEYWORD, |
| 196 | ) |
| 197 | ) |
| 198 | |
| 199 | return parameters |