"""Recommendation recall and fusion service exposed as LLM-callable tools.""" import math from .catalog import DimensionCatalog from .parsing import normalize_identifier, parse_ranked_items from .schemas import ( ALGORITHM_NAMES, DIMENSION_NAMES, LIST_TYPE_NAMES, get_tool_definitions, ) TOOLSET_VERSION = '1.0.0' MAX_EVIDENCE_PER_ITEM = 8 MAX_DIMENSION_PLANS = 120 BEHAVIOR_WEIGHTS = { 'click': 1.0, 'view': 1.0, 'addToPool': 2.0, 'addToCart': 3.0, 'contactFactory': 5.0, 'purchase': 10.0, } ALGORITHMS = { 'swing_cpp': { 'prefixes': ['item:similar:swing_cpp'], 'weight': 1.00, 'signal': 'high-scale co-interaction similarity', }, 'swing': { 'prefixes': ['item:similar:swing'], 'weight': 0.95, 'signal': 'time-aware co-interaction similarity', }, 'session_w2v': { 'prefixes': ['item:similar:session_w2v', 'item:similar:w2v'], 'weight': 0.90, 'signal': 'session sequence similarity', }, 'deepwalk': { 'prefixes': ['item:similar:deepwalk'], 'weight': 0.85, 'signal': 'behavior graph proximity', }, 'content_name': { 'prefixes': ['item:similar:content_name'], 'weight': 0.70, 'signal': 'name embedding similarity', }, 'content_pic': { 'prefixes': ['item:similar:content_pic'], 'weight': 0.65, 'signal': 'image embedding similarity', }, 'item_behavior': { 'prefixes': ['item:similar:item_behavior'], 'weight': 1.00, 'signal': 'item behavior similarity', }, } LIST_TYPE_WEIGHTS = { 'hot': 1.00, 'cart': 1.10, 'new': 0.85, 'global': 0.75, } DIMENSION_ALIASES = { 'platform': 'platform', 'client': 'client_platform', 'client_platform': 'client_platform', 'country': 'country_code', 'country_code': 'country_code', 'customer_type': 'customer_type', 'supplier': 'supplier', 'supplier_id': 'supplier', 'category_level1': 'category_level1', 'category_level1_id': 'category_level1', 'category_level2': 'category_level2', 'category_level2_id': 'category_level2', 'category_level3': 'category_level3', 'category_level3_id': 'category_level3', 'category_level4': 'category_level4', 'category_level4_id': 'category_level4', } DIRECT_DIMENSIONS = { 'platform', 'client_platform', 'supplier', 'category_level1', 'category_level2', 'category_level3', 'category_level4', } class ToolInputError(ValueError): """Raised when a tool call is well-formed JSON but semantically invalid.""" def _bounded_integer(value, name, default, minimum, maximum): if value is None: value = default if isinstance(value, bool): raise ToolInputError('%s must be an integer' % name) try: parsed = int(value) except (TypeError, ValueError, OverflowError): raise ToolInputError('%s must be an integer' % name) if parsed < minimum or parsed > maximum: raise ToolInputError( '%s must be between %s and %s' % (name, minimum, maximum) ) return parsed def _bounded_weight(value, name, default=1.0, allow_zero=False, maximum=10.0): if value is None: return default if isinstance(value, bool): raise ToolInputError('%s must be a number' % name) try: parsed = float(value) except (TypeError, ValueError, OverflowError): raise ToolInputError('%s must be a number' % name) minimum = 0.0 if allow_zero else 0.000001 if not math.isfinite(parsed) or parsed < minimum or parsed > maximum: qualifier = 'non-negative' if allow_zero else 'positive' raise ToolInputError('%s must be a %s number no greater than %s' % ( name, qualifier, maximum, )) return parsed def _safe_text(value, name, lower=False, upper=False, max_length=200, allow_separators=False): if value is None: return None text = str(value).strip() if not text: raise ToolInputError('%s must not be empty' % name) if len(text) > max_length: raise ToolInputError('%s is too long' % name) forbidden = ('\x00', '\r', '\n', '\t') if not allow_separators: forbidden += (':', ';') if any(char in text for char in forbidden): raise ToolInputError('%s contains an unsupported separator' % name) if lower: text = text.lower() if upper: text = text.upper() return text def _unique_strings(values, name, maximum=500): if values is None: return [] if not isinstance(values, (list, tuple)): raise ToolInputError('%s must be an array' % name) if len(values) > maximum: raise ToolInputError('%s contains too many values' % name) result = [] seen = set() for value in values: normalized = normalize_identifier(value) if normalized is None: raise ToolInputError('%s contains an invalid identifier' % name) if normalized not in seen: result.append(normalized) seen.add(normalized) return result def _unique_in_order(values): result = [] seen = set() for value in values: if value not in seen: result.append(value) seen.add(value) return result class RecommendationAgentTools(object): """Framework-neutral tools backed by the repository's Redis indices.""" def __init__(self, index_store, dimension_catalog=None, rrf_k=60): if index_store is None: raise ValueError('index_store is required') self.index_store = index_store self.dimension_catalog = dimension_catalog or DimensionCatalog() self.rrf_k = _bounded_integer(rrf_k, 'rrf_k', 60, 1, 1000) def tool_definitions(self): return get_tool_definitions() def call_tool(self, name, arguments=None): handlers = { 'recommendation_capabilities': self.recommendation_capabilities, 'resolve_recommendation_dimension': self.resolve_recommendation_dimension, 'recall_similar_products': self.recall_similar_products, 'recall_products_by_dimensions': self.recall_products_by_dimensions, 'build_recommendation_candidates': self.build_recommendation_candidates, } handler = handlers.get(name) if handler is None: return self._error('unknown_tool', 'Unknown tool: %s' % name) if arguments is None: arguments = {} if not isinstance(arguments, dict): return self._error('invalid_arguments', 'Tool arguments must be an object') try: return handler(**arguments) except ToolInputError as error: return self._error('invalid_arguments', str(error)) except TypeError as error: return self._error('invalid_arguments', str(error)) except Exception as error: return self._error( 'index_unavailable', 'Recommendation index query failed (%s)' % error.__class__.__name__, retryable=True, ) @staticmethod def _error(code, message, retryable=False): return { 'ok': False, 'error': { 'code': code, 'message': message, 'retryable': bool(retryable), }, } def recommendation_capabilities(self): algorithms = [] for name in ALGORITHM_NAMES: config = ALGORITHMS[name] algorithms.append({ 'name': name, 'signal': config['signal'], 'primary_key_pattern': '%s:{item_id}' % config['prefixes'][0], 'fallback_key_patterns': [ '%s:{item_id}' % prefix for prefix in config['prefixes'][1:] ], }) return { 'ok': True, 'version': TOOLSET_VERSION, 'catalog_available': self.dimension_catalog.available, 'algorithms': algorithms, 'list_types': [ { 'name': name, 'key_pattern': 'interest:%s:{dimension_key}' % name, } for name in LIST_TYPE_NAMES ], 'dimensions': [ {'name': 'platform', 'key': 'platform:{value}'}, {'name': 'client_platform', 'key': 'client_platform:{value}'}, {'name': 'supplier', 'key': 'supplier:{value}'}, {'name': 'category_level1', 'key': 'category_level1:{value}'}, {'name': 'category_level2', 'key': 'category_level2:{value}'}, {'name': 'category_level3', 'key': 'category_level3:{value}'}, {'name': 'category_level4', 'key': 'category_level4:{value}'}, { 'name': 'platform_client', 'key': 'platform_client:{platform}_{client_platform}', 'planned_automatically': True, }, { 'name': 'platform_category2', 'key': 'platform_category2:{platform}_{category_level2}', 'planned_automatically': True, }, { 'name': 'platform_category3', 'key': 'platform_category3:{platform}_{category_level3}', 'planned_automatically': True, }, { 'name': 'client_category2', 'key': 'client_category2:{client_platform}_{category_level2}', 'planned_automatically': True, }, { 'name': 'platform_country', 'key': 'platform:{platform};country_code:{country_code}', 'requires_platform': ['essa', 'essaone'], 'planned_automatically': True, }, { 'name': 'platform_country_customer', 'key': ( 'platform:{platform};country_code:{country_code};' 'customer_type:{customer_type}' ), 'requires_platform': ['essa', 'essaone'], 'planned_automatically': True, }, ], 'recommended_flow': [ 'Resolve category or supplier names when only natural language is known.', 'Build a hybrid candidate pool from strong seed items and profile dimensions.', 'Fetch live product details, price, inventory and eligibility with catalog tools.', 'Let the LLM compare the enriched products and explain the final choice.', ], 'ranking': { 'recall_fusion': 'weighted_reciprocal_rank_fusion', 'reason': 'Source scores have different scales and are not directly comparable.', 'score_range': [0, 1], }, } def resolve_recommendation_dimension(self, dimension, query, limit=10): canonical = DIMENSION_ALIASES.get(str(dimension or '').strip()) if canonical not in DIMENSION_NAMES: raise ToolInputError('Unsupported dimension: %s' % dimension) limit = _bounded_integer(limit, 'limit', 10, 1, 20) if query is None: raise ToolInputError('query is required') query = _safe_text( query, 'query', max_length=200, allow_separators=True ) matches = self.dimension_catalog.resolve(canonical, query, limit) return { 'ok': True, 'dimension': canonical, 'query': query, 'matches': matches, 'catalog_available': self.dimension_catalog.available, 'guidance': ( None if matches else 'No catalog match. Use an internal dimension ID returned by the product catalog.' ), } def recall_similar_products(self, seed_items, algorithms=None, top_k=50, per_seed_k=50, exclude_item_ids=None): top_k = _bounded_integer(top_k, 'top_k', 50, 1, 100) per_seed_k = _bounded_integer(per_seed_k, 'per_seed_k', 50, 1, 200) seeds = self._normalize_seed_items(seed_items) selected_algorithms = self._normalize_algorithms(algorithms) excluded = set(_unique_strings(exclude_item_ids, 'exclude_item_ids')) excluded.update(seed['item_id'] for seed in seeds) candidates = {} specifications = [] query_keys = [] for seed in seeds: for algorithm in selected_algorithms: aliases = [ '%s:%s' % (prefix, seed['item_id']) for prefix in ALGORITHMS[algorithm]['prefixes'] ] specifications.append({ 'seed': seed, 'algorithm': algorithm, 'aliases': aliases, }) query_keys.extend(aliases) query_keys = _unique_in_order(query_keys) values = self.index_store.get_many(query_keys) hit_sources = 0 malformed_sources = 0 missing_keys = [] excluded_count = 0 for specification in specifications: ranked_items = [] chosen_key = None saw_value = False for key in specification['aliases']: value = values.get(key) if value is None: continue saw_value = True ranked_items = parse_ranked_items(value) if ranked_items: chosen_key = key break if not ranked_items: if saw_value: malformed_sources += 1 missing_keys.append(specification['aliases'][0]) continue hit_sources += 1 algorithm = specification['algorithm'] seed = specification['seed'] source_weight = ALGORITHMS[algorithm]['weight'] * seed['weight'] for rank, (item_id, raw_score) in enumerate( ranked_items[:per_seed_k], start=1): if item_id in excluded: excluded_count += 1 continue contribution = source_weight / float(self.rrf_k + rank) evidence = { 'channel': 'collaborative', 'source': algorithm, 'key': chosen_key, 'seed_item_id': seed['item_id'], 'seed_reason': seed.get('reason'), 'rank': rank, 'raw_score': raw_score, 'contribution': round(contribution, 8), } self._add_candidate(candidates, item_id, contribution, evidence) items = self._render_candidates(candidates, top_k) return { 'ok': True, 'items': items, 'diagnostics': { 'strategy': 'weighted_reciprocal_rank_fusion', 'rrf_k': self.rrf_k, 'algorithms': selected_algorithms, 'seed_count': len(seeds), 'planned_source_count': len(specifications), 'queried_key_count': len(query_keys), 'hit_source_count': hit_sources, 'missing_source_count': len(missing_keys), 'malformed_source_count': malformed_sources, 'missing_keys_sample': missing_keys[:20], 'excluded_occurrence_count': excluded_count, 'candidate_count_before_limit': len(candidates), }, } def recall_products_by_dimensions(self, context=None, interests=None, list_types=None, top_k=50, per_source_k=100, exclude_item_ids=None): return self._recall_products_by_dimensions( context=context, interests=interests, list_types=list_types, top_k=top_k, per_source_k=per_source_k, exclude_item_ids=exclude_item_ids, ) def _recall_products_by_dimensions( self, context=None, interests=None, list_types=None, top_k=50, per_source_k=100, exclude_item_ids=None, additional_exclude_item_ids=None): top_k = _bounded_integer(top_k, 'top_k', 50, 1, 100) per_source_k = _bounded_integer( per_source_k, 'per_source_k', 100, 1, 500 ) selected_list_types = self._normalize_list_types(list_types) plans = self._plan_dimensions(context, interests) excluded = set(_unique_strings(exclude_item_ids, 'exclude_item_ids')) excluded.update(_unique_strings( additional_exclude_item_ids, 'additional_exclude_item_ids', maximum=20, )) source_plans = [] for plan in plans: for list_type in selected_list_types: source_plans.append({ 'key': 'interest:%s:%s' % (list_type, plan['dimension_key']), 'list_type': list_type, 'weight': plan['weight'] * LIST_TYPE_WEIGHTS[list_type], 'dimension_key': plan['dimension_key'], 'matched': plan['matched'], 'specificity': plan['specificity'], }) source_plans = source_plans[:500] query_keys = [plan['key'] for plan in source_plans] values = self.index_store.get_many(query_keys) candidates = {} hit_keys = [] missing_keys = [] malformed_keys = [] excluded_count = 0 for source in source_plans: value = values.get(source['key']) if value is None: missing_keys.append(source['key']) continue ranked_items = parse_ranked_items(value) if not ranked_items: malformed_keys.append(source['key']) continue hit_keys.append(source['key']) for rank, (item_id, raw_score) in enumerate( ranked_items[:per_source_k], start=1): if item_id in excluded: excluded_count += 1 continue contribution = source['weight'] / float(self.rrf_k + rank) evidence = { 'channel': 'dimension', 'source': source['list_type'], 'key': source['key'], 'dimension_key': source['dimension_key'], 'matched': source['matched'], 'specificity': source['specificity'], 'rank': rank, 'raw_score': raw_score, 'contribution': round(contribution, 8), } self._add_candidate(candidates, item_id, contribution, evidence) items = self._render_candidates(candidates, top_k) return { 'ok': True, 'items': items, 'diagnostics': { 'strategy': 'specificity_weighted_reciprocal_rank_fusion', 'rrf_k': self.rrf_k, 'list_types': selected_list_types, 'dimension_plan_count': len(plans), 'planned_source_count': len(source_plans), 'queried_key_count': len(query_keys), 'hit_source_count': len(hit_keys), 'missing_source_count': len(missing_keys), 'malformed_source_count': len(malformed_keys), 'hit_keys_sample': hit_keys[:20], 'missing_keys_sample': missing_keys[:20], 'excluded_occurrence_count': excluded_count, 'candidate_count_before_limit': len(candidates), }, } def build_recommendation_candidates( self, seed_items=None, context=None, interests=None, algorithms=None, list_types=None, top_k=50, per_seed_k=50, per_source_k=100, exclude_item_ids=None, collaborative_weight=0.65, dimension_weight=0.35): top_k = _bounded_integer(top_k, 'top_k', 50, 1, 100) if not seed_items and not context and not interests: raise ToolInputError( 'At least one seed item, context field, or dimension interest is required' ) collaborative_weight = _bounded_weight( collaborative_weight, 'collaborative_weight', 0.65, allow_zero=True, maximum=1.0, ) dimension_weight = _bounded_weight( dimension_weight, 'dimension_weight', 0.35, allow_zero=True, maximum=1.0, ) if collaborative_weight + dimension_weight <= 0: raise ToolInputError('At least one channel weight must be positive') seed_item_ids = [] if seed_items: normalized_seeds = self._normalize_seed_items(seed_items) seed_item_ids = [seed['item_id'] for seed in normalized_seeds] pool_size = min(100, max(top_k * 4, 50)) channel_results = {} if seed_items and collaborative_weight > 0: channel_results['collaborative'] = self.recall_similar_products( seed_items=seed_items, algorithms=algorithms, top_k=pool_size, per_seed_k=per_seed_k, exclude_item_ids=exclude_item_ids, ) if (context or interests) and dimension_weight > 0: channel_results['dimension'] = self._recall_products_by_dimensions( context=context, interests=interests, list_types=list_types, top_k=pool_size, per_source_k=per_source_k, exclude_item_ids=exclude_item_ids, additional_exclude_item_ids=seed_item_ids, ) if not channel_results: raise ToolInputError( 'No enabled channel has matching seed or dimension inputs' ) configured_weights = { 'collaborative': collaborative_weight, 'dimension': dimension_weight, } successful_channels = [ channel for channel, result in channel_results.items() if result.get('items') ] successful_weight = sum( configured_weights[channel] for channel in successful_channels ) effective_weights = {} if successful_weight: effective_weights = { channel: configured_weights[channel] / successful_weight for channel in successful_channels } combined = {} for channel in successful_channels: channel_weight = effective_weights[channel] for item in channel_results[channel]['items']: item_id = item['item_id'] target = combined.setdefault(item_id, { 'item_id': item_id, 'score': 0.0, 'channel_scores': {}, 'evidence': [], 'reasons': [], 'channels': set(), 'source_count': 0, }) target['score'] += channel_weight * item['score'] target['channel_scores'][channel] = item['score'] target['channels'].add(channel) target['source_count'] += item['source_count'] for evidence in item['evidence']: copied = dict(evidence) copied['hybrid_channel_weight'] = round(channel_weight, 6) target['evidence'].append(copied) target['reasons'].extend(item['reasons']) ranked = sorted( combined.values(), key=lambda item: (-item['score'], item['item_id']) ) maximum = ranked[0]['score'] if ranked else 1.0 final_items = [] for item in ranked[:top_k]: item['score'] = round(item['score'] / maximum, 6) item['channels'] = sorted(item['channels']) item['evidence'].sort( key=lambda evidence: -evidence.get('contribution', 0.0) ) item['evidence'] = item['evidence'][:MAX_EVIDENCE_PER_ITEM] item['reasons'] = self._deduplicate_dicts(item['reasons'])[:6] final_items.append(item) return { 'ok': True, 'items': final_items, 'diagnostics': { 'strategy': 'normalized_channel_blend', 'requested_channel_weights': configured_weights, 'effective_channel_weights': effective_weights, 'successful_channels': successful_channels, 'candidate_count_before_limit': len(combined), 'channel_diagnostics': { channel: result['diagnostics'] for channel, result in channel_results.items() }, 'next_step': ( 'Fetch live product details and eligibility before LLM reranking.' ), }, } @staticmethod def _normalize_algorithms(algorithms): if algorithms is None: return list(ALGORITHM_NAMES) if not isinstance(algorithms, (list, tuple)) or not algorithms: raise ToolInputError('algorithms must be a non-empty array') result = [] for algorithm in algorithms: if algorithm not in ALGORITHMS: raise ToolInputError('Unsupported algorithm: %s' % algorithm) if algorithm not in result: result.append(algorithm) return result @staticmethod def _normalize_list_types(list_types): if list_types is None: return list(LIST_TYPE_NAMES) if not isinstance(list_types, (list, tuple)) or not list_types: raise ToolInputError('list_types must be a non-empty array') result = [] for list_type in list_types: if list_type not in LIST_TYPE_NAMES: raise ToolInputError('Unsupported list type: %s' % list_type) if list_type not in result: result.append(list_type) return result @staticmethod def _normalize_seed_items(seed_items): if not isinstance(seed_items, (list, tuple)) or not seed_items: raise ToolInputError('seed_items must be a non-empty array') if len(seed_items) > 20: raise ToolInputError('seed_items supports at most 20 entries') normalized = {} for entry in seed_items: if isinstance(entry, dict): item_id = normalize_identifier(entry.get('item_id')) behavior = entry.get('behavior', 'click') if behavior not in BEHAVIOR_WEIGHTS: raise ToolInputError('Unsupported seed behavior: %s' % behavior) weight = _bounded_weight( entry.get('weight'), 'seed weight', BEHAVIOR_WEIGHTS[behavior] ) reason = entry.get('reason') if reason is not None: reason = _safe_text( reason, 'seed reason', max_length=200, allow_separators=True, ) else: item_id = normalize_identifier(entry) weight = 1.0 reason = None if item_id is None: raise ToolInputError('Every seed item requires a valid item_id') item_id = _safe_text(item_id, 'item_id', max_length=128) current = normalized.get(item_id) if current is None or weight > current['weight']: normalized[item_id] = { 'item_id': item_id, 'weight': weight, 'reason': reason, } return list(normalized.values()) def _normalize_context(self, context): if context is None: return {} if not isinstance(context, dict): raise ToolInputError('context must be an object') allowed = {'platform', 'client_platform', 'country_code', 'customer_type'} unknown = set(context) - allowed if unknown: raise ToolInputError('Unsupported context fields: %s' % ', '.join(sorted(unknown))) result = {} if context.get('platform') is not None: result['platform'] = _safe_text( context['platform'], 'platform', lower=True ) if context.get('client_platform') is not None: result['client_platform'] = _safe_text( context['client_platform'], 'client_platform', lower=True ) if context.get('country_code') is not None: result['country_code'] = _safe_text( context['country_code'], 'country_code', upper=True ) if context.get('customer_type') is not None: result['customer_type'] = _safe_text( context['customer_type'], 'customer_type' ) return result def _normalize_interests(self, interests): if interests is None: return [] if not isinstance(interests, (list, tuple)): raise ToolInputError('interests must be an array') if len(interests) > 30: raise ToolInputError('interests supports at most 30 entries') result = [] for entry in interests: if not isinstance(entry, dict): raise ToolInputError('Every interest must be an object') dimension = DIMENSION_ALIASES.get(str(entry.get('dimension', '')).strip()) if dimension not in DIMENSION_NAMES: raise ToolInputError('Unsupported dimension: %s' % entry.get('dimension')) value = self._normalize_dimension_value(dimension, entry.get('value')) weight = _bounded_weight(entry.get('weight'), 'interest weight', 1.0) reason = entry.get('reason') if reason is not None: reason = _safe_text( reason, 'interest reason', max_length=200, allow_separators=True, ) result.append({ 'dimension': dimension, 'value': value, 'weight': weight, 'origin': 'profile', 'reason': reason, }) return result @staticmethod def _normalize_dimension_value(dimension, value): normalized = normalize_identifier(value) if normalized is None: raise ToolInputError('%s requires a valid value' % dimension) if dimension in ('platform', 'client_platform'): return _safe_text(normalized, dimension, lower=True) if dimension == 'country_code': return _safe_text(normalized, dimension, upper=True) return _safe_text(normalized, dimension) def _plan_dimensions(self, context, interests): context = self._normalize_context(context) interests = self._normalize_interests(interests) values = {dimension: [] for dimension in DIMENSION_NAMES} for dimension, value in context.items(): values[dimension].append({ 'dimension': dimension, 'value': value, 'weight': 1.0, 'origin': 'context', 'reason': None, }) for interest in interests: values[interest['dimension']].append(interest) if not any(values.values()): raise ToolInputError('No queryable context or dimension interest was supplied') plans = {} for dimension in DIRECT_DIMENSIONS: for entry in values[dimension]: self._add_dimension_plan( plans, '%s:%s' % (dimension, entry['value']), entry['weight'], [self._matched_value(entry)], 1, ) for platform in values['platform']: for client in values['client_platform']: self._add_combination_plan( plans, 'platform_client:%s_%s' % ( platform['value'], client['value'] ), [platform, client], 1.20, 2, ) for category in values['category_level2']: self._add_combination_plan( plans, 'platform_category2:%s_%s' % ( platform['value'], category['value'] ), [platform, category], 1.30, 2, ) for category in values['category_level3']: self._add_combination_plan( plans, 'platform_category3:%s_%s' % ( platform['value'], category['value'] ), [platform, category], 1.35, 2, ) if platform['value'] in ('essa', 'essaone'): for country in values['country_code']: country_key = 'platform:%s;country_code:%s' % ( platform['value'], country['value'] ) self._add_combination_plan( plans, country_key, [platform, country], 1.40, 2 ) for customer_type in values['customer_type']: self._add_combination_plan( plans, '%s;customer_type:%s' % ( country_key, customer_type['value'] ), [platform, country, customer_type], 1.60, 3, ) for client in values['client_platform']: for category in values['category_level2']: self._add_combination_plan( plans, 'client_category2:%s_%s' % ( client['value'], category['value'] ), [client, category], 1.20, 2, ) ranked_plans = sorted( plans.values(), key=lambda plan: ( -plan['specificity'], -plan['weight'], plan['dimension_key'] ), ) if not ranked_plans: raise ToolInputError( 'The supplied dimensions require platform or another queryable dimension' ) return ranked_plans[:MAX_DIMENSION_PLANS] def _add_combination_plan(self, plans, key, entries, multiplier, specificity): average_weight = sum(entry['weight'] for entry in entries) / len(entries) self._add_dimension_plan( plans, key, average_weight * multiplier, [self._matched_value(entry) for entry in entries], specificity, ) @staticmethod def _add_dimension_plan(plans, key, weight, matched, specificity): current = plans.get(key) if current is None: plans[key] = { 'dimension_key': key, 'weight': weight, 'matched': matched, 'specificity': specificity, } return current['weight'] = max(current['weight'], weight) current['specificity'] = max(current['specificity'], specificity) current['matched'] = RecommendationAgentTools._deduplicate_dicts( current['matched'] + matched ) @staticmethod def _matched_value(entry): result = { 'dimension': entry['dimension'], 'value': entry['value'], 'origin': entry['origin'], } if entry.get('reason'): result['reason'] = entry['reason'] return result @staticmethod def _add_candidate(candidates, item_id, contribution, evidence): candidate = candidates.setdefault(item_id, { 'score': 0.0, 'evidence': [], 'channels': set(), }) candidate['score'] += contribution candidate['evidence'].append(evidence) candidate['channels'].add(evidence['channel']) def _render_candidates(self, candidates, top_k): ranked = sorted( candidates.items(), key=lambda entry: (-entry[1]['score'], entry[0]) ) maximum = ranked[0][1]['score'] if ranked else 1.0 items = [] for item_id, candidate in ranked[:top_k]: all_evidence = sorted( candidate['evidence'], key=lambda entry: -entry.get('contribution', 0.0), ) evidence = all_evidence[:MAX_EVIDENCE_PER_ITEM] items.append({ 'item_id': item_id, 'score': round(candidate['score'] / maximum, 6), 'channels': sorted(candidate['channels']), 'source_count': len({entry['key'] for entry in all_evidence}), 'reasons': self._build_reasons(evidence), 'evidence': evidence, }) return items @staticmethod def _build_reasons(evidence): collaborative = {} dimensions = {} for entry in evidence: if entry['channel'] == 'collaborative': seed = entry['seed_item_id'] reason = collaborative.setdefault(seed, { 'type': 'similar_to_seed', 'seed_item_id': seed, 'algorithms': [], }) if entry['source'] not in reason['algorithms']: reason['algorithms'].append(entry['source']) if entry.get('seed_reason'): reason['profile_reason'] = entry['seed_reason'] else: dimension_key = entry['dimension_key'] reason = dimensions.setdefault(dimension_key, { 'type': 'matched_dimension', 'dimension_key': dimension_key, 'list_types': [], 'matched': entry.get('matched', []), }) if entry['source'] not in reason['list_types']: reason['list_types'].append(entry['source']) return list(collaborative.values()) + list(dimensions.values()) @staticmethod def _deduplicate_dicts(values): result = [] seen = set() for value in values: marker = repr(sorted(value.items())) if marker not in seen: result.append(value) seen.add(marker) return result