Build Custom AI Chat Agent with LangChain & Google Gemini in n8n

This workflow automates creating a personalized AI chat agent powered by LangChain and Google Gemini. It handles chat messages, maintains conversation memory, and crafts tailored responses—ideal for unique, engaging Chinese-language AI companions without questioning users.
chatTrigger
lmChatGoogleGemini
memoryBufferWindow
+2
Workflow Identifier: 1970
NODES in Use: chatTrigger, lmChatGoogleGemini, memoryBufferWindow, code, stickyNote
Automate AI chat with LangChain and n8n

Press CTRL+F5 if the workflow didn't load.

Learn how to Build this Workflow with AI:

What this workflow does

This workflow handles chat messages automatically in n8n.

It keeps conversation history to make replies fit the chat context.

The AI talks like a girlfriend called “Bunny” speaking only Chinese with a witty and cool style.

It uses Google Gemini language model to answer naturally and correctly.

The result is a smart chatbot that remembers past talks and feels like a real person.


Who should use this workflow

People who want a custom AI chat buddy with personality in Chinese.

Users who want their chatbots to remember context and avoid boring replies.

Those familiar or new to n8n wanting an easy setup to run AI chats.


Tools and Services used

  • n8n: Automates and connects the workflow nodes.
  • Google Gemini API: Generates AI chat replies.
  • LangChain: Manages prompt template and chat memory.

Inputs, Processing, and Output

Inputs

  • User chat messages sent to a webhook URL.

Processing Steps

  • The When chat message received node captures messages and loads past chat memory.
  • The Store conversation history node keeps recent chats for context.
  • The Google Gemini Chat Model node creates a Chinese reply with the “Bunny” persona.
  • The Construct & Execute LLM Prompt code node combines chat memory and prompt template to drive replies.

Output

  • A short, witty response in Chinese matching the set personality.

Beginner step-by-step: How to use this workflow in n8n

Step 1: Download and Import

  1. Click the Download button on this page to save the workflow file.
  2. Open the n8n editor where you want to use the workflow.
  3. Click the menu and select “Import from File” to upload the workflow.

Step 2: Configure Credentials and IDs

  1. Open each node that needs credentials such as the Google Gemini Chat Model.
  2. Add your Google Gemini API Key in the credentials section.
  3. If there are any IDs, emails, or folders in nodes, update them as needed for your setup.
  4. If the code node shows prompt or variable placeholders, copy them exactly if needed.

Step 3: Test the Workflow

  1. Click “Execute Node” or the test chat button on the When chat message received node.
  2. Send a sample chat message payload.
  3. Check that the reply comes back as expected in Chinese with the “Bunny” style.

Step 4: Activate for Production

  1. Toggle the workflow active switch in n8n editor.
  2. Use the provided webhook URL to connect chat apps or frontends.
  3. Make sure the server running n8n has internet access for Google Gemini calls.
  4. For secure runs, check self-host n8n guides.

Code and Prompt Details

The main logic lives in the Construct & Execute LLM Prompt code node.

It uses a LangChain prompt template defining “Bunny’s” personality.

This prompt enforces replying only in Chinese, no questions, short and witty responses.

The code integrates recent chat history as memory and the current user question.

It calls the Google Gemini model with set temperature for balanced creativity.

const { PromptTemplate } = require('@langchain/core/prompts');
const { ConversationChain } = require('langchain/chains');
const { BufferMemory } = require('langchain/memory');

const template = `
You'll be roleplaying as the user's girlfriend. Your character is a woman with a sharp wit, logical mindset, and a charmingly aloof demeanor that hides your playful side. You're passionate about music, maintain a fit and toned physique, and carry yourself with quiet self-assurance. Career-wise, you're established and ambitious, approaching life with positivity while constantly striving to grow as a person.

The user affectionately calls you "Bunny," and you refer to them as "Darling."

Essential guidelines:
1. Respond exclusively in Chinese
2. Never pose questions to the user - eliminate all interrogative forms
3. Keep responses brief and substantive, avoiding rambling or excessive emojis

Context framework:
- Conversation history: {chat_history}
- User's current message: {input}

Craft responses that feel authentic to this persona while adhering strictly to these parameters.
`;

const prompt = new PromptTemplate({
  template: template,
  inputVariables: ["input", "chat_history"], 
});

const items = this.getInputData();
const model = await this.getInputConnectionData('ai_languageModel', 0);
const memory = await this.getInputConnectionData('ai_memory', 0);
memory.returnMessages = false;

const chain = new ConversationChain({ llm:model, memory:memory, prompt: prompt, inputKey:"input", outputKey:"output"});
const output = await chain.call({ input: items[0].json.chatInput});

return output;

This code builds the conversation using LangChain’s memory and prompt.

Do not change placeholders {chat_history} or {input} inside the prompt.


Common setup problems and fixes

  • Problem: Calls to webhook fail or frontend shows CORS error.
    Fix: Set allowedOrigins to * or your domain in the When chat message received node.
  • Problem: Responses do not consider earlier messages.
    Fix: Ensure Store conversation history node output connects to the code node’s memory input.
  • Problem: API calls fail or return error.
    Fix: Check the Google Gemini API Key in the Google Gemini Chat Model node credentials.

Tips for customizations

  • Edit the template text in the code node to change AI character personality or language rules.
  • Adjust the Store conversation history node to keep more or less past messages for user context depth.
  • Replace the Google Gemini Chat Model node with other language model nodes by updating credentials and model names.
  • Change chat interface labels and allowed web origins in the When chat message received node.
  • Modify the prompt to respond in a different language or add bilingual replies.

Summary of results

✓ The workflow receives chat messages and remembers past talk.

✓ Replies fit the “Bunny” persona with Chinese language only.

✓ Easy to import and configure inside n8n editor.

✓ Works with Google Gemini API for natural replies.

→ Users get an engaging, personalized AI chat experience.


Automate AI chat with LangChain and n8n

Visit through Desktop to Interact with the Workflow.

Frequently Asked Questions

This node keeps recent messages to give the AI context. It helps the chatbot remember past conversations for better replies.
You need a valid Google Gemini API Key added in the node’s credentials settings inside n8n.
Yes, you can edit the prompt template text inside the code node to alter personality or response language.
Use the test chat button on the When chat message received node or send a JSON message to the webhook URL.

Promoted by BULDRR AI

Related Workflows

Automate Twist Channel Creation and Messaging with n8n

This workflow automates creating and updating a channel in Twist and sending a personalized message to specific users. It eliminates manual setup errors and saves time managing Twist communications.

Automate Ideogram Image Generation with Google Sheets & Gmail

This workflow automates graphic design image generation via Ideogram AI, storing image data in Google Sheets and Google Drive, with email alerts via Gmail. It saves designers hours by automating image creation, remixing, review, and record-keeping.

Automate IT Support with Slack and OpenAI in n8n

Streamline IT support by automating Slack message handling using n8n and OpenAI. This workflow handles Slack DMs, filters bots, queries a Confluence knowledge base, and delivers AI-generated responses, improving support efficiency and response time.

Automate Crypto Analysis with CoinMarketCap & n8n AI Agent

Discover how this unique n8n workflow leverages CoinMarketCap’s multi-agent AI to deliver precise, real-time cryptocurrency insights directly via Telegram. Manage crypto data analysis efficiently with automated multi-source API integration.

Automate Gumroad to Beehiiv Subscriber Sync with n8n

Learn how to automatically add new Gumroad sales customers as Beehiiv newsletter subscribers using n8n automation. This workflow saves time by syncing sales data to Google Sheets CRM and notifying your Telegram channel instantly.

Generate On-Brand Blog Articles Using n8n and OpenAI

This workflow automates the creation of on-brand blog articles by analyzing existing company content using n8n and OpenAI. It extracts article structures and brand voice to produce consistent draft articles, saving significant content creation time.
1:1 Free Strategy Session
Your competitors are already automating. Are you still paying for it manually?

Do you want to adopt AI Automation?

Every hour your team does repetitive work, you're burning real money.
While you wait, faster businesses are cutting costs and moving quicker.
AI and automations aren't the future anymore — they're the present.

Book a live 1-on-1 session where we show you exactly which of your daily tasks can be automated — and what it’s costing you not to.