Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 1 addition & 19 deletions embeddings/embeddings_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,33 +88,15 @@ async def process_document_endpoint(
file: UploadFile = File(...),
document_id: str = Form(...)
):
print(f"\n\n--- New Processing Request ---")
print(f"Document ID: {document_id}")
print(f"Filename: {file.filename}")
print(f"Content type: {file.content_type}")

try:
# First verify we can read the file
print("Attempting to read file...")
contents = await file.read()
print(f"Successfully read {len(contents)} bytes")
await file.seek(0) # Rewind for actual processing

# Now process the document
print("Starting document processing...")
result = await process_document(file, document_id)
print("Document processing completed successfully")
return result

except Exception as e:
import traceback
print("\n!!! ERROR OCCURRED !!!")
print(f"Error type: {type(e).__name__}")
print(f"Error message: {str(e)}")
print("Stack trace:")
traceback.print_exc()
print("!!! END OF ERROR !!!\n")

except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Error processing document: {str(e)}"
Expand Down
3 changes: 1 addition & 2 deletions src/app/api/auth/verify-session/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ export async function GET(request: Request) {
})

} catch (error) {
console.error('Session verification error:', error)
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
return NextResponse.json({ error: error }, { status: 500 })
}
}
4 changes: 0 additions & 4 deletions src/app/api/chat/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,10 @@ export async function POST(req: NextRequest) {
user.apiKey
);

console.log(`Found ${relevantChunks.length} relevant chunks`);

if (!Array.isArray(relevantChunks)) {
console.warn("findSimilarChunks did not return an array");
relevantChunks = [];
}
} catch (error) {
console.error("Error retrieving similar chunks:", error instanceof Error ? error.message : String(error));
relevantChunks = [];
// Log a more detailed error to help with debugging
if (error instanceof Error) {
Expand Down
12 changes: 2 additions & 10 deletions src/app/api/documents/process/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ const EMBEDDINGS_SERVICE_URL = process.env.EMBEDDINGS_SERVICE_URL || "http://loc
export async function POST(req: NextRequest) {
try {
const { documentId } = await req.json();
console.log('Starting document processing for documentId: ', documentId);


// get document and user info
const document = await prisma.document.findUnique({
where: { id: documentId },
Expand Down Expand Up @@ -46,9 +45,6 @@ export async function POST(req: NextRequest) {
formData.append('file', pdfBlob, 'document.pdf');
formData.append('document_id', document.id);

// Send the PDF to the FastAPI service for processing
console.log('Sending PDF to FastAPI service for processing...');

try {

const processingResponse = await fetch(`${EMBEDDINGS_SERVICE_URL}/process-document`, {
Expand All @@ -63,11 +59,9 @@ export async function POST(req: NextRequest) {

// Get the processing results
const processingResult = await processingResponse.json();
console.log('Processing result:', processingResult);

// Save document chunks to database using Prisma
if (processingResult.chunks && processingResult.chunks.length > 0) {
console.log(`Saving ${processingResult.chunks.length} chunks to database...`);

// Save each chunk to the database
for (const chunk of processingResult.chunks) {
Expand Down Expand Up @@ -101,7 +95,6 @@ export async function POST(req: NextRequest) {
}
}

console.log(`Document processing complete. Successfully processed ${processingResult.chunks_processed} chunks. Failed: ${processingResult.chunks_failed}`);
return NextResponse.json({
success: true,
message: 'Document processed successfully',
Expand All @@ -114,9 +107,8 @@ export async function POST(req: NextRequest) {
}

} catch (error) {
console.error('Error processing document: ', error);
return NextResponse.json(
{ error: 'Failed to process document' },
{ error: error },
{ status: 500 }
)
}
Expand Down
17 changes: 1 addition & 16 deletions src/app/api/documents/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ export async function POST(req: Request): Promise<NextResponse> {
}

if(!process.env.AWS_ACCESS_KEY_ID || !process.env.AWS_SECRET_ACCESS_KEY || !process.env.S3_PDFBUCKET_NAME) {
console.error('Missing S3 credentials in environment variables');
return NextResponse.json(
{error: 'Server configuration error: Missing S3 credentials'},
{status: 500}
Expand Down Expand Up @@ -87,20 +86,7 @@ export async function POST(req: Request): Promise<NextResponse> {
body: JSON.stringify({documentId: document.id}),
});

console.log('Process Response:', processResponse);

let responseData;
try {
const responseText = await processResponse.text();
responseData = JSON.parse(responseText);
console.log('Process Response:', responseData);
} catch (error) {
console.error('Error parsing process response:', error);
console.error('Raw response: ', await processResponse.text());
}

if (!processResponse.ok) {
console.error('Document processing failed with status:', processResponse.status);
// Continue anyway, as processing can be retrieved later
return NextResponse.json({
url: s3Result.url,
Expand All @@ -118,7 +104,6 @@ export async function POST(req: Request): Promise<NextResponse> {
processingStatus: 'success'
});
} catch (error) {
console.log(error);
return NextResponse.json({ error: 'An error occurred' });
return NextResponse.json({ error: error });
}
}
4 changes: 2 additions & 2 deletions src/app/api/health/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ export async function GET() {
version: process.env.npm_package_version || 'unknown'
});
} catch (error) {
console.error('Health check failed:', error);
return NextResponse.json(
{
status: 'error',
message: 'Health check failed',
timestamp: new Date().toISOString()
timestamp: new Date().toISOString(),
error: error instanceof Error ? error.message : String(error)
},
{ status: 500 }
);
Expand Down
3 changes: 1 addition & 2 deletions src/app/api/user/apikey/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,8 @@ export async function POST(req: NextRequest) {
})
return NextResponse.json({ message: 'API key updated successfully' });
} catch (error) {
console.error('Error updating API key: ', error);
return NextResponse.json(
{error: 'Failed to update API key'},
{error: error},
{status: 500}
)
}
Expand Down
2 changes: 1 addition & 1 deletion src/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ export default function Home() {
router.push('/login');
}
} catch (error) {
console.error('Auth check error: ', error);
// on error, redirect to login
router.push('/login');
console.error('Auth check error: ', error);
}
};
checkAuth();
Expand Down
2 changes: 0 additions & 2 deletions src/components/ChatInterface.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ export default function ChatInterface({
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Failed to send message. Please try again.';
setError(errorMessage);
console.error('Error sending message: ', error);
} finally {
setIsLoading(false);
}
Expand All @@ -79,7 +78,6 @@ export default function ChatInterface({
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Failed to start voice recording. Please try again.';
setError(errorMessage);
console.error('Error with voice recording: ', error);
}
}

Expand Down
3 changes: 2 additions & 1 deletion src/components/ChatSidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,8 @@ const ChatSidebar = forwardRef<ChatSidebarRef, ChatSidebarProps>(({
onDeleteConversation(conversationId, documentId);
}
} catch (error) {
console.error('Error deleting conversation:', error);
//TODO: Display error message to user
console.error('Delete conversation error: ', error);
alert('Failed to delete conversation');
} finally {
setDeleting(null);
Expand Down
10 changes: 9 additions & 1 deletion src/components/Dashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ function DashboardWithSearchParams () {
// Update URL with the selected conversation
updateUrl(convoId);
} catch (error) {
console.error('Error loading conversations: ', error);
// TODO: Display error message to user
console.error('Error loading conversation: ', error);
setError('Failed to load conversation');
}
}, [conversationId, updateUrl]);
Expand All @@ -93,6 +94,7 @@ function DashboardWithSearchParams () {
router.push('/login')
}
} catch (error) {
// TODO: Display error message to user
console.error('Auth check error: ', error);
router.push('/login');
}
Expand All @@ -109,9 +111,11 @@ function DashboardWithSearchParams () {
if(response.ok) {
setUserId(data.id);
} else {
// TODO: Display error message to user
console.error('Failed to fetch user: ', data);
}
} catch (error) {
// TODO: Display error message to user
console.error('Error fetching user:', error);
}
};
Expand Down Expand Up @@ -152,6 +156,7 @@ function DashboardWithSearchParams () {
await handleSelectConversation(chatId, matchingConversation.documentId);
}
} catch (error) {
// TODO: Display error message to user
console.error('Error restoring conversations: ', error);
setError('Failed to restore conversation from URL');
} finally {
Expand All @@ -171,6 +176,7 @@ function DashboardWithSearchParams () {
const data = await response.json();
return data.conversations;
} catch (error) {
// TODO: Display error message to user
console.error('Error fetching conversations: ', error);
setError('Failed to fetch conversations');
return [];
Expand Down Expand Up @@ -247,6 +253,7 @@ function DashboardWithSearchParams () {
console.error('No conversationId returned from server');
}
} catch (error) {
// TODO: Display error message to user
console.error('Upload error:', error);
setError('Failed to upload document');
}
Expand Down Expand Up @@ -297,6 +304,7 @@ function DashboardWithSearchParams () {
data.assistantMessage // Add assistant response
]);
} catch (error) {
// TODO: Display error message to user
console.error('Chat error: ', error);
setError('Failed to send message');
}
Expand Down
6 changes: 0 additions & 6 deletions src/components/EnhancedPDFViewer.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
// app/components/EnhancedPDFViewer.tsx

import { ChevronLeft, ChevronRight, Loader, Loader2, Upload } from "lucide-react";
import { useRef, useState } from "react";
import {Document, Page, pdfjs} from 'react-pdf';
Expand All @@ -8,11 +7,6 @@ import 'react-pdf/dist/Page/TextLayer.css';
// Initialize pdfjs worker
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.mjs`;

// pdfjs.GlobalWorkerOptions.workerSrc = new URL(
// "pdfjs-dist/build/pdf.worker.min.mjs",
// import.meta.url
// ).toString();

interface EnhancedPDFViewerProps {
currentPDF: string | null;
onFileUpload: (e: React.ChangeEvent<HTMLInputElement>) => void;
Expand Down
2 changes: 2 additions & 0 deletions src/components/ForgotPasswordForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export default function ForgotPasswordForm() {
},
body: requestBody,
}).catch(fetchError => {
// TODO: Display error message to user
console.error('Fetch error:', fetchError);
throw new Error('Network error occurred');
});
Expand All @@ -52,6 +53,7 @@ export default function ForgotPasswordForm() {
setSuccess('If an account with that email exists, you will receive a password reset link.');
setEmail('');
} catch (error) {
// TODO: Display error message to user
console.error('Password reset request error:', error);
setError(error instanceof Error ? error.message : 'An error occurred');
} finally {
Expand Down
1 change: 1 addition & 0 deletions src/components/LogoutButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export default function LogoutButton() {
// Force a page refresh to clear any client-side state
router.refresh();
} catch (error) {
// TODO: Display error message to user
console.error('Logout error:', error);
} finally {
setIsLoading(false);
Expand Down
2 changes: 0 additions & 2 deletions src/lib/pgvector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@ export async function getBatchEmbeddings(texts: string[]): Promise<number[][]> {
const data = await response.json();
return data.embeddings;
} catch (error) {
console.error("Error getting batch embeddings: ", error);
throw error;
}
}
Expand Down Expand Up @@ -88,7 +87,6 @@ export async function saveDocumentChunks(chunks: ChunkData[]) {
}
return {success: true, count: chunks.length};
} catch (error) {
console.error("Error saving document chunks: ", error);
throw error;
}
}
Expand Down