We have implemented a chatbot, which is "save the user's past request contents in Redis and refer to it as needed to use it for bot reply". Specifically, the specifications and programs are as follows.
Request
type and use itjson
, save it as a string, and cast it to Request
type when retrievingfrom __future__ import annotations
from typing import Union, Optional
from typing_extensions import Literal
from .event import EventData
class Request(BaseModel):
user_id: str
session_id: str
command: Union[MessageCommand, ButtonCommand]
class MessageCommand(BaseModel):
"""When a free text message is entered"""
type: Literal["message"]
message: Optional[str]
is_first: bool = False
class ButtonCommand(BaseModel):
"""When the button is pressed"""
type: Literal["button"]
event: Optional[EventData]
is_first: bool = False
Request.update_forward_refs()
Initially, I didn't have a property for type
, and when retrieving from Redis, json, which should be ButtonCommand
, was accidentally cast as an empty MessageCommand
. When using the default value or ʻOptional`, you can cast even the wrong json.
By specifying a fixed character string with Literal
in the type
property, you can surely specify the conversion destination.
Recommended Posts