LangGraphLangGraph 1.2 · Python 3.10+
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
38 small wins to finish your pathNext lesson →

Chat models: init_chat_model

init_chat_model builds a chat model from a "provider:model" string. You call it with .invoke(messages) and get back an AIMessage.

Last updated: 27 Sep, 2026 · LangChain 1.4

A hosted model needs an API key. So the graph lessons can run without one, this course uses a small stand-in model that behaves like a real one; the only change to go live is the two lines below.

The init_chat_model call

python
from langchain.chat_models import init_chat_model

model = init_chat_model("openai:gpt-4.1")             # "provider:model"
model = init_chat_model("gpt-4.1", model_provider="openai", temperature=0)

reply = model.invoke("Why do parrots talk?")         # returns an AIMessage
print(reply.content)

A stand-in model

The graph lessons need a model, but a hosted one needs an API key. Build a small stand-in instead: a function that returns a fixed AIMessage, so the code runs with no key.

python
from langchain.messages import HumanMessage, AIMessage

def fake_model_invoke(messages):
    # a real model would read the messages and decide what to say
    return AIMessage("Thanks, I can help with that.")   # the stand-in always says this

Calling the stand-in

Call it the way you would call a real model, passing a list of messages, and read the reply's content.

python
reply = fake_model_invoke([HumanMessage("I was charged twice.")])
print(reply.content)

The stand-in in a run

The stand-in and the call together:

Example
from langchain.messages import HumanMessage, AIMessage

def fake_model_invoke(messages):
    # a stand-in: a real model would read the messages and think
    return AIMessage("Thanks, I can help with that.")

reply = fake_model_invoke([HumanMessage("I was charged twice.")])
print(reply.content)

What init_chat_model returns

  • init_chat_model takes a provider and model name and returns a model object.
  • .invoke accepts a string, a message list, or role dicts, and returns an AIMessage.
  • The stand-in returns a fixed AIMessage, which is enough to build and test a graph; swapping in init_chat_model is the only change to use a real model.

Two ways to name the model

FormExample
Single stringinit_chat_model("openai:gpt-4.1")
Name plus providerinit_chat_model("gpt-4.1", model_provider="openai")

Where the model call fits

  • The one line that turns a plain graph into one that calls a real model.
  • Swapping providers is a string change, not a rewrite.
Watch out. Model names like gpt-4.1 here stand for whatever current model you use. Check the provider's current model ids before shipping.
Try it yourself
  • Make the stand-in echo the last message's content back.
  • Put the stand-in inside a graph node that returns {"messages": [reply]}.

Little by little, you're building something great.