forked from openai/chatkit-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathactions.py
More file actions
53 lines (40 loc) · 1.5 KB
/
Copy pathactions.py
File metadata and controls
53 lines (40 loc) · 1.5 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
from __future__ import annotations
from typing import Any, Generic, Literal, TypeVar, get_args, get_origin
from pydantic import BaseModel, Field
Handler = Literal["client", "server"]
LoadingBehavior = Literal["auto", "none", "self", "container"]
DEFAULT_HANDLER: Handler = "server"
DEFAULT_LOADING_BEHAVIOR: LoadingBehavior = "auto"
class ActionConfig(BaseModel):
type: str
payload: Any = None
handler: Handler = DEFAULT_HANDLER
loadingBehavior: LoadingBehavior = DEFAULT_LOADING_BEHAVIOR
TType = TypeVar("TType", bound=str)
TPayload = TypeVar("TPayload")
class Action(BaseModel, Generic[TType, TPayload]):
type: TType = Field(default=TType, frozen=True) # pyright: ignore
payload: TPayload
@classmethod
def create(
cls,
payload: TPayload,
handler: Handler = DEFAULT_HANDLER,
loading_behavior: LoadingBehavior = DEFAULT_LOADING_BEHAVIOR,
) -> ActionConfig:
actionType: Any = None
anno = cls.model_fields["type"].annotation
if get_origin(anno) is Literal:
lits = get_args(anno)
if len(lits) == 1 and isinstance(lits[0], str):
actionType = lits[0]
if actionType is None:
raise TypeError(
"Cannot infer 'type' for this Action[...]. Do not call create() on generic Action."
)
return ActionConfig(
type=actionType,
payload=payload,
handler=handler,
loadingBehavior=loading_behavior,
)