stemeducationmetaverse commited on
Commit
06c3bfd
·
verified ·
1 Parent(s): 2f579c5

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +21 -33
src/streamlit_app.py CHANGED
@@ -1,44 +1,32 @@
1
  import streamlit as st
2
- import requests
3
  import os
4
- # ---------------- CONFIG ----------------
 
 
5
  HF_TOKEN = os.getenv("HF_TOKEN")
6
- API_URL = "https://api-inference.hf.co/models/google/flan-t5-small"
7
- headers = {
8
- "Authorization": f"Bearer {HF_TOKEN}",
9
- "Content-Type": "application/json",
10
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
11
- }
12
- # ---------------- UI ----------------
13
  st.title("🤖 My First AI Chatbot")
14
  user_input = st.text_input("Ask something:")
15
- # ---------------- FUNCTION ----------------
16
- def query(payload):
17
- try:
18
- response = requests.post(
19
- API_URL,
20
- headers=headers,
21
- json=payload,
22
- timeout=30
23
- )
24
- # Handle API errors safely
25
- if response.status_code != 200:
26
- return {"error": f"HTTP {response.status_code}: {response.text[:200]}"}
27
- return response.json()
28
- except Exception as e:
29
- return {"error": str(e)}
30
- # ---------------- MAIN ----------------
31
  if st.button("Send"):
32
  if not user_input.strip():
33
  st.warning("Please enter a question.")
 
 
34
  else:
35
- output = query({"inputs": user_input})
36
- # ---------------- SAFE OUTPUT HANDLING ----------------
37
- if "error" in output:
38
- st.error(output["error"])
39
- else:
40
  try:
41
- answer = output[0]["generated_text"]
 
 
 
 
 
42
  st.success(answer)
43
- except:
44
- st.error("Unexpected response format from model.")
 
 
 
1
  import streamlit as st
 
2
  import os
3
+ from huggingface_hub import InferenceClient # Pre-installed native wrapper
4
+
5
+ # 1. Pull the classic 'Write' token out of your secret settings
6
  HF_TOKEN = os.getenv("HF_TOKEN")
7
+
8
+ # 2. Fire up the native client using the token
9
+ client = InferenceClient(token=HF_TOKEN)
10
+
 
 
 
11
  st.title("🤖 My First AI Chatbot")
12
  user_input = st.text_input("Ask something:")
13
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  if st.button("Send"):
15
  if not user_input.strip():
16
  st.warning("Please enter a question.")
17
+ elif not HF_TOKEN:
18
+ st.error("Your HF_TOKEN secret key is entirely missing from Settings!")
19
  else:
20
+ with st.spinner("Processing natively through the cluster..."):
 
 
 
 
21
  try:
22
+ # 3. Route via internal endpoints rather than requests.post
23
+ answer = client.text_generation(
24
+ prompt=user_input,
25
+ model="google/flan-t5-small",
26
+ max_new_tokens=50
27
+ )
28
  st.success(answer)
29
+
30
+ except Exception as e:
31
+ # This explicitly unpacks server messages instead of dropping HTML text
32
+ st.error(f"System Response: {e}")