File size: 11,332 Bytes
d4abe4b |
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 345 346 347 348 349 350 351 352 353 354 355 356 |
import { SupabaseService } from './supabase.service.js';
import { logger } from '../utils/logger.js';
import { GeminiEmbedding } from '../agent/gemini-embedding.js';
export interface Specialty {
id: string;
name: string;
name_en?: string;
description?: string;
}
export interface Disease {
id: string;
specialty_id: string;
name: string;
synonyms?: string[];
icd10_code?: string;
description?: string;
}
export interface InfoDomain {
id: string;
name: string;
name_en?: string;
order_index: number;
description?: string;
}
export interface StructuredKnowledgeQuery {
specialty?: string;
disease?: string;
infoDomain?: string;
query: string;
}
/**
* Knowledge Base Service
* Provides structured access to medical knowledge using specialties, diseases, and info_domains
*/
export class KnowledgeBaseService {
private embedding: GeminiEmbedding;
constructor(private supabaseService: SupabaseService) {
this.embedding = new GeminiEmbedding();
}
/**
* Get all specialties
*/
async getSpecialties(): Promise<Specialty[]> {
try {
const { data, error } = await this.supabaseService.getClient()
.from('specialties')
.select('*')
.order('name');
if (error) throw error;
return data || [];
} catch (error) {
logger.error(`Error fetching specialties: ${error}`);
return [];
}
}
/**
* Get diseases by specialty
*/
async getDiseasesBySpecialty(specialtyName: string): Promise<Disease[]> {
try {
const { data, error } = await this.supabaseService.getClient()
.from('diseases')
.select('*, specialties!inner(name)')
.eq('specialties.name', specialtyName)
.order('name');
if (error) throw error;
return data || [];
} catch (error) {
logger.error(`Error fetching diseases for specialty ${specialtyName}: ${error}`);
return [];
}
}
/**
* Get all info domains
*/
async getInfoDomains(): Promise<InfoDomain[]> {
try {
const { data, error } = await this.supabaseService.getClient()
.from('info_domains')
.select('*')
.order('order_index');
if (error) throw error;
return data || [];
} catch (error) {
logger.error(`Error fetching info domains: ${error}`);
return [];
}
}
/**
* Find disease by name or synonym
*/
async findDisease(query: string): Promise<Disease | null> {
try {
logger.info('='.repeat(80));
logger.info('[MCP CSDL] findDisease INPUT:');
logger.info(` Query: "${query}"`);
const normalizedQuery = query.toLowerCase().trim();
// Exact match first
logger.info('[MCP CSDL] Trying exact match...');
const { data: exactMatch } = await this.supabaseService.getClient()
.from('diseases')
.select('*')
.ilike('name', normalizedQuery)
.limit(1)
.single();
if (exactMatch) {
logger.info('[MCP CSDL] findDisease OUTPUT (exact match):');
logger.info(` Disease: ${exactMatch.name} (ID: ${exactMatch.id})`);
logger.info('='.repeat(80));
return exactMatch;
}
// Fuzzy match on name
logger.info('[MCP CSDL] Trying fuzzy match on name...');
const { data: fuzzyMatch } = await this.supabaseService.getClient()
.from('diseases')
.select('*')
.ilike('name', `%${normalizedQuery}%`)
.limit(1)
.single();
if (fuzzyMatch) {
logger.info('[MCP CSDL] findDisease OUTPUT (fuzzy match):');
logger.info(` Disease: ${fuzzyMatch.name} (ID: ${fuzzyMatch.id})`);
logger.info('='.repeat(80));
return fuzzyMatch;
}
// Check synonyms
logger.info('[MCP CSDL] Trying synonym match...');
const { data: allDiseases } = await this.supabaseService.getClient()
.from('diseases')
.select('*');
if (allDiseases) {
for (const disease of allDiseases) {
if (disease.synonyms) {
for (const synonym of disease.synonyms) {
if (synonym.toLowerCase().includes(normalizedQuery) ||
normalizedQuery.includes(synonym.toLowerCase())) {
logger.info('[MCP CSDL] findDisease OUTPUT (synonym match):');
logger.info(` Disease: ${disease.name} (ID: ${disease.id})`);
logger.info(` Matched synonym: "${synonym}"`);
logger.info('='.repeat(80));
return disease;
}
}
}
}
}
logger.info('[MCP CSDL] findDisease OUTPUT: Not found');
logger.info('='.repeat(80));
return null;
} catch (error) {
logger.error('[MCP CSDL] ERROR in findDisease:');
logger.error(JSON.stringify(error, null, 2));
logger.info('='.repeat(80));
return null;
}
}
/**
* Find info domain by name
*/
async findInfoDomain(query: string): Promise<InfoDomain | null> {
try {
const normalizedQuery = query.toLowerCase().trim();
// Exact match
const { data: exactMatch } = await this.supabaseService.getClient()
.from('info_domains')
.select('*')
.ilike('name', normalizedQuery)
.limit(1)
.single();
if (exactMatch) return exactMatch;
// Fuzzy match
const { data: fuzzyMatch } = await this.supabaseService.getClient()
.from('info_domains')
.select('*')
.ilike('name', `%${normalizedQuery}%`)
.limit(1)
.single();
if (fuzzyMatch) return fuzzyMatch;
// Check English name
const { data: enMatch } = await this.supabaseService.getClient()
.from('info_domains')
.select('*')
.ilike('name_en', `%${normalizedQuery}%`)
.limit(1)
.single();
if (enMatch) return enMatch;
return null;
} catch (error) {
logger.error(`Error finding info domain: ${error}`);
return null;
}
}
/**
* Query structured knowledge with filters and vector similarity
*/
async queryStructuredKnowledge(
params: StructuredKnowledgeQuery
): Promise<any[]> {
try {
logger.info('='.repeat(80));
logger.info('[MCP CSDL] queryStructuredKnowledge INPUT:');
logger.info(JSON.stringify(params, null, 2));
// If we have a text query, use vector search + filtering (hybrid search)
if (params.query) {
logger.info('[MCP CSDL] Using vector search with query...');
const queryEmbedding = await this.embedding.embedQuery(params.query);
const rpcParams = {
query_embedding: queryEmbedding,
match_threshold: 0.3,
match_count: 10,
filter_specialty: params.specialty || null,
filter_disease: params.disease || null,
filter_specialty_id: null,
filter_disease_id: null,
filter_info_domain_id: null
};
logger.info('[MCP CSDL] Calling match_medical_knowledge RPC...');
logger.info(`[MCP CSDL] RPC params: { match_threshold: 0.3, match_count: 10, filter_specialty: ${params.specialty || 'null'}, filter_disease: ${params.disease || 'null'} }`);
const { data, error } = await this.supabaseService.getClient().rpc(
'match_medical_knowledge',
rpcParams
);
if (error) {
logger.error('[MCP CSDL] ERROR calling match_medical_knowledge RPC:');
logger.error(JSON.stringify(error, null, 2));
logger.info('[MCP CSDL] Falling back to text search...');
// Fallback to simple text filtering if RPC fails
return this.fallbackTextSearch(params);
}
// If vector search returns empty, try fallback text search
if (!data || data.length === 0) {
logger.info('[MCP CSDL] Vector search returned no results, falling back to text search');
return this.fallbackTextSearch(params);
}
// Filter by infoDomain if provided (since RPC filter for it is by ID, not name)
let results = data || [];
if (params.infoDomain) {
logger.info(`[MCP CSDL] Filtering by infoDomain: "${params.infoDomain}"`);
const beforeFilter = results.length;
results = results.filter((item: any) =>
item.section_title && item.section_title.toLowerCase().includes(params.infoDomain!.toLowerCase())
);
logger.info(`[MCP CSDL] Filtered from ${beforeFilter} to ${results.length} results`);
}
logger.info(`[MCP CSDL] queryStructuredKnowledge OUTPUT: Found ${results.length} structured knowledge chunks via vector search`);
results.forEach((item: any, index: number) => {
logger.info(`[MCP CSDL] Result ${index + 1}:`);
logger.info(` - Disease: ${item.disease || 'N/A'}`);
logger.info(` - Section: ${item.section_title || 'N/A'}`);
logger.info(` - Similarity: ${item.similarity?.toFixed(4) || 'N/A'}`);
logger.info(` - Content preview: ${item.content?.substring(0, 150) || 'N/A'}...`);
});
logger.info('='.repeat(80));
return results;
}
// No text query provided, fall back to simple text filtering
logger.info('[MCP CSDL] No query text provided, using fallback text search...');
return this.fallbackTextSearch(params);
} catch (error) {
logger.error('[MCP CSDL] ERROR in queryStructuredKnowledge:');
logger.error(JSON.stringify(error, null, 2));
logger.info('='.repeat(80));
return [];
}
}
private async fallbackTextSearch(params: StructuredKnowledgeQuery): Promise<any[]> {
logger.info('[MCP CSDL] fallbackTextSearch - Building query...');
let query = this.supabaseService.getClient()
.from('medical_knowledge_chunks')
.select('*');
// Apply filters if provided (using ilike for case-insensitive matching)
if (params.specialty) {
logger.info(`[MCP CSDL] Filtering by specialty: "${params.specialty}"`);
query = query.ilike('specialty', params.specialty);
}
if (params.disease) {
logger.info(`[MCP CSDL] Filtering by disease: "${params.disease}"`);
query = query.ilike('disease', params.disease);
}
if (params.infoDomain) {
logger.info(`[MCP CSDL] Filtering by infoDomain: "${params.infoDomain}"`);
query = query.ilike('section_title', params.infoDomain);
}
// Limit results
query = query.limit(10);
const { data, error } = await query;
if (error) {
logger.error('[MCP CSDL] ERROR in fallbackTextSearch:');
logger.error(JSON.stringify(error, null, 2));
throw error;
}
logger.info(`[MCP CSDL] fallbackTextSearch OUTPUT: Found ${data?.length || 0} structured knowledge chunks via text search`);
if (data && data.length > 0) {
data.forEach((item: any, index: number) => {
logger.info(`[MCP CSDL] Result ${index + 1}:`);
logger.info(` - Disease: ${item.disease || 'N/A'}`);
logger.info(` - Section: ${item.section_title || 'N/A'}`);
logger.info(` - Content preview: ${item.content?.substring(0, 150) || 'N/A'}...`);
});
}
logger.info('='.repeat(80));
return data || [];
}
}
|