Enhance client mode handling in ProcessRequest_chat

- Introduced a normalization function for client mode to default to "direct" when input is empty or None.
- Updated the clientMode field to use a new type with BeforeValidator for improved validation.
- Added a test to ensure empty client mode inputs correctly default to "direct".
This commit is contained in:
Xin Wang
2026-07-29 10:02:35 +08:00
parent 473fffd2f0
commit 3187713bfe
2 changed files with 24 additions and 3 deletions

View File

@@ -1,13 +1,22 @@
from pydantic import BaseModel, Field
from typing import Any, Literal, Optional
from pydantic import BaseModel, BeforeValidator, Field
from typing import Annotated, Any, Literal, Optional
ClientMode = Literal["direct", "browser_addon"]
def normalize_client_mode(value: Any) -> Any:
if value is None or (isinstance(value, str) and value.strip() == ""):
return "direct"
return value
NormalizedClientMode = Annotated[ClientMode, BeforeValidator(normalize_client_mode)]
class ProcessRequest_chat(BaseModel):
sessionId: str = Field(..., max_length=64)
timeStamp: str = Field(..., max_length=32)
text: str = Field(...)
clientMode: ClientMode = "direct"
clientMode: NormalizedClientMode = "direct"
needFormUpdate: bool = False
useTextChunk: bool = False

View File

@@ -36,6 +36,18 @@ def test_unknown_client_mode_is_rejected():
)
@pytest.mark.parametrize("client_mode", ["", " ", None])
def test_empty_client_mode_defaults_to_direct(client_mode):
request = ProcessRequest_chat(
sessionId="session-1",
timeStamp="1",
text="你好",
clientMode=client_mode,
)
assert request.clientMode == "direct"
@pytest.mark.parametrize(
("client_mode", "raw_code", "expected"),
[