Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Principle:Openai Openai python Chat Message Construction

From Leeroopedia
Revision as of 18:12, 16 February 2026 by Admin (talk | contribs) (Auto-imported from principles/Openai_Openai_python_Chat_Message_Construction.md)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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.

Related Pages

Implemented By

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment