SarahXia0405 commited on
Commit
0ef49d4
·
verified ·
1 Parent(s): 4041cbc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +144 -54
app.py CHANGED
@@ -1,70 +1,160 @@
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
 
 
 
 
 
 
 
4
 
5
- def respond(
6
- message,
7
- history: list[dict[str, str]],
8
- system_message,
9
- max_tokens,
10
- temperature,
11
- top_p,
12
- hf_token: gr.OAuthToken,
13
- ):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  """
15
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
 
16
  """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
18
 
19
- messages = [{"role": "system", "content": system_message}]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
- messages.extend(history)
 
 
 
 
22
 
23
- messages.append({"role": "user", "content": message})
 
 
24
 
25
- response = ""
26
 
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = choices[0].delta.content
 
 
 
 
 
 
 
 
38
 
39
- response += token
40
- yield response
 
41
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- chatbot = gr.ChatInterface(
47
- respond,
48
- type="messages",
49
- additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
53
- gr.Slider(
54
- minimum=0.1,
55
- maximum=1.0,
56
- value=0.95,
57
- step=0.05,
58
- label="Top-p (nucleus sampling)",
59
- ),
60
- ],
61
- )
62
-
63
- with gr.Blocks() as demo:
64
- with gr.Sidebar():
65
- gr.LoginButton()
66
- chatbot.render()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
 
 
68
 
 
69
  if __name__ == "__main__":
70
- demo.launch()
 
1
+ import os
2
+ from typing import List, Dict, Tuple
3
+
4
  import gradio as gr
5
+ from openai import OpenAI
6
 
7
+ # ---------- 读取 API Key ----------
8
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
9
+ if not OPENAI_API_KEY:
10
+ raise RuntimeError(
11
+ "OPENAI_API_KEY is not set. Please go to Settings → Variables and secrets and add it."
12
+ )
13
 
14
+ client = OpenAI(api_key=OPENAI_API_KEY)
15
+
16
+ # 你可以按需要换成 gpt-4.1, gpt-4o, gpt-4.1-nano 等
17
+ DEFAULT_MODEL = "gpt-4.1-mini"
18
+
19
+ # ---------- Clare 助教的系统设定 ----------
20
+ CLARE_SYSTEM_PROMPT = """
21
+ You are Clare, an AI teaching assistant for Hanbridge University.
22
+
23
+ Core identity:
24
+ - You are patient, encouraging, and structured like a very good TA.
25
+ - Your UI and responses should be in ENGLISH by default.
26
+ - However, you can understand BOTH English and Chinese questions, and you may reply in Chinese if the user asks you to or is clearly more comfortable in Chinese.
27
+
28
+ Your main jobs:
29
+ 1. Help students understand course concepts step by step.
30
+ 2. Ask short check-up questions to confirm understanding instead of giving huge long lectures.
31
+ 3. When the student is confused, break content into smaller chunks and use simple language first.
32
+ 4. When the student is advanced, you can switch to more technical explanations.
33
+
34
+ Teaching style:
35
+ - Prefer short paragraphs and bullet points.
36
+ - Use concrete examples and analogies.
37
+ - Frequently summarize: “So far, we have …”
38
+ - When appropriate, give simple practice questions or mini-exercises.
39
+ - If the user asks something outside the course, you can still help, but be honest about uncertainty.
40
+
41
+ Safety and honesty:
42
+ - If you don’t know, say you are not sure and suggest how to verify.
43
+ - Do not fabricate references, exam answers, or grades.
44
+ """
45
+
46
+
47
+ def build_messages(
48
+ user_message: str,
49
+ history: List[Tuple[str, str]],
50
+ language_preference: str,
51
+ ) -> List[Dict[str, str]]:
52
  """
53
+ 把历史对话 + 当前问题 转成 OpenAI Chat API 需要的 messages 列表。
54
+ history: List of (user, assistant)
55
  """
56
+ messages: List[Dict[str, str]] = [{"role": "system", "content": CLARE_SYSTEM_PROMPT}]
57
 
58
+ # 语言偏好控制(英文/中文/自动)
59
+ if language_preference == "English":
60
+ messages.append(
61
+ {
62
+ "role": "system",
63
+ "content": "Please answer in English.",
64
+ }
65
+ )
66
+ elif language_preference == "中文":
67
+ messages.append(
68
+ {
69
+ "role": "system",
70
+ "content": "请你用中文回答学生的问题。",
71
+ }
72
+ )
73
 
74
+ # 把历史对话加进去
75
+ for user, assistant in history:
76
+ messages.append({"role": "user", "content": user})
77
+ if assistant is not None:
78
+ messages.append({"role": "assistant", "content": assistant})
79
 
80
+ # 当前这一轮的问题
81
+ messages.append({"role": "user", "content": user_message})
82
+ return messages
83
 
 
84
 
85
+ def chat_with_clare(
86
+ message: str,
87
+ history: List[Tuple[str, str]],
88
+ model_name: str,
89
+ language_preference: str,
90
+ ):
91
+ """
92
+ Gradio 调用的主函数:输入当前 message + 历史 history,返回 Clare 的回答和新的 history。
93
+ """
94
+ try:
95
+ messages = build_messages(message, history, language_preference)
96
+ response = client.chat.completions.create(
97
+ model=model_name or DEFAULT_MODEL,
98
+ messages=messages,
99
+ temperature=0.5,
100
+ )
101
+ answer = response.choices[0].message.content
102
+ except Exception as e:
103
+ answer = f"⚠️ Error talking to the model: {e}"
104
 
105
+ # Gradio 需要返回 (回答, 更新后的 history)
106
+ history = history + [(message, answer)]
107
+ return answer, history
108
 
109
 
110
+ # ---------- Gradio UI ----------
111
+ with gr.Blocks(title="Clare Hanbridge AI Teaching Assistant") as demo:
112
+ gr.Markdown(
113
+ """
114
+ # 🎓 Clare – AI Teaching Assistant
115
+ **Hanbridge University** · English UI · Supports both English & Chinese questions.
116
+
117
+ - Ask in English Clare answers in English.
118
+ - Ask in Chinese Clare can answer in Chinese.
119
+ - Use it as your study companion for courses, assignments, and exam review.
120
+ """
121
+ )
122
+
123
+ with gr.Row():
124
+ model_name = gr.Textbox(
125
+ label="Model name",
126
+ value=DEFAULT_MODEL,
127
+ info="For example: gpt-4.1-mini, gpt-4.1, gpt-4o, etc.",
128
+ )
129
+ language_preference = gr.Radio(
130
+ choices=["Auto", "English", "中文"],
131
+ value="Auto",
132
+ label="Preferred answer language",
133
+ )
134
+
135
+ chatbot = gr.Chatbot(
136
+ label="Clare Chat",
137
+ height=450,
138
+ )
139
+ user_input = gr.Textbox(
140
+ label="Your question",
141
+ placeholder="Ask Clare anything about your course, assignment, or study plan...",
142
+ )
143
+ clear_btn = gr.Button("Reset conversation")
144
+
145
+ # 使用 ChatInterface 的逻辑:手写一个简单的 handler
146
+ def respond(message, chat_history):
147
+ answer, new_history = chat_with_clare(
148
+ message,
149
+ chat_history,
150
+ model_name=model_name.value,
151
+ language_preference=language_preference.value,
152
+ )
153
+ return "", new_history # 文本框清空 + 更新 history
154
 
155
+ user_input.submit(respond, [user_input, chatbot], [user_input, chatbot])
156
+ clear_btn.click(lambda: None, None, chatbot, queue=False)
157
 
158
+ # Gradio 启动
159
  if __name__ == "__main__":
160
+ demo.launch()