openai/chatkit-python
Publicmirrored from https://github.com/openai/chatkit-pythonAvailable
chatkit/actions.py
63lines · modeblame
f688d870victor-openai8 months ago | 1 | from __future__ import annotations |
| 2 | | |
| 3 | from typing import Any, Generic, Literal, TypeVar, get_args, get_origin | |
| 4 | | |
| 5 | from pydantic import BaseModel, Field | |
69ea9ef8Jiwon Kim7 months ago | 6 | from typing_extensions import deprecated |
f688d870victor-openai8 months ago | 7 | |
| 8 | Handler = Literal["client", "server"] | |
| 9 | LoadingBehavior = Literal["auto", "none", "self", "container"] | |
| 10 | | |
| 11 | DEFAULT_HANDLER: Handler = "server" | |
| 12 | DEFAULT_LOADING_BEHAVIOR: LoadingBehavior = "auto" | |
| 13 | | |
| 14 | | |
1b15f7deJiwon Kim7 months ago | 15 | _direct_usage_of_action_classes_deprecated = deprecated( |
| 16 | "Direct usage of named action classes is deprecated. " | |
| 17 | "Use WidgetTemplate to build widgets from .widget files instead. " | |
| 18 | "Visit https://widgets.chatkit.studio/ to author widget files." | |
69ea9ef8Jiwon Kim7 months ago | 19 | ) |
| 20 | | |
| 21 | | |
1b15f7deJiwon Kim7 months ago | 22 | @_direct_usage_of_action_classes_deprecated |
f688d870victor-openai8 months ago | 23 | class ActionConfig(BaseModel): |
| 24 | type: str | |
| 25 | payload: Any = None | |
| 26 | handler: Handler = DEFAULT_HANDLER | |
| 27 | loadingBehavior: LoadingBehavior = DEFAULT_LOADING_BEHAVIOR | |
| 28 | | |
| 29 | | |
| 30 | TType = TypeVar("TType", bound=str) | |
| 31 | TPayload = TypeVar("TPayload") | |
| 32 | | |
| 33 | | |
1b15f7deJiwon Kim7 months ago | 34 | @_direct_usage_of_action_classes_deprecated |
f688d870victor-openai8 months ago | 35 | class Action(BaseModel, Generic[TType, TPayload]): |
| 36 | type: TType = Field(default=TType, frozen=True) # pyright: ignore | |
367da6d8David Weedon7 months ago | 37 | payload: TPayload = None # pyright: ignore - default to None to allow no-payload actions |
f688d870victor-openai8 months ago | 38 | |
| 39 | @classmethod | |
| 40 | def create( | |
| 41 | cls, | |
| 42 | payload: TPayload, | |
| 43 | handler: Handler = DEFAULT_HANDLER, | |
| 44 | loading_behavior: LoadingBehavior = DEFAULT_LOADING_BEHAVIOR, | |
| 45 | ) -> ActionConfig: | |
| 46 | actionType: Any = None | |
| 47 | anno = cls.model_fields["type"].annotation | |
| 48 | if get_origin(anno) is Literal: | |
| 49 | lits = get_args(anno) | |
| 50 | if len(lits) == 1 and isinstance(lits[0], str): | |
| 51 | actionType = lits[0] | |
| 52 | | |
| 53 | if actionType is None: | |
| 54 | raise TypeError( | |
| 55 | "Cannot infer 'type' for this Action[...]. Do not call create() on generic Action." | |
| 56 | ) | |
| 57 | | |
| 58 | return ActionConfig( | |
| 59 | type=actionType, | |
| 60 | payload=payload, | |
| 61 | handler=handler, | |
| 62 | loadingBehavior=loading_behavior, | |
| 63 | ) |