Howwise RSS
AI & Automation6 min read

LangChain ConversationChain System Message: Working Setup

Short answer

For a langchain conversationchain system message, do not use a plain PromptTemplate. Build a ChatPromptTemplate with a ('system', ...) message, a MessagesPlaceholder for history, then ('human', '{input}'), and attach memory to it.

Key takeaways
  • A plain PromptTemplate produces one string, which a chat model receives as a single human message, so it cannot carry a real system role.
  • The legacy fix needs prompt variables 'history' and 'input' plus ConversationBufferMemory(return_messages=True).
  • ConversationChain and ConversationBufferMemory are deprecated since 0.2.7 and live in langchain-classic on 1.x, so new code should use ChatPromptTemplate | model wrapped in RunnableWithMessageHistory, or LangGraph with a checkpointer.
  • Keep the system message in the prompt, not in stored history, and escape literal braces as {{ }}.
  • Memory only works when every call reuses the same session_id and the store lives outside the request, for example in Redis or Postgres.

Is PromptTemplate the right way to set a system message?

No. A PromptTemplate renders to one string. When that string reaches a chat model such as ChatOpenAI, it is wrapped as a single human message, so the model never sees a message with the system role.

If you are used to sending [{'role': 'system', ...}, {'role': 'user', ...}] to the API directly, the LangChain equivalent is a ChatPromptTemplate. It holds a list of role-tagged message templates and renders to a list of messages.

The correct layout has three parts, in this order: a system message with your instructions, a MessagesPlaceholder where the conversation history is inserted, and a final human message holding the new user input.

from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a concise support assistant for Acme. Answer in two sentences or fewer."),
    MessagesPlaceholder("history"),
    ("human", "{input}"),
])
Tip: The ('system', '...') tuple is shorthand for SystemMessagePromptTemplate.from_template('...'). Both give the same result, so use whichever reads better.

Why does the default ConversationChain prompt ignore system roles?

ConversationChain ships with a default PromptTemplate that is one string: a short instruction sentence, then 'Current conversation:', then {history}, then 'Human: {input}' and 'AI:'. Everything is flattened into one text block with role names written as plain text.

The chat model receives that block as one human message. Your instructions are not in a system message, and past turns are not real chat messages, so the model sees a transcript rather than a conversation.

That is why the common first attempt, wrapping your instructions in a PromptTemplate, appears to work on some models and is weak on others. Models are trained to give system text special weight, and a flattened string loses it.

How do I set a LangChain ConversationChain system message in legacy code?

Pass your own chat prompt and a memory that returns messages. Two details decide whether it runs: variable names and return_messages.

On LangChain 1.x, ConversationChain and ConversationBufferMemory are no longer in the main package. Install langchain-classic and import from langchain_classic. If you are pinned to langchain<1.0, the old langchain.chains and langchain.memory imports still work.

ConversationChain validates that the prompt variables equal the memory variable plus the input key. By default that means exactly {history} and {input}. Rename either one and you get a validation error such as 'Got unexpected prompt input variables'.

return_messages=True matters because without it the memory injects history as one formatted string. A MessagesPlaceholder expects a list of messages, so you would get a type error or a garbled prompt.

# Legacy: deprecated since 0.2.7. On LangChain 1.x it lives in langchain-classic:
#   pip install langchain-classic langchain-openai
# (On langchain<1.0, import from langchain.chains / langchain.memory instead.)
from langchain_classic.chains import ConversationChain
from langchain_classic.memory import ConversationBufferMemory
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_openai import ChatOpenAI

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a concise support assistant for Acme."),
    MessagesPlaceholder("history"),      # must match memory_key
    ("human", "{input}"),                # must match input_key
])

chain = ConversationChain(
    llm=ChatOpenAI(model="gpt-4o-mini", temperature=0),
    prompt=prompt,
    memory=ConversationBufferMemory(return_messages=True),
)

print(chain.predict(input="Hi, my name is Dana."))
print(chain.predict(input="What is my name?"))
Warning: This is dead-end code. On LangChain 1.x the classic chains and memory classes were moved to langchain-classic, so the old langchain.chains imports raise ImportError on a fresh install. Use the next section for new projects.

How do I keep memory with RunnableWithMessageHistory?

The current replacement for ConversationChain is a plain runnable chain, prompt | model, wrapped in RunnableWithMessageHistory. The wrapper loads history before each call and saves the new human and AI messages after it.

You supply get_session_history, a function that takes a session id and returns a chat history object. The input_messages_key names the input variable, and history_messages_key names the MessagesPlaceholder.

The session id is passed in config, not in the input dict. Different ids give separate conversations.

from langchain_core.chat_history import InMemoryChatMessageHistory
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_openai import ChatOpenAI

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a concise support assistant for Acme."),
    MessagesPlaceholder("history"),
    ("human", "{input}"),
])
chain = prompt | ChatOpenAI(model="gpt-4o-mini", temperature=0)

store = {}
def get_session_history(session_id: str):
    if session_id not in store:
        store[session_id] = InMemoryChatMessageHistory()
    return store[session_id]

chat = RunnableWithMessageHistory(
    chain,
    get_session_history,
    input_messages_key="input",
    history_messages_key="history",
)

cfg = {"configurable": {"session_id": "abc"}}
chat.invoke({"input": "Hi, my name is Dana."}, config=cfg)
r = chat.invoke({"input": "What is my name?"}, config=cfg)
print(r.content)
Tip: The dict in store lives in process memory and disappears on restart. In production return a persistent history class backed by Redis, Postgres or SQLite from get_session_history. The wrapper does not care which store you use.

How do I add initial context, and what about long histories?

Separate static instructions from per-conversation context. Static rules belong in the system string. Dynamic facts, such as the customer's plan or a retrieved document, go in as a template variable.

Put {plan} or {context} in the system message and fill it per call through an input key. You can also fix it ahead of time with partial(). The wrapper still works because only input_messages_key and history_messages_key are special.

A second option is seeding the history. Call history.add_user_message(...) or history.add_ai_message(...) on the session's history before the first turn. This suits example exchanges but not rules, because seeded messages are ordinary history that can be trimmed.

Do not store a SystemMessage inside memory or history. It works at first, but it is duplicated when the history is re-saved or lost when you trim old messages. Keep it in the prompt, and cap the history with trim_messages to control token cost.

from langchain_core.messages import trim_messages
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_openai import ChatOpenAI

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a support assistant. Customer plan: {plan}. "
               "Reply as JSON like {{\"answer\": \"...\"}}."),
    MessagesPlaceholder("history"),
    ("human", "{input}"),
])

trimmer = trim_messages(
    max_tokens=2000,
    strategy="last",
    token_counter=ChatOpenAI(model="gpt-4o-mini"),
    include_system=False,   # system lives in the prompt, not history
    start_on="human",
)

# Trim the history before it reaches the prompt
chain = (
    {
        "input": lambda x: x["input"],
        "plan": lambda x: x["plan"],
        "history": lambda x: trimmer.invoke(x["history"]),
    }
    | prompt
    | ChatOpenAI(model="gpt-4o-mini")
)

# get_session_history is the function defined in the previous section
chat = RunnableWithMessageHistory(
    chain, get_session_history,
    input_messages_key="input", history_messages_key="history",
)
chat.invoke({"input": "Can I export data?", "plan": "Pro"},
            config={"configurable": {"session_id": "abc"}})
Warning: Literal braces in the system text, such as a JSON example, must be written as {{ and }}. Otherwise the template treats them as variables and raises a KeyError or a missing-variables error.

What errors will I hit, and what is the officially recommended path?

Most failures come from name mismatches between the prompt, the memory and the config. The table lists the ones that come up most.

For new applications, the recommended route is LangGraph. Use create_react_agent from langgraph.prebuilt, or a StateGraph with MessagesState, and compile it with a MemorySaver checkpointer. The system prompt goes through the prompt parameter, and the thread_id in config plays the role of session_id.

On LangChain 1.x, create_react_agent is deprecated in favor of create_agent in langchain.agents, which takes system_prompt and a checkpointer in a similar way. Both persist state per thread and can swap MemorySaver for a database-backed checkpointer.

SymptomCauseFix
Got unexpected prompt input variablesPrompt uses a name like chat_history, but the memory supplies 'history'Rename the placeholder to 'history', or set memory_key to match
KeyError or missing variables on a JSON exampleLiteral { } in the system text parsed as variablesEscape as {{ and }}
Model forgets earlier turnsDifferent session_id per call, or a new store dict each requestReuse one id per conversation and keep the store outside the request handler
History appears as a long string or type errorMemory created without return_messages=TrueSet return_messages=True, or move to RunnableWithMessageHistory
Instructions followed weaklyInstructions sent as a string, so a human messageUse a ('system', ...) message; for some reasoning models use the developer role
ImportError for ConversationChainClassic chains moved out of the main package on 1.xRun pip install langchain-classic and import from langchain_classic, or migrate to RunnableWithMessageHistory or LangGraph
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent
from langgraph.checkpoint.memory import MemorySaver

agent = create_react_agent(
    ChatOpenAI(model="gpt-4o-mini"),
    tools=[],
    prompt="You are a concise support assistant for Acme.",
    checkpointer=MemorySaver(),
)
cfg = {"configurable": {"thread_id": "abc"}}
agent.invoke({"messages": [("user", "Hi, I'm Dana.")]}, cfg)
out = agent.invoke({"messages": [("user", "What's my name?")]}, cfg)
print(out["messages"][-1].content)

Common questions

Can I pass a plain string as the prompt to ChatOpenAI?

Yes, but a string is sent as a single human message, not a system message. To send a system role, pass a list of messages or render a ChatPromptTemplate.

Do all models follow the system message equally?

No. Models vary in how strongly they weight system text, so test your instructions on the model you ship. Some reasoning models, such as older o1 versions, use a 'developer' role instead of 'system', so check which role your model expects.

Can I change the system message in the middle of a conversation?

Yes, because it lives in the prompt rather than stored history. Make it a variable such as {persona} and pass a different value on the next call. The stored messages stay unchanged.

Should I use MemorySaver in production?

No. MemorySaver keeps state in process memory, so it is lost on restart and not shared between workers. Use a database-backed checkpointer such as the Postgres or SQLite ones for persistence.

Related topics:langchainchatbotmemorysystem promptpython