openai/chatkit-python
Publicmirrored from https://github.com/openai/chatkit-pythonAvailable
chatkit/actions.py
53lines · 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 | |
| 6 | | |
| 7 | Handler = Literal["client", "server"] | |
| 8 | LoadingBehavior = Literal["auto", "none", "self", "container"] | |
| 9 | | |
| 10 | DEFAULT_HANDLER: Handler = "server" | |
| 11 | DEFAULT_LOADING_BEHAVIOR: LoadingBehavior = "auto" | |
| 12 | | |
| 13 | | |
| 14 | class ActionConfig(BaseModel): | |
| 15 | type: str | |
| 16 | payload: Any = None | |
| 17 | handler: Handler = DEFAULT_HANDLER | |
| 18 | loadingBehavior: LoadingBehavior = DEFAULT_LOADING_BEHAVIOR | |
| 19 | | |
| 20 | | |
| 21 | TType = TypeVar("TType", bound=str) | |
| 22 | TPayload = TypeVar("TPayload") | |
| 23 | | |
| 24 | | |
| 25 | class Action(BaseModel, Generic[TType, TPayload]): | |
| 26 | type: TType = Field(default=TType, frozen=True) # pyright: ignore | |
ee4063b8David Weedon8 months ago | 27 | payload: TPayload = None # pyright: ignore - default to None to allow no-payload actions |
f688d870victor-openai8 months ago | 28 | |
| 29 | @classmethod | |
| 30 | def create( | |
| 31 | cls, | |
| 32 | payload: TPayload, | |
| 33 | handler: Handler = DEFAULT_HANDLER, | |
| 34 | loading_behavior: LoadingBehavior = DEFAULT_LOADING_BEHAVIOR, | |
| 35 | ) -> ActionConfig: | |
| 36 | actionType: Any = None | |
| 37 | anno = cls.model_fields["type"].annotation | |
| 38 | if get_origin(anno) is Literal: | |
| 39 | lits = get_args(anno) | |
| 40 | if len(lits) == 1 and isinstance(lits[0], str): | |
| 41 | actionType = lits[0] | |
| 42 | | |
| 43 | if actionType is None: | |
| 44 | raise TypeError( | |
| 45 | "Cannot infer 'type' for this Action[...]. Do not call create() on generic Action." | |
| 46 | ) | |
| 47 | | |
| 48 | return ActionConfig( | |
| 49 | type=actionType, | |
| 50 | payload=payload, | |
| 51 | handler=handler, | |
| 52 | loadingBehavior=loading_behavior, | |
| 53 | ) |