LangChain Hands-on · Module 1 · Lab 01

LLMs & Chat Models

⏱ 20 min + hands-on🎯 Beginner🖼 1 diagram🧪 4 live demos🐍 Python code

Every LangChain app starts with one line: llm = ChatGroq(model="openai/gpt-oss-20b"). In this lab you learn to talk to that model the LangChain way: ask one question, stream the answer word by word, send many questions at once, give the model a role with messages, and read the token bill. The same code works for Groq, OpenAI, Gemini, Claude or a free local model.

In this session

  • What a chat model is: messages in, message out
  • invoke, stream, batch and ainvoke
  • SystemMessage, HumanMessage, AIMessage and few-shot examples
  • temperature, max_tokens, timeout and retries
  • Token usage and the model profile
  • init_chat_model: switch provider in one line

01The big idea: one remote for every TV

📺

Think of a universal TV remote. Sony, Samsung and LG TVs all work differently inside, but one universal remote has the same buttons for all of them. LangChain’s chat model is that remote: invoke, stream and batch work the same for Groq, OpenAI, Gemini or Ollama. Change the brand, keep your code.

Your messagessystem + humanChat modelChatGroq / ChatOpenAI …Provider APIGroq cloudAIMessage.content + usage
A chat model takes a list of messages and returns one AIMessage.
ProviderPackageClassKey name
Groq (free, very fast)langchain-groqChatGroqGROQ_API_KEY
Google Geminilangchain-google-genaiChatGoogleGenerativeAIGOOGLE_API_KEY
OpenAIlangchain-openaiChatOpenAIOPENAI_API_KEY
Anthropiclangchain-anthropicChatAnthropicANTHROPIC_API_KEY
Local (Ollama)langchain-ollamaChatOllamanone: runs on your laptop
Model update (Aug 2026): Groq retired llama-3.1-8b-instant and llama-3.3-70b-versatile for free users. Use openai/gpt-oss-20b (fast) or openai/gpt-oss-120b (stronger). Check the live list at console.groq.com/docs/models.

02Four ways to call a model

Demo · invoke · stream · batch · ainvoke

Messages give the model a role. The system message sets the rules, the human message is the question, and AI messages can be example answers that teach the pattern (few-shot):

MessageRoleUse
SystemMessagesystemhow the model should behave: “You are a strict interviewer”
HumanMessageuserthe question
AIMessageassistantthe model’s answer, or an example answer for few-shot
{"role": "user", "content": …}anyplain dicts work too
Demo · temperature: how creative should the model be?

Run the two tagline cells in the notebook: the factual model repeats itself, the creative one changes every time.

03Hands-on: run it here (no key)

This mirrors the notebook: invoke, read the response object, give roles, few-shot classify, stream and batch. Count the stream chunks: each | is one chunk arriving.

lab01_models.py
from standins import RuleModel
from langchain.messages import SystemMessage, HumanMessage, AIMessage

# In Colab: llm = ChatGroq(model="openai/gpt-oss-20b")
llm = RuleModel(rules={
    "daily life": "Google Maps uses AI to predict traffic and suggest the fastest route to office.",
    "gravity": "Gravity is the Earth's hug that never lets go! Drop your phone and it says hello to the floor.",
    "taste was bad": "NEGATIVE",
    "mumbai rains": "Grey clouds over Marine Drive,\nvada pav and cutting chai,\nlocal trains run, umbrellas fly,\nMumbai smiles at the monsoon sky.",
    "what is ai": "AI is making computers do tasks that need human intelligence.",
    "what is ml": "ML is a part of AI where computers learn patterns from data.",
    "deep learning": "Deep learning uses many-layered neural networks to learn from huge data.",
})

# 1. invoke
response = llm.invoke("Give me a short example of AI use in daily life?")
print(type(response).__name__, "->", response.content)
print("usage:", response.usage_metadata)

# 2. messages with roles
messages = [SystemMessage("You are a funny teacher. Answer in 2 lines."), HumanMessage("What is gravity?")]
print("\nteacher:", llm.invoke(messages).content)

# 3. few-shot with AIMessage examples
messages = [
    SystemMessage("Classify the review as POSITIVE or NEGATIVE. One word only."),
    HumanMessage("The food was amazing"), AIMessage("POSITIVE"),
    HumanMessage("Delivery was very late"), AIMessage("NEGATIVE"),
    HumanMessage("Packaging was good but taste was bad"),
]
print("few-shot:", llm.invoke(messages).content)

# 4. stream word by word
print("\nstream: ", end="")
chunks = 0
for chunk in llm.stream("Write a 4-line poem on Mumbai rains"):
    print(chunk.content, end="|", flush=True); chunks += 1
print(f"\n({chunks} chunks)")

# 5. batch many questions
questions = ["What is AI?", "What is ML?", "What is Deep Learning?"]
for q, r in zip(questions, llm.batch(questions)):
    print(q, "->", r.content)
AIMessage -> Google Maps uses AI to predict traffic and suggest the fastest route to office. usage: {'input_tokens': 11, 'output_tokens': 14, 'total_tokens': 25} teacher: Gravity is the Earth's hug that never lets go! Drop your phone and it says hello to the floor. few-shot: NEGATIVE stream: Grey |clouds |over |Marine |Drive, |vada |pav |and |cutting |chai, |local |trains |run, |umbrellas |fly, |Mumbai |smiles |at |the |monsoon |sky.|| (22 chunks) What is AI? -> AI is making computers do tasks that need human intelligence. What is ML? -> ML is a part of AI where computers learn patterns from data. What is Deep Learning? -> Deep learning uses many-layered neural networks to learn from huge data.
Runs here without any API key. A small stand-in plays the LLM (RuleModel or ScriptedModel from standins.py), so every output below is from a real run of this code. In Colab you swap one line: llm = ChatGroq(model="openai/gpt-oss-20b").

Read the response: .content is the text, .usage_metadata is the bill. Groq counts real tokens; the stand-in just counts words, so your numbers in Colab will differ. Every provider fills the same fields, which is the point of LangChain.

model_profile.py
profile = llm.profile or {}
print("Context window :", profile.get("max_input_tokens"))
print("Max output     :", profile.get("max_output_tokens"))
print("Tool calling   :", profile.get("tool_calling"))
print("Structured out :", profile.get("structured_output"))
print("Image input    :", profile.get("image_inputs"))
Context window : 131072 Max output : 65536 Tool calling : True Structured out : True Image input : False

That output is real: it is the model-profile cell of the notebook, run here. It tells you the context window (131,072 tokens) and that this model supports tool calling and structured output, which you need in Labs 3, 12 and 13.

04Hands-on: Ajeetkumar’s Colab notebook

Demo · Set up Colab + Groq in 4 steps
Demo · Notebook player · Lab 01

05Switch provider in one line

any_provider.py
from langchain.chat_models import init_chat_model

llm = init_chat_model("groq:openai/gpt-oss-20b", temperature=0)      # Groq
llm = init_chat_model("google_genai:gemini-2.5-flash")                # pip install langchain-google-genai
llm = init_chat_model("openai:gpt-4o-mini")                           # pip install langchain-openai
llm = init_chat_model("ollama:llama3.1")                              # free, runs on your laptop

print(llm.invoke("Capital of Maharashtra?").content)                   # same line for all
BenefitCare point
Same code for all providersone extra library layer over the raw API
Streaming, batching and async built insome provider-only features need provider parameters
Standard response: .content, .usage_metadatamodel names change often: check the provider docs
Plugs into prompts, chains, agents and RAGset timeout and max_retries for production

06Practice tasks

  1. Ask the same question to openai/gpt-oss-20b and openai/gpt-oss-120b and compare total_tokens and answer quality.
  2. Create a SystemMessage("You are a strict interviewer") and ask a Python question.
  3. Use batch() to translate 5 English sentences to Hindi.
  4. Stream a 100-word story and count the chunks.

Try these in the same Colab notebook after you finish the lab. Change one thing at a time and look at the output again.

07Summary

08Quick quiz

1. What does llm.invoke() return?

2. Which method shows the answer word by word?

3. You need the same answer every time for a classifier. Temperature?

4. Where do you see input and output token counts?

5. What is the AIMessage used for in a few-shot prompt?

09References

Created by Ajeetkumar