LLMs & Chat Models
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.
| Provider | Package | Class | Key name |
|---|---|---|---|
| Groq (free, very fast) | langchain-groq | ChatGroq | GROQ_API_KEY |
| Google Gemini | langchain-google-genai | ChatGoogleGenerativeAI | GOOGLE_API_KEY |
| OpenAI | langchain-openai | ChatOpenAI | OPENAI_API_KEY |
| Anthropic | langchain-anthropic | ChatAnthropic | ANTHROPIC_API_KEY |
| Local (Ollama) | langchain-ollama | ChatOllama | none: runs on your laptop |
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
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):
| Message | Role | Use |
|---|---|---|
SystemMessage | system | how the model should behave: “You are a strict interviewer” |
HumanMessage | user | the question |
AIMessage | assistant | the model’s answer, or an example answer for few-shot |
{"role": "user", "content": …} | any | plain dicts work too |
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.
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)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.
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"))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
05Switch provider in one line
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| Benefit | Care point |
|---|---|
| Same code for all providers | one extra library layer over the raw API |
| Streaming, batching and async built in | some provider-only features need provider parameters |
Standard response: .content, .usage_metadata | model names change often: check the provider docs |
| Plugs into prompts, chains, agents and RAG | set timeout and max_retries for production |
06Practice tasks
- Ask the same question to
openai/gpt-oss-20bandopenai/gpt-oss-120band comparetotal_tokensand answer quality. - Create a
SystemMessage("You are a strict interviewer")and ask a Python question. - Use
batch()to translate 5 English sentences to Hindi. - 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
- A chat model takes messages and returns an
AIMessage. invokefor one answer,streamfor live typing,batchfor many,ainvokefor web servers.- System sets rules, Human asks, AI messages can be few-shot examples.
temperature=0for facts, higher for creativity;max_tokenscaps length.usage_metadatashows tokens;llm.profileshows what the model can do.init_chat_model("provider:model")switches provider in one line.
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
- LangChain: Chat models
- Groq models list
- langchain-groq integration
- Ajeetkumar’s notebook: LC_01_LLMs_and_Chat_Models.ipynb (download)