Team Ai
Apppublic

Yash030/claude-code-proxy

sourceHugging Faceupdated 5mo agoView on Hugging Face
2likes
detection.py177 linesDownload Raw Back to api
1"""Request detection utilities for API optimizations.2 3Detects quota checks, title generation, prefix detection, suggestion mode,4and filepath extraction requests to enable fast-path responses.5"""6 7from core.anthropic import extract_text_from_content8 9from .models.anthropic import MessagesRequest10 11 12def is_trivial_text_request(request_data: MessagesRequest) -> tuple[bool, str]:13    """Detect trivial requests that can be fast-pathed.14 15    Returns (is_trivial, text_content) for trivial requests that only need16    a simple acknowledgment or echo response.17    """18    # Only for single short user messages with max_tokens=119    if request_data.max_tokens != 1:20        return False, ""21    if len(request_data.messages) != 1:22        return False, ""23    msg = request_data.messages[0]24    if msg.role != "user":25        return False, ""26 27    text = extract_text_from_content(msg.content)28    text_lower = text.lower().strip()29 30    # Single word or very short queries31    if len(text_lower) < 50:32        # "hi", "hello", "ok", "thanks", etc.33        if text_lower in (34            "hi",35            "hello",36            "ok",37            "thanks",38            "thank you",39            "yes",40            "no",41            "okay",42        ):43            return True, f"OK. {text}"44 45        # Health/status checks46        if any(kw in text_lower for kw in ["status", "health", "ping", "are you"]):47            return True, "I'm ready."48 49    return False, ""50 51 52def is_quota_check_request(request_data: MessagesRequest) -> bool:53    """Check if this is a quota probe request.54 55    Quota checks are typically simple requests with max_tokens=156    and a single message containing the word "quota".57    """58    if (59        request_data.max_tokens == 160        and len(request_data.messages) == 161        and request_data.messages[0].role == "user"62    ):63        text = extract_text_from_content(request_data.messages[0].content)64        if "quota" in text.lower():65            return True66    return False67 68 69def is_title_generation_request(request_data: MessagesRequest) -> bool:70    """Check if this is a conversation title generation request.71 72    Title generation requests are detected by a system prompt containing73    title extraction instructions, no tools, and a single user message.74 75    Matches Claude Code session title prompts (sentence-case title, JSON76    \"title\" field, etc.).77    """78    if not request_data.system or request_data.tools:79        return False80    system_text = extract_text_from_content(request_data.system).lower()81    if "title" not in system_text:82        return False83    return "sentence-case title" in system_text or (84        "return json" in system_text85        and "field" in system_text86        and ("coding session" in system_text or "this session" in system_text)87    )88 89 90def is_prefix_detection_request(request_data: MessagesRequest) -> tuple[bool, str]:91    """Check if this is a fast prefix detection request.92 93    Prefix detection requests contain a policy_spec block and94    a Command: section for extracting shell command prefixes.95 96    Returns:97        Tuple of (is_prefix_request, command_string)98    """99    if len(request_data.messages) != 1 or request_data.messages[0].role != "user":100        return False, ""101 102    content = extract_text_from_content(request_data.messages[0].content)103 104    if "<policy_spec>" in content and "Command:" in content:105        try:106            cmd_start = content.rfind("Command:") + len("Command:")107            return True, content[cmd_start:].strip()108        except TypeError:109            return False, ""110 111    return False, ""112 113 114def is_suggestion_mode_request(request_data: MessagesRequest) -> bool:115    """Check if this is a suggestion mode request.116 117    Suggestion mode requests contain "[SUGGESTION MODE:" in the user's message,118    used for auto-suggesting what the user might type next.119    """120    for msg in request_data.messages:121        if msg.role == "user":122            text = extract_text_from_content(msg.content)123            if "[SUGGESTION MODE:" in text:124                return True125    return False126 127 128def is_filepath_extraction_request(129    request_data: MessagesRequest,130) -> tuple[bool, str, str]:131    """Check if this is a filepath extraction request.132 133    Filepath extraction requests have a single user message with134    "Command:" and "Output:" sections, asking to extract file paths135    from command output.136 137    Returns:138        Tuple of (is_filepath_request, command, output)139    """140    if len(request_data.messages) != 1 or request_data.messages[0].role != "user":141        return False, "", ""142    if request_data.tools:143        return False, "", ""144 145    content = extract_text_from_content(request_data.messages[0].content)146 147    if "Command:" not in content or "Output:" not in content:148        return False, "", ""149 150    # Match if user content OR system block indicates filepath extraction151    user_has_filepaths = (152        "filepaths" in content.lower() or "<filepaths>" in content.lower()153    )154    system_text = (155        extract_text_from_content(request_data.system) if request_data.system else ""156    )157    system_has_extract = (158        "extract any file paths" in system_text.lower()159        or "file paths that this command" in system_text.lower()160    )161    if not user_has_filepaths and not system_has_extract:162        return False, "", ""163 164    cmd_start = content.find("Command:") + len("Command:")165    output_marker = content.find("Output:", cmd_start)166    if output_marker == -1:167        return False, "", ""168 169    command = content[cmd_start:output_marker].strip()170    output = content[output_marker + len("Output:") :].strip()171 172    for marker in ["<", "\n\n"]:173        if marker in output:174            output = output.split(marker)[0].strip()175 176    return True, command, output177