liveBook · Manning

Messages array

As explained in Starting Data Analytics with Generative AI and Python

An ordered array of message objects representing the conversation input supplied to a language model.

A messages array is the conversation context sent to a language model. Each message object contains a role and content, allowing the request to include instructions, questions, and earlier replies. section 1.3.3

Build the array around the conversation you want the model to understand:

  • Start with an optional system message that sets the assistant’s behavior, tone, or audience. section 1.3.3
  • Add user and assistant messages in alternating order to preserve the exchange history. section 1.3.3
  • Resend relevant history with every request because models do not retain past requests by default. section 1.3.3
Listing 1.1 Interacting with ChatGPT through the API
from openai import OpenAI
prompt_text = """Generate a list of 20 keywords indicating positive 
sentiment to be used for searching customer reviews in 
Portuguese."""
client = OpenAI(
    api_key=<<your-API-key-here>>,
)
chat_completion = client.chat.completions.create(
    messages=[
    {"role": "system", "content": "You are a scientific assistant, skilled
    at explaining science to schoolchildren."},
    {"role": "user", "content": "Explain resonance to first-graders?"},
    {"role": "assistant", "content": "Alright, kids, today we're going to
    talk about something really cool called resonance! (...)."},
    # Shortened from the full model response
    {"role": "user", "content": "Where can we use it?"}
  ],


    model="gpt-4-0125-preview",
    temperature=0.7,   
)
print(chat_completion.choices[0].message.content)

Inspect a Python API request containing system, user, and assistant messages, followed by a new user question. section 1.3.3

How Starting Data Analytics with Generative AI and Python covers it

How deep it goes
Defines message objects, roles, ordering, and history handling, but does not detail token limits or serialization internals.
Examples
Demonstrates a Python ChatGPT request containing a scientific-assistant instruction, a resonance explanation, and a follow-up question.
What it assumes
Assumes basic Python and API-key setup while teaching message roles and conversation context directly.
What you can do after
Apply it via the OpenAI Python API to construct context-aware conversational requests.
How it connects
Connects system messages, user messages, assistant messages, multiturn conversations, and language models.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Starting Data Analytics with Generative AI and Python. The section links point to the parts of the book it draws on.