alita-sdk 0.3.528__py3-none-any.whl → 0.3.554__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of alita-sdk might be problematic. Click here for more details.
- alita_sdk/community/__init__.py +8 -4
- alita_sdk/configurations/__init__.py +1 -0
- alita_sdk/configurations/openapi.py +111 -0
- alita_sdk/runtime/clients/client.py +185 -10
- alita_sdk/runtime/langchain/langraph_agent.py +2 -2
- alita_sdk/runtime/langchain/utils.py +46 -0
- alita_sdk/runtime/skills/__init__.py +91 -0
- alita_sdk/runtime/skills/callbacks.py +498 -0
- alita_sdk/runtime/skills/discovery.py +540 -0
- alita_sdk/runtime/skills/executor.py +610 -0
- alita_sdk/runtime/skills/input_builder.py +371 -0
- alita_sdk/runtime/skills/models.py +330 -0
- alita_sdk/runtime/skills/registry.py +355 -0
- alita_sdk/runtime/skills/skill_runner.py +330 -0
- alita_sdk/runtime/toolkits/__init__.py +2 -0
- alita_sdk/runtime/toolkits/skill_router.py +238 -0
- alita_sdk/runtime/toolkits/tools.py +76 -9
- alita_sdk/runtime/tools/__init__.py +3 -1
- alita_sdk/runtime/tools/artifact.py +70 -21
- alita_sdk/runtime/tools/image_generation.py +50 -44
- alita_sdk/runtime/tools/llm.py +363 -44
- alita_sdk/runtime/tools/loop.py +3 -1
- alita_sdk/runtime/tools/loop_output.py +3 -1
- alita_sdk/runtime/tools/skill_router.py +776 -0
- alita_sdk/runtime/tools/tool.py +3 -1
- alita_sdk/runtime/tools/vectorstore.py +7 -2
- alita_sdk/runtime/tools/vectorstore_base.py +7 -2
- alita_sdk/runtime/utils/AlitaCallback.py +2 -1
- alita_sdk/runtime/utils/utils.py +34 -0
- alita_sdk/tools/__init__.py +41 -1
- alita_sdk/tools/ado/work_item/ado_wrapper.py +33 -2
- alita_sdk/tools/base_indexer_toolkit.py +36 -24
- alita_sdk/tools/confluence/api_wrapper.py +5 -6
- alita_sdk/tools/confluence/loader.py +4 -2
- alita_sdk/tools/openapi/__init__.py +280 -120
- alita_sdk/tools/openapi/api_wrapper.py +883 -0
- alita_sdk/tools/openapi/tool.py +20 -0
- alita_sdk/tools/pandas/dataframe/generator/base.py +3 -1
- alita_sdk/tools/servicenow/__init__.py +9 -9
- alita_sdk/tools/servicenow/api_wrapper.py +1 -1
- {alita_sdk-0.3.528.dist-info → alita_sdk-0.3.554.dist-info}/METADATA +2 -2
- {alita_sdk-0.3.528.dist-info → alita_sdk-0.3.554.dist-info}/RECORD +46 -33
- {alita_sdk-0.3.528.dist-info → alita_sdk-0.3.554.dist-info}/WHEEL +0 -0
- {alita_sdk-0.3.528.dist-info → alita_sdk-0.3.554.dist-info}/entry_points.txt +0 -0
- {alita_sdk-0.3.528.dist-info → alita_sdk-0.3.554.dist-info}/licenses/LICENSE +0 -0
- {alita_sdk-0.3.528.dist-info → alita_sdk-0.3.554.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,883 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
import re
|
|
4
|
+
from urllib.parse import urlencode
|
|
5
|
+
from typing import Any, Callable, Optional
|
|
6
|
+
import copy
|
|
7
|
+
|
|
8
|
+
import yaml
|
|
9
|
+
from langchain_core.tools import ToolException
|
|
10
|
+
from pydantic import BaseModel, Field, PrivateAttr, create_model
|
|
11
|
+
from requests_openapi import Client, Operation
|
|
12
|
+
|
|
13
|
+
from ..elitea_base import BaseToolApiWrapper
|
|
14
|
+
from ..utils import clean_string
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _raise_openapi_tool_exception(
|
|
20
|
+
*,
|
|
21
|
+
code: str,
|
|
22
|
+
message: str,
|
|
23
|
+
operation_id: Optional[str] = None,
|
|
24
|
+
url: Optional[str] = None,
|
|
25
|
+
retryable: Optional[bool] = None,
|
|
26
|
+
missing_inputs: Optional[list[str]] = None,
|
|
27
|
+
http_status: Optional[int] = None,
|
|
28
|
+
http_body_preview: Optional[str] = None,
|
|
29
|
+
details: Optional[dict[str, Any]] = None,
|
|
30
|
+
) -> None:
|
|
31
|
+
payload: dict[str, Any] = {
|
|
32
|
+
"tool": "openapi",
|
|
33
|
+
"code": code,
|
|
34
|
+
"message": message,
|
|
35
|
+
}
|
|
36
|
+
if operation_id:
|
|
37
|
+
payload["operation_id"] = operation_id
|
|
38
|
+
if url:
|
|
39
|
+
payload["url"] = url
|
|
40
|
+
if retryable is not None:
|
|
41
|
+
payload["retryable"] = bool(retryable)
|
|
42
|
+
if missing_inputs:
|
|
43
|
+
payload["missing_inputs"] = list(missing_inputs)
|
|
44
|
+
if http_status is not None:
|
|
45
|
+
payload["http_status"] = int(http_status)
|
|
46
|
+
if http_body_preview:
|
|
47
|
+
payload["http_body_preview"] = str(http_body_preview)
|
|
48
|
+
if details:
|
|
49
|
+
payload["details"] = details
|
|
50
|
+
|
|
51
|
+
try:
|
|
52
|
+
details_json = json.dumps(payload, ensure_ascii=False, indent=2)
|
|
53
|
+
except Exception:
|
|
54
|
+
details_json = str(payload)
|
|
55
|
+
|
|
56
|
+
raise ToolException(f"{message}\n\nToolError:\n{details_json}")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _truncate(text: Any, max_len: int) -> str:
|
|
60
|
+
if text is None:
|
|
61
|
+
return ""
|
|
62
|
+
s = str(text)
|
|
63
|
+
if len(s) <= max_len:
|
|
64
|
+
return s
|
|
65
|
+
return s[:max_len] + "…"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _is_retryable_http_status(status_code: Optional[int]) -> bool:
|
|
69
|
+
if status_code is None:
|
|
70
|
+
return False
|
|
71
|
+
return int(status_code) in (408, 425, 429, 500, 502, 503, 504)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _get_base_url_from_spec(spec: dict) -> str:
|
|
75
|
+
servers = spec.get("servers") if isinstance(spec, dict) else None
|
|
76
|
+
if isinstance(servers, list) and servers:
|
|
77
|
+
first = servers[0]
|
|
78
|
+
if isinstance(first, dict) and isinstance(first.get("url"), str):
|
|
79
|
+
return first["url"].strip()
|
|
80
|
+
return ""
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _is_absolute_url(url: str) -> bool:
|
|
84
|
+
return isinstance(url, str) and (url.startswith("http://") or url.startswith("https://"))
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _apply_base_url_override(spec: dict, base_url_override: str) -> dict:
|
|
88
|
+
"""Normalize server URL when OpenAPI spec uses relative servers.
|
|
89
|
+
|
|
90
|
+
Some public specs (including Petstore) use relative server URLs like "/api/v3".
|
|
91
|
+
To execute requests against a real host, we can provide a base URL override like
|
|
92
|
+
"https://petstore3.swagger.io" and convert the first server URL to an absolute URL.
|
|
93
|
+
"""
|
|
94
|
+
if not isinstance(spec, dict):
|
|
95
|
+
return spec
|
|
96
|
+
if not isinstance(base_url_override, str) or not base_url_override.strip():
|
|
97
|
+
return spec
|
|
98
|
+
base_url_override = base_url_override.strip().rstrip("/")
|
|
99
|
+
|
|
100
|
+
servers = spec.get("servers")
|
|
101
|
+
if not isinstance(servers, list) or not servers:
|
|
102
|
+
spec["servers"] = [{"url": base_url_override}]
|
|
103
|
+
return spec
|
|
104
|
+
|
|
105
|
+
first = servers[0]
|
|
106
|
+
if not isinstance(first, dict):
|
|
107
|
+
return spec
|
|
108
|
+
server_url = first.get("url")
|
|
109
|
+
if not isinstance(server_url, str):
|
|
110
|
+
return spec
|
|
111
|
+
server_url = server_url.strip()
|
|
112
|
+
if not server_url:
|
|
113
|
+
first["url"] = base_url_override
|
|
114
|
+
return spec
|
|
115
|
+
if _is_absolute_url(server_url):
|
|
116
|
+
return spec
|
|
117
|
+
|
|
118
|
+
# Relative server URL ("/api/v3" or "api/v3") -> join with base host.
|
|
119
|
+
if not server_url.startswith("/"):
|
|
120
|
+
server_url = "/" + server_url
|
|
121
|
+
first["url"] = base_url_override + server_url
|
|
122
|
+
return spec
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _join_base_and_path(base_url: str, path: str) -> str:
|
|
126
|
+
base = (base_url or "").rstrip("/")
|
|
127
|
+
p = (path or "")
|
|
128
|
+
if not p.startswith("/"):
|
|
129
|
+
p = "/" + p
|
|
130
|
+
if not base:
|
|
131
|
+
return p
|
|
132
|
+
return base + p
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _parse_openapi_spec(spec: str | dict) -> dict:
|
|
136
|
+
if isinstance(spec, dict):
|
|
137
|
+
return spec
|
|
138
|
+
if not isinstance(spec, str) or not spec.strip():
|
|
139
|
+
_raise_openapi_tool_exception(code="missing_spec", message="OpenAPI spec is required")
|
|
140
|
+
|
|
141
|
+
try:
|
|
142
|
+
parsed = json.loads(spec)
|
|
143
|
+
except json.JSONDecodeError:
|
|
144
|
+
try:
|
|
145
|
+
parsed = yaml.safe_load(spec)
|
|
146
|
+
except yaml.YAMLError as e:
|
|
147
|
+
_raise_openapi_tool_exception(
|
|
148
|
+
code="invalid_spec",
|
|
149
|
+
message=f"Failed to parse OpenAPI spec as JSON or YAML: {e}",
|
|
150
|
+
details={"error": str(e)},
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
if not isinstance(parsed, dict):
|
|
154
|
+
_raise_openapi_tool_exception(code="invalid_spec", message="OpenAPI spec must parse to an object")
|
|
155
|
+
return parsed
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _guess_python_type(openapi_schema: dict | None) -> type:
|
|
159
|
+
schema_type = (openapi_schema or {}).get("type")
|
|
160
|
+
if schema_type == "integer":
|
|
161
|
+
return int
|
|
162
|
+
if schema_type == "number":
|
|
163
|
+
return float
|
|
164
|
+
if schema_type == "boolean":
|
|
165
|
+
return bool
|
|
166
|
+
# arrays/objects are left as string for now (simple start)
|
|
167
|
+
return str
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _schema_type_hint(openapi_schema: dict | None) -> str:
|
|
171
|
+
if not isinstance(openapi_schema, dict):
|
|
172
|
+
return ""
|
|
173
|
+
type_ = openapi_schema.get("type")
|
|
174
|
+
fmt = openapi_schema.get("format")
|
|
175
|
+
if not type_:
|
|
176
|
+
return ""
|
|
177
|
+
if fmt:
|
|
178
|
+
return f"{type_} ({fmt})"
|
|
179
|
+
return str(type_)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _extract_request_body_example(spec: Optional[dict], op_raw: dict) -> Optional[str]:
|
|
183
|
+
request_body = op_raw.get("requestBody") or {}
|
|
184
|
+
content = request_body.get("content") or {}
|
|
185
|
+
for media_type in ("application/json", "application/*+json"):
|
|
186
|
+
mt = content.get(media_type)
|
|
187
|
+
if not isinstance(mt, dict):
|
|
188
|
+
continue
|
|
189
|
+
|
|
190
|
+
if "example" in mt:
|
|
191
|
+
try:
|
|
192
|
+
return json.dumps(mt["example"], indent=2)
|
|
193
|
+
except Exception:
|
|
194
|
+
return str(mt["example"])
|
|
195
|
+
|
|
196
|
+
examples = mt.get("examples")
|
|
197
|
+
if isinstance(examples, dict) and examples:
|
|
198
|
+
first = next(iter(examples.values()))
|
|
199
|
+
if isinstance(first, dict) and "value" in first:
|
|
200
|
+
try:
|
|
201
|
+
return json.dumps(first["value"], indent=2)
|
|
202
|
+
except Exception:
|
|
203
|
+
return str(first["value"])
|
|
204
|
+
|
|
205
|
+
schema = mt.get("schema")
|
|
206
|
+
if isinstance(schema, dict) and "example" in schema:
|
|
207
|
+
try:
|
|
208
|
+
return json.dumps(schema["example"], indent=2)
|
|
209
|
+
except Exception:
|
|
210
|
+
return str(schema["example"])
|
|
211
|
+
|
|
212
|
+
# No explicit example found; fall back to schema-based template.
|
|
213
|
+
if isinstance(schema, dict):
|
|
214
|
+
template_obj = _schema_to_template_json(
|
|
215
|
+
spec=spec,
|
|
216
|
+
schema=schema,
|
|
217
|
+
max_depth=3,
|
|
218
|
+
max_properties=20,
|
|
219
|
+
)
|
|
220
|
+
if template_obj is not None:
|
|
221
|
+
try:
|
|
222
|
+
return json.dumps(template_obj, indent=2)
|
|
223
|
+
except Exception:
|
|
224
|
+
return str(template_obj)
|
|
225
|
+
return None
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _schema_to_template_json(
|
|
229
|
+
spec: Any,
|
|
230
|
+
schema: dict,
|
|
231
|
+
max_depth: int,
|
|
232
|
+
max_properties: int,
|
|
233
|
+
) -> Any:
|
|
234
|
+
"""Build a schema-shaped JSON template from an OpenAPI/JSONSchema fragment.
|
|
235
|
+
|
|
236
|
+
This is a best-effort helper intended for LLM prompting. It avoids infinite recursion
|
|
237
|
+
(via depth and $ref cycle checks) and prefers enum/default/example when available.
|
|
238
|
+
"""
|
|
239
|
+
visited_refs: set[str] = set()
|
|
240
|
+
return _schema_node_to_value(
|
|
241
|
+
spec=spec if isinstance(spec, dict) else None,
|
|
242
|
+
node=schema,
|
|
243
|
+
depth=0,
|
|
244
|
+
max_depth=max_depth,
|
|
245
|
+
max_properties=max_properties,
|
|
246
|
+
visited_refs=visited_refs,
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _schema_node_to_value(
|
|
251
|
+
spec: Optional[dict],
|
|
252
|
+
node: Any,
|
|
253
|
+
depth: int,
|
|
254
|
+
max_depth: int,
|
|
255
|
+
max_properties: int,
|
|
256
|
+
visited_refs: set[str],
|
|
257
|
+
) -> Any:
|
|
258
|
+
if depth > max_depth:
|
|
259
|
+
return "<...>"
|
|
260
|
+
|
|
261
|
+
if not isinstance(node, dict):
|
|
262
|
+
return "<value>"
|
|
263
|
+
|
|
264
|
+
# Prefer explicit example/default/enum at this node.
|
|
265
|
+
if "example" in node:
|
|
266
|
+
return node.get("example")
|
|
267
|
+
if "default" in node:
|
|
268
|
+
return node.get("default")
|
|
269
|
+
if isinstance(node.get("enum"), list) and node.get("enum"):
|
|
270
|
+
return node.get("enum")[0]
|
|
271
|
+
|
|
272
|
+
ref = node.get("$ref")
|
|
273
|
+
if isinstance(ref, str):
|
|
274
|
+
if ref in visited_refs:
|
|
275
|
+
return "<ref-cycle>"
|
|
276
|
+
visited_refs.add(ref)
|
|
277
|
+
resolved = _resolve_ref(spec, ref)
|
|
278
|
+
if resolved is None:
|
|
279
|
+
return "<ref>"
|
|
280
|
+
return _schema_node_to_value(
|
|
281
|
+
spec=spec,
|
|
282
|
+
node=resolved,
|
|
283
|
+
depth=depth + 1,
|
|
284
|
+
max_depth=max_depth,
|
|
285
|
+
max_properties=max_properties,
|
|
286
|
+
visited_refs=visited_refs,
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
# Combinators
|
|
290
|
+
for key in ("oneOf", "anyOf"):
|
|
291
|
+
if isinstance(node.get(key), list) and node.get(key):
|
|
292
|
+
return _schema_node_to_value(
|
|
293
|
+
spec=spec,
|
|
294
|
+
node=node.get(key)[0],
|
|
295
|
+
depth=depth + 1,
|
|
296
|
+
max_depth=max_depth,
|
|
297
|
+
max_properties=max_properties,
|
|
298
|
+
visited_refs=visited_refs,
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
if isinstance(node.get("allOf"), list) and node.get("allOf"):
|
|
302
|
+
# Best-effort merge for objects.
|
|
303
|
+
merged: dict = {"type": "object", "properties": {}, "required": []}
|
|
304
|
+
for part in node.get("allOf"):
|
|
305
|
+
part_resolved = _schema_node_to_value(
|
|
306
|
+
spec=spec,
|
|
307
|
+
node=part,
|
|
308
|
+
depth=depth + 1,
|
|
309
|
+
max_depth=max_depth,
|
|
310
|
+
max_properties=max_properties,
|
|
311
|
+
visited_refs=visited_refs,
|
|
312
|
+
)
|
|
313
|
+
# If a part produced an object template, merge keys.
|
|
314
|
+
if isinstance(part_resolved, dict):
|
|
315
|
+
for k, v in part_resolved.items():
|
|
316
|
+
merged.setdefault(k, v)
|
|
317
|
+
return merged
|
|
318
|
+
|
|
319
|
+
type_ = node.get("type")
|
|
320
|
+
fmt = node.get("format")
|
|
321
|
+
|
|
322
|
+
if type_ == "object" or (type_ is None and ("properties" in node or "additionalProperties" in node)):
|
|
323
|
+
props = node.get("properties") if isinstance(node.get("properties"), dict) else {}
|
|
324
|
+
required = node.get("required") if isinstance(node.get("required"), list) else []
|
|
325
|
+
|
|
326
|
+
out: dict[str, Any] = {}
|
|
327
|
+
# Prefer required fields, then a small subset of optional fields for guidance.
|
|
328
|
+
keys: list[str] = []
|
|
329
|
+
for k in required:
|
|
330
|
+
if isinstance(k, str) and k in props:
|
|
331
|
+
keys.append(k)
|
|
332
|
+
if not keys:
|
|
333
|
+
keys = list(props.keys())[: min(3, len(props))]
|
|
334
|
+
else:
|
|
335
|
+
optional = [k for k in props.keys() if k not in keys]
|
|
336
|
+
keys.extend(optional[: max(0, min(3, len(optional)))])
|
|
337
|
+
|
|
338
|
+
keys = keys[:max_properties]
|
|
339
|
+
for k in keys:
|
|
340
|
+
out[k] = _schema_node_to_value(
|
|
341
|
+
spec=spec,
|
|
342
|
+
node=props.get(k),
|
|
343
|
+
depth=depth + 1,
|
|
344
|
+
max_depth=max_depth,
|
|
345
|
+
max_properties=max_properties,
|
|
346
|
+
visited_refs=visited_refs,
|
|
347
|
+
)
|
|
348
|
+
return out
|
|
349
|
+
|
|
350
|
+
if type_ == "array":
|
|
351
|
+
items = node.get("items")
|
|
352
|
+
return [
|
|
353
|
+
_schema_node_to_value(
|
|
354
|
+
spec=spec,
|
|
355
|
+
node=items,
|
|
356
|
+
depth=depth + 1,
|
|
357
|
+
max_depth=max_depth,
|
|
358
|
+
max_properties=max_properties,
|
|
359
|
+
visited_refs=visited_refs,
|
|
360
|
+
)
|
|
361
|
+
]
|
|
362
|
+
|
|
363
|
+
if type_ == "integer":
|
|
364
|
+
return 0
|
|
365
|
+
if type_ == "number":
|
|
366
|
+
return 0.0
|
|
367
|
+
if type_ == "boolean":
|
|
368
|
+
return False
|
|
369
|
+
if type_ == "string":
|
|
370
|
+
if fmt == "date-time":
|
|
371
|
+
return "2025-01-01T00:00:00Z"
|
|
372
|
+
if fmt == "date":
|
|
373
|
+
return "2025-01-01"
|
|
374
|
+
if fmt == "uuid":
|
|
375
|
+
return "00000000-0000-0000-0000-000000000000"
|
|
376
|
+
return "<string>"
|
|
377
|
+
|
|
378
|
+
# Unknown: return a placeholder
|
|
379
|
+
return "<value>"
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def _resolve_ref(spec: Optional[dict], ref: str) -> Optional[dict]:
|
|
383
|
+
if not spec or not isinstance(ref, str):
|
|
384
|
+
return None
|
|
385
|
+
if not ref.startswith("#/"):
|
|
386
|
+
return None
|
|
387
|
+
# Only local refs supported for now.
|
|
388
|
+
parts = ref.lstrip("#/").split("/")
|
|
389
|
+
cur: Any = spec
|
|
390
|
+
for part in parts:
|
|
391
|
+
if not isinstance(cur, dict):
|
|
392
|
+
return None
|
|
393
|
+
cur = cur.get(part)
|
|
394
|
+
if isinstance(cur, dict):
|
|
395
|
+
return cur
|
|
396
|
+
return None
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def _normalize_output(value: Any) -> str:
|
|
400
|
+
if value is None:
|
|
401
|
+
return ""
|
|
402
|
+
if isinstance(value, bytes):
|
|
403
|
+
try:
|
|
404
|
+
return value.decode("utf-8")
|
|
405
|
+
except Exception:
|
|
406
|
+
return value.decode("utf-8", errors="replace")
|
|
407
|
+
return str(value)
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
class OpenApiApiWrapper(BaseToolApiWrapper):
|
|
411
|
+
"""Builds callable tool functions for OpenAPI operations and executes them."""
|
|
412
|
+
|
|
413
|
+
spec: dict = Field(description="Parsed OpenAPI spec")
|
|
414
|
+
base_headers: dict[str, str] = Field(default_factory=dict)
|
|
415
|
+
|
|
416
|
+
_client: Client = PrivateAttr()
|
|
417
|
+
_op_meta: dict[str, dict] = PrivateAttr(default_factory=dict)
|
|
418
|
+
_tool_defs: list[dict[str, Any]] = PrivateAttr(default_factory=list)
|
|
419
|
+
_tool_ref_by_name: dict[str, Callable[..., str]] = PrivateAttr(default_factory=dict)
|
|
420
|
+
|
|
421
|
+
def model_post_init(self, __context: Any) -> None:
|
|
422
|
+
# Build meta from raw spec (method/path/examples)
|
|
423
|
+
op_meta: dict[str, dict] = {}
|
|
424
|
+
paths = self.spec.get("paths") or {}
|
|
425
|
+
if isinstance(paths, dict):
|
|
426
|
+
for path, path_item in paths.items():
|
|
427
|
+
if not isinstance(path_item, dict):
|
|
428
|
+
continue
|
|
429
|
+
for method, op_raw in path_item.items():
|
|
430
|
+
if not isinstance(op_raw, dict):
|
|
431
|
+
continue
|
|
432
|
+
operation_id = op_raw.get("operationId")
|
|
433
|
+
if not operation_id:
|
|
434
|
+
continue
|
|
435
|
+
op_meta[str(operation_id)] = {
|
|
436
|
+
"method": str(method).upper(),
|
|
437
|
+
"path": str(path),
|
|
438
|
+
"raw": op_raw,
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
client = Client()
|
|
442
|
+
client.load_spec(self.spec)
|
|
443
|
+
if self.base_headers:
|
|
444
|
+
client.requestor.headers.update({str(k): str(v) for k, v in self.base_headers.items()})
|
|
445
|
+
|
|
446
|
+
self._client = client
|
|
447
|
+
self._op_meta = op_meta
|
|
448
|
+
|
|
449
|
+
# Build tool definitions once.
|
|
450
|
+
self._tool_defs = self._build_tool_defs()
|
|
451
|
+
self._tool_ref_by_name = {t["name"]: t["ref"] for t in self._tool_defs if "ref" in t}
|
|
452
|
+
|
|
453
|
+
def _build_tool_defs(self) -> list[dict[str, Any]]:
|
|
454
|
+
tool_defs: list[dict[str, Any]] = []
|
|
455
|
+
for operation_id, op in getattr(self._client, "operations", {}).items():
|
|
456
|
+
if not isinstance(op, Operation):
|
|
457
|
+
continue
|
|
458
|
+
op_id = str(operation_id)
|
|
459
|
+
meta = self._op_meta.get(op_id, {})
|
|
460
|
+
op_raw = meta.get("raw") if isinstance(meta.get("raw"), dict) else {}
|
|
461
|
+
|
|
462
|
+
method = meta.get("method")
|
|
463
|
+
path = meta.get("path")
|
|
464
|
+
|
|
465
|
+
title_line = ""
|
|
466
|
+
if method and path:
|
|
467
|
+
title_line = f"{method} {path}"
|
|
468
|
+
|
|
469
|
+
summary = op.spec.summary or ""
|
|
470
|
+
description = op.spec.description or ""
|
|
471
|
+
tool_desc_parts = [p for p in [title_line, summary, description] if p]
|
|
472
|
+
|
|
473
|
+
has_request_body = bool(op.spec.requestBody)
|
|
474
|
+
usage_lines: list[str] = ["How to call:"]
|
|
475
|
+
usage_lines.append("- Provide path/query parameters as named arguments.")
|
|
476
|
+
if has_request_body:
|
|
477
|
+
usage_lines.append("- For JSON request bodies, pass `body_json` as a JSON string.")
|
|
478
|
+
usage_lines.append(
|
|
479
|
+
"- Use `headers` only for per-call extra headers; base/toolkit headers (including auth) are already applied."
|
|
480
|
+
)
|
|
481
|
+
tool_desc_parts.append("\n".join(usage_lines))
|
|
482
|
+
|
|
483
|
+
args_schema = self._create_args_schema(op_id, op, op_raw)
|
|
484
|
+
ref = self._make_operation_callable(op_id)
|
|
485
|
+
|
|
486
|
+
tool_defs.append(
|
|
487
|
+
{
|
|
488
|
+
"name": op_id,
|
|
489
|
+
"description": "\n".join(tool_desc_parts).strip(),
|
|
490
|
+
"args_schema": args_schema,
|
|
491
|
+
"ref": ref,
|
|
492
|
+
}
|
|
493
|
+
)
|
|
494
|
+
return tool_defs
|
|
495
|
+
|
|
496
|
+
def _make_operation_callable(self, operation_id: str) -> Callable[..., str]:
|
|
497
|
+
def _call_operation(*args: Any, **kwargs: Any) -> str:
|
|
498
|
+
return self._execute(operation_id, *args, **kwargs)
|
|
499
|
+
|
|
500
|
+
return _call_operation
|
|
501
|
+
|
|
502
|
+
def _create_args_schema(self, operation_id: str, op: Operation, op_raw: dict) -> type[BaseModel]:
|
|
503
|
+
fields: dict[str, tuple[Any, Any]] = {}
|
|
504
|
+
|
|
505
|
+
# Parameters
|
|
506
|
+
raw_params = op_raw.get("parameters") or []
|
|
507
|
+
raw_param_map: dict[tuple[str, str], dict] = {}
|
|
508
|
+
if isinstance(raw_params, list):
|
|
509
|
+
for p in raw_params:
|
|
510
|
+
if isinstance(p, dict) and p.get("name") and p.get("in"):
|
|
511
|
+
raw_param_map[(str(p.get("name")), str(p.get("in")))] = p
|
|
512
|
+
|
|
513
|
+
for param in op.spec.parameters or []:
|
|
514
|
+
param_name = str(param.name)
|
|
515
|
+
param_in_obj = getattr(param, "param_in", None)
|
|
516
|
+
# requests_openapi uses an enum-like value for `param_in`.
|
|
517
|
+
# For prompt quality and stable matching against raw spec, normalize to e.g. "query".
|
|
518
|
+
if hasattr(param_in_obj, "value"):
|
|
519
|
+
param_in = str(getattr(param_in_obj, "value"))
|
|
520
|
+
else:
|
|
521
|
+
param_in = str(param_in_obj)
|
|
522
|
+
raw_param = raw_param_map.get((param_name, param_in), {})
|
|
523
|
+
|
|
524
|
+
required = bool(raw_param.get("required", False))
|
|
525
|
+
schema = raw_param.get("schema") if isinstance(raw_param.get("schema"), dict) else None
|
|
526
|
+
py_type = _guess_python_type(schema)
|
|
527
|
+
|
|
528
|
+
example = raw_param.get("example")
|
|
529
|
+
if example is None and isinstance(schema, dict):
|
|
530
|
+
example = schema.get("example")
|
|
531
|
+
|
|
532
|
+
default = getattr(param.param_schema, "default", None)
|
|
533
|
+
desc = (param.description or "").strip()
|
|
534
|
+
desc = f"({param_in}) {desc}".strip()
|
|
535
|
+
type_hint = _schema_type_hint(schema)
|
|
536
|
+
if type_hint:
|
|
537
|
+
desc = f"{desc}\nType: {type_hint}".strip()
|
|
538
|
+
if required:
|
|
539
|
+
desc = f"{desc}\nRequired: true".strip()
|
|
540
|
+
if example is not None:
|
|
541
|
+
desc = f"{desc}\nExample: {example}".strip()
|
|
542
|
+
if default is not None:
|
|
543
|
+
desc = f"{desc}\nDefault: {default}".strip()
|
|
544
|
+
|
|
545
|
+
# Required fields have no default.
|
|
546
|
+
if required:
|
|
547
|
+
fields[param_name] = (py_type, Field(description=desc))
|
|
548
|
+
else:
|
|
549
|
+
fields[param_name] = (Optional[py_type], Field(default=default, description=desc))
|
|
550
|
+
|
|
551
|
+
# Additional headers not modeled in spec
|
|
552
|
+
fields["headers"] = (
|
|
553
|
+
Optional[dict],
|
|
554
|
+
Field(
|
|
555
|
+
default_factory=dict,
|
|
556
|
+
description=(
|
|
557
|
+
"Additional HTTP headers to include in this request. "
|
|
558
|
+
"These are merged with the toolkit/base headers (including auth headers). "
|
|
559
|
+
"Only add headers if the API requires them. "
|
|
560
|
+
"Provide a JSON object/dict. Example: {\"X-Trace-Id\": \"123\"}"
|
|
561
|
+
),
|
|
562
|
+
),
|
|
563
|
+
)
|
|
564
|
+
|
|
565
|
+
# Request body
|
|
566
|
+
request_body = op_raw.get("requestBody") if isinstance(op_raw.get("requestBody"), dict) else None
|
|
567
|
+
body_required = bool((request_body or {}).get("required", False))
|
|
568
|
+
body_example = _extract_request_body_example(self.spec, op_raw)
|
|
569
|
+
body_desc = (
|
|
570
|
+
"Request body (JSON) as a string. The tool will parse it with json.loads and send as the request JSON body."
|
|
571
|
+
)
|
|
572
|
+
if body_example:
|
|
573
|
+
body_desc = f"{body_desc}\nExample JSON:\n{body_example}"
|
|
574
|
+
if op.spec.requestBody:
|
|
575
|
+
if body_required:
|
|
576
|
+
fields["body_json"] = (str, Field(description=body_desc))
|
|
577
|
+
else:
|
|
578
|
+
fields["body_json"] = (Optional[str], Field(default=None, description=body_desc))
|
|
579
|
+
|
|
580
|
+
model_name = f"OpenApi_{clean_string(operation_id, max_length=40) or 'Operation'}_Params"
|
|
581
|
+
return create_model(
|
|
582
|
+
model_name,
|
|
583
|
+
regexp=(
|
|
584
|
+
Optional[str],
|
|
585
|
+
Field(
|
|
586
|
+
description="Regular expression to remove from the final output (optional)",
|
|
587
|
+
default=None,
|
|
588
|
+
),
|
|
589
|
+
),
|
|
590
|
+
**fields,
|
|
591
|
+
)
|
|
592
|
+
|
|
593
|
+
def get_available_tools(self, selected_tools: Optional[list[str]] = None) -> list[dict[str, Any]]:
|
|
594
|
+
if not selected_tools:
|
|
595
|
+
return list(self._tool_defs)
|
|
596
|
+
selected_set = {t for t in selected_tools if isinstance(t, str) and t}
|
|
597
|
+
return [t for t in self._tool_defs if t.get("name") in selected_set]
|
|
598
|
+
|
|
599
|
+
def run(self, mode: str, *args: Any, **kwargs: Any) -> str:
|
|
600
|
+
try:
|
|
601
|
+
ref = self._tool_ref_by_name[mode]
|
|
602
|
+
except KeyError:
|
|
603
|
+
_raise_openapi_tool_exception(
|
|
604
|
+
code="unknown_operation",
|
|
605
|
+
message=f"Unknown operation: {mode}",
|
|
606
|
+
details={"known_operations": sorted(list(self._tool_ref_by_name.keys()))[:200]},
|
|
607
|
+
)
|
|
608
|
+
return ref(*args, **kwargs)
|
|
609
|
+
|
|
610
|
+
def _get_required_inputs_from_raw_spec(self, operation_id: str) -> dict[str, Any]:
|
|
611
|
+
meta = self._op_meta.get(str(operation_id), {})
|
|
612
|
+
op_raw = meta.get("raw") if isinstance(meta, dict) and isinstance(meta.get("raw"), dict) else {}
|
|
613
|
+
|
|
614
|
+
required_path: list[str] = []
|
|
615
|
+
required_query: list[str] = []
|
|
616
|
+
raw_params = op_raw.get("parameters")
|
|
617
|
+
if isinstance(raw_params, list):
|
|
618
|
+
for p in raw_params:
|
|
619
|
+
if not isinstance(p, dict):
|
|
620
|
+
continue
|
|
621
|
+
name = p.get("name")
|
|
622
|
+
where = p.get("in")
|
|
623
|
+
required = bool(p.get("required", False))
|
|
624
|
+
if not required or not isinstance(name, str) or not isinstance(where, str):
|
|
625
|
+
continue
|
|
626
|
+
if where == "path":
|
|
627
|
+
required_path.append(name)
|
|
628
|
+
elif where == "query":
|
|
629
|
+
required_query.append(name)
|
|
630
|
+
|
|
631
|
+
req_body = False
|
|
632
|
+
rb = op_raw.get("requestBody")
|
|
633
|
+
if isinstance(rb, dict):
|
|
634
|
+
req_body = bool(rb.get("required", False))
|
|
635
|
+
|
|
636
|
+
return {
|
|
637
|
+
"required_path": required_path,
|
|
638
|
+
"required_query": required_query,
|
|
639
|
+
"required_body": req_body,
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
def get_operation_request_url(self, operation_id: str, params: dict[str, Any]) -> str:
|
|
643
|
+
"""Best-effort resolved URL for debugging/prompt-quality inspection.
|
|
644
|
+
|
|
645
|
+
This does not execute the request.
|
|
646
|
+
"""
|
|
647
|
+
meta = self._op_meta.get(str(operation_id), {})
|
|
648
|
+
path = meta.get("path") if isinstance(meta, dict) else None
|
|
649
|
+
if not isinstance(path, str):
|
|
650
|
+
return ""
|
|
651
|
+
base_url = _get_base_url_from_spec(self.spec)
|
|
652
|
+
url = _join_base_and_path(base_url, path)
|
|
653
|
+
|
|
654
|
+
# Substitute {pathParams}
|
|
655
|
+
for k, v in (params or {}).items():
|
|
656
|
+
placeholder = "{" + str(k) + "}"
|
|
657
|
+
if placeholder in url:
|
|
658
|
+
url = url.replace(placeholder, str(v))
|
|
659
|
+
|
|
660
|
+
# Add query params if present.
|
|
661
|
+
query: dict[str, Any] = {}
|
|
662
|
+
try:
|
|
663
|
+
op = self._client.operations[str(operation_id)]
|
|
664
|
+
if isinstance(op, Operation):
|
|
665
|
+
for p in op.spec.parameters or []:
|
|
666
|
+
p_in_obj = getattr(p, "param_in", None)
|
|
667
|
+
p_in = str(getattr(p_in_obj, "value", p_in_obj))
|
|
668
|
+
if p_in != "query":
|
|
669
|
+
continue
|
|
670
|
+
name = str(p.name)
|
|
671
|
+
if name in (params or {}) and (params or {}).get(name) is not None:
|
|
672
|
+
query[name] = (params or {})[name]
|
|
673
|
+
except Exception:
|
|
674
|
+
query = {}
|
|
675
|
+
|
|
676
|
+
if query:
|
|
677
|
+
url = url + "?" + urlencode(query, doseq=True)
|
|
678
|
+
return url
|
|
679
|
+
|
|
680
|
+
def _execute(self, operation_id: str, *args: Any, **kwargs: Any) -> str:
|
|
681
|
+
regexp = kwargs.pop("regexp", None)
|
|
682
|
+
extra_headers = kwargs.pop("headers", None)
|
|
683
|
+
|
|
684
|
+
if extra_headers is not None and not isinstance(extra_headers, dict):
|
|
685
|
+
_raise_openapi_tool_exception(
|
|
686
|
+
code="invalid_headers",
|
|
687
|
+
message="'headers' must be a dict",
|
|
688
|
+
operation_id=str(operation_id),
|
|
689
|
+
details={"provided_type": str(type(extra_headers))},
|
|
690
|
+
)
|
|
691
|
+
|
|
692
|
+
# Preferred: body_json (string) -> parsed object -> Operation json=
|
|
693
|
+
if "body_json" in kwargs and kwargs.get("body_json") is not None:
|
|
694
|
+
raw_json = kwargs.pop("body_json")
|
|
695
|
+
if isinstance(raw_json, str):
|
|
696
|
+
try:
|
|
697
|
+
kwargs["json"] = json.loads(raw_json)
|
|
698
|
+
except Exception as e:
|
|
699
|
+
_raise_openapi_tool_exception(
|
|
700
|
+
code="invalid_json_body",
|
|
701
|
+
message=f"Invalid JSON body: {e}",
|
|
702
|
+
operation_id=str(operation_id),
|
|
703
|
+
details={"hint": "Ensure body_json is valid JSON (double quotes, no trailing commas)."},
|
|
704
|
+
)
|
|
705
|
+
else:
|
|
706
|
+
kwargs["json"] = raw_json
|
|
707
|
+
|
|
708
|
+
# Backward compatible: accept `json` as a string too.
|
|
709
|
+
if "json" in kwargs and isinstance(kwargs.get("json"), str):
|
|
710
|
+
try:
|
|
711
|
+
kwargs["json"] = json.loads(kwargs["json"])
|
|
712
|
+
except Exception as e:
|
|
713
|
+
_raise_openapi_tool_exception(
|
|
714
|
+
code="invalid_json_body",
|
|
715
|
+
message=f"Invalid JSON body: {e}",
|
|
716
|
+
operation_id=str(operation_id),
|
|
717
|
+
details={"hint": "If you pass `json` as a string, it must be valid JSON."},
|
|
718
|
+
)
|
|
719
|
+
|
|
720
|
+
try:
|
|
721
|
+
op = self._client.operations[operation_id]
|
|
722
|
+
except Exception:
|
|
723
|
+
_raise_openapi_tool_exception(
|
|
724
|
+
code="operation_not_found",
|
|
725
|
+
message=f"Operation '{operation_id}' not found in OpenAPI spec",
|
|
726
|
+
operation_id=str(operation_id),
|
|
727
|
+
)
|
|
728
|
+
if not isinstance(op, Operation):
|
|
729
|
+
_raise_openapi_tool_exception(
|
|
730
|
+
code="invalid_operation",
|
|
731
|
+
message=f"Operation '{operation_id}' is not a valid OpenAPI operation",
|
|
732
|
+
operation_id=str(operation_id),
|
|
733
|
+
)
|
|
734
|
+
|
|
735
|
+
# Best-effort URL reconstruction for error context.
|
|
736
|
+
debug_url = ""
|
|
737
|
+
try:
|
|
738
|
+
debug_url = self.get_operation_request_url(operation_id, dict(kwargs))
|
|
739
|
+
except Exception:
|
|
740
|
+
debug_url = ""
|
|
741
|
+
|
|
742
|
+
# Preflight required input checks (helps LLM recover without needing spec knowledge).
|
|
743
|
+
missing: list[str] = []
|
|
744
|
+
required_info = self._get_required_inputs_from_raw_spec(str(operation_id))
|
|
745
|
+
for name in required_info.get("required_path", []) or []:
|
|
746
|
+
if name not in kwargs or kwargs.get(name) is None:
|
|
747
|
+
missing.append(name)
|
|
748
|
+
for name in required_info.get("required_query", []) or []:
|
|
749
|
+
if name not in kwargs or kwargs.get(name) is None:
|
|
750
|
+
missing.append(name)
|
|
751
|
+
if bool(required_info.get("required_body")) and kwargs.get("json") is None:
|
|
752
|
+
missing.append("body_json")
|
|
753
|
+
|
|
754
|
+
# Also check for unresolved {param} placeholders in the path.
|
|
755
|
+
meta = self._op_meta.get(str(operation_id), {})
|
|
756
|
+
path = meta.get("path") if isinstance(meta, dict) else None
|
|
757
|
+
if isinstance(path, str):
|
|
758
|
+
for placeholder in re.findall(r"\{([^}]+)\}", path):
|
|
759
|
+
if placeholder and (placeholder not in kwargs or kwargs.get(placeholder) is None):
|
|
760
|
+
missing.append(str(placeholder))
|
|
761
|
+
|
|
762
|
+
if missing:
|
|
763
|
+
_raise_openapi_tool_exception(
|
|
764
|
+
code="missing_required_inputs",
|
|
765
|
+
message=f"Missing required inputs for operation '{operation_id}': {', '.join(sorted(set(missing)))}",
|
|
766
|
+
operation_id=str(operation_id),
|
|
767
|
+
url=debug_url or None,
|
|
768
|
+
retryable=True,
|
|
769
|
+
missing_inputs=sorted(set(missing)),
|
|
770
|
+
details={"hint": "Provide the missing fields and retry the same operation."},
|
|
771
|
+
)
|
|
772
|
+
|
|
773
|
+
# Preflight base URL check: requests_openapi needs an absolute server URL to execute HTTP.
|
|
774
|
+
base_url = _get_base_url_from_spec(self.spec)
|
|
775
|
+
if not base_url or not _is_absolute_url(base_url):
|
|
776
|
+
servers = self.spec.get("servers") if isinstance(self.spec, dict) else None
|
|
777
|
+
server_url = None
|
|
778
|
+
if isinstance(servers, list) and servers and isinstance(servers[0], dict):
|
|
779
|
+
server_url = servers[0].get("url")
|
|
780
|
+
|
|
781
|
+
_raise_openapi_tool_exception(
|
|
782
|
+
code="missing_base_url",
|
|
783
|
+
message=(
|
|
784
|
+
"Cannot execute HTTP request because the OpenAPI spec does not contain an absolute server URL. "
|
|
785
|
+
"Provide `base_url_override`/`base_url` in the toolkit settings (e.g. 'https://host') "
|
|
786
|
+
"or update `servers[0].url` to an absolute URL (https://...)."
|
|
787
|
+
),
|
|
788
|
+
operation_id=str(operation_id),
|
|
789
|
+
url=debug_url or None,
|
|
790
|
+
retryable=False,
|
|
791
|
+
details={
|
|
792
|
+
"servers_0_url": server_url,
|
|
793
|
+
"computed_base_url": base_url,
|
|
794
|
+
"hint": "If servers[0].url is relative like '/api/v3', set base_url_override to the host (e.g. 'https://petstore3.swagger.io').",
|
|
795
|
+
},
|
|
796
|
+
)
|
|
797
|
+
|
|
798
|
+
# Apply per-call extra headers (best-effort) without permanently mutating global headers.
|
|
799
|
+
old_headers = dict(getattr(self._client.requestor, "headers", {}) or {})
|
|
800
|
+
try:
|
|
801
|
+
if extra_headers:
|
|
802
|
+
self._client.requestor.headers.update({str(k): str(v) for k, v in extra_headers.items()})
|
|
803
|
+
response = op(*args, **kwargs)
|
|
804
|
+
except Exception as e:
|
|
805
|
+
_raise_openapi_tool_exception(
|
|
806
|
+
code="request_failed",
|
|
807
|
+
message=f"OpenAPI request failed for operation '{operation_id}': {e}",
|
|
808
|
+
operation_id=str(operation_id),
|
|
809
|
+
url=debug_url or None,
|
|
810
|
+
retryable=True,
|
|
811
|
+
details={"exception": repr(e)},
|
|
812
|
+
)
|
|
813
|
+
finally:
|
|
814
|
+
try:
|
|
815
|
+
self._client.requestor.headers.clear()
|
|
816
|
+
self._client.requestor.headers.update(old_headers)
|
|
817
|
+
except Exception:
|
|
818
|
+
pass
|
|
819
|
+
|
|
820
|
+
# If this looks like a requests.Response, raise on HTTP errors with actionable context.
|
|
821
|
+
status_code = getattr(response, "status_code", None)
|
|
822
|
+
if isinstance(status_code, int) and status_code >= 400:
|
|
823
|
+
body_preview = ""
|
|
824
|
+
for attr in ("text", "content", "data"):
|
|
825
|
+
if hasattr(response, attr):
|
|
826
|
+
body_preview = _normalize_output(getattr(response, attr))
|
|
827
|
+
break
|
|
828
|
+
body_preview = _truncate(body_preview, 2000)
|
|
829
|
+
retryable = _is_retryable_http_status(status_code)
|
|
830
|
+
|
|
831
|
+
hint = ""
|
|
832
|
+
if status_code in (401, 403):
|
|
833
|
+
hint = "Authentication/authorization failed. Verify toolkit authentication settings / base headers."
|
|
834
|
+
elif status_code == 404:
|
|
835
|
+
hint = "Resource not found. Check path parameters and identifiers."
|
|
836
|
+
elif status_code == 400:
|
|
837
|
+
hint = "Bad request. Check required parameters and request body schema."
|
|
838
|
+
elif status_code == 415:
|
|
839
|
+
hint = "Unsupported media type. The API may require Content-Type headers."
|
|
840
|
+
elif status_code == 429:
|
|
841
|
+
hint = "Rate limited. Retry after a short delay."
|
|
842
|
+
|
|
843
|
+
_raise_openapi_tool_exception(
|
|
844
|
+
code="http_error",
|
|
845
|
+
message=f"OpenAPI request failed with HTTP {status_code} for operation '{operation_id}'",
|
|
846
|
+
operation_id=str(operation_id),
|
|
847
|
+
url=debug_url or None,
|
|
848
|
+
retryable=retryable,
|
|
849
|
+
http_status=status_code,
|
|
850
|
+
http_body_preview=body_preview,
|
|
851
|
+
details={"hint": hint} if hint else None,
|
|
852
|
+
)
|
|
853
|
+
|
|
854
|
+
output = None
|
|
855
|
+
for attr in ("content", "data", "text"):
|
|
856
|
+
if hasattr(response, attr):
|
|
857
|
+
output = getattr(response, attr)
|
|
858
|
+
break
|
|
859
|
+
if output is None:
|
|
860
|
+
output = response
|
|
861
|
+
|
|
862
|
+
output_str = _normalize_output(output)
|
|
863
|
+
|
|
864
|
+
if regexp:
|
|
865
|
+
try:
|
|
866
|
+
output_str = re.sub(rf"{regexp}", "", output_str)
|
|
867
|
+
except Exception as e:
|
|
868
|
+
logger.debug(f"Failed to apply regexp filter: {e}")
|
|
869
|
+
|
|
870
|
+
return output_str
|
|
871
|
+
|
|
872
|
+
|
|
873
|
+
def build_wrapper(
|
|
874
|
+
openapi_spec: str | dict,
|
|
875
|
+
base_headers: Optional[dict[str, str]] = None,
|
|
876
|
+
base_url_override: Optional[str] = None,
|
|
877
|
+
) -> OpenApiApiWrapper:
|
|
878
|
+
parsed = _parse_openapi_spec(openapi_spec)
|
|
879
|
+
# Avoid mutating caller-owned spec dict.
|
|
880
|
+
spec = copy.deepcopy(parsed)
|
|
881
|
+
if base_url_override:
|
|
882
|
+
spec = _apply_base_url_override(spec, base_url_override)
|
|
883
|
+
return OpenApiApiWrapper(spec=spec, base_headers=base_headers or {})
|