-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathroute.ts
More file actions
344 lines (308 loc) · 11.7 KB
/
route.ts
File metadata and controls
344 lines (308 loc) · 11.7 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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
import { createLogger } from '@sim/logger'
import { type NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
import { generateRequestId } from '@/lib/core/utils/request'
import { batchChunkOperation, createChunk, queryChunks } from '@/lib/knowledge/chunks/service'
import { authorizeWorkflowByWorkspacePermission } from '@/lib/workflows/utils'
import { checkDocumentAccess, checkDocumentWriteAccess } from '@/app/api/knowledge/utils'
import { calculateCost } from '@/providers/utils'
const logger = createLogger('DocumentChunksAPI')
const GetChunksQuerySchema = z.object({
search: z.string().optional(),
enabled: z.enum(['true', 'false', 'all']).optional().default('all'),
limit: z.coerce.number().min(1).max(100).optional().default(50),
offset: z.coerce.number().min(0).optional().default(0),
sortBy: z.enum(['chunkIndex', 'tokenCount', 'enabled']).optional().default('chunkIndex'),
sortOrder: z.enum(['asc', 'desc']).optional().default('asc'),
})
const CreateChunkSchema = z.object({
content: z.string().min(1, 'Content is required').max(10000, 'Content too long'),
enabled: z.boolean().optional().default(true),
})
const BatchOperationSchema = z.object({
operation: z.enum(['enable', 'disable', 'delete']),
chunkIds: z
.array(z.string())
.min(1, 'At least one chunk ID is required')
.max(100, 'Cannot operate on more than 100 chunks at once'),
})
export async function GET(
req: NextRequest,
{ params }: { params: Promise<{ id: string; documentId: string }> }
) {
const requestId = generateRequestId()
const { id: knowledgeBaseId, documentId } = await params
try {
const auth = await checkSessionOrInternalAuth(req, { requireWorkflowId: false })
if (!auth.success || !auth.userId) {
logger.warn(`[${requestId}] Unauthorized chunks access attempt`)
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const userId = auth.userId
const accessCheck = await checkDocumentAccess(knowledgeBaseId, documentId, userId)
if (!accessCheck.hasAccess) {
if (accessCheck.notFound) {
logger.warn(
`[${requestId}] ${accessCheck.reason}: KB=${knowledgeBaseId}, Doc=${documentId}`
)
return NextResponse.json({ error: accessCheck.reason }, { status: 404 })
}
logger.warn(
`[${requestId}] User ${userId} attempted unauthorized chunks access: ${accessCheck.reason}`
)
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const doc = accessCheck.document
if (!doc) {
logger.warn(
`[${requestId}] Document data not available: KB=${knowledgeBaseId}, Doc=${documentId}`
)
return NextResponse.json({ error: 'Document not found' }, { status: 404 })
}
if (doc.processingStatus !== 'completed') {
logger.warn(
`[${requestId}] Document ${documentId} is not ready for chunk access (status: ${doc.processingStatus})`
)
return NextResponse.json(
{
error: 'Document is not ready for access',
details: `Document status: ${doc.processingStatus}`,
retryAfter: doc.processingStatus === 'processing' ? 5 : null,
},
{ status: 400 }
)
}
const { searchParams } = new URL(req.url)
const queryParams = GetChunksQuerySchema.parse({
search: searchParams.get('search') || undefined,
enabled: searchParams.get('enabled') || undefined,
limit: searchParams.get('limit') || undefined,
offset: searchParams.get('offset') || undefined,
sortBy: searchParams.get('sortBy') || undefined,
sortOrder: searchParams.get('sortOrder') || undefined,
})
const result = await queryChunks(knowledgeBaseId, documentId, queryParams, requestId)
return NextResponse.json({
success: true,
data: result.chunks,
pagination: result.pagination,
})
} catch (error) {
logger.error(`[${requestId}] Error fetching chunks`, error)
return NextResponse.json({ error: 'Failed to fetch chunks' }, { status: 500 })
}
}
export async function POST(
req: NextRequest,
{ params }: { params: Promise<{ id: string; documentId: string }> }
) {
const requestId = generateRequestId()
const { id: knowledgeBaseId, documentId } = await params
try {
const body = await req.json()
const { workflowId, ...searchParams } = body
const auth = await checkSessionOrInternalAuth(req, { requireWorkflowId: false })
if (!auth.success || !auth.userId) {
logger.warn(`[${requestId}] Authentication failed: ${auth.error || 'Unauthorized'}`)
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const userId = auth.userId
if (workflowId) {
const authorization = await authorizeWorkflowByWorkspacePermission({
workflowId,
userId,
action: 'write',
})
if (!authorization.allowed) {
return NextResponse.json(
{ error: authorization.message || 'Access denied' },
{ status: authorization.status }
)
}
}
const accessCheck = await checkDocumentWriteAccess(knowledgeBaseId, documentId, userId)
if (!accessCheck.hasAccess) {
if (accessCheck.notFound) {
logger.warn(
`[${requestId}] ${accessCheck.reason}: KB=${knowledgeBaseId}, Doc=${documentId}`
)
return NextResponse.json({ error: accessCheck.reason }, { status: 404 })
}
logger.warn(
`[${requestId}] User ${userId} attempted unauthorized chunk creation: ${accessCheck.reason}`
)
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const doc = accessCheck.document
if (!doc) {
logger.warn(
`[${requestId}] Document data not available: KB=${knowledgeBaseId}, Doc=${documentId}`
)
return NextResponse.json({ error: 'Document not found' }, { status: 404 })
}
if (doc.connectorId) {
logger.warn(
`[${requestId}] User ${userId} attempted to create chunk on connector-synced document: Doc=${documentId}`
)
return NextResponse.json(
{ error: 'Chunks from connector-synced documents are read-only' },
{ status: 403 }
)
}
// Allow manual chunk creation even if document is not fully processed
// but it should exist and not be in failed state
if (doc.processingStatus === 'failed') {
logger.warn(`[${requestId}] Document ${documentId} is in failed state, cannot add chunks`)
return NextResponse.json({ error: 'Cannot add chunks to failed document' }, { status: 400 })
}
try {
const validatedData = CreateChunkSchema.parse(searchParams)
const docTags = {
// Text tags (7 slots)
tag1: doc.tag1 ?? null,
tag2: doc.tag2 ?? null,
tag3: doc.tag3 ?? null,
tag4: doc.tag4 ?? null,
tag5: doc.tag5 ?? null,
tag6: doc.tag6 ?? null,
tag7: doc.tag7 ?? null,
// Number tags (5 slots)
number1: doc.number1 ?? null,
number2: doc.number2 ?? null,
number3: doc.number3 ?? null,
number4: doc.number4 ?? null,
number5: doc.number5 ?? null,
// Date tags (2 slots)
date1: doc.date1 ?? null,
date2: doc.date2 ?? null,
// Boolean tags (3 slots)
boolean1: doc.boolean1 ?? null,
boolean2: doc.boolean2 ?? null,
boolean3: doc.boolean3 ?? null,
}
const newChunk = await createChunk(
knowledgeBaseId,
documentId,
docTags,
validatedData,
requestId,
accessCheck.knowledgeBase?.workspaceId
)
let cost = null
try {
cost = calculateCost('text-embedding-3-small', newChunk.tokenCount, 0, false)
} catch (error) {
logger.warn(`[${requestId}] Failed to calculate cost for chunk upload`, {
error: error instanceof Error ? error.message : 'Unknown error',
})
// Continue without cost information rather than failing the upload
}
return NextResponse.json({
success: true,
data: {
...newChunk,
documentId,
documentName: doc.filename,
...(cost
? {
cost: {
input: cost.input,
output: cost.output,
total: cost.total,
tokens: {
prompt: newChunk.tokenCount,
completion: 0,
total: newChunk.tokenCount,
},
model: 'text-embedding-3-small',
pricing: cost.pricing,
},
}
: {}),
},
})
} catch (validationError) {
if (validationError instanceof z.ZodError) {
logger.warn(`[${requestId}] Invalid chunk creation data`, {
errors: validationError.errors,
})
return NextResponse.json(
{ error: 'Invalid request data', details: validationError.errors },
{ status: 400 }
)
}
throw validationError
}
} catch (error) {
logger.error(`[${requestId}] Error creating chunk`, error)
return NextResponse.json({ error: 'Failed to create chunk' }, { status: 500 })
}
}
export async function PATCH(
req: NextRequest,
{ params }: { params: Promise<{ id: string; documentId: string }> }
) {
const requestId = generateRequestId()
const { id: knowledgeBaseId, documentId } = await params
try {
const auth = await checkSessionOrInternalAuth(req, { requireWorkflowId: false })
if (!auth.success || !auth.userId) {
logger.warn(`[${requestId}] Unauthorized batch chunk operation attempt`)
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const userId = auth.userId
const accessCheck = await checkDocumentAccess(knowledgeBaseId, documentId, userId)
if (!accessCheck.hasAccess) {
if (accessCheck.notFound) {
logger.warn(
`[${requestId}] ${accessCheck.reason}: KB=${knowledgeBaseId}, Doc=${documentId}`
)
return NextResponse.json({ error: accessCheck.reason }, { status: 404 })
}
logger.warn(
`[${requestId}] User ${userId} attempted unauthorized batch chunk operation: ${accessCheck.reason}`
)
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
if (accessCheck.document?.connectorId) {
logger.warn(
`[${requestId}] User ${userId} attempted batch chunk operation on connector-synced document: Doc=${documentId}`
)
return NextResponse.json(
{ error: 'Chunks from connector-synced documents are read-only' },
{ status: 403 }
)
}
const body = await req.json()
try {
const validatedData = BatchOperationSchema.parse(body)
const { operation, chunkIds } = validatedData
const result = await batchChunkOperation(knowledgeBaseId, documentId, operation, chunkIds, requestId)
return NextResponse.json({
success: true,
data: {
operation,
successCount: result.processed,
errorCount: result.errors.length,
processed: result.processed,
errors: result.errors,
},
})
} catch (validationError) {
if (validationError instanceof z.ZodError) {
logger.warn(`[${requestId}] Invalid batch operation data`, {
errors: validationError.errors,
})
return NextResponse.json(
{ error: 'Invalid request data', details: validationError.errors },
{ status: 400 }
)
}
throw validationError
}
} catch (error) {
logger.error(`[${requestId}] Error in batch chunk operation`, error)
return NextResponse.json({ error: 'Failed to perform batch operation' }, { status: 500 })
}
}