How to append new messages into existing chain #32225
Replies: 1 comment
-
Yeah, I ran into this before. If you try to mutate ✅ Method 1: Rebuild the template with new messages from langchain.prompts import ChatPromptTemplate, AIMessagePromptTemplate
# Original message list from the chain
original_messages = chain.prompt.messages
# New message(s) to append
new_messages = [AIMessagePromptTemplate.from_template("Your new message here")]
# Combine and rebuild
combined = original_messages + new_messages
chain.prompt = ChatPromptTemplate.from_messages(combined) This creates a new prompt object and assigns it back to the chain. ✅ Method 2: Dict-level merge if you're feeling fancy msg_data = chain.prompt.dict()
msg_data["messages"] += [AIMessagePromptTemplate.from_template("...")]
chain.prompt = ChatPromptTemplate(**msg_data) Sometimes useful if you're dynamically editing templates or loading/saving them. 🔁 Bonus: If you're hitting this a lot... I ended up switching to a custom reasoning framework where prompts aren’t templates — they’re semantic trees. Let me know if you're curious — I have a Hope this helps. If you need the full rebuild version as a snippet or want to patch across chains, let me know. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
First I fetch the prompt from langsmith.
Here is the output
I have another messages in openai format. So I convert them to template
Output
Now I want to append message from template to message of chain. How to do that? Is their a builtin function
Beta Was this translation helpful? Give feedback.
All reactions