1+ """Complete n8n Integration Example for PraisonAI
2+
3+ This example demonstrates the complete bidirectional n8n ↔ PraisonAI integration:
4+
5+ 1. PraisonAI → n8n: Agents executing n8n workflows (using PraisonAI-Tools)
6+ 2. n8n → PraisonAI: n8n workflows invoking PraisonAI agents (using API endpoint)
7+
8+ Prerequisites:
9+ 1. Install dependencies:
10+ pip install "praisonai-tools[n8n]" fastapi uvicorn
11+
12+ 2. Set up n8n instance:
13+ docker run -it --rm --name n8n -p 5678:5678 -v n8n_data:/home/node/.n8n docker.n8n.io/n8nio/n8n
14+
15+ 3. Environment variables:
16+ export N8N_URL="http://localhost:5678"
17+ export N8N_API_KEY="your-api-key" # optional for local testing
18+
19+ Usage:
20+ python examples/python/n8n_integration_example.py
21+ """
22+
23+ import os
24+ import asyncio
25+ import uvicorn
26+ from fastapi import FastAPI
27+ from praisonaiagents import Agent
28+
29+
30+ def setup_praisonai_agents ():
31+ """Set up PraisonAI agents with n8n tools."""
32+ print ("🚀 Setting up PraisonAI agents with n8n capabilities..." )
33+
34+ try :
35+ from praisonai_tools .n8n import n8n_workflow , n8n_list_workflows
36+
37+ # Create automation agent with n8n tools
38+ automation_agent = Agent (
39+ name = "automation-agent" ,
40+ instructions = """
41+ You are an automation specialist with access to n8n's 400+ integrations.
42+ You can help users automate workflows across platforms like:
43+
44+ - Communication: Slack, Discord, Telegram, Gmail, Teams
45+ - Productivity: Notion, Google Sheets, Airtable, Trello
46+ - Databases: PostgreSQL, MongoDB, MySQL, Redis
47+ - APIs: REST, GraphQL, webhooks
48+
49+ When asked to perform automation tasks:
50+ 1. First list available n8n workflows if needed
51+ 2. Execute the appropriate workflow with the provided data
52+ 3. Explain what the workflow accomplished
53+
54+ Always be helpful and provide clear explanations.
55+ """ ,
56+ tools = [n8n_workflow , n8n_list_workflows ],
57+ llm = "gpt-4o-mini"
58+ )
59+
60+ # Create notification agent focused on messaging
61+ notification_agent = Agent (
62+ name = "notification-agent" ,
63+ instructions = """
64+ You specialize in sending notifications and messages across platforms.
65+ You have access to n8n workflows for various messaging platforms.
66+
67+ When asked to send notifications:
68+ 1. Determine the best platform for the message
69+ 2. Use appropriate n8n workflow for that platform
70+ 3. Include relevant context and formatting
71+
72+ Be efficient and reliable with notifications.
73+ """ ,
74+ tools = [n8n_workflow ],
75+ llm = "gpt-4o-mini"
76+ )
77+
78+ return {
79+ "automation" : automation_agent ,
80+ "notification" : notification_agent
81+ }
82+
83+ except ImportError as e :
84+ print (f"❌ Error importing n8n tools: { e } " )
85+ print ("💡 Install with: pip install 'praisonai-tools[n8n]'" )
86+ return {}
87+
88+
89+ def setup_api_server_with_agents (agents ):
90+ """Set up FastAPI server with agent invoke endpoints."""
91+ print ("🌐 Setting up API server for n8n → PraisonAI integration..." )
92+
93+ from praisonai .api .agent_invoke import register_agent , router
94+
95+ # Create FastAPI app
96+ app = FastAPI (
97+ title = "PraisonAI n8n Integration Server" ,
98+ description = "API server for n8n to invoke PraisonAI agents" ,
99+ version = "1.0.0"
100+ )
101+
102+ # Include agent invoke router
103+ app .include_router (router )
104+
105+ # Register agents
106+ for agent_id , agent in agents .items ():
107+ register_agent (agent_id , agent )
108+ print (f"📋 Registered agent: { agent_id } " )
109+
110+ @app .get ("/" )
111+ async def root ():
112+ """Root endpoint with integration information."""
113+ return {
114+ "message" : "PraisonAI n8n Integration Server" ,
115+ "available_agents" : list (agents .keys ()),
116+ "endpoints" : {
117+ "invoke_agent" : "/api/v1/agents/{agent_id}/invoke" ,
118+ "list_agents" : "/api/v1/agents" ,
119+ "agent_info" : "/api/v1/agents/{agent_id}"
120+ },
121+ "n8n_integration" : {
122+ "description" : "Use HTTP Request node in n8n to invoke agents" ,
123+ "example_url" : "http://localhost:8000/api/v1/agents/automation/invoke" ,
124+ "example_body" : {
125+ "message" : "Send a Slack message to #general saying 'Hello from n8n!'" ,
126+ "session_id" : "n8n-workflow-123"
127+ }
128+ }
129+ }
130+
131+ return app
132+
133+
134+ async def demo_praisonai_to_n8n (agents ):
135+ """Demonstrate PraisonAI agents calling n8n workflows."""
136+ print ("\n 🔄 Demo: PraisonAI → n8n Integration" )
137+ print ("=" * 50 )
138+
139+ if not agents :
140+ print ("❌ No agents available for demo" )
141+ return
142+
143+ automation_agent = agents .get ("automation" )
144+ if not automation_agent :
145+ print ("❌ Automation agent not available" )
146+ return
147+
148+ try :
149+ print ("📋 Testing agent with n8n workflow listing..." )
150+ response = automation_agent .start (
151+ "Can you list the available n8n workflows?"
152+ )
153+ print (f"🤖 Agent: { response } " )
154+
155+ print ("\n 🚀 Testing workflow execution..." )
156+ response = automation_agent .start (
157+ "I need to send a notification that our deployment was successful. "
158+ "Can you help me send this via Slack to the #deployments channel?"
159+ )
160+ print (f"🤖 Agent: { response } " )
161+
162+ except Exception as e :
163+ print (f"❌ Demo error: { e } " )
164+
165+
166+ async def demo_n8n_to_praisonai ():
167+ """Demonstrate n8n invoking PraisonAI agents via HTTP."""
168+ print ("\n 🔄 Demo: n8n → PraisonAI Integration" )
169+ print ("=" * 50 )
170+
171+ try :
172+ import httpx
173+
174+ # Simulate n8n HTTP Request node call
175+ print ("📡 Simulating n8n HTTP Request node call..." )
176+
177+ async with httpx .AsyncClient () as client :
178+ response = await client .post (
179+ "http://localhost:8000/api/v1/agents/notification/invoke" ,
180+ json = {
181+ "message" : "A new user has signed up: john@example.com. Please send a welcome email." ,
182+ "session_id" : "n8n-user-signup-workflow"
183+ },
184+ timeout = 30.0
185+ )
186+
187+ if response .status_code == 200 :
188+ data = response .json ()
189+ print (f"✅ Success: { data ['result' ]} " )
190+ print (f"📊 Session: { data ['session_id' ]} " )
191+ else :
192+ print (f"❌ Error: { response .status_code } - { response .text } " )
193+
194+ except httpx .ConnectError :
195+ print ("❌ Connection error: Make sure the API server is running" )
196+ print ("💡 Start server in another terminal: python examples/python/n8n_integration_example.py --server" )
197+ except Exception as e :
198+ print (f"❌ Demo error: { e } " )
199+
200+
201+ def create_n8n_workflow_examples ():
202+ """Show examples of n8n workflow configurations."""
203+ print ("\n 📝 n8n Workflow Configuration Examples" )
204+ print ("=" * 50 )
205+
206+ print ("""
207+ 🔹 HTTP Request Node (n8n → PraisonAI):
208+ Method: POST
209+ URL: http://localhost:8000/api/v1/agents/automation/invoke
210+ Body:
211+ {
212+ "message": "{{ $json.user_message }}",
213+ "session_id": "{{ $json.session_id || workflow.id }}"
214+ }
215+
216+ 🔹 Webhook Trigger for PraisonAI response:
217+ URL: http://localhost:8000/webhook/praisonai-response
218+ Method: POST
219+
220+ 🔹 Slack notification after agent response:
221+ Channel: {{ $json.channel || '#general' }}
222+ Message: Agent response: {{ $json.agent_result }}
223+ """ )
224+
225+
226+ async def run_interactive_demo ():
227+ """Run interactive demo of the integration."""
228+ print ("\n 🎮 Interactive Demo" )
229+ print ("=" * 20 )
230+
231+ # Set up agents
232+ agents = setup_praisonai_agents ()
233+ if not agents :
234+ print ("❌ Cannot run interactive demo without agents" )
235+ return
236+
237+ automation_agent = agents .get ("automation" )
238+ if not automation_agent :
239+ print ("❌ Automation agent not available" )
240+ return
241+
242+ print ("💬 Chat with the automation agent (type 'quit' to exit)" )
243+ print ("💡 Try: 'List available n8n workflows'" )
244+ print ("💡 Try: 'Send a Slack message to #general'" )
245+
246+ while True :
247+ try :
248+ user_input = input ("\n 👤 You: " ).strip ()
249+ if user_input .lower () in ['quit' , 'exit' , 'q' ]:
250+ break
251+
252+ if not user_input :
253+ continue
254+
255+ print ("🤖 Agent: " , end = "" , flush = True )
256+ response = automation_agent .start (user_input )
257+ print (response )
258+
259+ except KeyboardInterrupt :
260+ print ("\n 👋 Goodbye!" )
261+ break
262+ except Exception as e :
263+ print (f"\n ❌ Error: { e } " )
264+
265+
266+ def run_server (port = 8000 ):
267+ """Run the API server for n8n integration."""
268+ print (f"\n 🚀 Starting PraisonAI n8n Integration Server on port { port } ..." )
269+
270+ # Set up agents
271+ agents = setup_praisonai_agents ()
272+
273+ # Create app
274+ app = setup_api_server_with_agents (agents )
275+
276+ print (f"✅ Server ready at http://localhost:{ port } " )
277+ print (f"📊 Available agents: { list (agents .keys ())} " )
278+ print ("\n 🔗 n8n HTTP Request Node Configuration:" )
279+ print (f" URL: http://localhost:{ port } /api/v1/agents/{{agent_id}}/invoke" )
280+ print (" Method: POST" )
281+ print (' Body: {"message": "Your message here", "session_id": "optional"}' )
282+
283+ # Run server
284+ uvicorn .run (app , host = "0.0.0.0" , port = port )
285+
286+
287+ async def main ():
288+ """Main function to run demos."""
289+ import argparse
290+
291+ parser = argparse .ArgumentParser (description = "PraisonAI n8n Integration Demo" )
292+ parser .add_argument ("--server" , action = "store_true" , help = "Run API server" )
293+ parser .add_argument ("--demo" , action = "store_true" , help = "Run demos" )
294+ parser .add_argument ("--interactive" , action = "store_true" , help = "Run interactive demo" )
295+ parser .add_argument ("--port" , type = int , default = 8000 , help = "Server port" )
296+
297+ args = parser .parse_args ()
298+
299+ if args .server :
300+ run_server (args .port )
301+ elif args .interactive :
302+ await run_interactive_demo ()
303+ elif args .demo :
304+ # Set up agents for demos
305+ agents = setup_praisonai_agents ()
306+
307+ # Run demos
308+ await demo_praisonai_to_n8n (agents )
309+ create_n8n_workflow_examples ()
310+ print ("\n 💡 To test n8n → PraisonAI, start the server:" )
311+ print (" python examples/python/n8n_integration_example.py --server" )
312+ print (" Then run: python examples/python/n8n_integration_example.py --test-api" )
313+
314+ else :
315+ # Default: show info and run basic demo
316+ print ("🔗 PraisonAI ↔ n8n Bidirectional Integration" )
317+ print ("=" * 50 )
318+
319+ print ("\n 📋 Integration Components:" )
320+ print ("1. 🔧 PraisonAI-Tools: n8n workflow execution tools" )
321+ print ("2. 🌐 API Endpoint: Agent invoke endpoint for n8n" )
322+ print ("3. 🤖 Agents: PraisonAI agents with n8n capabilities" )
323+
324+ print ("\n 🚀 Available Commands:" )
325+ print (" --demo Run integration demos" )
326+ print (" --server Start API server for n8n" )
327+ print (" --interactive Run interactive agent chat" )
328+
329+ # Quick demo
330+ agents = setup_praisonai_agents ()
331+ if agents :
332+ await demo_praisonai_to_n8n (agents )
333+ create_n8n_workflow_examples ()
334+
335+
336+ if __name__ == "__main__" :
337+ asyncio .run (main ())
0 commit comments