Skip to main content
In this section, you will learn the absolute basics of initializing and invoking a LangChain chat model.

Objectives

  1. Understand the difference between using proprietary wrappers and core abstractions.
  2. Develop using both approaches to see how they differ in code.
  3. Adopt core abstractions for our implementations.
  4. Practice invoking various provider APIs in a uniform manner.

Understanding the LLM Interaction API (Step-by-Step)

Before writing the code, let’s understand the main API components used during the LLM interaction process in LangChain:

Step 1: Model Initialization (init_chat_model)

  • API Call: init_chat_model("model_name", model_provider="provider")
  • What it returns: It returns an initialized instance of a LangChain chat model wrapper (which inherits from the base BaseChatModel class).
  • Purpose: Dynamically switches and loads the appropriate client library (such as OpenAI, Anthropic, Google GenAI, or Groq) under a single uniform interface.

Step 2: Model Invocation (invoke)

  • API Call: model.invoke(input_data)
  • What it takes: It accepts a prompt string, a list of chat message objects (like HumanMessage, SystemMessage), or a formatted PromptValue.
  • What it returns: It returns an AIMessage response object from the language model.

Step 3: Handling the Response (AIMessage)

  • What it is: An object structure that encapsulates the output generated by the assistant model.
  • Key Attributes:
    • content: The raw string text returned by the model.
    • response_metadata: A dictionary holding extra metadata (such as token usage billing count, model name, and stop reason).
    • id: An optional unique identifier for the output message.

Step 4: Extracting the Output Text

  • To read the direct text answer generated by the model (filtering out structural metadata wrappers), access the .content attribute:

Chat Model Basic

Goal

Create a model instance using core abstractions and query it for the result of a simple math calculation.

Sample Input

Sample Output

Plan & Code Implementation

Method 1: Using Core Abstraction Helper (Recommended)
Plan:
  1. Import the core abstraction helper init_chat_model from langchain.chat_models.
  2. Initialize the model using init_chat_model("gpt-4o", model_provider="openai").
  3. Call model.invoke() with the input string and print the response.
Code Implementation:
Method 2: Using Proprietary Wrapper Class
Plan:
  1. Import the proprietary model wrapper ChatOpenAI from langchain_openai.
  2. Initialize the model using ChatOpenAI(model="gpt-4o").
  3. Call model.invoke() with the input string and print the response.
Code Implementation:

Proprietary Wrappers vs. Core Abstractions

As shown above, we used the unified core abstraction helper init_chat_model. Let’s compare this with proprietary wrappers:
  • Proprietary Wrappers: Using specific provider classes (e.g., ChatOpenAI from langchain_openai).
    • Advantages: Direct access to unique provider features and parameter optimizations.
    • Disadvantages: High code coupling; swapping providers requires refactoring imports and classes across your codebase.
    • Example:
  • Core Abstractions: Using the unified initializer helper (init_chat_model from langchain.chat_models).
    • Advantages: Standardized interface; swap providers simply by changing parameter strings.
    • Disadvantages: Advanced provider-specific parameters must be passed indirectly via model_kwargs.
    • Example:
[!IMPORTANT] To ensure maximum flexibility and avoid having to remember different SDK endpoints, imports, and API conventions, we will adopt Core Abstractions (init_chat_model) throughout this module to practice invoking various provider APIs in a uniform manner.

Shifting Providers Seamlessly (Gemini and Groq)

Because we use core abstractions, shifting our implementation to another provider requires zero changes to imports. We can swap the model provider simply by updating parameter strings:
1. Shifting to Google Gemini
2. Shifting to Groq

Exercise: Capital City Agent πŸ—

Goal

Build a basic prompt program that queries the chat model to find the capital of any given country.

Sample Input

Sample Output

Plan

  1. Use init_chat_model to load the OpenAI model.
  2. Invoke the model with a string querying the capital of India.
  3. Print the result content.

Practice & Exercises

To practice, open the interactive notebook:

Practice & Exercises

Practice initializing and running basic chat model queries.πŸ’» VS Code | πŸš€ Colab | πŸ“₯ Download