openai/chatkit-python
Publicmirrored fromhttps://github.com/openai/chatkit-pythonAvailable
chatkit/actions.py
56lines · modecode
| 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 | streaming: bool = True |
| 20 | |
| 21 | |
| 22 | TType = TypeVar("TType", bound=str) |
| 23 | TPayload = TypeVar("TPayload") |
| 24 | |
| 25 | |
| 26 | class Action(BaseModel, Generic[TType, TPayload]): |
| 27 | type: TType = Field(default=TType, frozen=True) # pyright: ignore |
| 28 | payload: TPayload = None # pyright: ignore - default to None to allow no-payload actions |
| 29 | |
| 30 | @classmethod |
| 31 | def create( |
| 32 | cls, |
| 33 | payload: TPayload, |
| 34 | handler: Handler = DEFAULT_HANDLER, |
| 35 | loading_behavior: LoadingBehavior = DEFAULT_LOADING_BEHAVIOR, |
| 36 | streaming: bool = True, |
| 37 | ) -> ActionConfig: |
| 38 | actionType: Any = None |
| 39 | anno = cls.model_fields["type"].annotation |
| 40 | if get_origin(anno) is Literal: |
| 41 | lits = get_args(anno) |
| 42 | if len(lits) == 1 and isinstance(lits[0], str): |
| 43 | actionType = lits[0] |
| 44 | |
| 45 | if actionType is None: |
| 46 | raise TypeError( |
| 47 | "Cannot infer 'type' for this Action[...]. Do not call create() on generic Action." |
| 48 | ) |
| 49 | |
| 50 | return ActionConfig( |
| 51 | type=actionType, |
| 52 | payload=payload, |
| 53 | handler=handler, |
| 54 | loadingBehavior=loading_behavior, |
| 55 | streaming=streaming, |
| 56 | ) |
| 57 | |