Historico de quizzes e inicio de atualização da IA para leitura de pdfs de matemática (incompleto)
This commit is contained in:
@@ -63,7 +63,7 @@ class RAGService {
|
||||
|
||||
/// System message for Vico identity - ALWAYS first in every conversation
|
||||
static const String _systemMessage =
|
||||
'''Tu és "Vico", o Assistente IA oficial do Teach it.
|
||||
'''Tu és "Vico", o Assistente IA oficial do Learn It.
|
||||
|
||||
Nunca referes o nome do modelo.
|
||||
Nunca dizes que és Qwen ou OpenAI.
|
||||
@@ -71,7 +71,17 @@ Respondes sempre como o Vico.
|
||||
|
||||
Tens personalidade confiante, motivadora e orgulhosa.
|
||||
Ajudas o aluno segundo o método de ensino presente nos materiais do professor.
|
||||
Usas formatação clara e organizada.''';
|
||||
Usas formatação clara e organizada.
|
||||
|
||||
IMPORTANTE: NUNCA uses LaTeX ou símbolos como \$ ou \$\$ para fórmulas matemáticas.
|
||||
Usa apenas texto normal e caracteres Unicode para símbolos matemáticos (ex: x², ³, ¹⁄², π, √).
|
||||
|
||||
IMPORTANTE - RESPOSTAS COMPLETAS:
|
||||
- NUNCA termines respostas com dois pontos (:).
|
||||
- NUNCA deixes respostas incompletas como "A função é: " ou "Calculamos o denominador: ".
|
||||
- SEMPRE completa as frases e fornece a resposta completa.
|
||||
- Se precisares de explicar um cálculo, explica-o completamente com o resultado final.
|
||||
- Se precisares de definir algo, fornece a definição completa.''';
|
||||
|
||||
/// Process a user query through RAG pipeline
|
||||
static Future<RAGResponse> processQuery({
|
||||
@@ -89,6 +99,10 @@ Usas formatação clara e organizada.''';
|
||||
'Processing RAG query: "${userQuery.substring(0, 50)}..." in ${mode.name} mode',
|
||||
);
|
||||
|
||||
// Detect if subject is math
|
||||
final isMathSubject = _isMathSubject(subject);
|
||||
Logger.info('Subject: $subject, Is math: $isMathSubject');
|
||||
|
||||
// 1. Generate embedding for user query
|
||||
final queryEmbedding = VectorService.generateEmbedding(userQuery);
|
||||
|
||||
@@ -109,8 +123,13 @@ Usas formatação clara e organizada.''';
|
||||
return _createNoContentResponse(userQuery, mode);
|
||||
}
|
||||
|
||||
// 3. Build context window
|
||||
final context = _buildContextWindow(relevantChunks, userQuery, mode);
|
||||
// 3. Build context window with math-specific filtering
|
||||
final context = _buildContextWindow(
|
||||
relevantChunks,
|
||||
userQuery,
|
||||
mode,
|
||||
isMathSubject: isMathSubject,
|
||||
);
|
||||
|
||||
// 4. Generate response (this will be handled by RAGAIService)
|
||||
final response = await _generateResponse(
|
||||
@@ -134,8 +153,9 @@ Usas formatação clara e organizada.''';
|
||||
static String _buildContextWindow(
|
||||
List<ContentChunk> chunks,
|
||||
String userQuery,
|
||||
TutorMode mode,
|
||||
) {
|
||||
TutorMode mode, {
|
||||
bool isMathSubject = false,
|
||||
}) {
|
||||
try {
|
||||
final contextBuilder = StringBuffer();
|
||||
|
||||
@@ -147,6 +167,13 @@ Usas formatação clara e organizada.''';
|
||||
|
||||
for (int i = 0; i < sortedChunks.length; i++) {
|
||||
final chunk = sortedChunks[i];
|
||||
var chunkText = chunk.text;
|
||||
|
||||
// Filter table data for math subjects
|
||||
if (isMathSubject) {
|
||||
chunkText = _filterTableData(chunkText);
|
||||
}
|
||||
|
||||
contextBuilder.writeln('--- Fonte ${i + 1} ---');
|
||||
contextBuilder.writeln('Disciplina: ${chunk.subject}');
|
||||
contextBuilder.writeln('Conceito: ${chunk.concept}');
|
||||
@@ -158,12 +185,30 @@ Usas formatação clara e organizada.''';
|
||||
if (chunk.pageNumber != null) {
|
||||
contextBuilder.writeln('Página: ${chunk.pageNumber}');
|
||||
}
|
||||
contextBuilder.writeln('\nConteúdo:\n${chunk.text}\n');
|
||||
contextBuilder.writeln('\nConteúdo:\n$chunkText\n');
|
||||
}
|
||||
|
||||
// Add mode-specific instructions
|
||||
contextBuilder.writeln('\n=== INSTRUÇÕES DE TUTORIA ===');
|
||||
contextBuilder.writeln('Modo: ${_getModeInstructions(mode)}');
|
||||
|
||||
// Add math-specific instructions if applicable
|
||||
if (isMathSubject) {
|
||||
contextBuilder.writeln('\n=== INSTRUÇÕES PARA MATEMÁTICA ===');
|
||||
contextBuilder.writeln('Para notações matemáticas:');
|
||||
contextBuilder.writeln(
|
||||
r'- NUNCA use LaTeX ou símbolos como $ ou $$ para fórmulas',
|
||||
);
|
||||
contextBuilder.writeln(
|
||||
'- Use apenas texto normal e caracteres Unicode (ex: x², ³, ¹⁄², π, √)',
|
||||
);
|
||||
contextBuilder.writeln(
|
||||
'- Preserve a notação matemática original quando possível',
|
||||
);
|
||||
contextBuilder.writeln('- Explique passo a passo os cálculos');
|
||||
contextBuilder.writeln('- Use exemplos numéricos concretos');
|
||||
}
|
||||
|
||||
contextBuilder.writeln('Pergunta do Aluno: $userQuery\n');
|
||||
|
||||
final contextText = contextBuilder.toString();
|
||||
@@ -241,7 +286,11 @@ Usas formatação clara e organizada.''';
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final responseData = jsonDecode(response.body);
|
||||
final answer = responseData['message']['content'] as String;
|
||||
var answer = responseData['message']['content'] as String;
|
||||
|
||||
// Post-process to remove LaTeX symbols
|
||||
answer = _removeLaTeXSymbols(answer);
|
||||
|
||||
final confidence = _calculateConfidence(sources);
|
||||
final relatedConcepts = _extractRelatedConcepts(sources);
|
||||
|
||||
@@ -344,7 +393,9 @@ $query
|
||||
- Use linguagem clara e educacional
|
||||
- Adapte a resposta ao nível do aluno
|
||||
- Forneça exemplos quando possível
|
||||
- Seja conciso mas completo''';
|
||||
- Seja conciso mas completo
|
||||
- NUNCA use LaTeX ou símbolos como \$ ou \$\$ para fórmulas
|
||||
- Use apenas texto normal e caracteres Unicode para símbolos matemáticos''';
|
||||
}
|
||||
|
||||
/// Calculate relevance score
|
||||
@@ -408,6 +459,77 @@ $query
|
||||
return concepts.toList()..sort();
|
||||
}
|
||||
|
||||
/// Detect if subject is math-related
|
||||
static bool _isMathSubject(String? subject) {
|
||||
if (subject == null) return false;
|
||||
final lowerSubject = subject.toLowerCase();
|
||||
|
||||
final mathKeywords = [
|
||||
'matemática',
|
||||
'math',
|
||||
'matematica',
|
||||
'álgebra',
|
||||
'algebra',
|
||||
'geometria',
|
||||
'cálculo',
|
||||
'calculo',
|
||||
'estatística',
|
||||
'estatistica',
|
||||
'funções',
|
||||
'funcoes',
|
||||
'equações',
|
||||
'equacoes',
|
||||
'números',
|
||||
'numeros',
|
||||
];
|
||||
|
||||
return mathKeywords.any((keyword) => lowerSubject.contains(keyword));
|
||||
}
|
||||
|
||||
/// Filter out table data from text (for math subjects)
|
||||
/// Removes lines that look like tabular data with multiple numbers
|
||||
static String _filterTableData(String text) {
|
||||
final lines = text.split('\n');
|
||||
final filtered = <String>[];
|
||||
|
||||
for (final line in lines) {
|
||||
final trimmed = line.trim();
|
||||
|
||||
// Skip lines that look like table data
|
||||
// Pattern: multiple numbers separated by spaces/tabs
|
||||
final numberPattern = RegExp(r'\d+\s+\d+');
|
||||
final matches = numberPattern.allMatches(trimmed);
|
||||
|
||||
// If a line has 2+ number pairs separated by spaces, it's likely table data
|
||||
if (matches.length >= 2) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip lines with specific date patterns (table data)
|
||||
if (RegExp(r'\d{1,2}/\d{1,2}/\d{4}').hasMatch(trimmed) &&
|
||||
RegExp(r'\d+').allMatches(trimmed).length > 2) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Keep the line
|
||||
filtered.add(line);
|
||||
}
|
||||
|
||||
return filtered.join('\n');
|
||||
}
|
||||
|
||||
/// Remove LaTeX symbols from AI response
|
||||
static String _removeLaTeXSymbols(String text) {
|
||||
// Remove patterns like $...$ and $$...$$
|
||||
var cleaned = text.replaceAll(RegExp(r'\$\$[^$]+\$\$'), '');
|
||||
cleaned = cleaned.replaceAll(RegExp(r'\$[^$]+\$'), '');
|
||||
|
||||
// Also remove standalone $ symbols
|
||||
cleaned = cleaned.replaceAll(r'$', r'\$');
|
||||
|
||||
return cleaned;
|
||||
}
|
||||
|
||||
/// Create response for no content found
|
||||
static RAGResponse _createNoContentResponse(String query, TutorMode mode) {
|
||||
return RAGResponse(
|
||||
|
||||
Reference in New Issue
Block a user