forked from gprzybycien/lf-gateway
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
201 lines (163 loc) · 5.35 KB
/
Copy pathserver.js
File metadata and controls
201 lines (163 loc) · 5.35 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
193
194
195
196
197
198
199
200
201
const express = require("express");
const app = express();
app.use(express.json());
const {
GATEWAY_API_KEY,
DATASTAX_LANGFLOW_URL,
LANGFLOW_TENANT_ID,
FLOW_ID,
ASTRA_ORG_ID,
APPLICATION_TOKEN
} = process.env;
app.get("/", (_req, res) => {
res.send("gateway alive");
});
app.get("/health", (_req, res) => {
res.json({ ok: true });
});
app.post("/run", async (req, res) => {
const received = (req.header("x-api-key") || "").trim().replace(/:$/, "");
if (received !== GATEWAY_API_KEY) {
return res.status(401).json({ error: "Unauthorized" });
}
const { raw_user_input, session_id } = req.body || {};
if (!raw_user_input || typeof raw_user_input !== "string") {
return res.status(400).json({ error: "Missing required field: raw_user_input" });
}
console.log("Incoming raw_user_input:", raw_user_input);
const url =
`${DATASTAX_LANGFLOW_URL}/lf/${LANGFLOW_TENANT_ID}/api/v1/run/${FLOW_ID}?stream=true`;
console.log("Calling Langflow URL:", url);
console.log("Environment check:", {
hasUrl: !!DATASTAX_LANGFLOW_URL,
hasTenant: !!LANGFLOW_TENANT_ID,
hasFlow: !!FLOW_ID,
hasOrg: !!ASTRA_ORG_ID,
hasToken: !!APPLICATION_TOKEN
});
// Check if client accepts streaming
const acceptHeader = req.header("accept") || "";
const wantsStreaming = acceptHeader.includes("text/event-stream");
try {
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${APPLICATION_TOKEN}`,
"X-DataStax-Current-Org": ASTRA_ORG_ID
},
body: JSON.stringify({
input_value: raw_user_input,
input_type: "chat",
output_type: "chat",
...(session_id ? { session_id } : {})
})
});
console.log("Langflow status:", response.status);
if (!response.ok) {
const text = await response.text();
let data;
try {
data = JSON.parse(text);
} catch {
data = { raw: text };
}
console.log("Langflow error response:", text);
return res.status(response.status).json({
error: "Langflow API error",
status: response.status,
response: data
});
}
// If client wants streaming, stream the response
if (wantsStreaming && response.body) {
console.log("Streaming response to client");
// Set headers for Server-Sent Events streaming
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.setHeader('X-Accel-Buffering', 'no'); // Disable nginx buffering
try {
// Stream the response
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
let eventCount = 0;
while (true) {
const { done, value } = await reader.read();
if (done) {
console.log(`Streaming complete. Total events: ${eventCount}`);
break;
}
// Decode the chunk
buffer += decoder.decode(value, { stream: true });
// Process complete lines
const lines = buffer.split('\n');
buffer = lines.pop() || ''; // Keep incomplete line in buffer
for (const line of lines) {
if (line.trim()) {
try {
// Parse and forward the event
const event = JSON.parse(line);
eventCount++;
// Forward as SSE
res.write(`data: ${line}\n\n`);
// Log event type
if (eventCount % 10 === 0) {
console.log(`Streamed ${eventCount} events...`);
}
} catch (e) {
console.error('Failed to parse event:', e);
}
}
}
}
// Process any remaining buffer
if (buffer.trim()) {
try {
const event = JSON.parse(buffer);
res.write(`data: ${buffer}\n\n`);
eventCount++;
} catch (e) {
console.error('Failed to parse final event:', e);
}
}
// End the stream
res.end();
} catch (streamError) {
console.error('Streaming error:', streamError);
res.write(`data: ${JSON.stringify({ event: 'error', data: { error: String(streamError) } })}\n\n`);
res.end();
}
} else {
// Non-streaming response (original behavior)
console.log("Returning non-streaming response");
const text = await response.text();
let data;
try {
data = JSON.parse(text);
} catch {
data = { raw: text };
}
const answer =
data?.outputs?.[0]?.outputs?.[0]?.results?.message?.text ??
data?.outputs?.[0]?.outputs?.[0]?.results?.message ??
"";
return res.json({
answer,
raw: data
});
}
} catch (err) {
console.error("Gateway failure:", err);
return res.status(500).json({
error: "Gateway failure",
details: String(err)
});
}
});
const port = process.env.PORT || 10000;
app.listen(port, () => {
console.log(`Gateway running on port ${port}`);
});
// Made with Bob