AI-powered Chinese college admission advisor with 240k+ real admission data records, multi-round dialogue, major filtering, and Zhang Xuefeng methodology
Installer avec Codex ou Claude Copiez ce prompt, collez-le dans Codex, Claude ou un autre assistant, puis laissez-le vérifier la page du skill et l'installer pour vous.
Une commande directe contourne le prompt de vérification. Examinez la source avant de l'exécuter.
AI-powered Chinese college admission advisor with 240k+ real admission data records, multi-round dialogue, major filtering, and Zhang Xuefeng methodology
triggers
["help me set up xuefeng agent for gaokao counseling","how do I configure the xuefeng college admission advisor","integrate xuefeng agent database for college recommendations","build a gaokao volunteer advisor with xuefeng agent","query admission data using xuefeng agent","set up deepseek api for xuefeng agent","how does xuefeng agent filter majors and universities","troubleshoot xuefeng agent database loading issues"]
Web search integration (Tavily AI search or Baidu fallback)
Browser-based UI with conversation history and dark mode
The agent automatically extracts student info (province, score rank, preferences) from natural language, queries the local SQLite database, performs web searches for latest data, and provides tailored "reach/match/safety" school recommendations.
Installation
Prerequisites
Python 3.10+
Windows (.bat launcher included), macOS/Linux (manual terminal launch)
Setup
# Clone or download the project
git clone https://github.com/ziqihe10-droid/xuefeng-agent.git
cd xuefeng-agent
# Install dependencies (auto-installed on first run, or manual):
pip install flask==2.3.3 openai==1.3.5 tavily-python==0.3.0
# On first run, the compressed database auto-extracts:# admission_clean.db.gz (27.6 MB) → admission_clean.db (143 MB)
Launch
Windows:
# Double-click 启动.bat# Or run manually:
python server.py
macOS/Linux:
python server.py
The server starts on http://localhost:5000 and opens automatically in your browser.
Architecture
User Query → AI Extracts (province, rank, majors)
↓
Local DB Query (admission_clean.db) + Major Keyword Filtering
↓
Web Search (Tavily or Baidu) for latest university/major info
↓
LLM Synthesizes [DB data + Web data] → Structured Response
↓
Browser UI displays with source attribution ([DB] or [Web])
Core Components
1. Database Schema
Table: admission_data
CREATE TABLE admission_data (
province TEXT, -- 省份 (e.g., "浙江", "河北")yearINTEGER, -- 年份 (2024/2025)
university TEXT, -- 学校名称
major TEXT, -- 专业名称
score INTEGER, -- 最低分
rank INTEGER, -- 位次
batch TEXT -- 批次 (本科一批/本科二批/专科)
);
CREATE INDEX idx_province_year_rank ON admission_data(province, year, rank);
CREATE INDEX idx_major ON admission_data(major);
2. Server Architecture (server.py)
from flask import Flask, request, jsonify, send_file
import sqlite3
import os
import openai
from tavily import TavilyClient
app = Flask(__name__)
DB_PATH = "admission_clean.db"# Auto-extract compressed DB on first runifnot os.path.exists(DB_PATH) and os.path.exists(f"{DB_PATH}.gz"):
import gzip
import shutil
with gzip.open(f"{DB_PATH}.gz", 'rb') as f_in:
withopen(DB_PATH, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
# Database query helperdefquery_db(province, rank, year=2025, majors=None, limit=100):
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
# Base query with rank-based filtering
query = """
SELECT university, major, score, rank, batch
FROM admission_data
WHERE province = ? AND year = ?
AND rank BETWEEN ? AND ?
"""
params = [province, year, rank - 5000, rank + 5000]
# Add major keyword filteringif majors:
major_conditions = " OR ".join(["major LIKE ?"for _ in majors])
query += f" AND ({major_conditions})"
params.extend([f"%{m}%"for m in majors])
query += " ORDER BY rank ASC LIMIT ?"
params.append(limit)
cursor.execute(query, params)
results = cursor.fetchall()
conn.close()
return [
{
"university": r[0],
"major": r[1],
"score": r[2],
"rank": r[3],
"batch": r[4]
}
for r in results
]
defweb_search(query, tavily_key=None):
"""
Search for latest university/major info
Falls back to Baidu if Tavily key not provided
"""if tavily_key:
# Tavily AI search (more accurate)
client = TavilyClient(api_key=tavily_key)
response = client.search(
query=query,
search_depth="advanced",
max_results=5
)
return response.get("results", [])
else:
# Baidu fallback (basic scraping)import requests
from bs4 import BeautifulSoup
url = f"https://www.baidu.com/s?wd={query}"
response = requests.get(url, headers={"User-Agent": "Mozilla/5.0"})
soup = BeautifulSoup(response.text, 'html.parser')
# Extract top 3 result snippets
results = []
for item in soup.select('.result')[:3]:
results.append({
"title": item.select_one('h3').text,
"snippet": item.select_one('.c-abstract').text
})
return results
Configuration
API Settings (Browser UI)
The UI stores settings in localStorage:
// Stored keys (in browser):
{
"apiKey": "sk-xxxxx", // OpenAI-compatible API key"baseUrl": "https://api.deepseek.com/v1", // Base URL"model": "deepseek-chat", // Model name"tavilyKey": "tvly-xxxxx"// Optional Tavily search key
}
Recommended Models:
DeepSeek (deepseek-chat): Most cost-effective, free tier available
Qwen (qwen-max): Good Chinese understanding
GLM (glm-4): Stable domestic option
GPT-4o: Premium option (requires VPN in China)
Environment Variables (Optional)
# For programmatic use (bypasses browser UI)export OPENAI_API_KEY="sk-xxxxx"export OPENAI_BASE_URL="https://api.deepseek.com/v1"export TAVILY_API_KEY="tvly-xxxxx"# Optional, enables AI search
defformat_school_entry(school, source):
"""
Tag each recommendation with data source
"""
tag = "[DB]"if source == "database"else"[联网]"returnf"· {school['university']}{school['major']}{school['score']}分/{school['rank']}位 {tag}"# In final response:# · 南京大学 计算机类 670分/3200位 [DB]# · 上海交大 人工智能 (最新数据:预估线665分) [联网]
Troubleshooting
Issue: Database not found
Symptom:
sqlite3.OperationalError: unable to open database file
Solution:
# Check if .gz file existsls -lh admission_clean.db.gz
# Manual extraction if auto-extract failed
gunzip admission_clean.db.gz
# Verify extractionls -lh admission_clean.db # Should be ~143 MB
Issue: Empty query results
Symptom:
Agent says "没有找到匹配的学校"
Causes & Fixes:
# 1. Rank out of range (no schools in ±5000 window)# Solution: Widen search range
params = [province, year, rank - 10000, rank + 10000]
# 2. Major keywords too strict# Solution: Use broader terms
majors = ["计算机"] # ✅ Broad
majors = ["计算机科学与技术(实验班)"] # ❌ Too specific# 3. Wrong province name# Solution: Normalize province names
province_map = {
"川": "四川", "京": "北京", "沪": "上海",
"浙": "浙江", "苏": "江苏", "粤": "广东"
}
province = province_map.get(input_province, input_province)
Issue: API timeout
Symptom:
openai.APITimeoutError: Request timed out
Solution:
# Increase timeout for large context
client = openai.OpenAI(
api_key=api_key,
base_url=base_url,
timeout=60.0# Default is 10s
)
# Or use streaming for long responses
stream = client.chat.completions.create(
model=model,
messages=messages,
stream=True
)
for chunk in stream:
print(chunk.choices[0].delta.content, end="")
Issue: Incorrect rank extraction
Symptom:
"一万三" extracted as 13 instead of 13000
Solution:
# Enhanced extraction prompt"""
位次提取规则:
- "一万三" → 13000
- "5k" → 5000
- "两万五" → 25000
- "123名" → 123
"""# Add validationdefvalidate_rank(rank, province):
# Sanity check: rank should be reasonableif rank < 100: # Likely error (e.g., "13" instead of "13000")
rank *= 1000
max_ranks = {"浙江": 300000, "河北": 500000}
if rank > max_ranks.get(province, 1000000):
raise ValueError(f"Rank {rank} out of range for {province}")
return rank
Issue: Web search returns irrelevant results
Symptom:
Baidu fallback returns ads or unrelated content
Solution:
# Use Tavily for better search (requires API key)
export TAVILY_API_KEY="tvly-xxxxx"# Or refine Baidu query with site-specific search
query = f"site:edu.cn {university}{major} 2025 录取分数线"# Filter results by domain whitelist
allowed_domains = [".edu.cn", "gaokao.chsi.com.cn", "eol.cn"]
filtered = [
r for r in results
ifany(domain in r.get("url", "") for domain in allowed_domains)
]
Knowledge Base Modules
The agent's system prompts include 17 knowledge modules:
方法论 - Zhang Xuefeng's core strategies
选科规则 - Subject selection for new高考
专业解析 - 61 major categories detailed analysis
学校联盟 - C9/985/211/双一流/行业特色高校
考研趋势 - Graduate school planning
就业数据 - Salary/employment rate by major
专科策略 - Vocational college selection
城市选择 - Regional development vs university tier trade-offs
import pandas as pd
import sqlite3
defrebuild_db():
conn = sqlite3.connect("admission_clean.db")
cursor = conn.cursor()
# Create table
cursor.execute("""
CREATE TABLE IF NOT EXISTS admission_data (
province TEXT, year INTEGER, university TEXT,
major TEXT, score INTEGER, rank INTEGER, batch TEXT
)
""")
# Import from all Excel filesfor file in glob.glob("raw_data/*.xlsx"):
province = extract_province_from_filename(file)
df = pd.read_excel(file)
df["province"] = province
df.to_sql("admission_data", conn, if_exists="append", index=False)
# Create indexes
cursor.execute("CREATE INDEX idx_province_year_rank ON admission_data(province, year, rank)")
conn.commit()