ishmeet-yo commited on
Commit
09e508e
·
verified ·
1 Parent(s): 50c885a

Update app/llm.py

Browse files
Files changed (1) hide show
  1. app/llm.py +69 -68
app/llm.py CHANGED
@@ -1,88 +1,89 @@
1
- import requests
2
  import os
3
  import random
 
 
 
 
4
  API_URL = "https://router.huggingface.co/v1/chat/completions"
5
 
6
- def load_tokens():
7
- tokens = []
8
- for k, v in os.environ.items():
9
- if k.startswith("HF_TOKEN_") and v:
10
- tokens.append(v)
 
 
 
 
 
 
 
 
 
 
 
11
  if not tokens:
12
- raise RuntimeError("No HF tokens found in environment variables")
 
 
 
 
13
  return tokens
14
 
 
15
  HF_TOKENS = load_tokens()
16
 
 
17
  def generate_answer(context: str, query: str) -> str:
18
- random.shuffle(HF_TOKENS)
 
 
 
 
19
 
20
- for token in HF_TOKENS:
21
  headers = {
22
  "Authorization": f"Bearer {token}",
23
  "Content-Type": "application/json",
24
  }
25
 
26
- response = requests.post(API_URL, headers=headers, json={
27
- "model": "deepseek-ai/DeepSeek-V3.2",
28
  "messages": [
29
- {"role": "system", "content": "You are a Harry Potter knowledge assistant."},
30
- {"role": "user", "content": f"Context:\n{context}\nQuestion:\n{query}\nAnswer:"},
 
 
 
 
 
 
31
  ],
32
  "temperature": 0.3,
33
  "max_tokens": 500,
34
- })
35
-
36
- if response.status_code == 200:
37
- return response.json()["choices"][0]["message"]["content"]
38
-
39
- if response.status_code != 429:
40
- break # real error, don't retry blindly
41
-
42
- return "All magical channels are busy right now. Please try again shortly."
43
-
44
- # def generate_answer(context: str, query: str) -> str:
45
- # headers = {
46
- # "Authorization": f"Bearer {HF_TOKEN}",
47
- # "Content-Type": "application/json",
48
- # }
49
-
50
- # payload = {
51
- # "model": "deepseek-ai/DeepSeek-V3.2",
52
- # "messages": [
53
- # {
54
- # "role": "system",
55
- # "content": (
56
- # """You are a Harry Potter knowledge assistant.
57
-
58
- # Answer the question concisely in 2–3 sentences.
59
- # Do not use bullet points.
60
- # Do not add extra background.
61
- # Be clear and direct."""
62
- # ),
63
- # },
64
- # {
65
- # "role": "user",
66
- # "content": f"""Context:
67
- # {context}
68
-
69
- # Question:
70
- # {query}
71
-
72
- # Answer:
73
- # """,
74
- # },
75
- # ],
76
- # "temperature": 0.3,
77
- # "max_tokens": 500,
78
- # }
79
-
80
- # response = requests.post(API_URL, headers=headers, json=payload)
81
-
82
- # if response.status_code != 200:
83
- # return (
84
- # "The magic is unstable right now.\n\n"
85
- # f"Model response: {response.status_code}\n\n"
86
- # "Try again in a moment."
87
- # )
88
- # return response.json()["choices"][0]["message"]["content"]
 
 
1
  import os
2
  import random
3
+ import time
4
+ import requests
5
+ from typing import List
6
+
7
  API_URL = "https://router.huggingface.co/v1/chat/completions"
8
 
9
+ MODEL_NAME = "mistralai/Mistral-7B-Instruct-v0.2"
10
+
11
+ TIMEOUT_SECONDS = 30
12
+ MAX_RETRIES_PER_TOKEN = 3
13
+
14
+
15
+ def load_tokens() -> List[str]:
16
+ """
17
+ Load all Hugging Face tokens that start with HF_TOKEN_
18
+ from environment variables.
19
+ """
20
+ tokens = [
21
+ v for k, v in os.environ.items()
22
+ if k.startswith("HF_TOKEN_") and v
23
+ ]
24
+
25
  if not tokens:
26
+ raise RuntimeError(
27
+ "No HF_TOKEN_* variables found. "
28
+ "Add at least one token in Hugging Face Space settings."
29
+ )
30
+
31
  return tokens
32
 
33
+
34
  HF_TOKENS = load_tokens()
35
 
36
+
37
  def generate_answer(context: str, query: str) -> str:
38
+
39
+ tokens = HF_TOKENS[:]
40
+ random.shuffle(tokens)
41
+
42
+ context = context[:3000]
43
 
44
+ for token in tokens:
45
  headers = {
46
  "Authorization": f"Bearer {token}",
47
  "Content-Type": "application/json",
48
  }
49
 
50
+ payload = {
51
+ "model": MODEL_NAME,
52
  "messages": [
53
+ {
54
+ "role": "system",
55
+ "content": "You are a Harry Potter knowledge assistant created by Ishmeet Kaur, who is awesome. Answer in short concise sentences, stay grounded and faithful."
56
+ },
57
+ {
58
+ "role": "user",
59
+ "content": f"Context:\n{context}\n\nQuestion:\n{query}\n\nAnswer:"
60
+ },
61
  ],
62
  "temperature": 0.3,
63
  "max_tokens": 500,
64
+ }
65
+
66
+ for attempt in range(MAX_RETRIES_PER_TOKEN):
67
+ try:
68
+ response = requests.post(
69
+ API_URL,
70
+ headers=headers,
71
+ json=payload,
72
+ timeout=TIMEOUT_SECONDS,
73
+ )
74
+ except requests.RequestException:
75
+ break
76
+
77
+ if response.status_code == 200:
78
+ return response.json()["choices"][0]["message"]["content"]
79
+
80
+ if response.status_code == 429:
81
+ time.sleep(2 ** attempt)
82
+ continue
83
+
84
+ break
85
+
86
+ return (
87
+ "The library is a bit crowded right now. "
88
+ "Please try again in a moment."
89
+ )