Principle:Openai Openai python Chat Message Construction
| Knowledge Sources | |
|---|---|
| Domains | NLP, Prompt_Engineering |
| Last Updated | 2026-02-15 00:00 GMT |
Overview
A structured message format that defines multi-turn conversations through role-annotated content items for language model interactions.
Description
Chat message construction is the process of building a conversation history as a sequence of typed messages. Each message carries a role (system, user, assistant, tool, developer) and content (text or multipart arrays). This format enables multi-turn conversations, system prompting, tool call results, and multimodal inputs (text + images).
The message structure follows a strict schema where each role has different allowed fields. System messages set behavioral guidelines, user messages provide queries, assistant messages capture model outputs (including tool calls), and tool messages return function results.
Usage
Use this principle whenever preparing input for the Chat Completions API. Every call to chat.completions.create() requires a properly structured message list. Understanding message roles is essential for multi-turn conversations, few-shot prompting, and tool-calling workflows.
Theoretical Basis
The message construction follows a discriminated union pattern based on the role field:
# Abstract message schema
Message = Union[
SystemMessage(role="system", content=str),
UserMessage(role="user", content=str | list[ContentPart]),
AssistantMessage(role="assistant", content=str, tool_calls=list),
ToolMessage(role="tool", content=str, tool_call_id=str),
DeveloperMessage(role="developer", content=str),
]
# Conversation = ordered list of Messages
conversation: list[Message] = [
SystemMessage("You are helpful"),
UserMessage("Hello"),
AssistantMessage("Hi there!"),
]
The ordering convention is: system/developer messages first, followed by alternating user/assistant messages, with tool messages inserted after assistant tool_calls.