Files
agriculture-qa/app.py
zhenghu c1fca98430 feat(ui): 重构农技问答应用界面与交互体验
- 将深色科技风改为清新农业暖色调主题( centered 布局)
  - 新增流式输出,支持实时显示推理过程与回答
  - 快捷问题改为顶部标签芯片形式,移除侧边栏
  - 模型参数收折至可展开的设置面板
  - 简化文案与页面标题,优化移动端体验
2026-04-14 11:08:01 +08:00

337 lines
10 KiB
Python

"""
农技智能问答
基于大模型的农业技术知识问答应用
"""
import json
import httpx
import streamlit as st
from config import CHAT_API_URL, CHAT_MODEL, HEADERS
# ─── Page Config ────────────────────────────────────────────────────────────
st.set_page_config(
page_title="农技问答",
page_icon="🌾",
layout="centered",
initial_sidebar_state="collapsed",
)
# ─── Custom CSS ──────────────────────────────────────────────────────────────
st.markdown("""
<style>
:root {
--soil: #8b5a2b;
--leaf: #4a7c59;
--leaf-light: #6b9e75;
--wheat: #d4a574;
--cream: #faf8f3;
--paper: #ffffff;
--ink: #2c2c2c;
--ink-muted: #5a5a5a;
--border: #e5e0d5;
}
html, body, [class*="css"] {
font-family: "PingFang SC", "Microsoft YaHei", "Noto Sans SC", sans-serif;
color: var(--ink);
}
.stApp {
background: var(--cream);
}
/* Header */
.app-header {
text-align: center;
padding: 40px 0 24px;
}
.app-header h1 {
font-size: 1.75rem;
font-weight: 600;
color: var(--soil);
margin-bottom: 6px;
letter-spacing: 0.02em;
}
.app-header p {
font-size: 0.95rem;
color: var(--ink-muted);
margin: 0;
}
/* Input area */
.question-box {
background: var(--paper);
border: 1px solid var(--border);
border-radius: 16px;
padding: 20px;
margin: 16px 0 24px;
box-shadow: 0 2px 8px rgba(0,0,0,0.03);
}
/* Answer card */
.answer-card {
background: var(--paper);
border: 1px solid var(--border);
border-radius: 16px;
padding: 24px;
margin: 16px 0;
line-height: 1.85;
box-shadow: 0 2px 10px rgba(0,0,0,0.04);
}
.answer-card h3 {
font-size: 1rem;
font-weight: 600;
color: var(--leaf);
margin-bottom: 14px;
display: flex;
align-items: center;
gap: 8px;
}
/* Thinking card */
.thinking-card {
background: #f7f9f7;
border: 1px dashed var(--leaf-light);
border-radius: 12px;
padding: 16px 18px;
margin: 12px 0;
color: var(--ink-muted);
font-size: 0.92rem;
line-height: 1.7;
}
/* Quick chips */
.quick-chips {
display: flex;
flex-wrap: wrap;
gap: 10px;
justify-content: center;
padding: 8px 0 24px;
}
.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;
}
.quick-chip:hover {
border-color: var(--leaf-light);
color: var(--leaf);
background: #f9fcf9;
}
/* Alert boxes */
.alert-error {
background: #fff5f5;
border: 1px solid #ffd1d1;
border-radius: 12px;
padding: 14px 18px;
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-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>
""", unsafe_allow_html=True)
# ─── Quick Questions ─────────────────────────────────────────────────────────
QUICK_QUESTIONS = [
"水稻稻瘟病怎么防治?",
"小麦锈病怎么处理?",
"玉米什么时候浇水最合适?",
"种榴莲需要注意什么?",
]
# ─── Header ──────────────────────────────────────────────────────────────────
st.markdown("""
<div class="app-header">
<h1>🌾 农技问答</h1>
<p>有农业问题,随时来问</p>
</div>
""", 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(
"请输入您的问题",
value=st.session_state.get("user_input", ""),
height=110,
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)
# ─── Settings Panel ──────────────────────────────────────────────────────────
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:
payload = {
"model": CHAT_MODEL,
"messages": [{"role": "user", "content": user_input.strip()}],
"temperature": temperature,
"top_p": top_p,
"presence_penalty": 1.5,
"chat_template_kwargs": {"enable_thinking": enable_thinking},
"stream": True,
}
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()
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
delta = chunk.get("choices", [{}])[0].get("delta", {})
reasoning_piece = delta.get("reasoning_content", "")
if reasoning_piece:
full_reasoning += reasoning_piece
if enable_thinking:
thinking_placeholder.markdown(
f'<div class="thinking-card">'
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 content_piece:
full_content += content_piece
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,
)
if full_reasoning and enable_thinking:
thinking_placeholder.empty()
with st.expander("查看推理过程"):
st.markdown(full_reasoning)
except httpx.HTTPStatusError as e:
st.markdown(
f'<div class="alert-error">请求失败 (HTTP {e.response.status_code}): {e.response.text}</div>',
unsafe_allow_html=True,
)
except Exception as e:
st.markdown(
f'<div class="alert-error">请求异常: {e}</div>',
unsafe_allow_html=True,
)
# ─── Footer ───────────────────────────────────────────────────────────────────
st.markdown("""
<div class="app-footer">
农业技术知识问答 · 仅供参考
</div>
""", unsafe_allow_html=True)