🐛 fix: RAG Results Sorted By Distance (#5931)

* refactor: Extract file unlinking logic into a separate function and don't throw error

* fix: RAG results are actually in distance, not score
This commit is contained in:
Danny Avila 2025-02-18 08:14:19 -05:00 committed by GitHub
parent 964a74c73b
commit ecddffa7b2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 20 additions and 7 deletions

View file

@ -106,19 +106,21 @@ const createFileSearchTool = async ({ req, files, entity_id }) => {
const formattedResults = validResults const formattedResults = validResults
.flatMap((result) => .flatMap((result) =>
result.data.map(([docInfo, relevanceScore]) => ({ result.data.map(([docInfo, distance]) => ({
filename: docInfo.metadata.source.split('/').pop(), filename: docInfo.metadata.source.split('/').pop(),
content: docInfo.page_content, content: docInfo.page_content,
relevanceScore, distance,
})), })),
) )
.sort((a, b) => b.relevanceScore - a.relevanceScore) // TODO: results should be sorted by relevance, not distance
.slice(0, 5); .sort((a, b) => a.distance - b.distance)
// TODO: make this configurable
.slice(0, 10);
const formattedString = formattedResults const formattedString = formattedResults
.map( .map(
(result) => (result) =>
`File: ${result.filename}\nRelevance: ${result.relevanceScore.toFixed(4)}\nContent: ${ `File: ${result.filename}\nRelevance: ${1.0 - result.distance.toFixed(4)}\nContent: ${
result.content result.content
}\n`, }\n`,
) )

View file

@ -175,6 +175,17 @@ const isValidPath = (req, base, subfolder, filepath) => {
return normalizedFilepath.startsWith(normalizedBase); return normalizedFilepath.startsWith(normalizedBase);
}; };
/**
* @param {string} filepath
*/
const unlinkFile = async (filepath) => {
try {
await fs.promises.unlink(filepath);
} catch (error) {
logger.error('Error deleting file:', error);
}
};
/** /**
* Deletes a file from the filesystem. This function takes a file object, constructs the full path, and * Deletes a file from the filesystem. This function takes a file object, constructs the full path, and
* verifies the path's validity before deleting the file. If the path is invalid, an error is thrown. * verifies the path's validity before deleting the file. If the path is invalid, an error is thrown.
@ -217,7 +228,7 @@ const deleteLocalFile = async (req, file) => {
throw new Error(`Invalid file path: ${file.filepath}`); throw new Error(`Invalid file path: ${file.filepath}`);
} }
await fs.promises.unlink(filepath); await unlinkFile(filepath);
return; return;
} }
@ -233,7 +244,7 @@ const deleteLocalFile = async (req, file) => {
throw new Error('Invalid file path'); throw new Error('Invalid file path');
} }
await fs.promises.unlink(filepath); await unlinkFile(filepath);
}; };
/** /**