Skip to main content
In this lesson we’ll examine message objects and best practices for constructing prompts for chat-based models. The goal is to demonstrate the typical flow: import message classes, initialize a chat model, create SystemMessage and HumanMessage objects, send them to the model, and inspect the returned AI message.
Module and API names in SDKs such as LangChain change frequently. If an import or method shown here fails, consult the latest SDK documentation and adapt import paths or method names accordingly.

Prerequisites

  • An OpenAI-compatible API key available in your environment.
  • A compatible version of the chat SDK you plan to use (e.g., LangChain). If imports differ, check the package docs.
If the model call fails with authentication errors, confirm that your OPENAI_API_KEY is set and that your SDK supports the provider and model you are calling.

Environment variable

Set your OpenAI API key in the shell before running Python examples. macOS / Linux (bash/zsh):
Windows (PowerShell):
You can also set the key programmatically in Python (not recommended for production):

Minimal Python example

This example shows a compact, runnable pattern using message objects and a chat model. Adjust imports and model initialization for your SDK version if necessary.
Note: If your SDK exposes a different method (e.g., generate or chat), adapt the invocation accordingly.

Example API response (illustrative)

The returned object is commonly an AIMessage-like structure. Example content (actual output varies):

Message roles — quick reference

Key points & troubleshooting

  • Keep SDK imports and method names up to date with the official docs. If from langchain.schema import SystemMessage, HumanMessage fails, consult the package docs for the correct path.
  • If you receive authentication or quota errors, verify that OPENAI_API_KEY is set in the environment and that your account has available quota.
  • For multi-turn conversations, append subsequent HumanMessage and AIMessage instances to the messages list to preserve context across turns.
  • Adjust model parameters (temperature, max tokens, model name) via the chat model constructor or call arguments depending on your SDK.

Further reading

That completes a concise walkthrough of constructing and exchanging messages with a chat-based language model. Subsequent sections can cover conversation history management, system-level instructions for role-based behavior, and advanced prompt design patterns.

Watch Video

Practice Lab