-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstudy_companion_api.py
More file actions
75 lines (65 loc) · 2.99 KB
/
study_companion_api.py
File metadata and controls
75 lines (65 loc) · 2.99 KB
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
import requests
import re
import json
API_URL = "http://localhost:11434/api/chat"
MODEL = "hf.co/Qwen/Qwen3-1.7B-GGUF:Q8_0"
SYSTEM_PROMPTS = {
"数学": "你是一位耐心的数学辅导老师。请展示计算步骤,解释推理过程,并给出最终答案,格式为“答案:...”注意使用中文回答。",
"化学": "你是一位细心的化学辅导老师。请写出配平后的化学方程式,提及安全注意事项,解释要通俗易懂。注意使用中文回答。",
"物理": "你是一位物理辅导老师。请明确假设条件,列出使用的公式,并标明单位。注意使用中文回答。",
"英语": "你是一位英语辅导老师。请解释语法并举例说明。注意使用中文回答。",
"生物": "你是一位生物辅导老师。请解释生物概念并举例说明。注意使用中文回答。",
"编程": "你是一位编程辅导老师。请解释代码并提供示例。注意使用中文回答。",
"default": "你是一位乐于助人的辅导老师。请清晰且逐步地回答问题。注意使用中文回答。"
}
CLASSIFIER_PROMPT = """
将以下问题分类为一个学科:
数学, 化学, 物理, 英语, 生物, 编程, 其他.
只输出单个标签词,不要添加其他内容。
问题:
\"\"\"{question}\"\"\"
"""
def ollama_chat(messages):
"""直接调用 Ollama /api/chat 接口"""
payload = {
"model": MODEL,
"messages": messages,
"stream": False
}
r = requests.post(API_URL, json=payload)
r.raise_for_status()
data = r.json()
return data["message"]["content"]
def classify_subject(question):
prompt = CLASSIFIER_PROMPT.format(question=question)
resp = ollama_chat([{"role": "user", "content": prompt}])
# 移除<think>到</think>之间的内容
resp = re.sub(r"<think>.*?</think>", "", resp, flags=re.DOTALL | re.IGNORECASE)
m = re.search(r"(数学|化学|物理|英语|生物|编程|其他)", resp.lower())
return m.group(1) if m else "其他"
def answer_question(question, subject):
system_prompt = SYSTEM_PROMPTS.get(subject, SYSTEM_PROMPTS["default"])
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": question}
]
return ollama_chat(messages)
def simple_math_verify(answer_text):
nums = re.findall(r"[-+]?\d*\.\d+|[-+]?\d+", answer_text)
return {"num_count": len(nums), "example_nums": nums[:5]}
def main():
print("数字学伴(终端 + Ollama API 原型)。输入 'quit' 退出。")
while True:
q = input("\n你的问题: ").strip()
if q.lower() in ("quit", "exit"):
break
subject = classify_subject(q)
print(f"[检测学科]: {subject}")
if subject == "其他":
print("抱歉,目前仅支持以下学科:数学、化学、物理、英语、生物、编程。")
continue
ans = answer_question(q, subject)
print("\n=== 回答 ===\n")
print(ans)
if __name__ == "__main__":
main()