forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaction.py
More file actions
57 lines (43 loc) · 1.56 KB
/
Copy pathaction.py
File metadata and controls
57 lines (43 loc) · 1.56 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
"""Actions"""
import re
from inspect import iscoroutinefunction
from typing import Optional, List, Callable, TypedDict, Any, cast
from .parameter import Parameter, normalize_parameters
class ActionDict(TypedDict):
"""Dict representation of an action"""
name: str
description: str
parameters: List[Parameter]
class ActionResultDict(TypedDict):
"""Dict representation of an action result"""
result: Any
class Action: # pylint: disable=too-few-public-methods
"""Action class for CopilotKit"""
def __init__(
self,
*,
name: str,
handler: Callable,
description: Optional[str] = None,
parameters: Optional[List[Parameter]] = None,
):
self.name = name
self.description = description
self.parameters = parameters
self.handler = handler
if not re.match(r"^[a-zA-Z0-9_-]+$", name):
raise ValueError(
f"Invalid action name '{name}': "
+ "must consist of alphanumeric characters, underscores, and hyphens only"
)
async def execute(self, *, arguments: dict) -> ActionResultDict:
"""Execute the action"""
result = self.handler(**arguments)
return {"result": await result if iscoroutinefunction(self.handler) else result}
def dict_repr(self) -> ActionDict:
"""Dict representation of the action"""
return {
"name": self.name,
"description": self.description or "",
"parameters": normalize_parameters(cast(Any, self.parameters)),
}