File size: 4,646 Bytes
1289247
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Direct (non-agent) LLM calls: tutoring/judging text and handwriting transcription.

Interactive tutoring needs second-scale latency, so these go straight to the HF Inference
router instead of through a multi-step CodeAgent. Each call tries the configured providers in
order (a provider outage or routing problem shouldn't take the tutor down).
"""

from __future__ import annotations

import base64
import json
import mimetypes
import re
from pathlib import Path

from huggingface_hub import InferenceClient

from src.config import TUTOR_MAX_TOKENS, TUTOR_MODEL, TUTOR_PROVIDERS, TUTOR_REASONING_EFFORT, VISION_MODELS


class LLMUnavailable(RuntimeError):
    pass


def _complete(model: str, providers: tuple[str, ...], messages: list[dict], max_tokens: int,
              temperature: float, json_mode: bool = False, extra_body: dict | None = None) -> str:
    errors = []
    for provider in providers:
        try:
            kwargs: dict = {"response_format": {"type": "json_object"}} if json_mode else {}
            if extra_body:
                kwargs["extra_body"] = extra_body
            out = InferenceClient(provider=provider, timeout=90).chat_completion(
                model=model, messages=messages, max_tokens=max_tokens, temperature=temperature, **kwargs)
            text = out.choices[0].message.content or ""
            if text.strip():
                return text
            errors.append(f"{provider}: empty response")
        except Exception as e:  # noqa: BLE001 — any provider failure → try the next one
            errors.append(f"{provider}: {str(e)[:160]}")
    raise LLMUnavailable(f"{model} failed on all providers: {errors}")


_TUTOR_EXTRA = {"reasoning_effort": TUTOR_REASONING_EFFORT}


def chat(system: str, user: str, max_tokens: int = TUTOR_MAX_TOKENS, temperature: float = 0.2) -> str:
    return _complete(TUTOR_MODEL, TUTOR_PROVIDERS,
                     [{"role": "system", "content": system}, {"role": "user", "content": user}],
                     max_tokens, temperature, extra_body=_TUTOR_EXTRA)


def _parse_json(text: str) -> dict:
    text = text.strip()
    text = re.sub(r"^```(?:json)?\s*|\s*```$", "", text)
    try:
        return json.loads(text)
    except json.JSONDecodeError:
        m = re.search(r"\{.*\}", text, re.DOTALL)
        if not m:
            raise
        return json.loads(m.group(0))


def chat_json(system: str, user: str, max_tokens: int = TUTOR_MAX_TOKENS) -> dict:
    """JSON-object response; retries once without response_format if the provider rejects it."""
    msgs = [{"role": "system", "content": system + "\nRespond with a single JSON object only."},
            {"role": "user", "content": user}]
    last: Exception | None = None
    for json_mode in (True, False):
        try:
            return _parse_json(_complete(TUTOR_MODEL, TUTOR_PROVIDERS, msgs, max_tokens, 0.1, json_mode,
                                         extra_body=_TUTOR_EXTRA))
        except (json.JSONDecodeError, LLMUnavailable) as e:
            last = e
    raise LLMUnavailable(f"no valid JSON from tutor model: {last}")


TRANSCRIBE_PROMPT = (
    "You are a transcription tool. Transcribe the handwritten math EXACTLY as written, line by line, using "
    "LaTeX inside $...$ for math. Do NOT correct, simplify, evaluate, or complete anything — mistakes must be "
    "preserved verbatim. Keep the student's words. If something is illegible write [illegible]. "
    "Output only the transcription."
)


def transcribe_handwriting(image_path: str | Path) -> str:
    """Photo of handwritten work → verbatim LaTeX-ish text (errors preserved on purpose)."""
    path = Path(image_path)
    mime = mimetypes.guess_type(path.name)[0] or "image/png"
    b64 = base64.b64encode(path.read_bytes()).decode()
    messages = [{"role": "user", "content": [
        {"type": "image_url", "image_url": {"url": f"data:{mime};base64,{b64}"}},
        {"type": "text", "text": TRANSCRIBE_PROMPT},
    ]}]
    errors = []
    for model, providers in VISION_MODELS:
        try:
            return _complete(model, providers, messages, max_tokens=1200, temperature=0.0).strip()
        except LLMUnavailable as e:
            errors.append(str(e))
    raise LLMUnavailable(f"handwriting transcription failed: {errors}")


def read_response(image_path: str | None, typed: str | None) -> str:
    """Combine a handwritten photo (transcribed) and/or typed text into one response string."""
    parts = []
    if image_path:
        parts.append(transcribe_handwriting(image_path))
    if typed and typed.strip():
        parts.append(typed.strip())
    return "\n\n".join(parts)