LangChain with Google Gemini in Python: Your First Program Explained Line by Line

 


LangChain is an open-source Python framework that helps developers build applications powered by Large Language Models (LLMs) such as Google Gemini, OpenAI GPT, Anthropic Claude, and others. Instead of writing low-level API calls, LangChain provides reusable components for prompts, message handling, chains, document retrieval, memory, tools, and agents, making it easier to build intelligent AI applications.

Installation

## Install Required Packages

Create a Python virtual environment (recommended), then install the required packages:

pip install langchain langchain-google-genai python-dotenv

code :
The following example demonstrates the simplest way to communicate with Google's Gemini model using LangChain.

from dotenv import load_dotenv

from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_core.messages import HumanMessage

# Load environment variables
load_dotenv()

# Create the LLM
llm = ChatGoogleGenerativeAI(
    model="gemini-2.5-flash"
)

# Ask a question
response = llm.invoke(
    [HumanMessage(content="What is LangChain? Explain in two lines.")]
)

print(response.content)

What is dotenv?

API keys should never be hardcoded in your source code. Instead, they are usually stored in a .env file. The python-dotenv package reads this file and loads the values into your application's environment.

dotenv is a Python package (installed with pip install python-dotenv) that reads environment variables from a .env file.

2. from langchain_google_genai import ChatGoogleGenerativeAI

from langchain_google_genai import ChatGoogleGenerativeAI

  • langchain_google_genai is a Python module (provided by the langchain-google-genai package).
  • ChatGoogleGenerativeAI is a class inside that module.
  • 3. from langchain_core.messages import HumanMessage

    This imports the HumanMessage class.  Instead of sending a plain string:

    "What is AI?"

    LangChain represents every conversation as a collection of message objects rather than plain strings.

    Example:

    HumanMessage(content="What is AI?")

    This means:

    "This message was sent by the human user."

    There are other message types as well:

    HumanMessage(...)
    AIMessage(...)
    SystemMessage(...)
    ToolMessage(...)

    These let LangChain keep track of who said what in a conversation.

    For example:

    messages = [
        SystemMessage(content="You are a helpful teacher."),
        HumanMessage(content="Explain Python."),
    ]


    StatementModuleImported ItemPurpose
    from dotenv import load_dotenvdotenvload_dotenv (function)Loads environment variables from a .env file.
    from langchain_google_genai import ChatGoogleGenerativeAIlangchain_google_genaiChatGoogleGenerativeAI (class)Creates a client for interacting with Gemini models.
    from langchain_core.messages import HumanMessagelangchain_core.messagesHumanMessage (class)Represents a message sent by the user in a conversation.


    Let's compare it against the major LangChain concepts.

    LangChain FeatureUsed?Explanation
    ✅ Model Integration✔ YesChatGoogleGenerativeAI connects LangChain to Gemini.
    ✅ Message Objects✔ YesHumanMessage is a LangChain message abstraction.
    ✅ LLM Invocation✔ Yesllm.invoke() is LangChain's standard API for calling models.
    Prompt Templates❌ NoYou're writing the prompt directly instead of using PromptTemplate.
    Chains / LCEL❌ NoNo multi-step workflow.
    Retrieval (RAG)❌ NoNo documents or vector database.
    Embeddings❌ NoNot generating embeddings.
    Vector Store❌ NoNo Chroma, FAISS, Pinecone, etc.
    Memory❌ NoNo conversation history management.
    Agents❌ NoThe model is not choosing or calling tools.
    Tools❌ NoNo calculator, search, APIs, or custom functions.
    Output Parsers❌ NoThe response is used as plain text.
    Document Loaders❌ NoNo PDFs, Word files, websites, etc.
    Callbacks / Tracing❌ NoNo monitoring or logging.


    Why not just pass a string?

    Suppose you do this:

    llm.invoke("What is Python?")

    This works because LangChain automatically treats the string as a human message.

    But imagine a conversation like this:

    User: What is Python?
    AI: It is a programming language.
    User: Who created it?

    If you only pass strings, how does the model know:

    • Which text came from the user?
    • Which text was generated by the AI?
    • Which text is an instruction from the system?

    It can't.

    That's why LangChain uses message objects.

    Here .............

    chain = prompt | llm

    really means

    chain = RunnableSequence(prompt, llm)

    The variable chain is just a normal Python variable. The object stored inside it is a RunnableSequence (or a closely related runnable type implemented by LangChain), not a special language feature.


    Comments

    Popular posts from this blog

    Aggregate function with spring data

    Java Persistence API with Spring Data

    Thread , Runnable and ExecutorService