File size: 7,342 Bytes
296b327
 
 
 
 
 
 
 
139f833
296b327
139f833
296b327
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139f833
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
296b327
 
 
 
 
 
 
 
 
 
 
 
 
 
139f833
 
296b327
139f833
 
 
296b327
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
#!/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())