#!/usr/bin/env python3 from __future__ import annotations import argparse import difflib import json import os import random import re import shutil import statistics from collections import Counter, defaultdict from pathlib import Path from typing import Any import pandas as pd DATASET_NAME = "LifeStreamingCoT" REPO_ID = "skyzhou06/LifeStreamingCoT" DATASET_VERSION = "v0.4" GENERATION_METHOD = "source_grounded_rule_based_v0.4_quality_refined" REASONING_POLICY = "selective_concise" CHUNKING_METHOD = "semantic_sentence_split_v0.4_refined" REFINEMENT_METHOD = "rule_based_quality_refinement_v0.4" INSTRUCTION = "Help the user complete a real-life task based on gradually revealed information." CACHE_DIR = Path(".lifesct_cache") SOURCE_CACHE = CACHE_DIR / "v0_2_source_rows.jsonl" BASE_FIELDS = [ "id", "domain", "source_dataset", "instruction", "context", "context_chunks", "streaming_reasoning", "deep_reasoning", "answer", "response", "messages", "text", "num_chunks", "language", "split", "generation_method", "quality_flags", "version", "reasoning_policy", "chunking_method", "chunk_labels", "skip_chunks", "skip_reasons", "reasoning_token_budget", "original_num_chunks", "chunk_split_count", ] V04_FIELDS = [ "quality_score", "is_high_quality", "refinement_method", "llm_augmented", "llm_augmentation_model", "rejected_reason", "state_tracking_confidence", ] REQUIRED_FIELDS = BASE_FIELDS + V04_FIELDS REASONING_TOKEN_BUDGET = { "streaming_reasoning_max_words_per_chunk": 18, "deep_reasoning_max_words": 45, "answer_max_sentences": 3, } FORBIDDEN_GENERIC_PHRASES = [ "the user is sharing everyday context", "the situation is about an everyday life situation", "the assistant should stay conversational", "the user is asking for help, clarification, or a next step", "support need centers on", "task_detail=noted", "emotion=positive; cause=", "emotion=negative; cause=", "given the full context", "tracked constraints so far", ] BLOCKLIST = [ "suicide", "self-harm", "self harm", "kill myself", "kill yourself", "sexual assault", "rape", "explicit sex", "porn", "build a gun", "make a bomb", "legal advice", "lawsuit", "attorney", "court case", "cocaine", "heroin", "methamphetamine", "credit card number", "social security number", ] STOPWORDS = { "about", "after", "again", "also", "and", "are", "because", "before", "being", "but", "can", "could", "does", "doing", "for", "from", "get", "got", "good", "great", "had", "has", "have", "how", "into", "its", "it's", "just", "know", "later", "like", "more", "much", "need", "only", "please", "really", "should", "some", "sure", "that", "the", "their", "there", "these", "they", "thing", "things", "this", "time", "today", "want", "was", "were", "well", "what", "when", "where", "which", "with", "would", "yeah", "yes", "you", "your", } NUMBER_WORDS = { "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10, } SEVERE_FLAGS = { "generic_reasoning", "closing_mishandled", "possible_slot_error", "excessive_chunking", "fragment_chunk", } FLAG_PENALTIES = { "generic_reasoning": 0.20, "excessive_chunking": 0.15, "fragment_chunk": 0.15, "copied_source_response": 0.15, "closing_mishandled": 0.15, "short_answer": 0.10, "weak_context": 0.10, "low_specificity": 0.10, "possible_slot_error": 0.10, "too_many_skips": 0.05, "no_skip_labels": 0.05, } def clean_text(value: Any, max_chars: int = 420) -> str: if value is None: return "" if isinstance(value, (list, tuple)): value = " ".join(clean_text(item, max_chars=max_chars) for item in value) text = str(value) text = text.replace("_comma_", ",") text = text.replace("\r", " ").replace("\n", " ").replace("\t", " ") text = text.replace("\u2019", "'").replace("\u2018", "'") text = text.replace("\u201c", '"').replace("\u201d", '"') text = re.sub(r"<[^>]{1,40}>", " ", text) text = re.sub(r"\b(Mr|Mrs|Ms|Dr)\s+\.", r"\1.", text) text = re.sub(r"\b([A-Za-z])\s+'\s+([A-Za-z])", r"\1'\2", text) text = re.sub(r"\s+([,.!?;:])", r"\1", text) text = re.sub(r"\s+", " ", text).strip() text = re.sub(r"\b[\w.+-]+@[\w-]+\.[\w.-]+\b", "[email removed]", text) text = re.sub(r"\b(?:\+?\d[\d .()-]{7,}\d)\b", "[phone removed]", text) if len(text) > max_chars: cut = text[:max_chars].rsplit(" ", 1)[0].strip() text = f"{cut}." return text def normalize(text: str) -> str: return re.sub(r"\W+", " ", text.lower()).strip() def word_count(text: str) -> int: return len(re.findall(r"\b[\w'-]+\b", str(text))) def tokenize_words(text: str) -> list[str]: return re.findall(r"[a-zA-Z][a-zA-Z'-]{2,}", text.lower()) def salient_terms(text: str, limit: int = 5) -> list[str]: terms: list[str] = [] for word in tokenize_words(text): word = word.strip("'") if word not in STOPWORDS and word not in terms: terms.append(word) if len(terms) >= limit: break return terms def compact_join(items: list[str], fallback: str = "") -> str: unique = [item for idx, item in enumerate(items) if item and item not in items[:idx]] if not unique: return fallback if len(unique) == 1: return unique[0] return ", ".join(unique[:-1]) + f", {unique[-1]}" def finish_sentence(text: str) -> str: text = clean_text(text, max_chars=500) if text and text[-1] not in ".!?": text += "." return text def read_jsonl(path: Path) -> list[dict[str, Any]]: rows: list[dict[str, Any]] = [] if not path.exists(): return rows with path.open("r", encoding="utf-8") as handle: for line in handle: line = line.strip() if line: rows.append(json.loads(line)) return rows def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8") as handle: for row in rows: handle.write(json.dumps(row, ensure_ascii=False) + "\n") def parse_context_chunks(row: dict[str, Any]) -> list[str]: chunks = row.get("context_chunks") if isinstance(chunks, list): return [clean_text(chunk, max_chars=420) for chunk in chunks if clean_text(chunk)] parsed: list[str] = [] for line in str(row.get("context") or "").splitlines(): match = re.match(r"\s*Chunk\s+\d+\s*:\s*(.+)$", line) if match: parsed.append(clean_text(match.group(1), max_chars=420)) return parsed def load_source_rows(output_dir: Path) -> tuple[list[dict[str, Any]], list[dict[str, str]]]: CACHE_DIR.mkdir(parents=True, exist_ok=True) if SOURCE_CACHE.exists(): return read_jsonl(SOURCE_CACHE), [] local_rows = read_jsonl(output_dir / "data" / "train.jsonl") + read_jsonl(output_dir / "data" / "eval.jsonl") if local_rows: write_jsonl(SOURCE_CACHE, local_rows) return local_rows, [{"name": "local output", "reason": "v0.2 cache was missing; used local dataset rows"}] try: from datasets import load_dataset ds = load_dataset(REPO_ID) rows: list[dict[str, Any]] = [] for split in ds: for row in ds[split]: rows.append(dict(row)) if rows: write_jsonl(SOURCE_CACHE, rows) return rows, [] except Exception as exc: # noqa: BLE001 return [], [{"name": REPO_ID, "reason": f"could not load existing dataset: {type(exc).__name__}"}] return [], [{"name": "source rows", "reason": "no local or remote source rows available"}] def build_context(chunks: list[str]) -> str: return "\n".join(f"Chunk {idx}: {chunk}" for idx, chunk in enumerate(chunks, start=1)) def protect_abbreviations(text: str) -> str: for abbr in ["Mr.", "Mrs.", "Ms.", "Dr.", "Prof.", "St."]: text = text.replace(abbr, abbr.replace(".", "")) return text def restore_abbreviations(text: str) -> str: return text.replace("", ".") def split_plain_sentences(text: str) -> list[str]: text = clean_text(text, max_chars=700) if not text: return [] protected = protect_abbreviations(text) pieces = re.split(r"(?<=[.!?])\s+|;\s+", protected) out: list[str] = [] for piece in pieces: piece = restore_abbreviations(piece) piece = clean_text(piece, max_chars=320).strip(" ,;") if piece: out.append(finish_sentence(piece)) return out or [finish_sentence(text)] def skip_reason_for_text(text: str) -> str | None: lower = normalize(text) raw = text.lower() if not lower: return "low_information" strong_info = re.search( r"\b(address|phone|postcode|post code|reference|book|booking|reserve|restaurant|hotel|train|taxi|attraction|museum|cost|fee|travel time|can i|get|could you|would you)\b", raw, ) if re.search(r"\b(that'?s all|that is all|that will be all|all i need(?:ed)?|everything i need(?:ed)?|that should be it|will be all|that was all i needed)\b", raw): return None if strong_info else "closing_only" if lower in {"hi", "hello", "hey", "good morning", "good afternoon", "good evening"}: return "greeting_only" if re.fullmatch(r"(great\s+)?thanks( so much)?( a lot)?( for your help( today)?)?", lower): return "thanks_only" if re.match(r"^(thank you|thanks|no thanks|no thank you|awesome thanks|great thanks)\b", lower) and not strong_info: return "thanks_only" if lower in {"goodbye", "bye", "see you", "see you later", "have a nice day", "have a great day"}: return "closing_only" if lower in {"ok", "okay", "alright", "sure", "sounds good", "fine", "got it", "really", "who", "what", "wow"}: return "backchannel_only" if lower in {"ok", "okay", "alright", "sure", "sounds good", "fine", "got it"} else "low_information" if lower in {"um", "uh", "hmm", "well", "let me see"}: return "filler_only" if lower in {"youre welcome", "you re welcome", "you're welcome", "you are welcome"}: return "acknowledgement_only" if re.fullmatch(r"(please|sorry|excuse me)[.!]?", raw.strip()): return "politeness_only" if word_count(text) <= 2 and not re.search(r"\b(book|yes|no|where|when|phone|address|cost|fee)\b", raw): return "low_information" return None def is_closing_or_thanks(text: str) -> bool: return skip_reason_for_text(text) in {"thanks_only", "closing_only", "politeness_only"} def is_meaningful_short_chunk(text: str) -> bool: lower = normalize(text) return lower in {"yes", "no", "ok", "okay", "thanks", "bye", "hello", "hi"} or bool(re.search(r"\b(stop|wait|leave|book|call|go|pay|wash|rinse|wipe|unplug)\b", lower)) def is_fragment_chunk(text: str) -> bool: stripped = clean_text(text, max_chars=80).strip() if not stripped: return True wc = word_count(stripped) if wc == 0: return True if wc <= 2 and re.fullmatch(r"[\W_]+", stripped): return True if re.fullmatch(r"(Mr|Mrs|Ms|Dr|Prof)\.?", stripped): return True if normalize(stripped) == "macmillan": return True if skip_reason_for_text(stripped) or is_meaningful_short_chunk(stripped): return False if wc <= 2 and re.fullmatch(r"[A-Z][a-z]+\.?", stripped): return True return False def merge_fragments(chunks: list[str]) -> tuple[list[str], bool]: merged: list[str] = [] changed = False prefix = "" for chunk in chunks: chunk = clean_text(chunk, max_chars=360) if not chunk: continue if is_fragment_chunk(chunk): changed = True if merged: merged[-1] = finish_sentence(merged[-1].rstrip(".!?") + " " + chunk.strip()) else: prefix = f"{prefix} {chunk}".strip() continue if prefix: chunk = finish_sentence(prefix + " " + chunk) prefix = "" if word_count(chunk) < 4 and merged and not is_meaningful_short_chunk(chunk): changed = True merged[-1] = finish_sentence(merged[-1].rstrip(".!?") + " " + chunk) else: merged.append(finish_sentence(chunk)) if prefix and merged: merged[-1] = finish_sentence(merged[-1].rstrip(".!?") + " " + prefix) return merged, changed def split_on_conjunctions(text: str, domain: str) -> list[str]: text = clean_text(text, max_chars=700) if word_count(text) <= 30: return [finish_sentence(text)] patterns = [r",\s+and\s+I\s+", r"\s+and\s+I\s+", r",\s+then\s+", r"\s+then\s+", r"\s+before\s+"] if domain == "emotional_support": patterns.extend([r"\s+because\s+", r",\s+but\s+", r"\s+but\s+"]) regex = "|".join(f"(?:{pattern})" for pattern in patterns) pieces = [clean_text(piece, max_chars=260).strip(" ,;") for piece in re.split(regex, text) if clean_text(piece)] if len(pieces) <= 1: return [finish_sentence(text)] merged, _ = merge_fragments([finish_sentence(piece) for piece in pieces if word_count(piece) >= 3]) return merged or [finish_sentence(text)] def contains_term(text: str, term: str) -> bool: if " " in term: return term in text return bool(re.search(rf"\b{re.escape(term)}\b", text)) def extract_task_details(text: str) -> dict[str, list[str]]: if is_closing_or_thanks(text): return {} lower = text.lower() details: dict[str, list[str]] = defaultdict(list) domain_terms = { "restaurant": ["restaurant", "food", "eat", "dinner", "lunch", "breakfast", "cuisine"], "hotel": ["hotel", "guesthouse", "guest house", "room", "stay", "lodging"], "taxi": ["taxi", "cab", "pickup", "pick me up"], "train": ["train", "rail", "station"], "attraction": ["museum", "park", "theatre", "theater", "attraction", "gallery", "college", "arts"], "hospital": ["hospital", "clinic"], } for label, terms in domain_terms.items(): if any(contains_term(lower, term) for term in terms): details["domain"].append(label) if re.search(r"\b(find|looking for|look for|need|want|search|assist|help|getting|get me)\b", lower): details["goal"].append("search") if re.search(r"\b(book|booking|reservation|reserve)\b", lower): details["goal"].append("booking") if re.search(r"\b(recommend|suggest|favorite|what about|how about)\b", lower): details["goal"].append("recommendation") if re.search(r"\b(different|another|alternative|instead|else)\b", lower): details["goal"].append("compare_alternative") if re.search(r"\b(change|switch|make it|same price|same pricerange|same area)\b", lower): details["goal"].append("modify_constraint") if re.search(r"\b(can i|get|give me|tell me|what is|what's|how much|phone|address|postcode|reference|travel time|fee|cost)\b", lower): details["goal"].append("request_info") if re.search(r"\b(yes|that works|perfect|sounds good|that will be fine)\b", lower) and re.search(r"\b(book|reservation|option|one)\b", lower): details["goal"].append("confirm_booking") for price in ["cheap", "moderate", "expensive", "affordable", "budget", "not too expensive", "same pricerange", "same price"]: if price in lower: details["price"].append("affordable" if price == "budget" else price.replace("same pricerange", "same price range")) for area in ["north", "south", "east", "west", "centre", "center", "downtown", "campus"]: if re.search(rf"\b{re.escape(area)}\b", lower): details["area"].append("centre" if area == "center" else area) for cuisine in ["italian", "chinese", "indian", "korean", "thai", "french", "mexican", "japanese", "british", "vegetarian", "seafood", "danish", "persian", "european", "turkish"]: if re.search(rf"\b{cuisine}\b", lower): details["food"].append(cuisine) for day in ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", "tomorrow"]: if re.search(rf"\b{day}\b", lower): details["day"].append(day) if re.search(r"\btoday\b", lower) and not is_closing_or_thanks(text): details["day"].append("today") for match in re.finditer(r"\b\d{1,2}(?::\d{2})?\s?(?:am|pm)?\b", lower): token = match.group(0).strip() window = lower[max(0, match.start() - 28) : min(len(lower), match.end() + 28)] if ":" in token or "am" in token or "pm" in token or re.search(r"\b(at|after|before|around|by|leave|arrive|time|starting)\b", window): details["time"].append(token) people_match = re.search(r"\b(?:for|party of|it would be|there will be|we are)\s+(\d+)\s+(?:people|guests|persons)\b", lower) if people_match: details["party_size"].append(f"{people_match.group(1)} people") else: bare_people_match = re.search(r"\b(\d+)\s+(?:people|guests|persons)\b", lower) if bare_people_match: details["party_size"].append(f"{bare_people_match.group(1)} people") if not details.get("party_size"): phrase_match = re.search(r"\bfor\s+the\s+(\w+)\s+of\s+us\b", lower) if phrase_match and phrase_match.group(1) in NUMBER_WORDS: details["party_size"].append(f"{NUMBER_WORDS[phrase_match.group(1)]} people") if not details.get("party_size"): for word, number in NUMBER_WORDS.items(): if re.search(rf"\b{word}\b[^.?!]{{0,20}}\b(people|guests|of us)\b", lower): details["party_size"].append(f"{number} people") break stay_match = re.search(r"\b(\d+)\s+nights?\b", lower) if stay_match: details["stay_length"].append(f"{stay_match.group(1)} nights") star_match = re.search(r"\b(\d+)\s*stars?\b", lower) if star_match: details["stars"].append(f"{star_match.group(1)} stars") for amenity in ["parking", "wifi", "internet", "free parking", "pool", "breakfast"]: if amenity in lower: details["amenities"].append(amenity) if "guesthouse" in lower or "guest house" in lower: details["hotel_type"].append("guesthouse") if "hotel" in lower: details["hotel_type"].append("hotel") route_match = re.search(r"\bfrom\s+(.+?)\s+(?:to|going to)\s+([^,.?]+)", lower) if route_match: details["departure"].append(re.sub(r"\b(going|on|at|after|before)\b.*$", "", route_match.group(1)).strip()) destination = re.sub(r"\b(on|at|after|before)\b.*$", "", route_match.group(2)).strip() details["destination"].append(destination) depart_match = re.search(r"\bdepart(?:ing)? from\s+([^,.?]+)", lower) if depart_match: details["departure"].append(depart_match.group(1).strip()) dest_match = re.search(r"\b(?:going to|heading to|arrive at|to)\s+([A-Z]?[a-z][^,.?]{2,40})", text) if dest_match and " from " not in lower and " to " not in lower[:8]: candidate = clean_text(dest_match.group(1), max_chars=60).lower() if not any(stop in candidate for stop in ["get ", "see ", "help", "book"]): details["destination"].append(candidate) if "no area preference" in lower or "any area" in lower: details["area"].append("any") if re.search(r"\bpark\b", lower): details["domain"].append("attraction") details["type"].append("park") info_map = [ ("address", "address"), ("phone", "phone"), ("telephone", "phone"), ("postcode", "postcode"), ("post code", "postcode"), ("postal code", "postcode"), ("reference", "reference_number"), ("travel time", "travel_time"), ("entrance fee", "entrance_fee"), ("admission", "entrance_fee"), ("cost", "price"), ("price", "price"), ("recommendation", "recommendation"), ] requestish = bool(re.search(r"\b(can you|could you|tell me|give me|what is|what's|how much|how long|need|need a|need an|i'll need|get a|get the)\b", lower)) for needle, label in info_map: if re.search(rf"\b{re.escape(needle)}\b", lower): always_info = label in {"phone", "address", "postcode", "reference_number", "travel_time", "entrance_fee"} if always_info or requestish: details["requested_info"].append(label) if re.search(r"\bhow long\b.*\b(journey|trip|travel|take)\b|\bjourney take\b", lower): details["requested_info"].append("travel_time") if re.search(r"\bfine arts?\b", lower): details["type"].append("fine_arts_museum") if re.search(r"\bsports?\b", lower): details["type"].append("sports") return {key: list(dict.fromkeys(values)) for key, values in details.items()} def semantic_split_task(text: str) -> list[str]: if is_closing_or_thanks(text): return split_plain_sentences(text) details = extract_task_details(text) slot_count = sum(len(values) for key, values in details.items() if key not in {"goal"}) if word_count(text) >= 18 and slot_count >= 4: chunks: list[str] = [] domains = details.get("domain", []) if "restaurant" in domains: desc = " ".join(part for part in [details.get("price", [""])[0], details.get("food", [""])[0], "restaurant"] if part) chunks.append(f"I want to find a {desc}.") elif "hotel" in domains: desc = " ".join(part for part in [details.get("price", [""])[0], details.get("hotel_type", ["hotel"])[0]] if part) chunks.append(f"I want to find a {desc}.") elif domains: chunks.append(f"I need help with {domains[0]}.") if details.get("area"): chunks.append(f"It should be in the {details['area'][0]} part of town.") if details.get("party_size"): chunks.append(f"It is for {details['party_size'][0]}.") if details.get("day") or details.get("time"): when = compact_join(details.get("day", []) + details.get("time", [])) chunks.append(f"The time is {when}.") if details.get("goal") and "booking" in details["goal"]: chunks.append("Please make a booking.") for info in details.get("requested_info", []): chunks.append(f"I also need the {info.replace('_', ' ')}.") if len(chunks) >= 2: return chunks out: list[str] = [] for sentence in split_plain_sentences(text): if word_count(sentence) > 30: out.extend(split_on_conjunctions(sentence, "task_oriented_assistant")) else: out.append(sentence) return out def semantic_split_emotional(text: str) -> list[str]: text = clean_text(text, max_chars=700) if word_count(text) <= 25: return split_plain_sentences(text) pieces = re.split(r"(?<=[.!?])\s+|,\s+and\s+I\s+|\s+and\s+I\s+|,\s+because\s+|\s+because\s+|,\s+but\s+|\s+but\s+", text, flags=re.IGNORECASE) pieces = [finish_sentence(piece.strip(" ,;")) for piece in pieces if word_count(piece) >= 4] return pieces if len(pieces) > 1 else split_plain_sentences(text) def semantic_split_daily(text: str) -> list[str]: out: list[str] = [] for sentence in split_plain_sentences(text): if word_count(sentence) > 30: out.extend(split_on_conjunctions(sentence, "daily_dialogue")) else: out.append(sentence) return out def semantic_split_how_to(text: str) -> list[str]: text = clean_text(text, max_chars=700) if text.lower().startswith("task:") or word_count(text) <= 30: return [finish_sentence(text)] pieces = re.split(r"(?<=[.!?])\s+|;\s+|,\s+then\s+|,\s+before\s+|\s+then\s+|\s+before\s+", text, flags=re.IGNORECASE) pieces = [finish_sentence(piece.strip(" ,;")) for piece in pieces if word_count(piece) >= 4] return pieces if len(pieces) > 1 else [finish_sentence(text)] def semantic_split_utterance(text: str, domain: str) -> tuple[list[str], bool]: text = clean_text(text, max_chars=700) if not text: return [], False if domain == "task_oriented_assistant": chunks = semantic_split_task(text) elif domain == "emotional_support": chunks = semantic_split_emotional(text) elif domain == "how_to_guidance": chunks = semantic_split_how_to(text) else: chunks = semantic_split_daily(text) merged, changed = merge_fragments(chunks) return merged or [finish_sentence(text)], changed def detect_emotion(text: str) -> str: lower = text.lower() rules = [ ("proud", ["proud", "accomplished", "achievement", "graduated", "promotion"]), ("happy", ["happy", "excited", "glad", "thrilled", "relieved", "wonderful"]), ("stressed", ["stressed", "stress", "overwhelmed", "burned out", "too much", "busy"]), ("anxious", ["anxious", "nervous", "panic", "afraid", "scared", "scary", "freaked", "embarrassing", "embarrassed"]), ("worried", ["worried", "worry", "concerned"]), ("sad", ["sad", "upset", "cry", "heartbroken", "grief"]), ("disappointed", ["disappointed", "let down", "failed", "badly", "poorly"]), ("frustrated", ["frustrated", "furious", "angry", "mad", "annoyed"]), ("lonely", ["lonely", "alone", "miss her", "miss him", "miss them"]), ("confused", ["confused", "unsure", "not sure", "don't know", "dont know"]), ] for label, words in rules: if any(word in lower for word in words): return label return "neutral" def clean_cause_phrase(phrase: str) -> str: phrase = clean_text(phrase, max_chars=180).strip(" .") phrase = re.sub(r"^(i am|i'm|i feel|i felt|i get|i was|because|when|after)\s+", "", phrase, flags=re.IGNORECASE) phrase = re.sub(r"\b(stressed|anxious|worried|sad|happy|excited|disappointed|frustrated|furious|angry|lonely|confused|proud|scared|scary|embarrassed|embarrassing)\b", "", phrase, flags=re.IGNORECASE) phrase = re.sub(r"\bi\s+(?:was|am|feel|felt)\s*$", "", phrase, flags=re.IGNORECASE) phrase = re.sub(r"\s+", " ", phrase).strip(" ,.") words = phrase.split() if len(words) > 12: phrase = " ".join(words[:12]) return phrase def extract_emotional_cause(text: str) -> str: lower = text.lower() if re.search(r"\b(that must have been|i bet you|you'll be fine|did they|what game|what language|would'?ve freaked|would have freaked)\b", lower): return "" won_match = re.search(r"\bwhen\s+(.+?)\s+i\s+(?:was|felt)\s+(?:happy|excited|proud|glad|thrilled)\b", text, flags=re.IGNORECASE) if won_match: phrase = clean_cause_phrase(won_match.group(1)) if word_count(phrase) >= 3: return phrase patterns = [ r"\bbecause\s+(.+?)(?:[.!?]|$)", r"\bafter\s+(.+?)(?:[.!?]|$)", r"\bwhen\s+(.+?)(?:[.!?]|$)", r"\babout\s+(.+?)(?:[.!?]|$)", ] for pattern in patterns: match = re.search(pattern, text, flags=re.IGNORECASE) if match: phrase = clean_cause_phrase(match.group(1)) if word_count(phrase) >= 3: return phrase if re.search(r"\bstudied\b.*\b(exam|test)\b", lower): return "studied hard but the exam went poorly" if re.search(r"\bcar\b.{0,40}\b(died|broke down|stopped)\b", lower): return "car broke down at night" if re.search(r"\btripped\b", lower): return "tripped in front of other people" if re.search(r"\bforeign language class\b", lower): return "worried about a required foreign language class" if re.search(r"\bspeak it in front of others\b", lower): return "worried about speaking in front of others" if re.search(r"\btime\b.*\b(flying|goes by|faster)\b", lower): return "time seems to be passing quickly" if re.search(r"\bvacation request\b", lower): return "vacation request may be denied" if re.search(r"\b(passed away|died)\b", lower) and not re.search(r"\b(car|phone|battery|engine|lights?)\b", lower): return "someone important passed away" if re.search(r"\bfriend|relationship|family|brother|sister|parent|grandmother|grandpa\b", lower): return clean_cause_phrase(text) or "a relationship or family situation" phrase = clean_cause_phrase(text) if word_count(phrase) >= 3 and re.search(r"\b(i|my|we|our)\b", lower) and detect_emotion(text) != "neutral": return phrase return "" def detect_user_need(text: str, emotion: str, cause: str) -> str: lower = text.lower() if re.search(r"\b(what should|how do|how can|advice|help me|catch up|plan)\b", lower): return "planning_help" if "plan" in lower or "catch up" in lower else "practical_next_step" if "?" in text: return "clarification" if emotion in {"happy", "proud"}: return "celebration" if emotion in {"anxious", "worried", "confused"}: return "reassurance" if emotion in {"sad", "disappointed", "frustrated", "lonely", "stressed"}: return "validation" return "encouragement" if cause else "validation" def classify_chunk(chunk: str, previous_chunks: list[str], domain: str, state: dict[str, Any]) -> tuple[str, str]: lower = chunk.lower().strip() base_skip = skip_reason_for_text(chunk) if re.fullmatch(r"(okay|ok)[.!]?", lower): return "skip", base_skip or "backchannel_only" if re.fullmatch(r"(yes|yeah|yep|sure|sounds good)[.!]?", lower): if state.get("proposal_pending") or state.get("booking_intent") or "book" in " ".join(previous_chunks).lower(): return "reason", "booking_confirmation" if domain == "task_oriented_assistant" else "decision_point" return "skip", base_skip or "acknowledgement_only" if re.fullmatch(r"(no|nope|nah)[.!]?", lower): if state.get("proposal_pending") or state.get("booking_intent") or re.search(r"\b(anything else|more|book|confirm)\b", " ".join(previous_chunks).lower()): return "reason", "decision_point" return "skip", "acknowledgement_only" if base_skip: return "skip", base_skip terms = salient_terms(chunk, 5) seen = set(state.get("seen_terms", [])) if terms and set(terms).issubset(seen) and word_count(chunk) <= 26: return "skip", "repeated_information" if domain == "task_oriented_assistant": details = extract_task_details(chunk) if details.get("goal") or details.get("domain") or details.get("requested_info"): return "reason", details.get("goal", ["new_constraint"])[0] return "reason", "new_constraint" if domain == "emotional_support": emotion = detect_emotion(chunk) if emotion != "neutral": return "reason", "new_emotion" if extract_emotional_cause(chunk): return "reason", "new_cause" return "reason", "new_request" if "?" in chunk else "task_progress_update" if domain == "how_to_guidance": return "reason", "safety_or_order_constraint" if re.search(r"\b(turn off|unplug|avoid|careful|before|do not|don't)\b", lower) else "task_progress_update" return "reason", "daily_state_update" def state_add(state: dict[str, Any], key: str, values: list[str]) -> list[str]: state.setdefault(key, []) added: list[str] = [] for value in values: if value and value not in state[key]: state[key].append(value) added.append(value) return added def update_seen_terms(state: dict[str, Any], chunk: str) -> None: seen = state.setdefault("seen_terms", []) for term in salient_terms(chunk, 5): if term not in seen: seen.append(term) def task_update(chunk: str, state: dict[str, Any]) -> str: details = extract_task_details(chunk) if is_closing_or_thanks(chunk): state["closing_detected"] = True return "goal=closing" pieces: list[str] = [] for key in ["domain", "goal", "area", "food", "price", "time", "day", "party_size", "stay_length", "hotel_type", "stars", "amenities", "destination", "departure", "requested_info", "type"]: added = state_add(state, key, details.get(key, [])) if not added: continue label = "cuisine" if key == "food" else key if key == "goal" and "booking" in added: state["booking_intent"] = True if key == "requested_info": pieces.append(f"requested_info+={compact_join(added)}") elif key == "domain": pieces.append(f"domain={added[-1]}") elif key == "goal": pieces.append(f"goal={added[-1]}") else: pieces.append(f"{label}+={compact_join(added)}") if re.search(r"\b(yes|perfect|sounds good|that works|that will be fine)\b", chunk.lower()): if state.get("booking_intent"): pieces.append("goal=confirm_booking") else: pieces.append("acceptance=selected_option") if "not picky" in chunk.lower() or "isn't important" in chunk.lower(): pieces.append("preference=flexible") if not pieces: if "?" in chunk: pieces.append("goal=request_info") elif re.search(r"\b(no|not|instead|second thought)\b", chunk.lower()): pieces.append("goal=modify_constraint") else: pieces.append("intent=context_update") return "; ".join(pieces) def emotional_update(chunk: str, state: dict[str, Any]) -> str: emotion = detect_emotion(chunk) cause = extract_emotional_cause(chunk) need = detect_user_need(chunk, emotion, cause) pieces: list[str] = [] if emotion != "neutral": state["emotion"] = emotion pieces.append(f"emotion={emotion}") if cause and (not state.get("cause") or emotion != "neutral" or cause.startswith("worried about speaking")): state["cause"] = cause if emotion in {"happy", "proud"}: pieces.append(f"event={cause}") else: pieces.append(f"cause={cause}") stable_needs = {"reassurance", "celebration", "planning_help", "practical_next_step"} if ( need and need != state.get("user_need") and (emotion != "neutral" or cause or not state.get("user_need")) and not (emotion == "neutral" and state.get("user_need") in stable_needs and need in {"encouragement", "validation"}) ): state["user_need"] = need pieces.append(f"need={need}") if not pieces: return "support_signal=received" return "; ".join(pieces) def daily_label_and_value(chunk: str, state: dict[str, Any]) -> str: lower = chunk.lower() if re.search(r"\b(drive safely|safe drive|icy roads?|ice on the roads?|be careful)\b", lower): state["safety_reminder"] = True return "safety_reminder=icy_roads" if "ice" in lower or "icy" in lower else "safety_reminder=true" if re.search(r"\b(have to|must|had better|need to)\s+(go|leave|head off|be going)\b|\bi'?m afraid i have to go\b", lower): state["closing"] = True return "leaving_reason=needs_to_go" dinner_plan = re.search(r"\b(?:i'?m|i am|we'?re|we are)\s+(?:meeting|going to meet)\s+(.+?)\s+for\s+dinner\b", lower) if dinner_plan: person = clean_text(dinner_plan.group(1), max_chars=50).replace("my ", "") state["plan_update"] = True return f"plan_update=dinner_with_{normalize(person).replace(' ', '_') or 'someone'}" if re.search(r"\b(would you like(?:\s+to|\s+a|\s+some)?|do you want to|want to come|invite you|join me|come with me)\b", lower): state["proposal_pending"] = True state["invitation"] = True return "invitation=true" if re.search(r"\b(can you|could you|may i|would you)\b", lower) or "?" in chunk: state["question"] = True return "question=true" if re.search(r"\b(i'll keep it in mind|keep that in mind|thanks for the advice|advice)\b", lower): state["advice_received"] = True return "advice_received=true" if re.search(r"\b(can't|cannot|busy|appointment|schedule conflict|have to work|at work|in class)\b", lower): state["schedule_conflict"] = True return "schedule_conflict=true" if re.search(r"\b(yes|sure|sounds good|why not|ok|okay)\b", lower) and state.get("proposal_pending"): state["acceptance"] = True return "acceptance=true" if re.search(r"\b(no|can't|cannot|not possible)\b", lower) and state.get("proposal_pending"): state["refusal"] = True return "refusal=true" if re.search(r"\b(prefer|like|would rather|favorite)\b", lower): state["preference"] = True return "preference=true" if is_closing_or_thanks(chunk): state["closing"] = True return "closing=true" terms = salient_terms(chunk, 3) state_add(state, "casual_terms", terms[:2]) return f"casual_comment={compact_join(terms[:2], 'context')}" def action_label(chunk: str) -> str: text = re.sub(r"^Task:\s*", "", clean_text(chunk, max_chars=180), flags=re.IGNORECASE) text = re.sub(r"[•*]+", " ", text) words = text.strip(" .").split() if not words: return "continue" return "_".join(re.sub(r"[^a-z0-9]+", "", word.lower()) for word in words[:4]).strip("_") or "continue" def action_text(chunk: str, max_words: int = 10) -> str: text = re.sub(r"^Task:\s*", "", clean_text(chunk, max_chars=260), flags=re.IGNORECASE) text = re.sub(r"[•*]+", " ", text) text = re.sub(r"\([^)]{0,80}\)", " ", text) text = re.sub(r"\s+", " ", text).strip(" .;:-") return " ".join(text.split()[:max_words]) or "continue" def how_to_update(chunk: str, state: dict[str, Any], idx: int) -> str: lower = chunk.lower() if lower.startswith("task:") or (idx == 1 and not state.get("task")): state["task"] = action_label(chunk) state["task_text"] = action_text(chunk, 8) return f"task={state['task']}" label = action_label(chunk) state_add(state, "steps", [label]) state_add(state, "step_texts", [action_text(chunk)]) if re.search(r"\b(turn off|unplug|avoid|careful|before|do not|don't|must)\b", lower): state_add(state, "safety", [label]) return f"step={label}; safety=true" return f"step={label}" def build_reasoning(domain: str, chunks: list[str]) -> tuple[str, str, list[str], list[int], dict[str, str], dict[str, Any]]: state: dict[str, Any] = {} parts: list[str] = [] labels: list[str] = [] skip_chunks: list[int] = [] skip_reasons: dict[str, str] = {} previous: list[str] = [] for idx, chunk in enumerate(chunks, start=1): label, reason = classify_chunk(chunk, previous, domain, state) if label == "skip": labels.append("skip") skip_chunks.append(idx) skip_reasons[str(idx)] = reason if reason in {"closing_only", "thanks_only"}: state["closing_detected" if domain == "task_oriented_assistant" else "closing"] = True parts.append(f"C{idx} [SKIP: {reason}].") else: labels.append("reason") if domain == "task_oriented_assistant": update = task_update(chunk, state) elif domain == "emotional_support": update = emotional_update(chunk, state) elif domain == "how_to_guidance": update = how_to_update(chunk, state, idx) else: update = daily_label_and_value(chunk, state) parts.append(f"C{idx} {update}.") update_seen_terms(state, chunk) previous.append(chunk) streaming = " ".join(parts) deep = build_deep_reasoning(domain, state, chunks) return streaming, deep, labels, skip_chunks, skip_reasons, state def build_deep_reasoning(domain: str, state: dict[str, Any], chunks: list[str]) -> str: if domain == "task_oriented_assistant": bits: list[str] = [] if state.get("domain"): bits.append(f"domain={compact_join(state['domain'])}") if state.get("goal"): bits.append(f"goal={compact_join(state['goal'])}") for key in ["area", "food", "price", "party_size", "stay_length", "stars", "amenities", "destination", "departure", "requested_info"]: if state.get(key): bits.append(f"{key}={compact_join(state[key])}") when = state.get("day", []) + state.get("time", []) if when: bits.append(f"when={compact_join(when)}") if state.get("closing_detected"): bits.append("closing_detected") return "Need " + "; ".join(bits) + "." if bits else "Need more concrete task details before acting." if domain == "emotional_support": emotion = state.get("emotion", "neutral") cause = state.get("cause", "the situation") need = state.get("user_need", "validation") if emotion == "neutral": return f"User is processing {cause} and needs {need}." if emotion in {"happy", "proud"}: return f"User feels {emotion} because {cause} and needs {need}." return f"User feels {emotion} after {cause} and needs {need}." if domain == "how_to_guidance": task = state.get("task_text") or (state.get("task") or action_label(chunks[0] if chunks else "task")).replace("_", " ") steps = compact_join(state.get("step_texts", [])[:5], "ordered steps") safety = "; keep safety/order constraints" if state.get("safety") else "" return f"Procedure for {task}: {steps}{safety}." if state.get("safety_reminder"): return "Conversation is closing with a safety reminder; answer politely and acknowledge caution." if state.get("closing"): return "Conversation is closing; answer politely without adding a new task." daily_bits: list[str] = [] if state.get("invitation"): daily_bits.append("invitation") if state.get("question"): daily_bits.append("question") if state.get("plan_update"): daily_bits.append("plan update") if state.get("schedule_conflict"): daily_bits.append("schedule conflict") if state.get("preference"): daily_bits.append("preference") if state.get("advice_received"): daily_bits.append("advice received") topic = compact_join(state.get("casual_terms", [])[:4], "current topic") if daily_bits: return f"Dialogue state: {compact_join(daily_bits)} around {topic}; respond briefly." return f"Dialogue state: casual exchange about {topic}; respond briefly." def missing_task_slots(state: dict[str, Any]) -> list[str]: domains = set(state.get("domain", [])) missing: list[str] = [] if "restaurant" in domains: for key, label in [("area", "area"), ("food", "cuisine"), ("price", "price range")]: if not state.get(key): missing.append(label) if "hotel" in domains: for key, label in [("area", "area"), ("price", "price range"), ("day", "date"), ("party_size", "guests")]: if not state.get(key): missing.append(label) if domains & {"taxi", "train"}: for key, label in [("destination", "destination"), ("departure", "departure"), ("day", "date"), ("time", "time")]: if not state.get(key): missing.append(label) return missing[:2] def build_task_answer(state: dict[str, Any]) -> str: if state.get("closing_detected"): return "You're welcome. Glad I could help; have a great day." if state.get("requested_info"): return f"I can help with that and include the {compact_join(state['requested_info']).replace('_', ' ')} once I find the matching option." missing = missing_task_slots(state) if missing: return f"What {compact_join(missing)} should I use for the search?" pieces = [] if state.get("domain"): pieces.append(compact_join(state["domain"])) for key in ["area", "food", "price", "party_size"]: if state.get(key): pieces.append(compact_join(state[key])) if state.get("day") or state.get("time"): pieces.append(compact_join(state.get("day", []) + state.get("time", []))) return f"Got it. I will use {compact_join(pieces, 'those details')} and move the task forward." def build_emotional_answer(state: dict[str, Any]) -> str: emotion = state.get("emotion", "neutral") cause = state.get("cause", "what happened") need = state.get("user_need", "validation") if emotion == "neutral": return f"That sounds like a lot to process, especially with {cause}. Start with one small next step and give yourself room to sort it out." if emotion in {"happy", "proud"}: return f"That is worth celebrating, especially because {cause}. Take a moment to enjoy it and share the good news with someone who will be happy for you." if need in {"planning_help", "practical_next_step"}: return f"That is frustrating, especially after {cause}. Start with one concrete next step, then focus your energy on the part you can control today." if need == "reassurance": return f"It makes sense to feel {emotion} after {cause}. Slow down, check what is actually known, and take one small step before deciding what comes next." return f"It makes sense to feel {emotion} after {cause}. Give yourself a moment, then choose one manageable action instead of trying to solve everything at once." def build_how_to_answer(state: dict[str, Any], chunks: list[str]) -> str: task = state.get("task_text") or (state.get("task") or action_label(chunks[0] if chunks else "task")).replace("_", " ") steps = state.get("step_texts", [])[:4] or [action_text(chunk) for chunk in chunks[:4]] caution = " Keep the order and pause if a step seems unsafe." if state.get("safety") else "" return f"For {task}, follow the steps in order: {compact_join(steps)}.{caution}".strip() def build_daily_answer(state: dict[str, Any], chunks: list[str]) -> str: if state.get("safety_reminder"): return "Thanks, I'll be careful. See you next time." if state.get("closing"): return "Sounds good. Take care, and see you next time." joined = " ".join(chunks).lower() if state.get("invitation"): return "That sounds nice. I can join; what time should I be there?" if state.get("question"): topic = compact_join(salient_terms(" ".join(chunks), 4), "the situation") return f"Good question. The main topic is {topic}, so I would answer that directly first." if "dinner" in joined and "meeting" in joined: return "Thanks, I should head out for dinner now. See you next time." topic = compact_join(salient_terms(" ".join(chunks), 4), "the situation") return f"Got it. The main point is {topic}, so I will keep the reply brief and clear." def build_answer(domain: str, state: dict[str, Any], chunks: list[str]) -> str: if domain == "task_oriented_assistant": answer = build_task_answer(state) elif domain == "emotional_support": answer = build_emotional_answer(state) elif domain == "how_to_guidance": answer = build_how_to_answer(state, chunks) else: answer = build_daily_answer(state, chunks) return " ".join(re.split(r"(?<=[.!?])\s+", finish_sentence(answer))[:3]).strip() def copied_ratio(answer: str, source_answer: str | None) -> float: source = normalize(source_answer or "") generated = normalize(answer) if not source or not generated: return 0.0 if source in generated or generated in source: return 1.0 return difflib.SequenceMatcher(None, source, generated).ratio() def has_forbidden_phrase(*texts: str) -> bool: joined = "\n".join(texts).lower() return any(phrase in joined for phrase in FORBIDDEN_GENERIC_PHRASES) def is_safe_example(chunks: list[str], answer: str) -> bool: joined = " ".join(chunks + [answer]).lower() if any(term in joined for term in BLOCKLIST): return False if "[email removed]" in joined or "[phone removed]" in joined: return False return sum(word_count(chunk) for chunk in chunks) >= 8 and word_count(answer) >= 3 def is_undesired_how_to(chunks: list[str]) -> bool: joined = " ".join(chunks).lower() off_topic = [ "windows movie maker", "movie maker", "inshot", "pinterest", "ipod", "jailbreak", "slackline", "bonfire", "lighter fluid", "synthetic coon", "manga", "runescape", "minecraft", "photoshop", "illustrator", "html", "css", "javascript", "server", "login", "paypal", "twitter", "instagram", "tiktok", ] return any(term in joined for term in off_topic) def compute_quality_flags( domain: str, chunks: list[str], labels: list[str], state: dict[str, Any], source_answer: str | None, streaming_reasoning: str, deep_reasoning: str, answer: str, merged_fragments: bool, ) -> list[str]: flags: list[str] = [] if word_count(streaming_reasoning) > 160: flags.append("long_streaming_reasoning") if word_count(deep_reasoning) > 60: flags.append("long_deep_reasoning") if any(skip_reason_for_text(chunk) for chunk in chunks) and "skip" not in labels: flags.append("no_skip_labels") if labels and labels.count("skip") / len(labels) > 0.70: flags.append("too_many_skips") avg_chunk_words = statistics.mean(word_count(chunk) for chunk in chunks) if chunks else 0 if avg_chunk_words < 4 or len(chunks) > 12: flags.append("excessive_chunking") if any(is_fragment_chunk(chunk) for chunk in chunks): flags.append("fragment_chunk") if merged_fragments: flags.append("merged_fragments") if has_forbidden_phrase(streaming_reasoning, deep_reasoning, answer): flags.append("generic_reasoning") if copied_ratio(answer, source_answer) >= 0.72: flags.append("copied_source_response") if word_count(answer) < 5: flags.append("short_answer") if len(chunks) < 2 or sum(word_count(chunk) for chunk in chunks) < 12: flags.append("weak_context") if is_closing_or_thanks(" ".join(chunks)) and "today" in state.get("day", []): flags.append("possible_slot_error") if (state.get("closing_detected") or state.get("closing")) and re.search(r"\?|please confirm|what .*should|share .*", answer.lower()): flags.append("closing_mishandled") if domain == "task_oriented_assistant" and not any(state.get(key) for key in ["domain", "goal", "requested_info", "destination", "departure"]): flags.append("low_specificity") if domain == "emotional_support" and re.search(r"\b[a-z]+,\s+[a-z]+,\s+[a-z]+", deep_reasoning.lower()): flags.append("generic_reasoning") return list(dict.fromkeys(flags)) def compute_state_tracking_confidence(domain: str, state: dict[str, Any], flags: list[str]) -> float: score = 0.85 if domain == "task_oriented_assistant": if state.get("domain"): score += 0.06 if state.get("goal"): score += 0.05 if state.get("requested_info"): score += 0.03 elif domain == "emotional_support": if state.get("emotion") and state.get("emotion") != "neutral": score += 0.06 if state.get("cause"): score += 0.05 if state.get("user_need"): score += 0.03 elif domain == "daily_dialogue": if state.get("closing") or state.get("safety_reminder") or state.get("proposal_pending"): score += 0.04 else: if state.get("steps"): score += 0.06 score -= 0.05 * len([flag for flag in flags if flag in SEVERE_FLAGS]) return round(max(0.0, min(1.0, score)), 3) def compute_quality_score(flags: list[str], streaming_reasoning: str, deep_reasoning: str) -> float: score = 1.0 for flag in set(flags): score -= FLAG_PENALTIES.get(flag, 0.0) if word_count(streaming_reasoning) > 120: score -= 0.05 if word_count(deep_reasoning) > 45: score -= 0.05 return round(max(0.0, min(1.0, score)), 3) def is_high_quality_row(row: dict[str, Any]) -> bool: flags = set(row.get("quality_flags", [])) return ( row.get("quality_score", 0) >= 0.85 and not (flags & SEVERE_FLAGS) and word_count(row.get("streaming_reasoning", "")) <= 120 and word_count(row.get("deep_reasoning", "")) <= 45 and not has_forbidden_phrase(row.get("streaming_reasoning", ""), row.get("deep_reasoning", ""), row.get("answer", "")) ) def make_response(streaming_reasoning: str, deep_reasoning: str, answer: str) -> str: return f"Streaming reasoning: {streaming_reasoning}\n\nDeep reasoning: {deep_reasoning}\n\nAnswer: {answer}" def make_messages(instruction: str, context: str, response: str) -> list[dict[str, str]]: return [ {"role": "user", "content": f"Instruction: {instruction}\n\nContext:\n{context}"}, {"role": "assistant", "content": response}, ] def make_text(messages: list[dict[str, str]]) -> str: return f"<|user|>\n{messages[0]['content']}\n<|assistant|>\n{messages[1]['content']}" def transform_row(row: dict[str, Any]) -> dict[str, Any] | None: domain = str(row.get("domain") or "daily_dialogue") source_dataset = str(row.get("source_dataset") or "local_source") original_chunks = parse_context_chunks(row) if len(original_chunks) < 2: return None chunks: list[str] = [] merged_fragments = False for chunk in original_chunks: split_chunks, changed = semantic_split_utterance(chunk, domain) chunks.extend(split_chunks) merged_fragments = merged_fragments or changed chunks, changed = merge_fragments(chunks) merged_fragments = merged_fragments or changed chunks = [clean_text(chunk, max_chars=340) for chunk in chunks if clean_text(chunk)] if len(chunks) < 2: return None if len(chunks) > 13: chunks = chunks[:13] if domain == "how_to_guidance" and is_undesired_how_to(chunks): return None streaming, deep, labels, skip_chunks, skip_reasons, state = build_reasoning(domain, chunks) answer = build_answer(domain, state, chunks) if not is_safe_example(chunks, answer): return None flags = compute_quality_flags(domain, chunks, labels, state, row.get("answer"), streaming, deep, answer, merged_fragments) quality_score = compute_quality_score(flags, streaming, deep) confidence = compute_state_tracking_confidence(domain, state, flags) context = build_context(chunks) response = make_response(streaming, deep, answer) messages = make_messages(INSTRUCTION, context, response) example = { "id": "", "domain": domain, "source_dataset": source_dataset, "instruction": INSTRUCTION, "context": context, "context_chunks": chunks, "streaming_reasoning": streaming, "deep_reasoning": deep, "answer": answer, "response": response, "messages": messages, "text": make_text(messages), "num_chunks": len(chunks), "language": "en", "split": "", "generation_method": GENERATION_METHOD, "quality_flags": flags, "version": DATASET_VERSION, "reasoning_policy": REASONING_POLICY, "chunking_method": CHUNKING_METHOD, "chunk_labels": labels, "skip_chunks": skip_chunks, "skip_reasons": skip_reasons, "reasoning_token_budget": REASONING_TOKEN_BUDGET, "original_num_chunks": len(original_chunks), "chunk_split_count": max(0, len(chunks) - len(original_chunks)), "quality_score": quality_score, "is_high_quality": False, "refinement_method": REFINEMENT_METHOD, "llm_augmented": False, "llm_augmentation_model": None, "rejected_reason": None, "state_tracking_confidence": confidence, } example["is_high_quality"] = is_high_quality_row(example) return example def select_source_rows(rows: list[dict[str, Any]], max_examples: int, seed: int) -> list[dict[str, Any]]: groups: dict[str, list[dict[str, Any]]] = defaultdict(list) for row in rows: groups[str(row.get("domain") or "daily_dialogue")].append(row) rng = random.Random(seed) for group in groups.values(): rng.shuffle(group) selected: list[dict[str, Any]] = [] domains = sorted(groups) index = 0 while len(selected) < max_examples: added = False for domain in domains: if index < len(groups[domain]): selected.append(groups[domain][index]) added = True if len(selected) >= max_examples: break if not added: break index += 1 return selected def deduplicate(rows: list[dict[str, Any]]) -> list[dict[str, Any]]: seen_texts: set[str] = set() unique: list[dict[str, Any]] = [] for row in rows: key = normalize(row["text"]) if not key or key in seen_texts: continue seen_texts.add(key) unique.append(row) return unique def assign_ids_and_splits(rows: list[dict[str, Any]], seed: int) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: rng = random.Random(seed) rng.shuffle(rows) split_at = max(1, int(len(rows) * 0.8)) train_rows = rows[:split_at] eval_rows = rows[split_at:] if not eval_rows and len(train_rows) > 1: eval_rows = [train_rows.pop()] domain_counts: Counter[str] = Counter() for split_name, split_rows in [("train", train_rows), ("eval", eval_rows)]: for row in split_rows: domain_counts[row["domain"]] += 1 slug = re.sub(r"[^a-z0-9]+", "_", row["domain"].lower()).strip("_") row["id"] = f"life_{slug}_{domain_counts[row['domain']]:06d}" row["split"] = split_name row["messages"] = make_messages(row["instruction"], row["context"], row["response"]) row["text"] = make_text(row["messages"]) return train_rows, eval_rows def select_review_samples(rows: list[dict[str, Any]], sample_size: int = 120) -> list[dict[str, Any]]: by_domain: dict[str, list[dict[str, Any]]] = defaultdict(list) for row in rows: by_domain[row["domain"]].append(row) selected: list[dict[str, Any]] = [] seen: set[str] = set() per_domain = 30 for domain in ["task_oriented_assistant", "emotional_support", "daily_dialogue", "how_to_guidance"]: candidates = by_domain.get(domain, []) buckets = [ [row for row in candidates if row.get("is_high_quality")], [row for row in candidates if row.get("skip_chunks")], [row for row in candidates if row.get("quality_flags")], candidates, ] picked = 0 for bucket in buckets: for row in bucket: if row["id"] in seen: continue selected.append(row) seen.add(row["id"]) picked += 1 if picked >= per_domain: break if picked >= per_domain: break for row in rows: if len(selected) >= sample_size: break if row["id"] not in seen: selected.append(row) seen.add(row["id"]) sample_fields = [ "id", "domain", "context_chunks", "chunk_labels", "skip_reasons", "streaming_reasoning", "deep_reasoning", "answer", "quality_flags", "quality_score", "is_high_quality", "refinement_method", "split", ] return [{field: row.get(field) for field in sample_fields} for row in selected[:sample_size]] def write_parquet(path: Path, rows: list[dict[str, Any]]) -> None: path.parent.mkdir(parents=True, exist_ok=True) pd.DataFrame(rows, columns=REQUIRED_FIELDS).to_parquet(path, index=False) def source_summary(rows: list[dict[str, Any]]) -> list[dict[str, Any]]: counts = Counter(row["source_dataset"] for row in rows) domains: dict[str, set[str]] = defaultdict(set) for row in rows: domains[row["source_dataset"]].add(row["domain"]) return [{"name": source, "domain": ",".join(sorted(domains[source])), "rows": count} for source, count in sorted(counts.items())] def quality_counts(rows: list[dict[str, Any]]) -> dict[str, int]: return dict(sorted(Counter(flag for row in rows for flag in row.get("quality_flags", [])).items())) def avg(values: list[float]) -> float: return statistics.mean(values) if values else 0.0 def build_dataset_info(train_rows: list[dict[str, Any]], eval_rows: list[dict[str, Any]], hq_train: list[dict[str, Any]], hq_eval: list[dict[str, Any]], skipped_sources: list[dict[str, str]]) -> dict[str, Any]: rows = train_rows + eval_rows total_chunks = sum(row["num_chunks"] for row in rows) skip_chunks = sum(len(row["skip_chunks"]) for row in rows) return { "dataset_name": DATASET_NAME, "repo_id": REPO_ID, "version": DATASET_VERSION, "created_by": "skyzhou06 with Codex", "generation_method": GENERATION_METHOD, "reasoning_policy": REASONING_POLICY, "chunking_method": CHUNKING_METHOD, "refinement_method": REFINEMENT_METHOD, "schema": {field: "required" for field in REQUIRED_FIELDS}, "source_datasets_used": source_summary(rows), "skipped_source_datasets": skipped_sources, "total_rows": len(rows), "train_rows": len(train_rows), "eval_rows": len(eval_rows), "high_quality_train_rows": len(hq_train), "high_quality_eval_rows": len(hq_eval), "domains": dict(sorted(Counter(row["domain"] for row in rows).items())), "average_num_chunks": avg([row["num_chunks"] for row in rows]), "average_chunk_length": avg([word_count(chunk) for row in rows for chunk in row["context_chunks"]]), "average_original_num_chunks": avg([row["original_num_chunks"] for row in rows]), "average_chunk_split_count": avg([row["chunk_split_count"] for row in rows]), "average_streaming_reasoning_words": avg([word_count(row["streaming_reasoning"]) for row in rows]), "average_deep_reasoning_words": avg([word_count(row["deep_reasoning"]) for row in rows]), "average_quality_score": avg([row["quality_score"] for row in rows]), "high_quality_percentage": (len(hq_train) + len(hq_eval)) / len(rows) if rows else 0, "skip_chunk_ratio": skip_chunks / total_chunks if total_chunks else 0, "examples_with_at_least_one_skip": sum(1 for row in rows if row["skip_chunks"]), "quality_flags_distribution": quality_counts(rows), "llm_augmented_count": sum(1 for row in rows if row.get("llm_augmented")), "limitations": [ "v0.4 is primarily rule-based unless optional LLM augmentation is run.", "The high-quality subset is recommended for serious SFT experiments.", "Some source datasets are dialogue-style and may not perfectly match ideal assistant behavior.", "The dataset is not intended for expert medical, legal, financial, emergency, or safety-critical advice.", ], "samples_for_review": "samples_for_review.jsonl", } def dataset_card(info: dict[str, Any], example: dict[str, Any] | None) -> str: used = "\n".join(f"- `{item['name']}`: {item['rows']} rows, domain `{item['domain']}`" for item in info["source_datasets_used"]) or "- None" skipped = "\n".join(f"- `{item['name']}`: {item['reason']}" for item in info["skipped_source_datasets"]) or "- None" flags = "\n".join(f"- `{flag}`: {count}" for flag, count in info["quality_flags_distribution"].items()) or "- None" example_json = json.dumps(example or {}, ensure_ascii=False, indent=2) schema = "\n".join(f"- `{field}`" for field in REQUIRED_FIELDS) return f"""--- pretty_name: LifeStreamingCoT language: - en license: apache-2.0 version: "{DATASET_VERSION}" task_categories: - text-generation tags: - streaming-reasoning - selective-reasoning - quality-refined - supervised-fine-tuning - sft - dialogue - task-oriented-dialogue - life-assistant - streamingthinker size_categories: - 1K= 0.85) ``` Removing flagged data: ```python clean = ds.filter(lambda x: len(x["quality_flags"]) == 0) ``` ## Schema {schema} ## Source Datasets Used sources: {used} Skipped sources: {skipped} ## Splits - Train: {info['train_rows']} - Eval: {info['eval_rows']} - Total: {info['total_rows']} - High-quality train: {info['high_quality_train_rows']} - High-quality eval: {info['high_quality_eval_rows']} ## Statistics - Average chunks: {info['average_num_chunks']:.2f} - Average chunk length: {info['average_chunk_length']:.2f} - Average streaming reasoning words: {info['average_streaming_reasoning_words']:.2f} - Average deep reasoning words: {info['average_deep_reasoning_words']:.2f} - Average quality score: {info['average_quality_score']:.3f} - High-quality percentage: {info['high_quality_percentage']:.2%} - Skip chunk ratio: {info['skip_chunk_ratio']:.4f} - LLM augmented rows: {info['llm_augmented_count']} ## Quality Flags {flags} ## Example ```json {example_json} ``` ## Limitations - Still primarily rule-based unless optional LLM augmentation is run. - Not expert advice. - Some source datasets are dialogue-style and may not perfectly match assistant behavior. - The high-quality subset is recommended for serious SFT experiments. """ def print_stats(rows: list[dict[str, Any]], train_rows: list[dict[str, Any]], eval_rows: list[dict[str, Any]], hq_train: list[dict[str, Any]], hq_eval: list[dict[str, Any]], skipped: list[dict[str, str]], llm_status: str) -> None: total_chunks = sum(row["num_chunks"] for row in rows) skip_chunks = sum(len(row["skip_chunks"]) for row in rows) print("\nBuild stats") print(f"total examples: {len(rows)}") print(f"train examples: {len(train_rows)}") print(f"eval examples: {len(eval_rows)}") print(f"high-quality train examples: {len(hq_train)}") print(f"high-quality eval examples: {len(hq_eval)}") print(f"domains: {dict(sorted(Counter(row['domain'] for row in rows).items()))}") print(f"source datasets: {dict(Counter(row['source_dataset'] for row in rows))}") print(f"average chunks: {avg([row['num_chunks'] for row in rows]):.2f}") print(f"average chunk length: {avg([word_count(chunk) for row in rows for chunk in row['context_chunks']]):.2f}") print(f"average streaming reasoning words: {avg([word_count(row['streaming_reasoning']) for row in rows]):.2f}") print(f"average deep reasoning words: {avg([word_count(row['deep_reasoning']) for row in rows]):.2f}") print(f"average quality score: {avg([row['quality_score'] for row in rows]):.3f}") print(f"high-quality percentage: {(len(hq_train) + len(hq_eval)) / len(rows) if rows else 0:.2%}") print(f"skip chunk ratio: {skip_chunks / total_chunks if total_chunks else 0:.4f}") print(f"quality flags: {quality_counts(rows)}") print(f"llm augmentation: {llm_status}") print(f"skipped source datasets: {skipped}") def sync_scripts_to_dataset(output_dir: Path) -> None: script_dir = Path(__file__).resolve().parent target = output_dir / "scripts" target.mkdir(parents=True, exist_ok=True) for name in ["build_life_streaming_cot.py", "validate_dataset.py", "upload_to_hf.py", "augment_with_llm.py", "analyze_quality.py"]: src = script_dir / name if src.exists(): shutil.copy2(src, target / name) def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--output-dir", default="life_streaming_cot_dataset") parser.add_argument("--max-examples", type=int, default=10000) parser.add_argument("--smoke-test", action="store_true") parser.add_argument("--seed", type=int, default=42) parser.add_argument("--llm-augment", action="store_true", help="Reserved hook for optional LLM augmentation.") args = parser.parse_args() output_dir = Path(args.output_dir) data_dir = output_dir / "data" data_dir.mkdir(parents=True, exist_ok=True) max_examples = min(args.max_examples, 300 if args.smoke_test else args.max_examples) source_rows, skipped_sources = load_source_rows(output_dir) if not source_rows: raise RuntimeError("No source rows were available.") source_rows = select_source_rows(source_rows, max_examples=max_examples * 5, seed=args.seed) rows: list[dict[str, Any]] = [] for source_row in source_rows: example = transform_row(source_row) if example: rows.append(example) if len(rows) >= max_examples: break rows = deduplicate(rows) if len(rows) > max_examples: rows = rows[:max_examples] if len(rows) < min(5000, max_examples) and not args.smoke_test: raise RuntimeError(f"Only {len(rows)} examples were produced; expected at least {min(5000, max_examples)}.") if len(rows) < 10: raise RuntimeError("Fewer than 10 examples were produced.") llm_available = bool(os.getenv("OPENAI_API_KEY") or os.getenv("OPENAI_BASE_URL") or os.getenv("LOCAL_LLM_BASE_URL")) if args.llm_augment and llm_available: llm_status = "available but not run in build script; use scripts/augment_with_llm.py for explicit augmentation" elif args.llm_augment: llm_status = "skipped: no supported API key or local model endpoint found" else: llm_status = "skipped: optional LLM augmentation was not requested" train_rows, eval_rows = assign_ids_and_splits(rows, args.seed) all_rows = train_rows + eval_rows hq_train = [row for row in train_rows if row["is_high_quality"]] hq_eval = [row for row in eval_rows if row["is_high_quality"]] write_jsonl(data_dir / "train.jsonl", train_rows) write_jsonl(data_dir / "eval.jsonl", eval_rows) write_jsonl(data_dir / "train_high_quality.jsonl", hq_train) write_jsonl(data_dir / "eval_high_quality.jsonl", hq_eval) write_parquet(data_dir / "train.parquet", train_rows) write_parquet(data_dir / "eval.parquet", eval_rows) write_parquet(data_dir / "train_high_quality.parquet", hq_train) write_parquet(data_dir / "eval_high_quality.parquet", hq_eval) write_jsonl(output_dir / "samples_for_review.jsonl", select_review_samples(all_rows, sample_size=120)) info = build_dataset_info(train_rows, eval_rows, hq_train, hq_eval, skipped_sources) (output_dir / "dataset_info.json").write_text(json.dumps(info, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") (output_dir / "README.md").write_text(dataset_card(info, hq_train[0] if hq_train else train_rows[0]), encoding="utf-8") (output_dir / "requirements.txt").write_text(Path("requirements.txt").read_text(encoding="utf-8"), encoding="utf-8") sync_scripts_to_dataset(output_dir) print_stats(all_rows, train_rows, eval_rows, hq_train, hq_eval, skipped_sources, llm_status) if __name__ == "__main__": main()