"""Run Iris Content Guard on ZeroGPU and return probabilities for the turn plots.""" import spaces import torch import transformers CATEGORIES = ( 'cyber', 'fraud', 'privacy', 'bio_weapons', 'chem_weapons', 'rn_weapons', 'child_safety_non_csae', 'violence', 'self_harm', 'grooming', 'sex_crimes', 'sex_content', 'illegal_activities', 'hate', ) type TurnScores = dict[str, dict[str, float] | None] classifier = transformers.pipeline( 'token-classification', model='reflection/Iris-Content-Guard', trust_remote_code=True, # ZeroGPU stages tensors placed on CUDA at startup. device='cuda', ) def _category_scores(side: dict[str, dict[str, float]]) -> dict[str, float]: probabilities = side['category_harm_probabilities'] scores = {category: probabilities[category] for category in CATEGORIES} if not all( type(value) in (float, int) and 0 <= value <= 1 for value in scores.values() ): raise ValueError('Invalid Iris Content Guard probabilities') return scores @spaces.GPU(size='xlarge') def score_conversation(messages: list[dict[str, str]]) -> TurnScores: """Score the latest user request and its visible reply in conversation context.""" with torch.inference_mode(): result = classifier(messages) reply = result['response'] if (reply is not None) != (messages[-1]['role'] == 'assistant'): raise ValueError('Iris Content Guard reply does not match the conversation') return { 'request': _category_scores(result['request']), 'response': _category_scores(reply) if reply is not None else None, }