File size: 19,312 Bytes
f368481
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
"""
ReAct agent core (Phase 2) — thay one-shot Route bằng MỘT pydantic_ai Agent có
tool-calling tự quyết định. Mỗi module là một function tool; web_search/fetch_url
đăng ký thẳng. Sự kiện route/step phát ra NGAY trong hàm tool (chạy đồng bộ cùng
thread) qua callback `emit` trong Deps — giữ nguyên đường SSE hiện có.

Khác atria: không tự viết vòng while HTTP; dùng agent.run_sync + UsageLimits làm
số vòng tối đa. Text trả lời cuối của agent CHÍNH LÀ reply (hấp thụ narrate()).
"""
from __future__ import annotations

import datetime
import json
import random
import re
import threading
from dataclasses import dataclass, field
from pathlib import Path

from pydantic_ai import Agent, RunContext
from pydantic_ai.usage import UsageLimits

from .. import config
from ..memory import ConversationState
from ..tool_base import Tool, ToolResult
from ..web_search import web_search, fetch_url
from .llm import thinking_trace
from .prompts.composition import create_main_composer

TEMPLATES_DIR = Path(__file__).resolve().parent / "prompts" / "templates"

# Một lock toàn cục quanh tool.run() (browser Playwright chung) — CHỈ ôm phần chạy
# tool, không ôm LLM/web call. Thay cho _lock cả-request của webapp cũ.
TOOL_LOCK = threading.Lock()

STYLE_HINTS = (
    "Ngắn gọn, đi thẳng vào việc.",
    "Thân thiện, thêm chút hào hứng tự nhiên.",
    "Điềm đạm, chuyên nghiệp, gọn gàng.",
    "Súc tích một-hai câu là đủ.",
    "Mô tả một chút về thứ vừa tạo cho sinh động.",
)


@dataclass
class Deps:
    emit: object                       # callable(event: dict) -> None  (SSE bridge)
    attachment: str | None
    transcript: str
    catalog: str
    style: str
    today: str
    # trạng thái tích luỹ trong lượt
    routed: list = field(default_factory=list)     # tên module đã gọi đầu tiên
    last_data: dict = field(default_factory=dict)  # data của tool result gần nhất
    last_summary: str = ""                          # summary thô của tool gần nhất
    any_ok: list = field(default_factory=list)     # [True] nếu có tool thành công
    any_fail: list = field(default_factory=list)   # [True] nếu có tool thất bại
    searched: bool = False                          # đã gọi web_search/fetch_url chưa


# Một số model Groq (llama) IN tool-call ra dưới dạng TEXT thay vì gọi thật, ví dụ
#   <function/run_cnc_websim>{"task": "..."}</function>
#   <function=web_search>("...")</function>
#   <function=web_search={"query":"..."}>
# Bắt lại để tự thực thi (fallback cho model không tool-call native).
_TEXT_CALL_NAME_RE = re.compile(
    r"<function\s*[=/]?\s*(run_[a-z0-9_]+|web_search|fetch_url)\b",
    re.IGNORECASE)
# Để dọn text-call còn sót khỏi câu trả lời cuối.
_TEXT_CALL_RE = re.compile(r"<function\b.*?(?:</function>|>)", re.IGNORECASE | re.DOTALL)

# Câu hỏi THỜI SỰ rõ rệt: phải có dữ liệu web mới nhất, KHÔNG được trả lời từ trí nhớ.
# Model yếu (cerebras/gpt-oss effort thấp) hay lờ luật "phải search" -> lưới an toàn:
# nếu khớp mà agent KHÔNG search thì tự search rồi tổng hợp lại.
_TIME_SENSITIVE_RE = re.compile(
    r"(tỉ số|tỷ số|kết quả|ai thắng|ai đang thắng|thắng mấy|mấy\s*[-–]\s*mấy|"
    r"đang đá|đang diễn ra|trực tiếp|livescore|hiện tại|bây giờ|lúc này|hôm nay|"
    r"tối nay|sáng nay|chiều nay|mới nhất|vừa xong|đang dẫn|bao nhiêu tuổi|"
    r"giá.*(hôm nay|hiện tại|bây giờ)|thời tiết)",
    re.IGNORECASE)


def _parse_text_call(text: str) -> tuple[str, str] | None:
    """Trả (tool_name, arg) nếu text là một tool-call bị in ra dạng chữ.
    Args nằm sau tên (có thể sau dấu '>'): {"task"/"query"/"url":...} hoặc ("...")."""
    m = _TEXT_CALL_NAME_RE.search(text or "")
    if not m:
        return None
    name = m.group(1)
    window = text[m.end():m.end() + 400]
    arg = ""
    j = window.find("{")
    if j != -1:                                   # dạng {"task"/"query"/"url": "..."}
        try:
            obj = json.loads(window[j:window.rfind("}") + 1])
            arg = str(obj.get("task") or obj.get("query") or obj.get("url") or "").strip()
        except Exception:
            arg = ""
    if not arg:                                   # dạng ("...") hoặc "..."
        m2 = re.search(r'["\']([^"\']{2,})["\']', window)
        arg = m2.group(1).strip() if m2 else ""
    return (name, arg)


def _observe(res: ToolResult) -> str:
    """Rút gọn ToolResult thành observation cho LLM (tiết kiệm token)."""
    head = "OK" if res.ok else "LỖI"
    summary = (res.summary or "").strip().replace("\n", " ")[:400]
    arts = []
    if isinstance(res.data, dict):
        for k in ("gcode_file", "stl_file", "video", "image", "screenshot", "file"):
            v = res.data.get(k)
            if isinstance(v, str):
                arts.append(v.replace("\\", "/").rsplit("/", 1)[-1])
    tail = f" | tệp: {', '.join(arts)}" if arts else ""
    # Khi LỖI: nhắc agent truyền đạt ĐÚNG lý do + gợi ý của công cụ cho người dùng,
    # đừng tự bịa nguyên nhân khác (vd tool báo "đang chạy cloud nên không thấy máy
    # in" mà agent lại nói "máy in bị tắt").
    hint = "" if res.ok else (" || Nhắc: nói lại cho người dùng ĐÚNG lý do và gợi ý ở trên, "
                              "GIỮ nguyên ý (kể cả cách khắc phục), ĐỪNG tự bịa nguyên nhân khác.")
    return f"{head}: {summary}{tail}{hint}"


class ReactAgent:
    """Bọc một pydantic_ai Agent có: module tools + web_search/fetch_url + system
    prompt ghép từ template. Dùng lại cho mọi lượt; deps mang ngữ cảnh từng lượt."""

    def __init__(self, model_name: str, tools: dict[str, Tool]):
        self.model_name = model_name
        self.tools = tools
        self._composer = create_main_composer(TEMPLATES_DIR)
        self._static_prompt = self._composer.compose({})
        self._max_requests = config.REACT_MAX_REQUESTS
        self._build()

    # ---- catalog (mô tả module cho system prompt, từ SKILL.md) ----
    def _catalog(self) -> str:
        from ..modules.registry import get_registry
        lines = []
        reg_by_name = {m.name: m for m in get_registry().all()}
        for name in self.tools:
            m = reg_by_name.get(name)
            if m is None:
                lines.append(f"### {name}\n{self.tools[name].description}")
                continue
            # SKILL.md đã bỏ frontmatter; cắt ~550 ký tự để giữ token nhỏ (Groq free TPM).
            _, body = _split_frontmatter(m.skill_md)
            lines.append(body.strip()[:550])
        return "## Công cụ hiện có\n\n" + "\n\n".join(lines)

    def _build(self) -> None:
        model = config.pydantic_model(self.model_name)
        # Effort THẤP cho ReAct: vòng lặp đã lo phần suy luận nhiều bước; reasoning
        # nặng mỗi request chỉ làm chậm (mỗi vòng gpt-oss ~28s ở medium).
        settings = config.reasoning_settings(self.model_name, effort=config.REACT_REASONING_EFFORT)
        agent = Agent(model, deps_type=Deps, model_settings=settings,
                      instructions=self._static_prompt)

        @agent.instructions
        def _dynamic(ctx: RunContext[Deps]) -> str:
            parts = [ctx.deps.catalog,
                     f"Bây giờ là {ctx.deps.today}. Dùng mốc này để biết sự kiện nào ĐÃ "
                     "diễn ra (giờ đã qua) và cái nào SẮP tới.", ctx.deps.style]
            if ctx.deps.transcript:
                parts.append("## Lịch sử hội thoại\n" + ctx.deps.transcript)
            if ctx.deps.attachment:
                ext = ctx.deps.attachment.lower().rsplit(".", 1)[-1]
                parts.append(f"(Người dùng vừa đính kèm một file .{ext}. "
                             "Định tuyến theo đuôi file như hướng dẫn.)")
            return "\n\n".join(p for p in parts if p)

        # web grounding tools — bọc qua ctx để ĐÁNH DẤU deps.searched (biết agent đã
        # tra web chưa, phục vụ lưới an toàn thời sự). strict=False đồng nhất trên MỌI
        # tool: Cerebras (OpenAI-compat) cấm trộn strict true/false giữa các tool.
        def _web_search(ctx: RunContext[Deps], query: str) -> str:
            """Tra cứu web để lấy thông tin MỚI/thời sự (tin tức, tỉ số, giá, 'hiện tại').
            Trả về tiêu đề + trích đoạn + link. Cần chi tiết thì fetch_url link phù hợp."""
            ctx.deps.searched = True
            return web_search(query)

        def _fetch_url(ctx: RunContext[Deps], url: str) -> str:
            """Đọc nội dung THẬT của một URL rồi trả về văn bản (không đoán từ tiêu đề)."""
            ctx.deps.searched = True
            return fetch_url(url)

        agent.tool(_web_search, name="web_search", strict=False)
        agent.tool(_fetch_url, name="fetch_url", strict=False)

        # mỗi module -> một function tool run_<name>
        for name, tool in self.tools.items():
            self._register_module_tool(agent, name, tool)

        self.agent = agent

    def _exec_module(self, name: str, task: str, deps: Deps) -> ToolResult:
        """Chạy một module tool: phát route/step, ôm TOOL_LOCK, cập nhật deps."""
        tool = self.tools[name]
        emit = deps.emit
        if not deps.routed:                         # phát route chip ở lần gọi module đầu
            deps.routed.append(name)
            if callable(emit):
                emit({"type": "route", "tool": name, "reason": "agent chọn công cụ"})
        if callable(emit):
            emit({"type": "step", "kind": "running", "name": tool.name, "machine": name})

        def on_progress(ev):
            if callable(emit):
                emit({"type": "step", **ev})

        try:
            with TOOL_LOCK:                          # serialize browser Playwright dùng chung
                res = tool.run(task, attachment=deps.attachment, on_progress=on_progress)
        except Exception as e:
            res = ToolResult(ok=False, summary=f"Lỗi khi chạy {name}: {e}")

        deps.last_data = res.data if isinstance(res.data, dict) else {}
        deps.last_summary = res.summary or ""
        (deps.any_ok if res.ok else deps.any_fail).append(True)
        if callable(emit):
            emit({"type": "step", "kind": "done", "name": tool.name, "machine": name,
                  "status": "ok" if res.ok else "fail", "detail": (res.summary or "")[:200]})
        return res

    def _register_module_tool(self, agent: Agent, name: str, tool: Tool) -> None:
        desc = (tool.description or name).strip().split("\n")[0][:180]

        def _run_module(ctx: RunContext[Deps], task: str) -> str:
            return _observe(self._exec_module(name, task, ctx.deps))

        _run_module.__name__ = f"run_{name}"
        _run_module.__doc__ = f"{desc}\n\nArgs:\n    task: yêu cầu cụ thể cho công cụ {name}."
        agent.tool(_run_module, name=f"run_{name}", strict=False)

    def _text_web_fallback(self, tool_name: str, arg: str, message: str) -> str:
        """llama in web_search/fetch_url ra chữ -> chạy thật rồi tổng hợp MỘT lần
        bằng agent không-tool (tránh lại đẻ ra text-call)."""
        try:
            data = fetch_url(arg) if tool_name == "fetch_url" else web_search(arg or message)
        except Exception:
            return "Xin lỗi, mình chưa lấy được thông tin đáng tin cậy cho câu này."
        try:
            now_vn = (datetime.datetime.now(datetime.timezone.utc)
                      + datetime.timedelta(hours=7)).strftime("%Y-%m-%d %H:%M")
            plain = Agent(config.pydantic_model(self.model_name), instructions=(
                f"Bây giờ là {now_vn} (giờ Việt Nam). Trả lời NGẮN GỌN bằng tiếng Việt DỰA "
                "HOÀN TOÀN vào dữ liệu web bên dưới. KHÔNG gọi công cụ, KHÔNG bịa tỉ số/số "
                "liệu. Quy tắc cho tin thể thao/tỉ số: nếu dữ liệu CÓ tỉ số thì nêu tỉ số + "
                "nguồn, và nếu nguồn ghi 'LIVE'/'đang đá'/còn phút thi đấu thì NÓI RÕ 'trận "
                "đang diễn ra, tỉ số có thể đã đổi — xem trực tiếp để cập nhật'. Nếu các "
                "nguồn cho tỉ số KHÁC nhau (trận live), lấy tỉ số ở nguồn MỚI/CAO nhất. "
                "Nếu dữ liệu chỉ có LỊCH mà KHÔNG có tỉ số, nói trung tính 'chưa tra được tỉ "
                "số chính thức', đừng tự phán trận 'chưa diễn ra' hay 'đã xong'. Thiếu dữ "
                "liệu thì nói thẳng là chưa chắc."))
            out = plain.run_sync(f"Câu hỏi: {message}\n\n[Dữ liệu web]:\n{data[:2500]}").output
            return (out or "").strip() or data[:500]
        except Exception:
            return data[:500]

    # ---- API dùng bởi facade Harness ----
    def stream(self, message: str, state: ConversationState | None,
               attachment: str | None, emit) -> ToolResult:
        """Chạy một lượt ReAct, phát sự kiện qua emit, trả ToolResult cuối."""
        from .. import usage as _usage
        _usage.reset()                     # đếm token của lượt này (cùng thread worker)
        transcript = state.transcript() if (state and state.turns) else ""
        # Giờ VIỆT NAM (UTC+7): server HF chạy giờ UTC. Có GIỜ hiện tại thì model mới
        # phân biệt được trận "đã đá" (giờ đã qua) vs "sắp/đang đá tối nay".
        now_vn = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=7)
        deps = Deps(emit=emit, attachment=attachment, transcript=transcript,
                    catalog=self._catalog(), style=random.choice(STYLE_HINTS),
                    today=now_vn.strftime("%Y-%m-%d %H:%M") + " (giờ Việt Nam, UTC+7)")
        limits = UsageLimits(request_limit=self._max_requests)
        reasoning = ""
        try:
            # KHÔNG dùng run_with_retry ở top-level: retry sẽ chạy LẠI tool từ đầu.
            # Một lần chạy; 429 sau khi tool đã chạy được handler dưới cứu last_data.
            res = self.agent.run_sync(message, deps=deps, usage_limits=limits)
            text = (res.output or "").strip()
            reasoning = thinking_trace(res)
            from .. import usage as _usage
            _usage.add(res.usage)             # cả vòng ReAct (mọi iteration) trong 1 lần
        except Exception as e:
            from .llm import rate_limit_wait
            # QUAN TRỌNG: nếu một công cụ ĐÃ chạy (có kết quả), phần việc đắt giá đã
            # xong — chỉ bước tổng hợp NL cuối bị lỗi (429 TPM / hết vòng). Đừng vứt
            # kết quả: trả summary thô của tool + artifacts để người dùng vẫn nhận được.
            if deps.routed and (deps.any_ok or deps.last_data):
                text = deps.last_summary or "Đã xử lý xong yêu cầu; kết quả sẵn bên dưới."
            elif rate_limit_wait(str(e)) is not None:
                return ToolResult(True, f"Model “{self.model_name}” đang bị nhà cung cấp giới hạn "
                                        "tốc độ (rate limit). Thử lại sau một lát, hoặc bấm nút 🔌 "
                                        "đổi sang nhà cung cấp/model khác (Groq, Cerebras, Gemini).",
                                  {"kind": "chat"})
            elif "request_limit" in str(e).lower():
                # Agent lặp quá nhiều bước (thường do tra web mãi không xong) -> câu
                # thân thiện thay vì lỗi thô, kèm gợi ý.
                return ToolResult(True, "Câu này cần khá nhiều bước nên mình tạm dừng để tránh "
                                        "chạy quá lâu. Bạn thử nói cụ thể hơn (ví dụ tên/số hiệu "
                                        "văn bản), hoặc gửi lại giúp mình nhé.", {"kind": "chat"})
            else:
                return ToolResult(False, f"Lỗi khi xử lý: {e}", {"kind": "chat"})

        # Fallback: model (llama) in tool-call ra dạng CHỮ thay vì gọi thật -> tự thực thi.
        if not deps.routed:
            parsed = _parse_text_call(text)
            if parsed:
                tname, arg = parsed
                mod = tname[4:] if tname.startswith("run_") else ""
                if mod in self.tools:
                    res2 = self._exec_module(mod, arg or message, deps)
                    text = res2.summary or text
                elif tname in ("web_search", "fetch_url"):
                    text = self._text_web_fallback(tname, arg, message)
                    deps.searched = True

        # LƯỚI AN TOÀN thời sự: câu hỏi tỉ số/kết quả/"hiện tại" mà agent trả lời kiểu
        # chat (không chạy module). Kể cả khi model ĐÃ search, câu trả lời cuối của model
        # yếu vẫn hay sai mốc thời gian/bịa -> ép tổng hợp lại từ web bằng prompt tập
        # trung (có ngày hôm nay). Chốt chặn chống bịa, không phụ thuộc model ngoan hay không.
        safety = False
        if not deps.routed and _TIME_SENSITIVE_RE.search(message or ""):
            if callable(emit):
                emit({"type": "step", "kind": "running", "name": "Tra web (chống bịa)",
                      "machine": "web_search"})
            grounded = self._text_web_fallback("web_search", message, message)
            if callable(emit):
                emit({"type": "step", "kind": "done", "name": "Tra web (chống bịa)",
                      "machine": "web_search", "status": "ok"})
            if grounded:
                text, safety, deps.searched = grounded, True, True

        if not deps.routed and callable(emit):
            emit({"type": "route", "tool": "web" if safety else "chat",
                  "reason": "tra web (chống bịa)" if safety else "trò chuyện / hỏi đáp"})

        text = _TEXT_CALL_RE.sub("", text).strip() or text   # dọn text-call còn sót
        ok = not (deps.any_fail and not deps.any_ok)
        data = dict(deps.last_data)
        if reasoning:
            data.setdefault("reasoning", reasoning)
        data.setdefault("kind", deps.routed[0] if deps.routed else "chat")
        data["usage"] = _usage.get()
        return ToolResult(ok, text or "(không có nội dung trả lời)", data)


def _split_frontmatter(text: str) -> tuple[str, str]:
    from ..modules.store import parse_frontmatter
    meta, body = parse_frontmatter(text)
    return "", body