Micro-llm / hf_retrieval.py
Valeztiro's picture
Micro-llm V1.0.1
673d750 verified
Raw History Blame Contribute Delete
3.49 kB
"""Retrieve similar No Robots demonstrations only when Hugging Face is reachable."""
from __future__ import annotations
import math
import re
import socket
from functools import lru_cache
from typing import Any, Iterable
DATASET_NAME = "HuggingFaceH4/no_robots"
STOP_WORDS = {
"about", "above", "after", "again", "against", "all", "also", "am", "an",
"and", "any", "are", "as", "at", "be", "because", "been", "before",
"being", "below", "between", "both", "but", "by", "can", "could", "did",
"do", "does", "doing", "down", "during", "each", "few", "for", "from",
"further", "had", "has", "have", "having", "he", "her", "here", "hers",
"herself", "him", "himself", "his", "how", "i", "if", "in", "into", "is",
"it", "its", "itself", "just", "me", "more", "most", "my", "myself", "no",
"nor", "not", "of", "off", "on", "once", "only", "or", "other", "our",
"ours", "ourselves", "out", "over", "own", "same", "she", "should", "so",
"some", "such", "than", "that", "the", "their", "theirs", "them",
"themselves", "then", "there", "these", "they", "this", "those", "through",
"to", "too", "under", "until", "up", "very", "was", "we", "were", "what",
"when", "where", "which", "while", "who", "whom", "why", "will", "with",
"would", "you", "your", "yours", "yourself", "yourselves",
}
WORD_PATTERN = re.compile(r"[a-z0-9]{3,}")
def hugging_face_is_reachable(timeout: float = 2.0) -> bool:
try:
with socket.create_connection(("huggingface.co", 443), timeout=timeout):
return True
except OSError:
return False
def _terms(text: str) -> set[str]:
return {term for term in WORD_PATTERN.findall(text.lower()) if term not in STOP_WORDS}
def find_relevant_examples(
query: str, rows: Iterable[dict[str, Any]], limit: int = 2
) -> list[tuple[str, str]]:
query_terms = _terms(query)
if not query_terms:
return []
minimum_overlap = 1 if len(query_terms) < 3 else 2
matches: list[tuple[int, float, str, str]] = []
for row in rows:
if str(row.get("category", "")).lower() == "generation":
continue
messages = row.get("messages")
if not isinstance(messages, list):
continue
user_text = None
assistant_text = None
for message in messages:
if not isinstance(message, dict):
continue
role = str(message.get("role", "")).lower()
content = message.get("content")
if not isinstance(content, str) or not content.strip():
continue
if role == "user" and user_text is None:
user_text = content.strip()
elif role == "assistant" and user_text is not None:
assistant_text = content.strip()
break
if user_text is None or assistant_text is None:
continue
row_terms = _terms(user_text)
overlap = query_terms & row_terms
if len(overlap) < minimum_overlap:
continue
score = len(overlap) / math.sqrt(len(query_terms) * len(row_terms))
matches.append((len(overlap), score, user_text, assistant_text))
matches.sort(key=lambda match: (match[0], match[1]), reverse=True)
return [(user_text, assistant_text) for _, _, user_text, assistant_text in matches[:limit]]
@lru_cache(maxsize=1)
def _load_training_split():
from datasets import load_dataset
return load_dataset(DATASET_NAME, split="train")
def retrieve_examples(query: str, limit: int = 2) -> list[tuple[str, str]]:
if limit < 1 or not hugging_face_is_reachable():
return []
try:
return find_relevant_examples(query, _load_training_split(), limit)
except Exception as error:
print(f"Hugging Face example lookup unavailable: {error}")
return []