File size: 2,415 Bytes
c12625f
 
e46d575
 
 
 
 
c12625f
e46d575
 
 
c12625f
e46d575
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c12625f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e46d575
 
 
 
 
 
 
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
import logging

from fastapi import APIRouter, Depends
from fastapi.responses import StreamingResponse

from backend.core.auth import get_current_user
from backend.models.explain import ExplainRequest
from backend.core.config import settings
from backend.services import claude_service, prompt_templates, supabase_service

router = APIRouter(prefix="/api", tags=["explain"])
logger = logging.getLogger(__name__)


@router.post("/explain")
async def explain(
    body: ExplainRequest,
    user: dict = Depends(get_current_user),
):
    """
    Stream a grade-appropriate explanation for the student's math query.
    Also creates a session record in Supabase and returns session_id in headers.
    """
    system = prompt_templates.explanation_system(body.grade)
    user_msg = prompt_templates.explanation_user(body.query)

    # Collect full explanation for DB storage while streaming to client
    full_text_parts: list[str] = []

    async def generate():
        try:
            async for chunk in claude_service.stream(system, user_msg):
                full_text_parts.append(chunk)
                yield chunk
        except Exception as e:
            # Avoid terminating the HTTP chunked stream mid-flight.
            logger.exception("Explanation stream failed: %s", e)
            provider = settings.llm_provider.strip().lower()
            if provider == "ollama":
                hint = (
                    "Please ensure Ollama is running and the model is available "
                    f"({settings.llm_model}) at {settings.llm_base_url}."
                )
            else:
                hint = "Please verify your Anthropic API key and billing, then try again."
            yield (
                "\n\nSorry, I could not generate the explanation right now. "
                + hint
            )
            return

        # After successful stream — save session to Supabase
        full_text = "".join(full_text_parts).strip()
        if full_text:
            supabase_service.create_session(
                user_id=user["id"],
                topic=_extract_topic(body.query),
                grade=body.grade,
                explanation=full_text,
            )

    return StreamingResponse(generate(), media_type="text/plain")


def _extract_topic(query: str) -> str:
    """Simple topic extraction — first 80 chars of query as topic label."""
    return query[:80].strip()