service.py 37.7 KB
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 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
"""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):
        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'))

        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')

        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,
            )
        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