Skip to content
Merged

. #9

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
2 changes: 0 additions & 2 deletions backend/src/config/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ interface EnvConfig {
PORT: number;
DATABASE_URL: string;
LLM_BACKEND_URL: string;
OLLAMA_EMBEDDINGS_URL: string | null;
EMBEDDING_MODEL: string;
}

Expand All @@ -34,7 +33,6 @@ function validateEnv(): EnvConfig {
PORT: port,
DATABASE_URL: databaseUrl,
LLM_BACKEND_URL: process.env.LLM_BACKEND_URL || 'http://localhost:8000',
OLLAMA_EMBEDDINGS_URL: process.env.OLLAMA_EMBEDDINGS_URL || null,
EMBEDDING_MODEL: process.env.EMBEDDING_MODEL || 'nomic-embed-text',
};
}
Expand Down
8 changes: 4 additions & 4 deletions backend/src/services/document_rag.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,9 @@ export async function indexDocument(params: {
await pool.query('DELETE FROM document_chunks WHERE document_id = $1', [params.documentId]);
await pool.query(
`UPDATE documents
SET status = 'processing', total_chunks = $2, processing_progress = 0.00, error_message = NULL, summary = $3, content_text = $4
SET status = 'processing', total_chunks = $2, processing_progress = 0.00, error_message = NULL, summary = $3
WHERE id = $1`,
[params.documentId, totalChunks, summary, text]
[params.documentId, totalChunks, summary]
);

let processed = 0;
Expand Down Expand Up @@ -136,9 +136,9 @@ export async function indexDocument(params: {

await pool.query(
`UPDATE documents
SET status = 'ready', total_chunks = $2, indexed_at = NOW(), error_message = NULL, processing_progress = 1.00, summary = $3, content_text = $4
SET status = 'ready', total_chunks = $2, indexed_at = NOW(), error_message = NULL, processing_progress = 1.00, summary = $3
WHERE id = $1`,
[params.documentId, totalChunks, summary, text]
[params.documentId, totalChunks, summary]
);
} catch (e) {
await markDocumentFailed(params.documentId, 'Doküman işlenirken hata oluştu.');
Expand Down
55 changes: 19 additions & 36 deletions backend/src/services/llm_backend.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,6 @@ interface EmbeddingResponse {
embeddings: number[][];
}

interface OllamaEmbeddingResponse {
embedding: number[];
}

interface RagAnswerResponse {
answer: string;
}
Expand All @@ -18,41 +14,28 @@ interface ChatResponse {
}

export async function embedTexts(texts: string[]): Promise<number[][]> {
if (!config.OLLAMA_EMBEDDINGS_URL) {
throw new Error('Ollama embeddings endpoint is not configured');
}

const embeddings: number[][] = [];
for (const text of texts) {
let lastError: Error | null = null;
for (let attempt = 1; attempt <= 3; attempt += 1) {
try {
const response = await fetch(config.OLLAMA_EMBEDDINGS_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model: config.EMBEDDING_MODEL, prompt: text }),
});
if (!response.ok) {
const body = await response.text();
throw new Error(`Ollama embedding error: ${response.status} ${body}`);
}
const data = (await response.json()) as OllamaEmbeddingResponse;
embeddings.push(data.embedding);
lastError = null;
break;
} catch (error) {
lastError = error instanceof Error ? error : new Error('Ollama embedding failed');
if (attempt < 3) {
await new Promise((resolve) => setTimeout(resolve, 500 * attempt));
}
let lastError: Error | null = null;
for (let attempt = 1; attempt <= 3; attempt += 1) {
try {
const response = await fetch(`${config.LLM_BACKEND_URL}/rag/embeddings`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ texts }),
});
if (!response.ok) {
const body = await response.text();
throw new Error(`Embedding error: ${response.status} ${body}`);
}
const data = (await response.json()) as EmbeddingResponse;
return data.embeddings;
} catch (error) {
lastError = error instanceof Error ? error : new Error('Embedding request failed');
if (attempt < 3) {
await new Promise((resolve) => setTimeout(resolve, 500 * attempt));
}
}
if (lastError) {
throw lastError;
}
}

return embeddings;
throw lastError!;
}

export async function answerWithContext(question: string, context: string): Promise<string> {
Expand Down
8 changes: 4 additions & 4 deletions lib/features/auth/data/api_auth_repository.dart
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,10 @@ class ApiAuthRepository implements AuthRepository {
print('✅ Current user: ${user['email']}');

return AuthUser(
id: user['id'] as String,
email: user['email'] as String,
displayName: user['displayName'] as String? ?? 'User',
isGuest: user['isGuest'] as bool? ?? false,
id: (user['id'] as String?) ?? '',
email: (user['email'] as String?) ?? '',
displayName: (user['displayName'] as String?) ?? 'User',
isGuest: (user['isGuest'] as bool?) ?? false,
);
} catch (e) {
print('❌ Get current user failed: $e');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,6 @@ class _TreePainter extends CustomPainter {

// Recursive branches
if (currentDepth > 0) {
const int branches = 2; // Split into 2
final double spreadAngle =
0.6 + (currentLevel * 0.04).clamp(0.0, 0.4); // Wider spread

Expand Down
9 changes: 8 additions & 1 deletion lib/shared/data/api_document_repository.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,13 @@ class ApiDocumentRepository {
Future<List<Document>> getDocuments() async {
try {
final response = await _dio.get<Map<String, dynamic>>('/documents');
print('📄 getDocuments response: ${response.data}');
final data = response.data!['documents'] as List<dynamic>;
return data
.map((json) => Document.fromJson(json as Map<String, dynamic>))
.toList();
} catch (e) {
// Return empty list on error for now or rethrow
print('❌ getDocuments error: $e');
rethrow;
}
}
Expand All @@ -39,10 +40,13 @@ class ApiDocumentRepository {
data: formData,
);

print('📄 Upload response: ${response.data}');

return Document.fromJson(
response.data!['document'] as Map<String, dynamic>,
);
} catch (e) {
print('❌ Upload error: $e');
rethrow;
}
}
Expand All @@ -63,10 +67,13 @@ class ApiDocumentRepository {
data: formData,
);

print('📄 Upload bytes response: ${response.data}');

return Document.fromJson(
response.data!['document'] as Map<String, dynamic>,
);
} catch (e) {
print('❌ Upload bytes error: $e');
rethrow;
}
}
Expand Down
12 changes: 9 additions & 3 deletions lib/shared/models/models.dart
Original file line number Diff line number Diff line change
Expand Up @@ -150,12 +150,18 @@ class Document extends Equatable {
final progressRaw = json['processing_progress'];
final progress = progressRaw is num ? progressRaw.toDouble() : 0.0;

DateTime? uploadedAt;
final uploadedAtRaw = json['uploaded_at'];
if (uploadedAtRaw is String) {
uploadedAt = DateTime.tryParse(uploadedAtRaw);
}

return Document(
id: json['id'] as String?,
title: json['title'] as String,
summary: json['summary'] as String? ?? '',
title: (json['title'] as String?) ?? 'Untitled',
summary: (json['summary'] as String?) ?? '',
status: status,
uploadedAt: DateTime.parse(json['uploaded_at'] as String),
uploadedAt: uploadedAt,
processingProgress: progress,
);
}
Expand Down
5 changes: 3 additions & 2 deletions lib/shared/services/api_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,9 @@ class ApiService {
_dio = Dio(
BaseOptions(
baseUrl: baseUrl,
connectTimeout: const Duration(seconds: 15),
receiveTimeout: const Duration(seconds: 15),
connectTimeout: const Duration(seconds: 30),
receiveTimeout: const Duration(seconds: 60),
sendTimeout: const Duration(seconds: 60),
),
);
print('🔌 ApiService Initialized');
Expand Down
4 changes: 0 additions & 4 deletions llm_backend/app/api/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,3 @@ def chat(req: ChatRequest):
except Exception as e:
logger.error(f"Chat error: {str(e)}")
raise HTTPException(status_code=500, detail="LLM error")

except Exception as e:
logger.error(str(e))
raise HTTPException(status_code=500, detail="LLM error")
2 changes: 0 additions & 2 deletions scripts/dev_start.sh
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,6 @@ start_process "llm_backend" "cd '$ROOT/llm_backend' && \
uvicorn app.main:app --host 0.0.0.0 --port 8000"
start_process "backend" "cd '$ROOT/backend' && \
export NODE_ENV='development' && \
export OLLAMA_EMBEDDINGS_URL='http://127.0.0.1:11434/api/embeddings' && \
export EMBEDDING_MODEL='nomic-embed-text' && \
npm run start"

echo "All services started. Logs: $LOG_DIR"
Loading