File size: 10,021 Bytes
a017e41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8695d3a
 
 
37d6467
a017e41
107a904
 
 
37d6467
 
107a904
37d6467
 
 
 
 
 
 
 
 
 
 
 
107a904
 
37d6467
107a904
37d6467
107a904
 
 
a017e41
 
 
 
 
107a904
 
 
 
 
a017e41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107a904
 
 
a017e41
 
 
107a904
 
 
a017e41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107a904
 
 
a017e41
 
 
 
 
 
 
 
 
 
 
107a904
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a017e41
 
 
 
 
 
 
 
 
 
 
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
"""
NVIDIA NIM fallback β€” stronger free fallback than Groq/Llama-70B.

NVIDIA's API (https://integrate.api.nvidia.com/v1) is OpenAI-compatible and
free-tier, hosting large models (DeepSeek, Llama 405B, Nemotron). We use it as
the FIRST fallback when Claude is unavailable, then Groq remains as a final
backstop.

Same grounding discipline as claude_engine / groq_fallback: answer only from
context, never invent ALU facts. The richer model follows that prompt better
than Llama-3.3-70B did.

Configuration (Hugging Face Space secrets):
    NVIDIA_API_KEY  -> key from build.nvidia.com (starts with "nvapi-")
    NVIDIA_MODEL    -> optional, defaults to deepseek-ai/deepseek-v4-flash
                       (a fast chat-oriented model; avoid pure-reasoner ids
                        unless you want <think> blocks, which we strip anyway)
"""

import os
import re
import logging

logger = logging.getLogger(__name__)

NVIDIA_BASE_URL = "https://integrate.api.nvidia.com/v1"
# A non-reasoning instruct model β€” fast enough for a fallback. DeepSeek V4 was
# tried first but its reasoning chains took >75s, blowing the request timeout.
# Override with NVIDIA_MODEL if you want a different one.
DEFAULT_NVIDIA_MODEL = "meta/llama-3.3-70b-instruct"

# Tried in order when the configured model is rejected. A hardcoded id is a
# silent-failure waiting to happen: when a model is retired the call fails with
# a 404 that looks exactly like an expired key from the outside, and the
# fallback quietly stops working. This list is what stopped that being fatal
# for Groq, where TWO ids in a row turned out to be retired.
#
# Ids verified against NVIDIA's supported-models documentation rather than
# recalled β€” the exact string matters (mixtral is "-v01", not "-v0.1") and a
# wrong one is indistinguishable from a dead key at runtime.
#
# Ordering is deliberate, and it is NOT "best model first":
#   - Only instruct models. No pure reasoners. A fallback runs when something
#     else already broke, so a model that thinks for 75 seconds (DeepSeek V4
#     did exactly that here) is worse than no model β€” it burns the request
#     timeout and the student still sees an error, just more slowly.
#   - Capable-but-fast first, then smaller models as the safety net. A 70B
#     instruct model answers a grounded RAG question in a couple of seconds;
#     the 8B is there so there is always something that responds.
MODEL_CANDIDATES = [
    "meta/llama-3.3-70b-instruct",
    "nvidia/llama-3.1-nemotron-70b-instruct",
    "meta/llama-3.1-70b-instruct",
    "nv-mistralai/mistral-nemo-12b-instruct",
    "meta/llama-3.1-8b-instruct",
]

# Some DeepSeek/reasoning models prepend a <think>...</think> chain. Strip it so
# only the final answer reaches the student.
_THINK_BLOCK = re.compile(r"<think>.*?</think>", re.DOTALL | re.IGNORECASE)


# Shared with the Groq fallback β€” one tested implementation rather than two
# that can drift apart. Re-exported so existing imports keep working.
from model_discovery import is_model_error as _is_model_error  # noqa: E402


class NvidiaFallback:
    """OpenAI-compatible NVIDIA NIM client. Enabled when NVIDIA_API_KEY is set."""

    # Reuse the same grounded system prompt discipline as the Groq fallback.
    SYSTEM_PROMPT = """You are the ALU Student Companion, an AI assistant for African Leadership University (ALU).

# Most important rule
Answer ONLY from the context provided below. If the context does not contain a fact, do not invent it. Specifically NEVER invent course codes, credit hours, module names, tuition amounts, fees, scholarship values, faculty names/titles, deadlines, term dates, or statistics. When the context doesn't have what's needed, say so plainly and point to the official source β€” students would rather hear "I don't have that, here's where to find it" than a confident wrong answer.

# Style
- Lead with a one-sentence direct answer, then detail.
- Use markdown sparingly; bullet lists only for genuine lists.
- No emoji. No "Is there anything else..." filler.
- When a Source in the context has a url=..., cite it as a markdown link the first time you use that fact.
- Do not show your reasoning or thinking steps; give only the final answer.

# Facts you may always state without context
- ALU was founded by Fred Swaniker in 2015, part of the African Leadership Group.
- Campuses in Kigali, Rwanda and Pamplemousses, Mauritius.
- Main site https://www.alueducation.com ; support https://support.alueducation.com
- Student emails end @alustudent.com ; staff/public @alueducation.com

Everything else β€” programmes, fees, dates, people β€” must come from the context. If it is not there, say you don't know and point to support.alueducation.com."""

    def __init__(self):
        self.api_key = os.getenv("NVIDIA_API_KEY", "")
        # An explicitly configured model is honoured and never auto-switched β€”
        # if an operator names a model, a silent swap would hide their mistake.
        self._model_pinned = bool(os.getenv("NVIDIA_MODEL"))
        self.model = os.getenv("NVIDIA_MODEL", DEFAULT_NVIDIA_MODEL)
        self.enabled = bool(self.api_key)
        self.client = None
        # Candidates already tried and rejected, so one dead model is not
        # re-attempted on every question.
        self._exhausted = set()

        if not self.enabled:
            logger.info("[INFO] NVIDIA fallback disabled (no NVIDIA_API_KEY)")
            return

        try:
            # The OpenAI SDK ships transitively (anthropic/groq pull deps); if
            # absent, degrade gracefully.
            from openai import OpenAI
            self.client = OpenAI(api_key=self.api_key, base_url=NVIDIA_BASE_URL)
            logger.info(f"[OK] NVIDIA fallback enabled (model={self.model})")
        except ImportError:
            logger.warning("[!] openai package not installed β€” pip install openai")
            self.enabled = False
        except Exception as e:
            logger.error(f"[FAIL] Failed to initialize NVIDIA client: {e}")
            self.enabled = False

    def generate_response(self, query: str, alu_context: str = "", history=None) -> str:
        """
        Generate a grounded answer via NVIDIA NIM. Same signature as the Groq
        fallback so the call sites are interchangeable.
        """
        if not self.enabled or not self.client:
            return None

        try:
            messages = [{"role": "system", "content": self.SYSTEM_PROMPT}]

            for entry in (history or [])[-8:]:
                role = entry.get("role")
                content = entry.get("content", "")
                if role in ("user", "assistant") and content:
                    messages.append({"role": role, "content": content})

            if alu_context:
                user_message = (
                    "Use the following context from the ALU knowledge base to "
                    "answer the question. If the context does not contain the "
                    "answer, say so honestly and point to the official source.\n\n"
                    f"=== CONTEXT ===\n{alu_context}\n=== END CONTEXT ===\n\n"
                    f"Question: {query}"
                )
            else:
                user_message = query
            messages.append({"role": "user", "content": user_message})

            response = self._create_with_fallback(messages)
            if response is None:
                return None

            answer = (response.choices[0].message.content or "").strip()
            # Strip any leaked reasoning block before returning.
            answer = _THINK_BLOCK.sub("", answer).strip()
            logger.info(f"[OK] NVIDIA response generated ({len(answer)} chars)")
            return answer or None

        except Exception as e:
            logger.error(f"[FAIL] NVIDIA API error: {e}")
            return None

    def _create_with_fallback(self, messages):
        """Call the configured model; on a model-not-found error, walk the
        candidate list and adopt the first that works.

        Only model-resolution errors trigger a switch. An auth failure or a
        rate limit means every candidate would fail the same way, so retrying
        four more times just multiplies the latency on a request that is
        already the last thing between a student and an error message.
        """
        attempts = [self.model]
        if not self._model_pinned:
            attempts += [
                m for m in MODEL_CANDIDATES
                if m != self.model and m not in self._exhausted
            ]

        last_error = None
        for candidate in attempts:
            try:
                response = self.client.chat.completions.create(
                    model=candidate,
                    messages=messages,
                    temperature=0.4,
                    max_tokens=1024,
                    top_p=0.9,
                )
                if candidate != self.model:
                    logger.warning(
                        "[!] NVIDIA model %s unusable β€” switched to %s",
                        self.model, candidate,
                    )
                    self.model = candidate
                return response
            except Exception as e:
                last_error = e
                if not _is_model_error(e):
                    # Auth, quota, network: no other model would help.
                    raise
                self._exhausted.add(candidate)
                logger.warning("[!] NVIDIA model %s rejected: %s", candidate, e)

        logger.error("[FAIL] no usable NVIDIA model; last error: %s", last_error)
        return None

    def get_status(self) -> dict:
        return {
            "enabled": self.enabled,
            "api_key_set": bool(self.api_key),
            "client_initialized": self.client is not None,
            "model": self.model if self.enabled else None,
        }


# Module-level singleton, matches the groq_fallback / claude_engine pattern.
nvidia_fallback = NvidiaFallback()