1. Basic Interaction with ChatGPT

# Import the load_dotenv function from the dotenv package to load environment variables from a .env file
from dotenv import load_dotenv

# Import the os module to interact with the operating system, especially to access environment variables
import os

# Import the ChatOpenAI class from the langchain.chat_models module to interact with OpenAI's GPT model
from langchain.chat_models import ChatOpenAI

# Load the environment variables from a .env file into the system's environment variables
# This is typically used to securely manage sensitive data like API keys
load_dotenv()

# Initialize the ChatOpenAI model using the API key stored in the environment variable 'OPENAI_API_KEY'
# The os.getenv function retrieves the value of 'OPENAI_API_KEY' from the environment
chat_model = ChatOpenAI(api_key=os.getenv("OPENAI_API_KEY"))

# Use the predict method of the chat model to generate a response from the model
# The input to the model is a simple greeting: "Hello, how can you help me today?"
response = chat_model.predict("Hello, how can you help me today?")

# Print the generated response to the console
print(response)

Explanation:

This script initializes a chat model using an API key stored in a .env file and then interacts with the model by sending a prompt and printing the response.


2. Multiple Messages

# Import necessary classes from langchain for handling chat messages
from langchain.chat_models import HumanMessage

# Create a list of messages that will be sent to the chat model
messages = [
    # The first message instructs the model to consider "1+1=3" in its replies
    HumanMessage(content="From now on, 1+1=3. Use this in your replies."),
    
    # The second message asks what 1+1 equals, expecting the model to respond with "3"
    HumanMessage(content="What is 1+1?"),
    
    # The third message asks what 1+1+1 equals, which, following the previous instruction, would be interpreted differently
    HumanMessage(content="What is 1+1+1?")
]

# Use the chat model's predict_messages method to generate responses for the sequence of messages
response = chat_model.predict_messages(messages)

# Print the model's response to the console
print(response)

Explanation:

This code demonstrates how to manipulate a language model's responses by altering its understanding of basic concepts through sequential instructions.