> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Messages in ChatModel Demo

> Guide to using message objects and best practices for constructing prompts with chat models, including examples, environment setup, and troubleshooting for SDKs like LangChain

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.

<Callout icon="lightbulb" color="#1CB2FE">
  Module and API names in SDKs such as [LangChain](https://learn.kodekloud.com/user/courses/langchain) change frequently. If an import or method shown here fails, consult the latest SDK documentation and adapt import paths or method names accordingly.
</Callout>

## 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.

<Callout icon="warning" color="#FF6B6B">
  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.
</Callout>

## Environment variable

Set your OpenAI API key in the shell before running Python examples.

macOS / Linux (bash/zsh):

```bash theme={null}
export OPENAI_API_KEY="your_api_key_here"
```

Windows (PowerShell):

```powershell theme={null}
$env:OPENAI_API_KEY = "your_api_key_here"
```

You can also set the key programmatically in Python (not recommended for production):

```python theme={null}
import os
os.environ["OPENAI_API_KEY"] = "your_api_key_here"
```

## 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.

```python theme={null}
# example_chat_messages.py
from langchain.chat_models import ChatOpenAI
from langchain.schema import SystemMessage, HumanMessage
import os

# Optional: set the API key from Python (best practice is to use environment variables)
# Initialize the chat model (adjust parameters like temperature, model name as needed)
model = ChatOpenAI()

# Define the assistant persona and the user's prompt
sysmsg = "You are a Physics teacher."
humanmsg = "Explain the concept of a galaxy."

messages = [
    SystemMessage(content=sysmsg),
    HumanMessage(content=humanmsg),
]

# Invoke the model with the list of messages.
# Many LangChain chat model wrappers provide `predict_messages` which returns an AIMessage-like object.
response = model.predict_messages(messages)

# Inspect the returned AIMessage object
print(response)            # full AIMessage representation
print(response.content)    # just the textual content returned by the model
```

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):

```python theme={null}
AIMessage(
    content="A galaxy is a massive ensemble of stars, stellar remnants, interstellar gas, dust, dark matter, and other celestial objects bound together by gravity. Galaxies come in several shapes — spiral, elliptical, and irregular — and form the large-scale structure of the universe. The Milky Way, our home galaxy, is a spiral galaxy..."
)
```

## Message roles — quick reference

| Role          | Purpose                                                     | Typical use                                                    |
| ------------- | ----------------------------------------------------------- | -------------------------------------------------------------- |
| SystemMessage | Defines persona, global instructions, or assistant behavior | `SystemMessage(content="You are a concise technical writer.")` |
| HumanMessage  | The user's prompt or question                               | `HumanMessage(content="Explain recursion in simple terms.")`   |
| AIMessage     | The model's response (returned by the API)                  | Inspect with `response.content`                                |

## 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

* [LangChain Documentation](https://learn.kodekloud.com/user/courses/langchain)
* [OpenAI API Reference](https://platform.openai.com/docs)
* SDK-specific migration guides and release notes (check the package repo or docs for breaking changes)

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.

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/langchain/module/ae260750-791b-496c-991f-0d0333f61e40/lesson/c67000e4-0960-4e50-a4e4-b8cb159f2f1e" />

  <Card title="Practice Lab" icon="flask-conical" cta="Learn more" href="https://learn.kodekloud.com/user/courses/langchain/module/ae260750-791b-496c-991f-0d0333f61e40/lesson/0dfdfd01-a5b0-4e95-9ccd-49e5189bcd2e" />
</CardGroup>
