File size: 10,349 Bytes
510314e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
"""AgentLongBench x Flash Next: parti comuni (percorsi, prompt e scorer UFFICIALI, conteggio token, client HTTP).

Il prompt e lo scorer sono il codice ufficiale (src/AgentLongBench, commit 57e13e8) importato così com'è:
  eval.common.question_logic.build_prompt / parse_response   (come eval/run.py)
  eval.evaluate.evaluate                                      (scorer)
Interprete: venv-proxy-v0.3.2/bin/python (stdlib + tokenizers + ctxproxy per il template di Flash Next).
"""
from __future__ import annotations

import http.client
import json
import os
import sys
import tempfile
import time
import urllib.parse
from pathlib import Path

BENCH = Path(__file__).resolve().parent.parent          # alb-bench-v2 (copia di lavoro su MVLINNA)
A = Path(os.environ.get("ALB", str(BENCH / "alb")))     # dati, scorer ufficiale e proxy 0.3.4 copiati da PC4070TI
DATA = A / "data/benchmark"
OFFICIAL = A / "src/AgentLongBench"
PACK_TOK = os.environ.get("PACK_TOK", str(BENCH / "tok"))   # copia di /mnt/gsq-ssd/strata-data/packs/iq3_xxs/tokenizer
PROXY_SRC = Path(os.environ.get("PROXY_SRC", str(A / "src/mnemonic-proxy-034")))   # proxy installato 0.3.4
MODEL_NAME = "qwen3.8-flash-next-iq3_xxs"

sys.path.insert(0, str(OFFICIAL))
from eval.common.mapping import infer_context_from_path  # noqa: E402  (ufficiale)
from eval.common.question_logic import build_prompt, parse_response  # noqa: E402  (ufficiale)
from eval import evaluate as official_evaluate  # noqa: E402  (ufficiale)


# ---------------------------------------------------------------------------------------------------------------
def load_sample(path: Path, qid: str) -> dict:
    with open(path) as f:
        for line in f:
            if f'"id": "{qid}"' in line[:200] or f'"id":"{qid}"' in line[:200]:
                r = json.loads(line)
                if r.get("id") == qid:
                    return r
    with open(path) as f:                       # ricerca lenta (id non in testa alla riga)
        for line in f:
            r = json.loads(line)
            if r.get("id") == qid:
                return r
    raise KeyError(qid)


def official_messages(sample: dict, path: Path) -> list[dict]:
    """Messaggi esattamente come eval/run.py::_process_sample: system ufficiale + storia (senza il system del
    campione) + domanda come ultimo messaggio user."""
    _, knowledge_label, _, history_label = infer_context_from_path(path)
    return build_prompt(sample["question_type"], sample, history_label, knowledge_label)


def official_parse(sample: dict, path: Path, raw: str):
    _, _, _, history_label = infer_context_from_path(path)
    return parse_response(sample["question_type"], history_label, raw)


def official_score(sample: dict, path: Path, raw: str) -> dict:
    """Punteggio del singolo campione con eval.evaluate.evaluate ufficiale (file di predizione di una riga, record
    costruito come in eval/run.py)."""
    pred, kind = official_parse(sample, path, raw)
    rec = {"id": sample.get("id"), "sample_id": sample.get("sample_id"), "question_type": sample["question_type"],
           "pred_answer": pred, "parse_kind": kind, "raw_response": raw}
    for k in ("round", "i_round", "j_round"):
        if k in sample:
            rec[k] = sample[k]
    with tempfile.NamedTemporaryFile("w", suffix=".jsonl", delete=False, dir=os.environ.get("TMPDIR")) as f:
        f.write(json.dumps(rec, ensure_ascii=False) + "\n")
        pp = f.name
    try:
        res = official_evaluate.evaluate(Path(path), Path(pp))
    finally:
        os.unlink(pp)
    return {"pred_answer": pred, "parse_kind": kind, "score": res.get("score"), "metric": res.get("metric"),
            "official": res}


# ---------------------------------------------------------------------------------------------------------------
class Counter:
    """Token esatti del prompt come li conta Strata: template (ctxproxy.render, verificato == prompt_tokens nel
    pilota bench-reddit) + tokenizer del pack."""

    def __init__(self):
        sys.path.insert(0, str(PROXY_SRC))
        from ctxproxy import render
        from ctxproxy.packtok import build
        self.render = render
        self.tk = build(PACK_TOK)

    def text(self, s: str) -> int:
        return len(self.tk.encode(s, add_special_tokens=False).ids)

    def prompt(self, messages, tools=None) -> int:
        return self.text(self.render.render([{k: v for k, v in m.items() if k != "extra"} for m in messages], tools))


# ---------------------------------------------------------------------------------------------------------------
class EngineHTTPError(Exception):
    def __init__(self, status, text):
        super().__init__("HTTP %d: %s" % (status, text[:2000]))
        self.status, self.text = status, text


def chat(base_url: str, messages: list, *, max_tokens: int, sampling: dict, tools=None, stream=True,
         extra_body=None, timeout=3600.0, kind="answer", sink=None, headers=None) -> dict:
    """Una richiesta OpenAI /v1/chat/completions (stdlib). -> {message, finish_reason, usage, timings, m}.
    m = metriche registrate (TTFT visibile al client, tempi, usage, timings di Strata)."""
    body = {"model": MODEL_NAME, "messages": messages, "stream": stream, "max_tokens": int(max_tokens)}
    if stream:
        body["stream_options"] = {"include_usage": True}
    if tools:
        body["tools"] = tools
    body.update(sampling or {})
    body.update(extra_body or {})
    u = urllib.parse.urlparse(base_url)
    t0 = time.time()
    conn = http.client.HTTPConnection(u.hostname, u.port or 80, timeout=timeout)
    t_first = None
    try:
        conn.request("POST", "/v1/chat/completions", json.dumps(body, ensure_ascii=False).encode(),
                     {"Content-Type": "application/json", **(headers or {})})
        r = conn.getresponse()
        if r.status >= 400:
            txt = r.read().decode("utf-8", "replace")
            m = {"kind": kind, "t_start": t0, "wall_s": time.time() - t0, "http_status": r.status, "error": txt[:2000],
                 "n_messages": len(messages)}
            if sink:
                sink(m)
            raise EngineHTTPError(r.status, txt)
        if not stream:
            d = json.loads(r.read())
            ch = d["choices"][0]
            msg, finish, usage, timings = ch["message"], ch.get("finish_reason"), d.get("usage"), d.get("timings")
        else:
            content, reasoning, calls, finish, usage, timings = [], [], {}, None, None, None
            while True:
                line = r.readline()
                if not line:
                    break
                line = line.strip()
                if not line.startswith(b"data:"):
                    continue
                data = line[5:].strip()
                if data == b"[DONE]":
                    break
                try:
                    c = json.loads(data)
                except ValueError:
                    continue
                if c.get("error"):
                    raise EngineHTTPError(599, "stream error: %s" % json.dumps(c["error"]))
                if c.get("usage"):
                    usage = c["usage"]
                if c.get("timings"):
                    timings = c["timings"]
                for ch in c.get("choices") or []:
                    d = ch.get("delta") or {}
                    if t_first is None and (d.get("content") or d.get("reasoning_content") or d.get("tool_calls")):
                        t_first = time.time()
                    content.append(d.get("content") or "")
                    reasoning.append(d.get("reasoning_content") or "")
                    for tc in d.get("tool_calls") or []:
                        cur = calls.setdefault(tc.get("index", len(calls)),
                                               {"id": None, "type": "function", "function": {"name": "", "arguments": ""}})
                        cur["id"] = tc.get("id") or cur["id"]
                        fn = tc.get("function") or {}
                        cur["function"]["name"] += fn.get("name") or ""
                        cur["function"]["arguments"] += fn.get("arguments") or ""
                    if ch.get("finish_reason"):
                        finish = ch["finish_reason"]
            msg = {"role": "assistant", "content": "".join(content) or None}
            if "".join(reasoning):
                msg["reasoning_content"] = "".join(reasoning)
            if calls:
                msg["tool_calls"] = [calls[i] for i in sorted(calls)]
    finally:
        conn.close()
    t1 = time.time()
    m = {"kind": kind, "t_start": t0, "wall_s": t1 - t0, "ttft_client_s": (t_first - t0) if t_first else None,
         "finish_reason": finish, "usage": usage, "timings": timings, "n_messages": len(messages),
         "content_chars": len(msg.get("content") or ""), "reasoning_chars": len(msg.get("reasoning_content") or ""),
         "n_tool_calls": len(msg.get("tool_calls") or []), "max_tokens": int(max_tokens)}
    if sink:
        sink(m)
    return {"message": msg, "finish_reason": finish, "usage": usage, "timings": timings, "m": m}


def answer_text(msg: dict) -> str:
    """Testo valutato: il content (come eval/run.py, che legge solo delta.content)."""
    return msg.get("content") or ""


def transcript_line(m: dict, idx: int | None = None) -> str:
    """v2 (BRIEF §3): un messaggio della storia come testo per il riassunto di B, SENZA perdere nulla di ciò che ALB
    chiede: numero del messaggio, ruolo, content, nome e argomenti di ogni tool_call (con il suo id), nome e id della
    chiamata per i risultati degli strumenti. (answer_text resta il solo content: è il testo che lo scorer valuta.)"""
    head = "[msg %d | %s" % (idx, m.get("role")) if idx is not None else "[%s" % m.get("role")
    if m.get("role") == "tool":
        head += " | %s" % (m.get("name") or "tool") + (" | %s" % m["tool_call_id"] if m.get("tool_call_id") else "")
    parts = [head + "]"]
    c = m.get("content")
    if c:
        parts.append(c if isinstance(c, str) else json.dumps(c, ensure_ascii=False))
    for tc in m.get("tool_calls") or []:
        fn = tc.get("function") or {}
        parts.append("<tool_call id=%s name=%s>%s</tool_call>" % (tc.get("id"), fn.get("name"), fn.get("arguments")))
    return " ".join(parts) if len(parts) == 1 else parts[0] + " " + "\n".join(parts[1:])