-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodels.py
More file actions
688 lines (544 loc) · 23 KB
/
models.py
File metadata and controls
688 lines (544 loc) · 23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
from __future__ import annotations
import base64
import json
import logging
from collections.abc import Sequence
from datetime import datetime, timezone
from enum import Enum
from typing import Annotated, Any, ClassVar, TypeAlias, cast
from urllib.parse import quote
import httpx
from langchain_core.tools import BaseTool
from pydantic import BaseModel, BeforeValidator, Field, PrivateAttr
# Type aliases for common types
JsonDict: TypeAlias = dict[str, Any]
Headers: TypeAlias = dict[str, str]
logger = logging.getLogger("stackone.tools")
class StackOneError(Exception):
"""Base exception for StackOne errors"""
pass
class StackOneAPIError(StackOneError):
"""Raised when the StackOne API returns an error"""
def __init__(self, message: str, status_code: int, response_body: Any) -> None:
super().__init__(message)
self.status_code = status_code
self.response_body = response_body
class ParameterLocation(str, Enum):
"""Valid locations for parameters in requests"""
HEADER = "header"
QUERY = "query"
PATH = "path"
BODY = "body"
FILE = "file" # For file uploads
def validate_method(v: str) -> str:
"""Validate HTTP method is uppercase and supported"""
method = v.upper()
if method not in {"GET", "POST", "PUT", "DELETE", "PATCH"}:
raise ValueError(f"Unsupported HTTP method: {method}")
return method
class ExecuteConfig(BaseModel):
"""Configuration for executing a tool against an API endpoint"""
headers: Headers = Field(default_factory=dict, description="HTTP headers to include in the request")
method: Annotated[str, BeforeValidator(validate_method)] = Field(description="HTTP method to use")
url: str = Field(description="API endpoint URL")
name: str = Field(description="Tool name")
body_type: str | None = Field(default=None, description="Content type for request body")
parameter_locations: dict[str, ParameterLocation] = Field(
default_factory=dict, description="Maps parameter names to their location in the request"
)
class ToolParameters(BaseModel):
"""Schema definition for tool parameters"""
type: str = Field(description="JSON Schema type")
properties: JsonDict = Field(description="JSON Schema properties")
class ToolDefinition(BaseModel):
"""Complete definition of a tool including its schema and execution config"""
description: str = Field(description="Tool description")
parameters: ToolParameters = Field(description="Tool parameter schema")
execute: ExecuteConfig = Field(description="Tool execution configuration")
class StackOneTool(BaseModel):
"""Base class for all StackOne tools. Provides functionality for executing API calls
and converting to various formats (OpenAI, LangChain)."""
name: str = Field(description="Tool name")
description: str = Field(description="Tool description")
parameters: ToolParameters = Field(description="Tool parameters")
_execute_config: ExecuteConfig = PrivateAttr()
_api_key: str = PrivateAttr()
_account_id: str | None = PrivateAttr(default=None)
_FEEDBACK_OPTION_KEYS: ClassVar[set[str]] = {
"feedback_session_id",
"feedback_user_id",
"feedback_metadata",
}
@property
def connector(self) -> str:
"""Extract connector from tool name.
Tool names follow the format: {connector}_{action}_{entity}
e.g., 'bamboohr_create_employee' -> 'bamboohr'
Returns:
Connector name in lowercase
"""
return self.name.split("_")[0].lower()
def __init__(
self,
description: str,
parameters: ToolParameters,
_execute_config: ExecuteConfig,
_api_key: str,
_account_id: str | None = None,
) -> None:
super().__init__(
name=_execute_config.name,
description=description,
parameters=parameters,
)
self._execute_config = _execute_config
self._api_key = _api_key
self._account_id = _account_id
@classmethod
def _split_feedback_options(cls, params: JsonDict, options: JsonDict | None) -> tuple[JsonDict, JsonDict]:
merged_params = dict(params)
feedback_options = dict(options or {})
for key in cls._FEEDBACK_OPTION_KEYS:
if key in merged_params and key not in feedback_options:
feedback_options[key] = merged_params.pop(key)
return merged_params, feedback_options
def _prepare_headers(self) -> Headers:
"""Prepare headers for the API request
Returns:
Headers to use in the request
"""
auth_string = base64.b64encode(f"{self._api_key}:".encode()).decode()
headers: Headers = {
"Authorization": f"Basic {auth_string}",
"User-Agent": "stackone-python/1.0.0",
}
if self._account_id:
headers["x-account-id"] = self._account_id
# Add predefined headers
headers.update(self._execute_config.headers)
return headers
def _prepare_request_params(self, kwargs: JsonDict) -> tuple[str, JsonDict, JsonDict]:
"""Prepare URL and parameters for the API request
Args:
kwargs: Arguments to process
Returns:
Tuple of (url, body_params, query_params)
"""
url = self._execute_config.url
body_params: JsonDict = {}
query_params: JsonDict = {}
for key, value in kwargs.items():
param_location = self._execute_config.parameter_locations.get(key)
if param_location == ParameterLocation.PATH:
# Safely encode path parameters to prevent SSRF attacks
encoded_value = quote(str(value), safe="")
url = url.replace(f"{{{key}}}", encoded_value)
elif param_location == ParameterLocation.QUERY:
query_params[key] = value
elif param_location in (ParameterLocation.BODY, ParameterLocation.FILE):
body_params[key] = value
else:
# Default behavior
if f"{{{key}}}" in url:
# Safely encode path parameters to prevent SSRF attacks
encoded_value = quote(str(value), safe="")
url = url.replace(f"{{{key}}}", encoded_value)
elif self._execute_config.method in {"GET", "DELETE"}:
query_params[key] = value
else:
body_params[key] = value
return url, body_params, query_params
def execute(
self, arguments: str | JsonDict | None = None, *, options: JsonDict | None = None
) -> JsonDict:
"""Execute the tool with the given parameters
Args:
arguments: Tool arguments as string or dict
options: Execution options (e.g. feedback metadata)
Returns:
API response as dict
Raises:
StackOneAPIError: If the API request fails
ValueError: If the arguments are invalid
"""
datetime.now(timezone.utc)
feedback_options: JsonDict = {}
result_payload: JsonDict | None = None
response_status: int | None = None
error_message: str | None = None
status = "success"
url_used = self._execute_config.url
try:
if isinstance(arguments, str):
parsed_arguments = json.loads(arguments)
else:
parsed_arguments = arguments or {}
if not isinstance(parsed_arguments, dict):
status = "error"
error_message = "Tool arguments must be a JSON object"
raise ValueError(error_message)
kwargs = parsed_arguments
dict(kwargs)
headers = self._prepare_headers()
url_used, body_params, query_params = self._prepare_request_params(kwargs)
request_kwargs: dict[str, Any] = {
"method": self._execute_config.method,
"url": url_used,
"headers": headers,
}
if body_params:
body_type = self._execute_config.body_type or "json"
if body_type == "json":
request_kwargs["json"] = body_params
elif body_type == "form":
request_kwargs["data"] = body_params
if query_params:
request_kwargs["params"] = query_params
response = httpx.request(**request_kwargs)
response_status = response.status_code
response.raise_for_status()
result = response.json()
result_payload = cast(JsonDict, result) if isinstance(result, dict) else {"result": result}
return result_payload
except json.JSONDecodeError as exc:
status = "error"
error_message = f"Invalid JSON in arguments: {exc}"
raise ValueError(error_message) from exc
except httpx.HTTPStatusError as exc:
status = "error"
response_body = None
if exc.response.text:
try:
response_body = exc.response.json()
except json.JSONDecodeError:
response_body = exc.response.text
raise StackOneAPIError(
str(exc),
exc.response.status_code,
response_body,
) from exc
except httpx.RequestError as exc:
status = "error"
raise StackOneError(f"Request failed: {exc}") from exc
finally:
datetime.now(timezone.utc)
metadata: JsonDict = {
"http_method": self._execute_config.method,
"url": url_used,
"status_code": response_status,
"status": status,
}
feedback_metadata = feedback_options.get("feedback_metadata")
if isinstance(feedback_metadata, dict):
metadata["feedback_metadata"] = feedback_metadata
if feedback_options:
metadata["feedback_options"] = {
key: value
for key, value in feedback_options.items()
if key in {"feedback_session_id", "feedback_user_id"} and value is not None
}
# Implicit feedback removed - just API calls
def call(self, *args: Any, options: JsonDict | None = None, **kwargs: Any) -> JsonDict:
"""Call the tool with the given arguments
This method provides a more intuitive way to execute tools directly.
Args:
*args: If a single argument is provided, it's treated as the full arguments dict/string
**kwargs: Keyword arguments to pass to the tool
options: Optional execution options
Returns:
API response as dict
Raises:
StackOneAPIError: If the API request fails
ValueError: If the arguments are invalid
Examples:
>>> tool.call({"name": "John", "email": "john@example.com"})
>>> tool.call(name="John", email="john@example.com")
"""
if args and kwargs:
raise ValueError("Cannot provide both positional and keyword arguments")
if args:
if len(args) > 1:
raise ValueError("Only one positional argument is allowed")
return self.execute(args[0])
return self.execute(kwargs if kwargs else None)
def __call__(self, *args: Any, options: JsonDict | None = None, **kwargs: Any) -> JsonDict:
"""Make the tool directly callable.
Alias for :meth:`call` so that ``tool(query="…")`` works.
"""
return self.call(*args, options=options, **kwargs)
def _build_json_schema(self) -> JsonDict:
"""Build a standard JSON Schema dict for this tool's parameters.
Computes ``required`` from ``nullable`` flags on each property
(same convention used by the MCP schema normaliser and the ADK plugin)
and strips the internal ``nullable`` key from the output.
Returns:
JSON Schema dict with ``type``, ``properties``, and optionally ``required``.
"""
clean_properties: JsonDict = {}
required: list[str] = []
for name, prop in self.parameters.properties.items():
if isinstance(prop, dict):
clean_properties[name] = {k: v for k, v in prop.items() if k != "nullable"}
if not prop.get("nullable", False):
required.append(name)
else:
clean_properties[name] = {"type": "string"}
required.append(name)
schema: JsonDict = {"type": self.parameters.type, "properties": clean_properties}
if required:
schema["required"] = required
return schema
def to_openai_function(self) -> JsonDict:
"""Convert this tool to OpenAI's function format
Returns:
Tool definition in OpenAI function format
"""
# Clean properties and handle special types
properties = {}
required = []
for name, prop in self.parameters.properties.items():
if isinstance(prop, dict):
# Only keep standard JSON Schema properties
cleaned_prop = {}
# Copy basic properties
if "type" in prop:
cleaned_prop["type"] = prop["type"]
if "description" in prop:
cleaned_prop["description"] = prop["description"]
if "enum" in prop:
cleaned_prop["enum"] = prop["enum"]
# Handle array types
if cleaned_prop.get("type") == "array" and "items" in prop:
if isinstance(prop["items"], dict):
cleaned_prop["items"] = {
k: v for k, v in prop["items"].items() if k in ("type", "description", "enum")
}
# Handle object types
if cleaned_prop.get("type") == "object" and "properties" in prop:
cleaned_prop["properties"] = {
k: {sk: sv for sk, sv in v.items() if sk in ("type", "description", "enum")}
for k, v in prop["properties"].items()
}
# Handle required fields - if not explicitly nullable
if not prop.get("nullable", False):
required.append(name)
properties[name] = cleaned_prop
else:
properties[name] = {"type": "string"}
required.append(name)
# Create the OpenAI function schema
parameters = {
"type": "object",
"properties": properties,
}
# Only include required if there are required fields
if required:
parameters["required"] = required
return {
"type": "function",
"function": {
"name": self.name,
"description": self.description,
"parameters": parameters,
},
}
def to_langchain(self) -> BaseTool:
"""Convert this tool to LangChain format
Returns:
Tool in LangChain format
"""
# Create properly annotated schema for the tool
schema_props: dict[str, Any] = {}
annotations: dict[str, Any] = {}
for name, details in self.parameters.properties.items():
python_type: type = str # Default to str
if isinstance(details, dict):
type_str = details.get("type", "string")
if type_str == "number":
python_type = float
elif type_str == "integer":
python_type = int
elif type_str == "boolean":
python_type = bool
field = Field(description=details.get("description", ""))
else:
field = Field(description="")
schema_props[name] = field
annotations[name] = python_type
# Create the schema class with proper annotations
schema_class = type(
f"{self.name.title()}Args",
(BaseModel,),
{
"__annotations__": annotations,
"__module__": __name__,
**schema_props,
},
)
parent_tool = self
class StackOneLangChainTool(BaseTool):
name: str = parent_tool.name
description: str = parent_tool.description
args_schema: type[BaseModel] = schema_class # ty: ignore[invalid-assignment]
func = staticmethod(parent_tool.execute) # Required by CrewAI
def _run(self, **kwargs: Any) -> Any:
return parent_tool.execute(kwargs)
return StackOneLangChainTool()
def to_pydantic_ai(self) -> Any:
"""Convert this tool to a native Pydantic AI Tool.
Returns a ``pydantic_ai.Tool`` created via ``Tool.from_schema()``
with the tool's JSON Schema and execution function.
Returns:
pydantic_ai.Tool instance
Raises:
ImportError: If pydantic-ai is not installed
"""
try:
from pydantic_ai import Tool
except ImportError:
raise ImportError(
"pydantic-ai is required for to_pydantic_ai(). Install with: pip install pydantic-ai"
) from None
return Tool.from_schema(
function=self.execute,
name=self.name,
description=self.description,
json_schema=self._build_json_schema(),
)
def to_adk(self) -> Any:
"""Convert this tool to a native Google ADK BaseTool.
Returns an ADK ``BaseTool`` subclass that wraps this tool's
execution via ``run_async()`` and provides a ``FunctionDeclaration``
with the correct JSON Schema.
Returns:
google.adk.tools.BaseTool instance
Raises:
ImportError: If google-adk is not installed
"""
try:
from google.adk.tools import BaseTool as AdkBaseTool
from google.adk.tools import ToolContext
from google.genai import types
except ImportError:
raise ImportError(
"google-adk is required for to_adk(). Install with: pip install google-adk"
) from None
parent_tool = self
json_schema = self._build_json_schema()
class _StackOneAdkTool(AdkBaseTool):
def __init__(self) -> None:
super().__init__(name=parent_tool.name, description=parent_tool.description)
def _get_declaration(self) -> types.FunctionDeclaration:
if not json_schema.get("properties"):
return types.FunctionDeclaration(name=self.name, description=self.description)
return types.FunctionDeclaration(
name=self.name,
description=self.description,
parameters_json_schema=json_schema,
)
async def run_async(self, *, args: dict[str, Any], tool_context: ToolContext) -> Any:
import asyncio
loop = asyncio.get_running_loop()
result = await loop.run_in_executor(None, parent_tool.execute, args)
return result if isinstance(result, dict) else {"result": result}
return _StackOneAdkTool()
def set_account_id(self, account_id: str | None) -> None:
"""Set the account ID for this tool
Args:
account_id: The account ID to use, or None to clear it
"""
self._account_id = account_id
def get_account_id(self) -> str | None:
"""Get the current account ID for this tool
Returns:
Current account ID or None if not set
"""
return self._account_id
class Tools:
"""Container for Tool instances with lookup capabilities"""
def __init__(
self,
tools: list[StackOneTool],
) -> None:
"""Initialize Tools container
Args:
tools: List of Tool instances to manage
"""
self.tools = tools
self._tool_map = {tool.name: tool for tool in tools}
def __getitem__(self, index: int) -> StackOneTool:
return self.tools[index]
def __len__(self) -> int:
return len(self.tools)
def __iter__(self) -> Any:
"""Make Tools iterable"""
return iter(self.tools)
def to_list(self) -> list[StackOneTool]:
"""Convert to list of tools
Returns:
List of StackOneTool instances
"""
return list(self.tools)
def get_tool(self, name: str) -> StackOneTool | None:
"""Get a tool by its name
Args:
name: Name of the tool to retrieve
Returns:
The tool if found, None otherwise
"""
return self._tool_map.get(name)
def set_account_id(self, account_id: str | None) -> None:
"""Set the account ID for all tools in this collection
Args:
account_id: The account ID to use, or None to clear it
"""
for tool in self.tools:
tool.set_account_id(account_id)
def get_account_id(self) -> str | None:
"""Get the current account ID for this collection
Returns:
The first non-None account ID found, or None if none set
"""
for tool in self.tools:
account_id = tool.get_account_id()
if isinstance(account_id, str):
return account_id
return None
def get_connectors(self) -> set[str]:
"""Get unique connector names from all tools.
Returns:
Set of connector names (lowercase)
Example:
tools = toolset.fetch_tools()
connectors = tools.get_connectors()
# {'bamboohr', 'hibob', 'slack', ...}
"""
return {tool.connector for tool in self.tools}
def to_openai(self) -> list[JsonDict]:
"""Convert all tools to OpenAI function format
Returns:
List of tools in OpenAI function format
"""
return [tool.to_openai_function() for tool in self.tools]
def to_langchain(self) -> Sequence[BaseTool]:
"""Convert all tools to LangChain format
Returns:
Sequence of tools in LangChain format
"""
return [tool.to_langchain() for tool in self.tools]
def to_pydantic_ai(self) -> list[Any]:
"""Convert all tools to native Pydantic AI Tools.
Returns:
List of pydantic_ai.Tool instances
Raises:
ImportError: If pydantic-ai is not installed
"""
return [tool.to_pydantic_ai() for tool in self.tools]
def to_adk(self) -> list[Any]:
"""Convert all tools to native Google ADK BaseTools.
Returns:
List of google.adk.tools.BaseTool instances
Raises:
ImportError: If google-adk is not installed
"""
return [tool.to_adk() for tool in self.tools]