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
