#!/usr/bin/env python3 from __future__ import annotations import argparse import json import os import re import sys import urllib.request from pathlib import Path from types import SimpleNamespace from typing import Any DEFAULT_MODEL = "gpt-4.1-mini" FORBIDDEN_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=", ] 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 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 has_forbidden(text: str) -> bool: lower = text.lower() return any(phrase in lower for phrase in FORBIDDEN_PHRASES) def word_count(text: str) -> int: return len(re.findall(r"\b[\w'-]+\b", text)) def parse_json_object(text: str) -> dict[str, str]: match = re.search(r"\{.*\}", text, flags=re.DOTALL) if not match: raise ValueError("model did not return a JSON object") data = json.loads(match.group(0)) required = ["streaming_reasoning", "deep_reasoning", "answer"] if not all(isinstance(data.get(key), str) and data[key].strip() for key in required): raise ValueError("model JSON is missing required string fields") return {key: data[key].strip() for key in required} def augment_row(client: Any, row: dict[str, Any], model: str) -> dict[str, Any]: prompt = { "domain": row.get("domain"), "context_chunks": row.get("context_chunks"), "chunk_labels": row.get("chunk_labels"), "skip_reasons": row.get("skip_reasons"), "current_streaming_reasoning": row.get("streaming_reasoning"), "current_deep_reasoning": row.get("deep_reasoning"), "current_answer": row.get("answer"), } completion = client.chat.completions.create( model=model, temperature=0.2, messages=[ { "role": "system", "content": ( "Rewrite synthetic supervised rationale summaries for a streaming assistant dataset. " "Keep the source context fixed. Rewrite only streaming_reasoning, deep_reasoning, and answer. " "Use concise state updates, not private chain-of-thought. Do not invent facts. " "Return only a JSON object with those three keys." ), }, {"role": "user", "content": json.dumps(prompt, ensure_ascii=False)}, ], ) content = completion.choices[0].message.content or "" rewritten = parse_json_object(content) combined = "\n".join(rewritten.values()) if has_forbidden(combined): raise ValueError("rewrite contains forbidden phrase") if word_count(rewritten["streaming_reasoning"]) > 140 or word_count(rewritten["deep_reasoning"]) > 55: raise ValueError("rewrite is too long") updated = dict(row) updated.update(rewritten) updated["response"] = make_response(updated["streaming_reasoning"], updated["deep_reasoning"], updated["answer"]) updated["messages"] = make_messages(updated["instruction"], updated["context"], updated["response"]) updated["text"] = make_text(updated["messages"]) updated["llm_augmented"] = True updated["llm_augmentation_model"] = model updated["refinement_method"] = "llm_augmented_quality_refinement_v0.4" return updated class HttpChatCompletions: def __init__(self, api_key: str, base_url: str) -> None: self.api_key = api_key self.base_url = base_url.rstrip("/") def create(self, **payload: Any) -> Any: body = json.dumps(payload).encode("utf-8") request = urllib.request.Request( f"{self.base_url}/chat/completions", data=body, headers={ "Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json", }, method="POST", ) with urllib.request.urlopen(request, timeout=60) as response: # noqa: S310 - caller opts into API use data = json.loads(response.read().decode("utf-8")) content = data["choices"][0]["message"]["content"] return SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content=content))]) class HttpOpenAICompatClient: def __init__(self, api_key: str, base_url: str) -> None: self.chat = SimpleNamespace(completions=HttpChatCompletions(api_key, base_url)) def main() -> None: parser = argparse.ArgumentParser(description="Optionally augment a small v0.4 subset with an LLM.") parser.add_argument("--input", default="life_streaming_cot_dataset/data/train_high_quality.jsonl") parser.add_argument("--output", default="life_streaming_cot_dataset/data/train_high_quality_llm_augmented.jsonl") parser.add_argument("--limit", type=int, default=100) parser.add_argument("--model", default=os.getenv("OPENAI_MODEL", DEFAULT_MODEL)) args = parser.parse_args() if not os.getenv("OPENAI_API_KEY"): print("LLM augmentation skipped: OPENAI_API_KEY is not set.") return try: from openai import OpenAI client = OpenAI() except Exception as exc: # noqa: BLE001 base_url = os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1") print(f"openai package unavailable ({type(exc).__name__}); using HTTPS fallback client.") client = HttpOpenAICompatClient(os.environ["OPENAI_API_KEY"], base_url) rows = read_jsonl(Path(args.input)) if not rows: print(f"LLM augmentation skipped: no rows found in {args.input}.") return output_rows: list[dict[str, Any]] = [] failures = 0 for row in rows[: args.limit]: try: output_rows.append(augment_row(client, row, args.model)) except Exception: # noqa: BLE001 failures += 1 output_rows.append(row) write_jsonl(Path(args.output), output_rows) print(f"wrote {len(output_rows)} rows to {args.output}; failed rewrites: {failures}") if __name__ == "__main__": sys.exit(main())