openai/chatkit-python

Public

mirrored fromhttps://github.com/openai/chatkit-pythonAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v1.6.0

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

chatkit/actions.py

53lines · modecode

1from __future__ import annotations
2
3from typing import Any, Generic, Literal, TypeVar, get_args, get_origin
4
5from pydantic import BaseModel, Field
6
7Handler = Literal["client", "server"]
8LoadingBehavior = Literal["auto", "none", "self", "container"]
9
10DEFAULT_HANDLER: Handler = "server"
11DEFAULT_LOADING_BEHAVIOR: LoadingBehavior = "auto"
12
13
14class ActionConfig(BaseModel):
15 type: str
16 payload: Any = None
17 handler: Handler = DEFAULT_HANDLER
18 loadingBehavior: LoadingBehavior = DEFAULT_LOADING_BEHAVIOR
19
20
21TType = TypeVar("TType", bound=str)
22TPayload = TypeVar("TPayload")
23
24
25class Action(BaseModel, Generic[TType, TPayload]):
26 type: TType = Field(default=TType, frozen=True) # pyright: ignore
27 payload: TPayload = None # pyright: ignore - default to None to allow no-payload actions
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 )
54