How to build AI agents with persistence on n8n
Build AI agents with persistence in n8n by combining AI nodes with memory storage solutions like PostgreSQL or Google Sheets. Use workflow variables and database connections to maintain conversation history and agent state across multiple interactions.
Prerequisites
- Basic n8n workflow knowledge
- OpenAI API key or similar AI service
- Understanding of JSON data structures
- Familiarity with HTTP requests
Step-by-Step Instructions
Set up the database for persistence
session_id, message, timestamp, and agent_state to store conversation history and agent memory.Configure the webhook trigger
POST. Enable Response Mode to Respond to Webhook and set Response Data to Last Node. This creates an endpoint where users can send messages to your AI agent and receive responses.Retrieve conversation history
SELECT * FROM conversations WHERE session_id = '{{$json.session_id}}' ORDER BY timestamp DESC LIMIT 10. This retrieves the last 10 messages for context. Use the IF node to handle cases where no history exists for new conversations.Format context for the AI model
const context = items[0].json.history.map(msg => `${msg.role}: ${msg.content}`).join('\n'). Structure this as the input for your AI model.Process with AI model
gpt-3.5-turbo or gpt-4, input your formatted context as the Messages, and configure Temperature between 0.3-0.7 for consistent responses. The AI will generate responses based on the persistent conversation history.Save the interaction to database
INSERT INTO conversations (session_id, role, message, timestamp) VALUES ('{{$json.session_id}}', 'user', '{{$json.user_message}}', NOW()). Repeat for the AI response to maintain complete conversation history.Implement agent state management
if (message.includes('remember')) { updateState('preference', extractedValue) }. This enables the agent to remember important details across sessions.Return formatted response
{ "response": "{{$json.ai_message}}", "session_id": "{{$json.session_id}}", "timestamp": "{{$now}}" }. Set the Response Code to 200 and Content-Type to application/json.Common Issues & Troubleshooting
Database connection timeouts during high traffic
Implement connection pooling in your database settings and add Wait nodes with 1-2 second delays between database operations. Consider using Redis for session storage instead of PostgreSQL for better performance.
AI responses are inconsistent across conversation sessions
Check your context formatting in the Code node and ensure conversation history is properly retrieved. Verify that your session_id is consistent and that the ORDER BY clause includes timestamp ASC for chronological context.
Webhook responses timing out
Add Error Trigger nodes to handle failures gracefully and implement async processing by storing requests in a queue table. Use the HTTP Request node to send responses via callback URLs for long-running AI operations.
Memory usage growing too large with conversation history
Implement automatic cleanup by adding a scheduled workflow that deletes conversations older than 30 days: DELETE FROM conversations WHERE timestamp < NOW() - INTERVAL '30 days'. Limit context retrieval to essential recent messages only.