feat(ui): 重构农技问答应用界面与交互体验

- 将深色科技风改为清新农业暖色调主题( centered 布局)
  - 新增流式输出,支持实时显示推理过程与回答
  - 快捷问题改为顶部标签芯片形式,移除侧边栏
  - 模型参数收折至可展开的设置面板
  - 简化文案与页面标题,优化移动端体验
This commit is contained in:
zhenghu
2026-04-14 11:08:01 +08:00
parent 256fe12605
commit c1fca98430

399
app.py
View File

@@ -1,156 +1,195 @@
""" """
农技智能问答 农技智能问答
基于 Qwen3.5 大模型的农业技术知识问答应用 基于大模型的农业技术知识问答应用
""" """
import json
import httpx import httpx
import streamlit as st import streamlit as st
from config import CHAT_API_URL, CHAT_MODEL, HEADERS from config import CHAT_API_URL, CHAT_MODEL, HEADERS
# ─── Page Config ──────────────────────────────────────────────────────────── # ─── Page Config ────────────────────────────────────────────────────────────
st.set_page_config( st.set_page_config(
page_title="农技智能问答", page_title="农技问答",
page_icon="🌾", page_icon="🌾",
layout="wide", layout="centered",
initial_sidebar_state="expanded", initial_sidebar_state="collapsed",
) )
# ─── Custom CSS ────────────────────────────────────────────────────────────── # ─── Custom CSS ──────────────────────────────────────────────────────────────
st.markdown(""" st.markdown("""
<style> <style>
:root { :root {
--bg-dark: #0a1628; --soil: #8b5a2b;
--bg-card: #0f2040; --leaf: #4a7c59;
--accent-green: #4ade80; --leaf-light: #6b9e75;
--accent-gold: #f59e0b; --wheat: #d4a574;
--accent-blue: #38bdf8; --cream: #faf8f3;
--text-primary: #e2e8f0; --paper: #ffffff;
--text-muted: #64748b; --ink: #2c2c2c;
--border: rgba(74, 222, 128, 0.2); --ink-muted: #5a5a5a;
--border: #e5e0d5;
} }
html, body, [class*="css"] { html, body, [class*="css"] {
font-family: "PingFang SC", "Microsoft YaHei", "Noto Serif SC", serif; font-family: "PingFang SC", "Microsoft YaHei", "Noto Sans SC", sans-serif;
background-color: var(--bg-dark); color: var(--ink);
color: var(--text-primary);
} }
.stApp { .stApp {
background: linear-gradient(135deg, #0a1628 0%, #0d1f3c 50%, #091520 100%); background: var(--cream);
} }
/* Sidebar */ /* Header */
[data-testid="stSidebar"] { .app-header {
background: linear-gradient(180deg, #0f2040 0%, #0a1628 100%); text-align: center;
border-right: 1px solid var(--border); padding: 40px 0 24px;
} }
[data-testid="stSidebar"] .stSlider label, .app-header h1 {
[data-testid="stSidebar"] .stCheckbox label { font-size: 1.75rem;
color: var(--accent-green) !important; font-weight: 600;
font-size: 0.82rem; color: var(--soil);
font-family: "JetBrains Mono", "Fira Code", "Source Code Pro", monospace; margin-bottom: 6px;
letter-spacing: 0.05em; letter-spacing: 0.02em;
}
.app-header p {
font-size: 0.95rem;
color: var(--ink-muted);
margin: 0;
} }
/* Section headers */ /* Input area */
.section-header { .question-box {
font-size: 0.75rem; background: var(--paper);
font-family: "JetBrains Mono", "Fira Code", "Source Code Pro", monospace; border: 1px solid var(--border);
letter-spacing: 0.15em; border-radius: 16px;
color: var(--accent-gold); padding: 20px;
text-transform: uppercase; margin: 16px 0 24px;
border-bottom: 1px solid rgba(245,158,11,0.3); box-shadow: 0 2px 8px rgba(0,0,0,0.03);
padding-bottom: 6px;
margin-bottom: 16px;
margin-top: 24px;
}
/* Hero title */
.hero-title {
font-size: 2rem;
font-weight: 700;
background: linear-gradient(135deg, var(--accent-green), var(--accent-blue));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
line-height: 1.2;
}
.hero-sub {
font-family: "JetBrains Mono", "Fira Code", "Source Code Pro", monospace;
font-size: 0.8rem;
color: var(--text-muted);
letter-spacing: 0.1em;
margin-top: 4px;
} }
/* Answer card */ /* Answer card */
.answer-card { .answer-card {
background: linear-gradient(135deg, #0f2040, #132b55); background: var(--paper);
border: 1px solid var(--border); border: 1px solid var(--border);
border-radius: 12px; border-radius: 16px;
padding: 24px; padding: 24px;
margin: 16px 0; margin: 16px 0;
line-height: 1.8; line-height: 1.85;
box-shadow: 0 2px 10px rgba(0,0,0,0.04);
} }
.answer-card h3 { .answer-card h3 {
color: var(--accent-green); font-size: 1rem;
font-family: "JetBrains Mono", "Fira Code", "Source Code Pro", monospace; font-weight: 600;
font-size: 0.85rem; color: var(--leaf);
letter-spacing: 0.08em; margin-bottom: 14px;
margin-bottom: 12px; display: flex;
align-items: center;
gap: 8px;
} }
/* Thinking card */ /* Thinking card */
.thinking-card { .thinking-card {
background: rgba(56, 189, 248, 0.05); background: #f7f9f7;
border: 1px solid rgba(56, 189, 248, 0.2); border: 1px dashed var(--leaf-light);
border-radius: 10px; border-radius: 12px;
padding: 18px; padding: 16px 18px;
margin: 12px 0; margin: 12px 0;
color: var(--ink-muted);
font-size: 0.92rem;
line-height: 1.7;
} }
/* Token usage */ /* Quick chips */
.token-usage { .quick-chips {
font-family: "JetBrains Mono", "Fira Code", "Source Code Pro", monospace; display: flex;
font-size: 0.78rem; flex-wrap: wrap;
color: var(--text-muted); gap: 10px;
background: rgba(255,255,255,0.03); justify-content: center;
border-radius: 6px; padding: 8px 0 24px;
padding: 8px 14px; }
margin-top: 12px; .quick-chip {
background: var(--paper);
border: 1px solid var(--border);
border-radius: 999px;
padding: 8px 16px;
font-size: 0.88rem;
color: var(--ink-muted);
cursor: pointer;
transition: all 0.2s ease;
text-decoration: none;
display: inline-block; display: inline-block;
} }
.quick-chip:hover {
/* Quick question buttons */ border-color: var(--leaf-light);
[data-testid="stSidebar"] button[kind="secondary"] { color: var(--leaf);
background: rgba(74,222,128,0.08); background: #f9fcf9;
border: 1px solid rgba(74,222,128,0.2);
color: var(--text-primary);
font-size: 0.82rem;
text-align: left;
white-space: normal;
line-height: 1.4;
transition: all 0.2s ease;
}
[data-testid="stSidebar"] button[kind="secondary"]:hover {
background: rgba(74,222,128,0.15);
border-color: rgba(74,222,128,0.4);
}
/* Override streamlit slider colors */
.stSlider [data-baseweb="slider"] [data-testid="stTickBarMin"],
.stSlider [data-baseweb="slider"] [data-testid="stTickBarMax"] {
color: var(--text-muted);
} }
/* Alert boxes */ /* Alert boxes */
.alert-error { .alert-error {
background: rgba(239,68,68,0.1); background: #fff5f5;
border-left: 3px solid #ef4444; border: 1px solid #ffd1d1;
border-radius: 0 8px 8px 0; border-radius: 12px;
padding: 12px 16px; padding: 14px 18px;
margin: 8px 0; margin: 10px 0;
font-size: 0.92rem;
color: #b33a3a;
}
/* Streamlit native overrides */
.stTextArea textarea {
border: 1px solid var(--border) !important;
border-radius: 12px !important;
font-size: 1rem !important;
color: var(--ink) !important;
background: var(--paper) !important;
}
.stTextArea textarea:focus {
border-color: var(--leaf-light) !important;
box-shadow: 0 0 0 2px rgba(74, 124, 89, 0.08) !important;
}
.stButton > button {
border-radius: 10px !important;
padding: 10px 28px !important;
font-size: 0.95rem !important;
background: var(--leaf) !important;
border: none !important;
color: #fff !important;
}
.stButton > button:hover {
background: var(--leaf-light) !important;
}
/* Settings panel */
.settings-panel {
background: var(--paper);
border: 1px solid var(--border);
border-radius: 14px;
padding: 18px 20px;
margin-bottom: 20px;
}
.settings-panel summary {
font-size: 0.9rem; font-size: 0.9rem;
font-weight: 500;
color: var(--ink-muted);
cursor: pointer;
list-style: none;
display: flex;
align-items: center;
gap: 6px;
}
.settings-panel summary::-webkit-details-marker {
display: none;
}
/* Footer */
.app-footer {
text-align: center;
font-size: 0.8rem;
color: #aaa;
padding: 32px 0 16px;
} }
</style> </style>
""", unsafe_allow_html=True) """, unsafe_allow_html=True)
@@ -158,50 +197,63 @@ html, body, [class*="css"] {
# ─── Quick Questions ───────────────────────────────────────────────────────── # ─── Quick Questions ─────────────────────────────────────────────────────────
QUICK_QUESTIONS = [ QUICK_QUESTIONS = [
"水稻稻瘟病怎么防治?什么时候打药效果最好?", "水稻稻瘟病怎么防治?",
"小麦叶片上出现铁锈色的粉状物是什么病?怎么处理?", "小麦锈病怎么处理?",
"如何判断玉米是否需要灌溉?有哪些判断方法", "玉米什么时候浇水最合适",
"如何种榴莲?怎样成熟快", "种榴莲需要注意什么",
] ]
# ─── Sidebar ───────────────────────────────────────────────────────────────── # ─── Header ─────────────────────────────────────────────────────────────────
with st.sidebar:
st.markdown('<div class="hero-title">🌾 农技问答</div>', unsafe_allow_html=True)
st.markdown('<div class="hero-sub">AGRICULTURE QA SYSTEM v1.0</div>', unsafe_allow_html=True)
st.markdown("---")
st.markdown('<div class="section-header">⚙️ 模型参数</div>', unsafe_allow_html=True)
temperature = st.slider("Temperature", 0.0, 1.0, 0.7, 0.1)
top_p = st.slider("Top P", 0.0, 1.0, 0.8, 0.1)
enable_thinking = st.checkbox("开启思维链", value=True)
st.markdown('<div class="section-header">💡 快捷提问</div>', unsafe_allow_html=True)
for q in QUICK_QUESTIONS:
if st.button(q, key=q):
st.session_state.user_input = q
# ─── Main Layout ─────────────────────────────────────────────────────────────
st.markdown(""" st.markdown("""
<div style="display:flex; align-items:baseline; gap:16px; margin-bottom:4px;"> <div class="app-header">
<div class="hero-title">农技智能问答</div> <h1>🌾 农技问答</h1>
<p>有农业问题,随时来问</p>
</div> </div>
<div class="hero-sub">Powered by Qwen3.5 &nbsp;|&nbsp; 支持思维链推理的农业技术知识问答</div>
""", unsafe_allow_html=True) """, unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True) # ─── Quick Questions ─────────────────────────────────────────────────────────
chips_html = '<div class="quick-chips">'
for q in QUICK_QUESTIONS:
chips_html += f'<span class="quick-chip" onclick="">{q}</span>'
chips_html += '</div>'
st.markdown(chips_html, unsafe_allow_html=True)
# 输入区域 # Handle chip clicks via native buttons (invisible, placed neatly)
cols = st.columns(len(QUICK_QUESTIONS))
for i, q in enumerate(QUICK_QUESTIONS):
with cols[i]:
st.markdown("<div style='margin-top:-52px;'>" + " " + "</div>", unsafe_allow_html=True)
if st.button(q, key=f"chip_{q}", use_container_width=True):
st.session_state.user_input = q
st.rerun()
# ─── Input ───────────────────────────────────────────────────────────────────
st.markdown('<div class="question-box">', unsafe_allow_html=True)
user_input = st.text_area( user_input = st.text_area(
"请输入您的农业问题", "请输入您的问题",
value=st.session_state.get("user_input", ""), value=st.session_state.get("user_input", ""),
height=120, height=110,
placeholder="例如:水稻稻瘟病怎么防治?", placeholder="例如:水稻稻瘟病怎么防治?",
label_visibility="collapsed",
) )
col1, col2 = st.columns([1, 6])
with col1:
submitted = st.button("发送", use_container_width=True)
st.markdown('</div>', unsafe_allow_html=True)
if st.button("提交", type="primary") and user_input.strip(): # ─── Settings Panel ──────────────────────────────────────────────────────────
with st.spinner("模型正在思考中..."): with st.expander("⚙️ 模型设置"):
col_t, col_p, col_c = st.columns(3)
with col_t:
temperature = st.slider("Temperature", 0.0, 1.0, 0.7, 0.1)
with col_p:
top_p = st.slider("Top P", 0.0, 1.0, 0.8, 0.1)
with col_c:
enable_thinking = st.checkbox("显示推理过程", value=True)
# ─── Request & Stream ────────────────────────────────────────────────────────
if submitted and user_input.strip():
try: try:
payload = { payload = {
"model": CHAT_MODEL, "model": CHAT_MODEL,
@@ -210,39 +262,60 @@ if st.button("提交", type="primary") and user_input.strip():
"top_p": top_p, "top_p": top_p,
"presence_penalty": 1.5, "presence_penalty": 1.5,
"chat_template_kwargs": {"enable_thinking": enable_thinking}, "chat_template_kwargs": {"enable_thinking": enable_thinking},
"stream": True,
} }
resp = httpx.post(
CHAT_API_URL, headers=HEADERS, json=payload, timeout=120 thinking_placeholder = st.empty()
) answer_placeholder = st.empty()
full_reasoning = ""
full_content = ""
with httpx.stream(
"POST", CHAT_API_URL, headers=HEADERS, json=payload, timeout=120
) as resp:
resp.raise_for_status() resp.raise_for_status()
data = resp.json() for line in resp.iter_lines():
if not line.startswith("data: "):
continue
data_str = line[6:]
if data_str == "[DONE]":
break
try:
chunk = json.loads(data_str)
except json.JSONDecodeError:
continue
choice = data["choices"][0]["message"] delta = chunk.get("choices", [{}])[0].get("delta", {})
reasoning = choice.get("reasoning_content", "")
content = choice["content"]
usage = data["usage"]
# 显示回答 reasoning_piece = delta.get("reasoning_content", "")
st.markdown(f""" if reasoning_piece:
<div class="answer-card"> full_reasoning += reasoning_piece
<h3>💬 模型回答</h3> if enable_thinking:
<div style="color: var(--text-primary); font-size: 0.95rem;">{content}</div> thinking_placeholder.markdown(
</div> f'<div class="thinking-card">'
""", unsafe_allow_html=True) f'<strong>正在思考...</strong><br>'
f'<div style="white-space:pre-wrap;margin-top:6px;">{full_reasoning}</div>'
f'</div>',
unsafe_allow_html=True,
)
# 显示思考过程(可折叠) content_piece = delta.get("content", "")
if reasoning and enable_thinking: if content_piece:
with st.expander("🧠 查看思考过程"): full_content += content_piece
st.markdown(reasoning) answer_placeholder.markdown(
f'<div class="answer-card">'
f'<h3>🌱 回答</h3>'
f'<div style="color:var(--ink);font-size:1rem;white-space:pre-wrap;">'
f'{full_content}</div>'
f'</div>',
unsafe_allow_html=True,
)
# Token 用量 if full_reasoning and enable_thinking:
st.markdown(f""" thinking_placeholder.empty()
<div class="token-usage"> with st.expander("查看推理过程"):
Token 用量 — 输入: {usage['prompt_tokens']} | \ st.markdown(full_reasoning)
输出: {usage['completion_tokens']} | \
合计: {usage['total_tokens']}
</div>
""", unsafe_allow_html=True)
except httpx.HTTPStatusError as e: except httpx.HTTPStatusError as e:
st.markdown( st.markdown(
@@ -256,10 +329,8 @@ if st.button("提交", type="primary") and user_input.strip():
) )
# ─── Footer ─────────────────────────────────────────────────────────────────── # ─── Footer ───────────────────────────────────────────────────────────────────
st.markdown("<br>", unsafe_allow_html=True)
st.markdown(""" st.markdown("""
<div style="text-align:center; font-family:'JetBrains Mono',monospace; font-size:0.72rem; <div class="app-footer">
color:#334155; padding:16px; border-top:1px solid rgba(74,222,128,0.1);"> 农业技术知识问答 · 仅供参考
Qwen3.5 + Thinking Chain &nbsp;|&nbsp; 农技智能问答系统
</div> </div>
""", unsafe_allow_html=True) """, unsafe_allow_html=True)