-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathn8n-workflow-v3.json
More file actions
192 lines (192 loc) · 7.52 KB
/
n8n-workflow-v3.json
File metadata and controls
192 lines (192 loc) · 7.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
{
"name": "Chatbot Workflow - JavaScript Request Builder",
"nodes": [
{
"parameters": {
"httpMethod": "POST",
"path": "chatbot-v3",
"responseMode": "responseNode",
"options": {}
},
"id": "webhook-trigger",
"name": "Webhook Trigger",
"type": "n8n-nodes-base.webhook",
"typeVersion": 1,
"position": [240, 300],
"webhookId": "your-webhook-id-v3"
},
{
"parameters": {
"conditions": {
"options": {
"caseSensitive": true,
"leftValue": "",
"typeValidation": "strict"
},
"conditions": [
{
"id": "condition1",
"leftValue": "={{ $json.body.session_variables['x-hasura-user-id'] }}",
"rightValue": "",
"operator": {
"type": "string",
"operation": "notEmpty"
}
}
],
"combinator": "and"
}
},
"id": "validate-user",
"name": "Validate User",
"type": "n8n-nodes-base.if",
"typeVersion": 2,
"position": [460, 300]
},
{
"parameters": {
"jsCode": "// Extract webhook data and prepare OpenRouter request\nconst webhookData = $input.first().json;\nconsole.log('Webhook Data:', JSON.stringify(webhookData, null, 2));\n\nconst userMessage = webhookData.body.input.message;\nconst chatId = webhookData.body.input.chat_id;\nconst userId = webhookData.body.session_variables['x-hasura-user-id'];\n\nconsole.log('User Message:', userMessage);\nconsole.log('Chat ID:', chatId);\nconsole.log('User ID:', userId);\n\n// Prepare OpenRouter API request\nconst openRouterRequest = {\n model: \"openai/gpt-3.5-turbo\",\n messages: [\n {\n role: \"system\",\n content: \"You are a helpful AI assistant. Be concise and friendly in your responses.\"\n },\n {\n role: \"user\",\n content: userMessage\n }\n ],\n max_tokens: 150,\n temperature: 0.7\n};\n\nconsole.log('OpenRouter Request:', JSON.stringify(openRouterRequest, null, 2));\n\nreturn {\n openRouterRequest: openRouterRequest,\n chatId: chatId,\n userMessage: userMessage,\n userId: userId\n};"
},
"id": "prepare-request",
"name": "Prepare Request",
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [680, 200]
},
{
"parameters": {
"method": "POST",
"url": "https://openrouter.ai/api/v1/chat/completions",
"sendHeaders": true,
"headerParameters": {
"parameters": [
{
"name": "Authorization",
"value": "Bearer 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"
},
{
"name": "Content-Type",
"value": "application/json"
},
{
"name": "HTTP-Referer",
"value": "https://your-app-domain.com"
},
{
"name": "X-Title",
"value": "Chatbot App"
}
]
},
"sendBody": true,
"specifyBody": "json",
"jsonBody": "={{ $json.openRouterRequest }}",
"options": {}
},
"id": "call-openrouter",
"name": "Call OpenRouter AI",
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4.2,
"position": [900, 200]
},
{
"parameters": {
"jsCode": "// Process OpenRouter response and save to database\nconst openRouterResponse = $input.first().json;\nconst requestData = $('Prepare Request').first().json;\n\nconsole.log('OpenRouter Response:', JSON.stringify(openRouterResponse, null, 2));\nconsole.log('Request Data:', JSON.stringify(requestData, null, 2));\n\n// Extract AI content (handle both array and object responses)\nlet aiContent;\nif (Array.isArray(openRouterResponse)) {\n aiContent = openRouterResponse[0]?.choices?.[0]?.message?.content;\n} else {\n aiContent = openRouterResponse?.choices?.[0]?.message?.content;\n}\n\nconst chatId = requestData.chatId;\nconst userMessage = requestData.userMessage;\n\nconsole.log('Extracted AI Content:', aiContent);\nconsole.log('Chat ID:', chatId);\n\nif (!aiContent) {\n throw new Error('Failed to extract AI content from OpenRouter response');\n}\n\n// Save to database using n8n's $http helper\nconst graphqlQuery = {\n query: `mutation InsertBotMessage($chatId: uuid!, $content: String!) { \n insert_messages_one(object: { chat_id: $chatId, content: $content, is_bot: true }) { \n id \n } \n }`,\n variables: {\n chatId: chatId,\n content: aiContent\n }\n};\n\nconsole.log('GraphQL Query:', JSON.stringify(graphqlQuery, null, 2));\n\n// Make the GraphQL request using n8n's $http helper\ntry {\n const dbResult = await $http.request({\n method: 'POST',\n url: 'https://wertssqowjrkykmeovsg.hasura.ap-south-1.nhost.run/v1/graphql',\n headers: {\n 'Content-Type': 'application/json',\n 'x-hasura-admin-secret': 'Hq=1ILX8*V%Df8PlCyljd*BVys-::p,A'\n },\n body: graphqlQuery\n });\n \n console.log('Database Save Result:', JSON.stringify(dbResult, null, 2));\n \n if (dbResult.errors) {\n console.error('Database save failed:', dbResult.errors);\n }\n} catch (dbError) {\n console.error('Database request failed:', dbError);\n // Don't throw error, just log it and continue\n}\n\n// Return success response\nreturn {\n success: true,\n message: 'Response generated successfully',\n response: aiContent,\n debug: {\n openRouterResponse: openRouterResponse,\n chatId: chatId\n }\n};"
},
"id": "process-and-save",
"name": "Process and Save",
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [1120, 200]
},
{
"parameters": {
"respondWith": "json",
"responseBody": "={{ $json }}"
},
"id": "success-response",
"name": "Success Response",
"type": "n8n-nodes-base.respondToWebhook",
"typeVersion": 1,
"position": [1340, 200]
},
{
"parameters": {
"respondWith": "json",
"responseBody": "{\n \"success\": false,\n \"message\": \"Authentication required: No valid user session\",\n \"response\": null\n}",
"options": {
"responseCode": 401
}
},
"id": "auth-required-response",
"name": "Auth Required Response",
"type": "n8n-nodes-base.respondToWebhook",
"typeVersion": 1,
"position": [460, 400]
}
],
"connections": {
"Webhook Trigger": {
"main": [
[
{
"node": "Validate User",
"type": "main",
"index": 0
}
]
]
},
"Validate User": {
"main": [
[
{
"node": "Prepare Request",
"type": "main",
"index": 0
}
],
[
{
"node": "Auth Required Response",
"type": "main",
"index": 0
}
]
]
},
"Prepare Request": {
"main": [
[
{
"node": "Call OpenRouter AI",
"type": "main",
"index": 0
}
]
]
},
"Call OpenRouter AI": {
"main": [
[
{
"node": "Process and Save",
"type": "main",
"index": 0
}
]
]
},
"Process and Save": {
"main": [
[
{
"node": "Success Response",
"type": "main",
"index": 0
}
]
]
}
}
}