#37Validate a chat messageEasy

Validate a chat message

Background

Before sending messages to an LLM, it's worth checking each one is well-formed: a dict with a known role and a string content. A malformed message (missing content, an unknown role) is a common, silent bug.

Valid roles in this course: "system", "user", "assistant".

Problem statement

Implement is_valid_message(msg) returning whether msg is a well-formed chat message.

Input

  • msg — any value (expected to be a message dict).

Output

Returns a bool: True iff msg is a dict with msg["role"] in {"system", "user", "assistant"} and msg["content"] a str.

Examples

Example 1 — valid

Input:  {"role": "user", "content": "hi"}
Output: True

Example 2 — bad role

Input:  {"role": "bot", "content": "hi"}
Output: False

Example 3 — non-string content

Input:  {"role": "system", "content": 123}
Output: False

Constraints

  • Must be a dict.
  • role{"system", "user", "assistant"}.
  • content is a str.

Notes

  • Catch malformed messages early — a missing content key turns into a confusing provider-side error otherwise.
Python
Loading...

▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.

  • Reference example: valid user message
  • Sample: unknown role is rejected
  • Reference: non-string content is rejected