Sending User Input
When building an AI application, you need to collect user input and safely include it in your API request. This section shows how to structure messages correctly.
8 min•By Priygop Team•Updated 2026
Building Messages from User Input
Building Messages from User Input
# Building a proper messages array from user input
import os
def build_chat_messages(user_input, system_instruction=None):
"""
Build a properly formatted messages array for the OpenAI API.
Parameters:
- user_input: the text the user typed
- system_instruction: optional instruction that defines how the AI should behave
"""
messages = []
# Add system message if provided (sets the AI's behavior for the entire conversation)
if system_instruction:
messages.append({
"role": "system",
"content": system_instruction
})
# Add the user's message
messages.append({
"role": "user",
"content": user_input
})
return messages
# Example usage
user_text = "What is machine learning in simple terms?"
system = "You are a patient AI tutor for beginners. Always use simple language and everyday analogies. Avoid technical jargon. Keep answers under 150 words."
messages = build_chat_messages(user_text, system_instruction=system)
print("Built messages array:")
import json
print(json.dumps(messages, indent=2))Diagram
Loading diagram…
Deep Learning ⊂ Machine Learning ⊂ Artificial Intelligence