Session 6· 02· 10 min

Invoke with Single & Multi-Turn Messages

What you'll learn
  • Call model.invoke() with a plain string or a list of messages
  • Use SystemMessage, HumanMessage, AIMessage for multi-turn
  • Read the AIMessage result object

invoke() is the one-and-done synchronous call. Pass a string for a quick question, or a list of message objects for a multi-turn conversation — same pattern as Session 1 but through LangChain's message classes.

scripts/02_invoke_single_and_messages.py
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage   ①

# Option A — plain string
result = model.invoke("Hello!")                            ②

# Option B — a list of message objects
history = [
    SystemMessage(content="You are a concise tutor."),     ③
    HumanMessage(content="What is a vector?"),
]
result = model.invoke(history)                              ④
print(result.content)                                        ⑤
Three message classes — one per role. Import from langchain_core.messages.
A plain string becomes a single HumanMessage under the hood.
SystemMessage sets persona and rules (same job as system role in Session 1).
Pass a list of messages for multi-turn conversations.
result is an AIMessage; .content is the reply string.
$ python scripts/02_invoke_single_and_messages.py
Code Check
What Python class represents "a previous reply from the model" in LangChain?
Recap — what you just learned
  • invoke() takes either a string or a list of messages
  • Message classes: SystemMessage, HumanMessage, AIMessage
  • Result is always an AIMessage with .content
Next up: 03 — Streaming