前端转 AI 100 天 Day 55:RAG 项目实战(四)——前端完善,做一个能用的产品

前端转 AI 第 55 天:RAG 项目实战(四)- 前端完善,做一个能用的产品

昨日回顾

Day 54 上了多轮对话,RAG 能"接着聊"了。

但前端界面还是"最简陋的 Demo"------没有会话列表、没有反馈、没有错误处理。

今天发挥你的老本行------把前端打磨成"能用的产品"。

Day 55 目标:完整的 React 知识库问答界面,包含会话管理、打字机、来源展示、反馈按钮、错误处理。


一、产品级界面该有什么

1. 一个真正的知识库产品

对比"Demo"和"产品":

功能 Demo 产品
多会话 单次对话 侧边栏管理多个
来源展示 只显示答案 展示引用 + 相关度
流式效果 无 打字机
错误处理 崩了就崩了 友好提示 + 重试
加载状态 空白 Skeleton + Loading
反馈 无 点赞/点踩
会话持久 刷新丢失 后端存储
Markdown 纯文本 渲染表格、代码

今天把这 8 项全做上。

2. 前端视角:这是你的主场

做了这么多年前端,你比纯后端工程师更懂"产品体验":

  • 一个按钮的反馈 → 让用户觉得"有反应"
  • 一个 Loading → 让用户觉得"在努力"
  • 一个错误提示 → 让用户"知道怎么回事"
  • 一个细节动效 → 让用户"觉得高级"

在 AI 产品里,这些"软技能"就是"护城河"------ 因为很多 AI 产品的后端都差不多,前端的差距是"天壤之别"。

今天的主题就是:用你前端的能力,把 RAG 从"能用"变成"好用"。


二、项目准备

1. 技术栈

延续 Day 44 的技术栈:

层 选型
构建 Vite
框架 React 18
语言 TypeScript
样式 Tailwind CSS
状态 Zustand
图标 lucide-react
Markdown react-markdown + remark-gfm

新增依赖:

bash 复制代码
cd day55/enterprise-kb/frontend
npm install react-markdown remark-gfm zustand lucide-react
npm install -D tailwindcss postcss autoprefixer

2. 项目结构

复制代码
frontend/
├── src/
│   ├── main.tsx
│   ├── App.tsx
│   ├── index.css
│   │
│   ├── api/
│   │   └── client.ts
│   │
│   ├── store/
│   │   └── kbStore.ts
│   │
│   ├── hooks/
│   │   ├── useStreamAsk.ts
│   │   └── useSessions.ts
│   │
│   ├── components/
│   │   ├── Layout.tsx
│   │   ├── Sidebar.tsx
│   │   ├── ChatArea.tsx
│   │   ├── MessageItem.tsx
│   │   ├── SourceCard.tsx
│   │   ├── InputBox.tsx
│   │   ├── EmptyState.tsx
│   │   ├── LoadingDots.tsx
│   │   ├── FeedbackButtons.tsx
│   │   └── Toast.tsx
│   │
│   ├── types/
│   │   └── index.ts
│   │
│   └── utils/
│       └── format.ts
│
├── index.html
├── package.json
├── vite.config.ts
├── tailwind.config.js
└── .env

3. 初始化

bash 复制代码
npm create vite@latest frontend -- --template react-ts
cd frontend
npm install
npm install zustand lucide-react react-markdown remark-gfm
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

tailwind.config.js:

js 复制代码
export default {
  content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"],
  theme: {
    extend: {
      animation: {
        "pulse-dot": "pulse-dot 1.4s infinite ease-in-out both",
      },
      keyframes: {
        "pulse-dot": {
          "0%, 80%, 100%": { transform: "scale(0)" },
          "40%": { transform: "scale(1)" },
        },
      },
    },
  },
  plugins: [],
};

src/index.css:

css 复制代码
@tailwind base;
@tailwind components;
@tailwind utilities;

html, body, #root {
  height: 100%;
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}

/* 滚动条美化 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}
::-webkit-scrollbar-thumb {
  background: #d1d5db;
  border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
  background: #9ca3af;
}

.env:

复制代码
VITE_API_BASE=http://localhost:8000

三、类型定义与 API

1. 类型

src/types/index.ts:

typescript 复制代码
export interface Source {
  source: string;
  score: number;
  content: string;
}

export interface Message {
  id: string;
  role: "user" | "assistant";
  content: string;
  sources?: Source[];
  streaming?: boolean;
  timestamp: number;
  feedback?: "up" | "down" | null;
}

export interface Session {
  id: string;
  title: string;
  turn_count: number;
  updated_at: string;
}

// SSE 事件
export type StreamEvent =
  | {
      type: "meta";
      data: {
        session_id: string;
        rewritten_question?: string;
        sources: Source[];
      };
    }
  | { type: "delta"; content: string }
  | { type: "done"; data: { session_id: string; latency_ms: number } }
  | { type: "error"; message: string };

2. API 客户端

src/api/client.ts:

typescript 复制代码
import type { Session, StreamEvent } from "../types";

const API_BASE = import.meta.env.VITE_API_BASE || "http://localhost:8000";

async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
  const res = await fetch(`${API_BASE}${path}`, {
    ...options,
    headers: {
      "Content-Type": "application/json",
      ...options.headers,
    },
  });

  if (!res.ok) {
    const error = await res.json().catch(() => ({ detail: res.statusText }));
    throw new Error(error.detail || `HTTP ${res.status}`);
  }

  return res.json();
}

// ============ 问答 ============

export async function* streamAsk(
  question: string,
  sessionId?: string | null,
  docTypes?: string[]
): AsyncGenerator<StreamEvent> {
  const res = await fetch(`${API_BASE}/api/qa/stream`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      question,
      session_id: sessionId,
      doc_types: docTypes,
    }),
  });

  if (!res.ok) throw new Error(`HTTP ${res.status}`);

  const reader = res.body!.getReader();
  const decoder = new TextDecoder();
  let buffer = "";

  try {
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      buffer += decoder.decode(value, { stream: true });
      const parts = buffer.split("\n\n");
      buffer = parts.pop() || "";

      for (const part of parts) {
        if (!part.trim()) continue;
        const line = part.split("\n").find((l) => l.startsWith("data: "));
        if (!line) continue;
        yield JSON.parse(line.slice(6));
      }
    }
  } finally {
    reader.releaseLock();
  }
}

// ============ 会话管理 ============

export async function listSessions(): Promise<Session[]> {
  return request("/api/qa/sessions");
}

export async function getSession(sessionId: string): Promise<any> {
  return request(`/api/qa/sessions/${sessionId}`);
}

export async function deleteSession(sessionId: string): Promise<void> {
  await request(`/api/qa/sessions/${sessionId}`, { method: "DELETE" });
}

// ============ 反馈 ============

export async function sendFeedback(
  sessionId: string,
  messageIndex: number,
  feedback: "up" | "down"
): Promise<void> {
  // 实际场景要有后端接口
  console.log("Feedback:", { sessionId, messageIndex, feedback });
}

四、状态管理

src/store/kbStore.ts:

typescript 复制代码
import { create } from "zustand";
import type { Message, Session, Source } from "../types";

interface KBStore {
  // 会话
  sessions: Session[];
  currentSessionId: string | null;

  // 消息
  messages: Message[];

  // UI 状态
  streaming: boolean;
  loadingSessions: boolean;
  error: string | null;

  // Actions
  setSessions: (sessions: Session[]) => void;
  setCurrentSession: (id: string | null) => void;
  setStreaming: (v: boolean) => void;
  setLoadingSessions: (v: boolean) => void;
  setError: (e: string | null) => void;

  addMessage: (msg: Partial<Message>) => string;
  appendToLast: (text: string) => void;
  setLastSources: (sources: Source[]) => void;
  setMessageFeedback: (id: string, feedback: "up" | "down") => void;

  clearMessages: () => void;
  newSession: () => void;
}

function genId() {
  return Math.random().toString(36).slice(2, 10);
}

export const useKBStore = create<KBStore>((set, get) => ({
  sessions: [],
  currentSessionId: null,
  messages: [],
  streaming: false,
  loadingSessions: false,
  error: null,

  setSessions: (sessions) => set({ sessions }),
  setCurrentSession: (id) => set({ currentSessionId: id }),
  setStreaming: (v) => set({ streaming: v }),
  setLoadingSessions: (v) => set({ loadingSessions: v }),
  setError: (e) => set({ error: e }),

  addMessage: (msg) => {
    const id = genId();
    const message: Message = {
      id,
      role: msg.role || "user",
      content: msg.content || "",
      timestamp: Date.now(),
      sources: msg.sources,
      streaming: msg.streaming,
      feedback: msg.feedback ?? null,
    };
    set((s) => ({ messages: [...s.messages, message] }));
    return id;
  },

  appendToLast: (text) => {
    set((s) => {
      const messages = [...s.messages];
      const last = messages[messages.length - 1];
      if (last && last.role === "assistant") {
        messages[messages.length - 1] = {
          ...last,
          content: last.content + text,
        };
      }
      return { messages };
    });
  },

  setLastSources: (sources) => {
    set((s) => {
      const messages = [...s.messages];
      const last = messages[messages.length - 1];
      if (last && last.role === "assistant") {
        messages[messages.length - 1] = { ...last, sources };
      }
      return { messages };
    });
  },

  setMessageFeedback: (id, feedback) => {
    set((s) => ({
      messages: s.messages.map((m) =>
        m.id === id ? { ...m, feedback } : m
      ),
    }));
  },

  clearMessages: () => set({ messages: [], currentSessionId: null, error: null }),

  newSession: () =>
    set({ messages: [], currentSessionId: null, error: null }),
}));

为什么用 Zustand 而不是 Redux?

简洁------几行代码一个 store,没有 boilerplate。

做过大型前端项目的你,会欣赏这种"轻量但够用"。


五、核心 Hook

src/hooks/useStreamAsk.ts:

typescript 复制代码
import { useRef, useCallback } from "react";
import { streamAsk, listSessions } from "../api/client";
import { useKBStore } from "../store/kbStore";

export function useStreamAsk() {
  const abortRef = useRef<AbortController | null>(null);

  const {
    currentSessionId,
    addMessage,
    appendToLast,
    setLastSources,
    setCurrentSession,
    setStreaming,
    setError,
    setSessions,
  } = useKBStore();

  const stop = useCallback(() => {
    abortRef.current?.abort();
    abortRef.current = null;
    setStreaming(false);
  }, [setStreaming]);

  const send = useCallback(
    async (question: string, docTypes?: string[]) => {
      if (!question.trim()) return;

      setError(null);

      // 用户消息
      addMessage({ role: "user", content: question });

      // 空的助手消息(占位)
      addMessage({ role: "assistant", content: "", streaming: true });

      setStreaming(true);

      const controller = new AbortController();
      abortRef.current = controller;

      try {
        for await (const event of streamAsk(
          question,
          currentSessionId,
          docTypes
        )) {
          switch (event.type) {
            case "meta":
              if (!currentSessionId) {
                setCurrentSession(event.data.session_id);
              }
              if (event.data.sources?.length) {
                setLastSources(event.data.sources);
              }
              break;

            case "delta":
              appendToLast(event.content);
              break;

            case "done":
              setStreaming(false);
              // 刷新会话列表
              listSessions().then(setSessions).catch(console.error);
              break;

            case "error":
              setError(event.message);
              appendToLast(`\n\n❌ ${event.message}`);
              break;
          }
        }
      } catch (err: any) {
        if (err.name === "AbortError") {
          appendToLast("\n\n_[已停止]_");
        } else {
          setError(err.message);
          appendToLast(`\n\n❌ 出错了:${err.message}`);
        }
      } finally {
        setStreaming(false);
        abortRef.current = null;
      }
    },
    [
      currentSessionId,
      addMessage,
      appendToLast,
      setLastSources,
      setCurrentSession,
      setStreaming,
      setError,
      setSessions,
    ]
  );

  return { send, stop };
}

src/hooks/useSessions.ts:

typescript 复制代码
import { useEffect, useCallback } from "react";
import { listSessions, getSession, deleteSession } from "../api/client";
import { useKBStore } from "../store/kbStore";

export function useSessions() {
  const {
    sessions,
    setSessions,
    setLoadingSessions,
    currentSessionId,
    setCurrentSession,
    clearMessages,
    addMessage,
    newSession,
  } = useKBStore();

  // 初始加载
  useEffect(() => {
    setLoadingSessions(true);
    listSessions()
      .then(setSessions)
      .catch(console.error)
      .finally(() => setLoadingSessions(false));
  }, [setSessions, setLoadingSessions]);

  // 切换会话
  const switchSession = useCallback(
    async (sessionId: string) => {
      if (sessionId === currentSessionId) return;

      try {
        const data = await getSession(sessionId);
        clearMessages();
        setCurrentSession(sessionId);

        // 恢复消息
        for (const turn of data.turns || []) {
          addMessage({
            role: turn.role,
            content: turn.content,
            sources: turn.sources,
          });
        }
      } catch (e) {
        console.error(e);
      }
    },
    [currentSessionId, clearMessages, setCurrentSession, addMessage]
  );

  // 删除会话
  const removeSession = useCallback(
    async (sessionId: string) => {
      await deleteSession(sessionId);
      const updated = sessions.filter((s) => s.id !== sessionId);
      setSessions(updated);
      if (sessionId === currentSessionId) {
        newSession();
      }
    },
    [sessions, currentSessionId, setSessions, newSession]
  );

  return { sessions, switchSession, removeSession, newSession };
}

六、组件实现

1. 布局

src/components/Layout.tsx:

tsx 复制代码
import { Sidebar } from "./Sidebar";
import { ChatArea } from "./ChatArea";
import { Toast } from "./Toast";

export function Layout() {
  return (
    <div className="flex h-full bg-gray-50">
      <Sidebar />
      <div className="flex-1 flex flex-col min-w-0">
        <ChatArea />
      </div>
      <Toast />
    </div>
  );
}

2. 侧边栏

src/components/Sidebar.tsx:

tsx 复制代码
import { Plus, MessageSquare, Trash2, BookOpen } from "lucide-react";
import { useKBStore } from "../store/kbStore";
import { useSessions } from "../hooks/useSessions";
import { formatRelativeTime } from "../utils/format";

export function Sidebar() {
  const { sessions, currentSessionId, newSession } = useKBStore();
  const { switchSession, removeSession } = useSessions();

  const handleDelete = async (id: string, e: React.MouseEvent) => {
    e.stopPropagation();
    if (!confirm("确定删除这个会话?")) return;
    await removeSession(id);
  };

  return (
    <aside className="w-64 bg-slate-900 text-slate-100 flex flex-col flex-shrink-0">
      {/* Logo */}
      <div className="p-4 flex items-center gap-2 border-b border-slate-700">
        <BookOpen size={20} className="text-blue-400" />
        <span className="font-semibold">企业知识库</span>
      </div>

      {/* 新建 */}
      <div className="p-3">
        <button
          onClick={newSession}
          className="w-full px-3 py-2 rounded-lg border border-slate-700 
                     hover:bg-slate-800 flex items-center gap-2 text-sm 
                     transition-colors"
        >
          <Plus size={16} />
          新建对话
        </button>
      </div>

      {/* 会话列表 */}
      <div className="flex-1 overflow-y-auto px-2 py-1">
        {sessions.length === 0 ? (
          <div className="text-xs text-slate-500 p-4 text-center">
            还没有会话
          </div>
        ) : (
          sessions.map((s) => (
            <div
              key={s.id}
              onClick={() => switchSession(s.id)}
              className={`group px-3 py-2 rounded-lg mb-1 cursor-pointer 
                         flex items-start gap-2 transition-colors
                ${
                  s.id === currentSessionId
                    ? "bg-slate-700"
                    : "hover:bg-slate-800"
                }`}
            >
              <MessageSquare
                size={14}
                className="flex-shrink-0 mt-0.5 text-slate-400"
              />
              <div className="flex-1 min-w-0">
                <div className="text-sm truncate">{s.title || "未命名"}</div>
                <div className="text-xs text-slate-500 mt-0.5">
                  {s.turn_count / 2} 轮 · {formatRelativeTime(s.updated_at)}
                </div>
              </div>
              <button
                onClick={(e) => handleDelete(s.id, e)}
                className="opacity-0 group-hover:opacity-100 text-slate-400 
                           hover:text-red-400 transition-opacity"
                title="删除"
              >
                <Trash2 size={14} />
              </button>
            </div>
          ))
        )}
      </div>

      {/* 底部信息 */}
      <div className="p-4 text-xs text-slate-500 border-t border-slate-800">
        <div>基于 RAG 的知识库</div>
        <div className="mt-1">v0.1.0</div>
      </div>
    </aside>
  );
}

3. 聊天区

src/components/ChatArea.tsx:

tsx 复制代码
import { useEffect, useRef } from "react";
import { useKBStore } from "../store/kbStore";
import { MessageItem } from "./MessageItem";
import { EmptyState } from "./EmptyState";
import { InputBox } from "./InputBox";

export function ChatArea() {
  const messages = useKBStore((s) => s.messages);
  const bottomRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages]);

  return (
    <>
      <div className="flex-1 overflow-y-auto">
        {messages.length === 0 ? (
          <EmptyState />
        ) : (
          <div className="max-w-4xl mx-auto px-6 py-6 space-y-6">
            {messages.map((m) => (
              <MessageItem key={m.id} message={m} />
            ))}
            <div ref={bottomRef} />
          </div>
        )}
      </div>
      <InputBox />
    </>
  );
}

4. 空状态

src/components/EmptyState.tsx:

tsx 复制代码
import { BookOpen } from "lucide-react";

const SUGGESTIONS = [
  "年假有几天?",
  "怎么上传文档?",
  "差旅住宿标准是多少?",
  "API 限流是多少?",
];

export function EmptyState() {
  return (
    <div className="h-full flex items-center justify-center">
      <div className="text-center max-w-2xl px-6">
        <div className="inline-flex items-center justify-center w-16 h-16 
                        rounded-full bg-blue-100 mb-6">
          <BookOpen size={28} className="text-blue-600" />
        </div>

        <h1 className="text-2xl font-semibold text-gray-900 mb-2">
          企业知识库助手
        </h1>
        <p className="text-gray-500 mb-8">
          基于内部文档回答你的问题,答案带引用可追溯
        </p>

        <div className="grid grid-cols-2 gap-3 max-w-lg mx-auto">
          {SUGGESTIONS.map((s) => (
            <button
              key={s}
              onClick={() => {
                const input = document.querySelector<HTMLInputElement>("input[data-chat-input]");
                if (input) {
                  input.value = s;
                  input.dispatchEvent(new Event("input", { bubbles: true }));
                  input.focus();
                }
              }}
              className="p-3 text-left text-sm bg-white border border-gray-200 
                         rounded-lg hover:border-blue-400 hover:shadow-sm 
                         transition-all"
            >
              {s}
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

5. 消息项(含 Markdown 渲染)

src/components/MessageItem.tsx:

tsx 复制代码
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import type { Message } from "../types";
import { SourceCard } from "./SourceCard";
import { FeedbackButtons } from "./FeedbackButtons";
import { LoadingDots } from "./LoadingDots";

export function MessageItem({ message }: { message: Message }) {
  const isUser = message.role === "user";

  return (
    <div className={`flex ${isUser ? "justify-end" : "justify-start"}`}>
      <div className={`max-w-[85%] ${isUser ? "" : "w-full"}`}>
        {/* 角色标签 */}
        {!isUser && (
          <div className="flex items-center gap-2 mb-2 text-xs text-gray-500">
            <div className="w-6 h-6 rounded-full bg-blue-100 flex items-center 
                            justify-center text-blue-600 font-medium">
              AI
            </div>
            <span>知识库助手</span>
          </div>
        )}

        {/* 内容 */}
        <div
          className={`rounded-2xl px-4 py-3 ${
            isUser
              ? "bg-blue-600 text-white"
              : "bg-white border border-gray-200 text-gray-900"
          }`}
        >
          {isUser ? (
            <div className="whitespace-pre-wrap break-words">
              {message.content}
            </div>
          ) : (
            <>
              {message.content ? (
                <div className="markdown-body prose prose-sm max-w-none 
                                prose-p:my-2 prose-ul:my-2 prose-ol:my-2 
                                prose-li:my-0 prose-h1:text-xl prose-h2:text-lg 
                                prose-h3:text-base">
                  <ReactMarkdown remarkPlugins={[remarkGfm]}>
                    {message.content}
                  </ReactMarkdown>
                </div>
              ) : (
                <LoadingDots />
              )}
              {message.streaming && message.content && (
                <span className="inline-block w-1 h-4 bg-gray-400 
                                 ml-0.5 animate-pulse align-middle" />
              )}
            </>
          )}
        </div>

        {/* 来源 */}
        {!isUser && message.sources && message.sources.length > 0 && (
          <div className="mt-3 space-y-2">
            <div className="text-xs text-gray-500 font-medium">
              📚 参考来源({message.sources.length})
            </div>
            <div className="space-y-1.5">
              {message.sources.map((s, i) => (
                <SourceCard key={i} source={s} index={i + 1} />
              ))}
            </div>
          </div>
        )}

        {/* 反馈按钮 */}
        {!isUser && !message.streaming && message.content && (
          <FeedbackButtons messageId={message.id} feedback={message.feedback} />
        )}
      </div>
    </div>
  );
}

6. 来源卡片

src/components/SourceCard.tsx:

tsx 复制代码
import { useState } from "react";
import { FileText, ChevronDown, ChevronUp } from "lucide-react";
import type { Source } from "../types";

export function SourceCard({ source, index }: { source: Source; index: number }) {
  const [expanded, setExpanded] = useState(false);

  // 相关度可视化
  const scorePercent = Math.min(100, Math.max(0, source.score * 10));
  const scoreColor =
    source.score > 3 ? "bg-green-500"
    : source.score > 1 ? "bg-yellow-500"
    : "bg-gray-400";

  return (
    <div className="border border-gray-200 rounded-lg bg-gray-50 overflow-hidden">
      <button
        onClick={() => setExpanded(!expanded)}
        className="w-full px-3 py-2 flex items-center gap-2 text-sm 
                   hover:bg-gray-100 transition-colors text-left"
      >
        <FileText size={14} className="text-gray-500 flex-shrink-0" />
        <span className="font-medium text-gray-700 truncate">
          {index}. {source.source}
        </span>

        {/* 相关度条 */}
        <div className="flex items-center gap-1.5 ml-auto flex-shrink-0">
          <div className="w-12 h-1.5 bg-gray-200 rounded-full overflow-hidden">
            <div
              className={`h-full ${scoreColor} transition-all`}
              style={{ width: `${scorePercent}%` }}
            />
          </div>
          <span className="text-xs text-gray-500 tabular-nums w-8">
            {source.score.toFixed(1)}
          </span>
          {expanded ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
        </div>
      </button>

      {expanded && (
        <div className="px-3 py-2 text-xs text-gray-600 bg-white 
                        border-t border-gray-200 whitespace-pre-wrap">
          {source.content}
        </div>
      )}
    </div>
  );
}

关键设计:

  • 相关度可视化:绿色/黄色/灰色
  • 可展开:默认收起,点击看全文
  • 紧凑:不占主视觉

7. 反馈按钮

src/components/FeedbackButtons.tsx:

tsx 复制代码
import { ThumbsUp, ThumbsDown, Check } from "lucide-react";
import { useKBStore } from "../store/kbStore";
import { sendFeedback } from "../api/client";

export function FeedbackButtons({
  messageId,
  feedback,
}: {
  messageId: string;
  feedback?: "up" | "down" | null;
}) {
  const { setMessageFeedback, currentSessionId } = useKBStore();

  const handleFeedback = async (type: "up" | "down") => {
    // 已点过就不重复
    if (feedback === type) return;

    setMessageFeedback(messageId, type);

    // 上报(可选)
    if (currentSessionId) {
      await sendFeedback(currentSessionId, 0, type).catch(console.error);
    }
  };

  return (
    <div className="mt-2 flex items-center gap-2 text-xs text-gray-400">
      <span>这个回答有帮助吗?</span>
      <button
        onClick={() => handleFeedback("up")}
        className={`p-1.5 rounded hover:bg-gray-100 transition-colors ${
          feedback === "up" ? "text-green-600 bg-green-50" : "hover:text-gray-700"
        }`}
        title="有帮助"
      >
        {feedback === "up" ? <Check size={14} /> : <ThumbsUp size={14} />}
      </button>
      <button
        onClick={() => handleFeedback("down")}
        className={`p-1.5 rounded hover:bg-gray-100 transition-colors ${
          feedback === "down" ? "text-red-600 bg-red-50" : "hover:text-gray-700"
        }`}
        title="没帮助"
      >
        <ThumbsDown size={14} />
      </button>
    </div>
  );
}

8. Loading 动画

src/components/LoadingDots.tsx:

tsx 复制代码
export function LoadingDots() {
  return (
    <div className="flex items-center gap-1 py-1">
      <div className="w-2 h-2 rounded-full bg-gray-400 animate-pulse-dot" 
           style={{ animationDelay: "0ms" }} />
      <div className="w-2 h-2 rounded-full bg-gray-400 animate-pulse-dot" 
           style={{ animationDelay: "160ms" }} />
      <div className="w-2 h-2 rounded-full bg-gray-400 animate-pulse-dot" 
           style={{ animationDelay: "320ms" }} />
    </div>
  );
}

9. 输入框

src/components/InputBox.tsx:

tsx 复制代码
import { useState, useRef, useEffect } from "react";
import { Send, Square, Filter } from "lucide-react";
import { useKBStore } from "../store/kbStore";
import { useStreamAsk } from "../hooks/useStreamAsk";

const DOC_TYPE_LABELS: Record<string, string> = {
  hr: "人事",
  product: "产品",
  tech: "技术",
};

export function InputBox() {
  const [text, setText] = useState("");
  const [docType, setDocType] = useState<string>("");
  const streaming = useKBStore((s) => s.streaming);
  const { send, stop } = useStreamAsk();
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  const handleSubmit = () => {
    if (streaming || !text.trim()) return;
    send(text, docType ? [docType] : undefined);
    setText("");
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSubmit();
    }
  };

  // 自适应高度
  useEffect(() => {
    const el = textareaRef.current;
    if (!el) return;
    el.style.height = "auto";
    el.style.height = Math.min(el.scrollHeight, 200) + "px";
  }, [text]);

  return (
    <div className="border-t border-gray-200 bg-white">
      <div className="max-w-4xl mx-auto p-4">
        {/* 过滤栏 */}
        <div className="flex items-center gap-2 mb-2 text-xs">
          <Filter size={12} className="text-gray-400" />
          <span className="text-gray-500">范围:</span>
          <div className="flex gap-1">
            <FilterChip active={!docType} onClick={() => setDocType("")}>
              全部
            </FilterChip>
            {Object.entries(DOC_TYPE_LABELS).map(([k, label]) => (
              <FilterChip
                key={k}
                active={docType === k}
                onClick={() => setDocType(k)}
              >
                {label}
              </FilterChip>
            ))}
          </div>
        </div>

        {/* 输入框 */}
        <div className="flex items-end gap-2 border border-gray-300 rounded-xl 
                        bg-white shadow-sm focus-within:border-blue-400 
                        focus-within:ring-2 focus-within:ring-blue-100 
                        transition-all">
          <textarea
            ref={textareaRef}
            data-chat-input
            value={text}
            onChange={(e) => setText(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder="输入你的问题... (Enter 发送,Shift+Enter 换行)"
            className="flex-1 resize-none px-4 py-3 outline-none 
                       bg-transparent max-h-52"
            rows={1}
            disabled={streaming}
          />

          {streaming ? (
            <button
              onClick={stop}
              className="m-2 p-2.5 bg-gray-100 hover:bg-gray-200 
                         rounded-lg transition-colors"
              title="停止生成"
            >
              <Square size={16} className="fill-gray-700" />
            </button>
          ) : (
            <button
              onClick={handleSubmit}
              disabled={!text.trim()}
              className="m-2 p-2.5 bg-blue-600 text-white rounded-lg 
                         hover:bg-blue-700 disabled:opacity-40 
                         disabled:cursor-not-allowed transition-colors"
              title="发送"
            >
              <Send size={16} />
            </button>
          )}
        </div>

        <div className="mt-2 text-xs text-gray-400 text-center">
          AI 会基于内部文档回答,可能不完美,请核实重要信息
        </div>
      </div>
    </div>
  );
}

function FilterChip({
  active,
  onClick,
  children,
}: {
  active: boolean;
  onClick: () => void;
  children: React.ReactNode;
}) {
  return (
    <button
      onClick={onClick}
      className={`px-2 py-1 rounded transition-colors ${
        active
          ? "bg-blue-100 text-blue-700 font-medium"
          : "bg-gray-100 text-gray-600 hover:bg-gray-200"
      }`}
    >
      {children}
    </button>
  );
}

10. Toast

src/components/Toast.tsx:

tsx 复制代码
import { useEffect } from "react";
import { AlertCircle, X } from "lucide-react";
import { useKBStore } from "../store/kbStore";

export function Toast() {
  const error = useKBStore((s) => s.error);
  const setError = useKBStore((s) => s.setError);

  useEffect(() => {
    if (error) {
      const timer = setTimeout(() => setError(null), 5000);
      return () => clearTimeout(timer);
    }
  }, [error, setError]);

  if (!error) return null;

  return (
    <div className="fixed bottom-6 right-6 max-w-md z-50 animate-in 
                    slide-in-from-bottom-2">
      <div className="bg-red-50 border border-red-200 rounded-lg shadow-lg 
                      px-4 py-3 flex items-start gap-3">
        <AlertCircle size={18} className="text-red-600 flex-shrink-0 mt-0.5" />
        <div className="flex-1 text-sm text-red-800">{error}</div>
        <button
          onClick={() => setError(null)}
          className="text-red-400 hover:text-red-600"
        >
          <X size={16} />
        </button>
      </div>
    </div>
  );
}

11. 工具函数

src/utils/format.ts:

typescript 复制代码
export function formatRelativeTime(isoString: string): string {
  if (!isoString) return "";

  const date = new Date(isoString);
  const now = new Date();
  const diffMs = now.getTime() - date.getTime();
  const diffMin = Math.floor(diffMs / 60000);
  const diffHour = Math.floor(diffMs / 3600000);
  const diffDay = Math.floor(diffMs / 86400000);

  if (diffMin < 1) return "刚刚";
  if (diffMin < 60) return `${diffMin} 分钟前`;
  if (diffHour < 24) return `${diffHour} 小时前`;
  if (diffDay < 7) return `${diffDay} 天前`;

  return date.toLocaleDateString("zh-CN");
}

12. 应用入口

src/App.tsx:

tsx 复制代码
import { useEffect } from "react";
import { Layout } from "./components/Layout";
import { listSessions } from "./api/client";
import { useKBStore } from "./store/kbStore";

function App() {
  const setSessions = useKBStore((s) => s.setSessions);

  useEffect(() => {
    listSessions().then(setSessions).catch(console.error);
  }, [setSessions]);

  return <Layout />;
}

export default App;

七、启动测试

1. 启动后端

bash 复制代码
cd day55/enterprise-kb
uvicorn kb.api.app:app --reload --port 8000

2. 启动前端

bash 复制代码
cd day55/enterprise-kb/frontend
npm run dev

打开 http://localhost:5173:

复制代码
┌──────────────────────────────────────────────────────────┐
│  📖 企业知识库   │   企业知识库助手                       │
│                 │                                        │
│  [+ 新建对话]   │      ┌─────────────────────────┐      │
│                 │      │  年假有几天?           │      │
│  💬 年假有几天? │      └─────────────────────────┘      │
│    4 轮 · 刚刚  │                                        │
│                 │   AI  知识库助手                       │
│  💬 API 限流    │      ┌─────────────────────────┐      │
│    2 轮 · 5分钟 │      │ 年假按入职年限计算:     │      │
│                 │      │ - 满 1 年:5 天         │      │
│  💬 差旅标准    │      │ - 满 3 年:10 天        │      │
│    6 轮 · 1 小时│      │ - 满 5 年:15 天        │      │
│                 │      │ - 满 10 年:20 天       │      │
│                 │      │                         │      │
│                 │      │ 【来源:请假制度.md】    │      │
│                 │      └─────────────────────────┘      │
│                 │                                        │
│                 │      📚 参考来源(3)                  │
│                 │      ┌─────────────────────────┐      │
│                 │      │ 1. 请假制度.md ████ 5.7│      │
│                 │      │ 2. 请假制度.md ██ 2.2  │      │
│                 │      │ 3. 请假制度.md █ 1.5   │      │
│                 │      └─────────────────────────┘      │
│                 │                                        │
│                 │      这个回答有帮助吗? 👍 👎         │
│                 │                                        │
│  v0.1.0         │  ┌──────────────────────────┐          │
│                 │  │ 范围: [全部][人事][产品] │          │
│                 │  ├──────────────────────────┤          │
│                 │  │ 输入你的问题...      📤 │          │
│                 │  └──────────────────────────┘          │
└──────────────────────────────────────────────────────────┘

3. 测试清单

逐个测一遍:

场景 预期
输入问题按 Enter 流式出答案
点"停止" 中断生成
切换会话 加载历史
删除会话 从列表消失
点来源 展开全文
点赞/点踩 状态变化
过滤范围 只搜指定类型
后端挂了 Toast 提示错误
刷新页面 会话还在

全通过 = 产品级。


八、前端视角:你的"AI 产品力"

55 天来,你在前端上的打磨总结:

组件 作用
Sidebar 会话管理
ChatArea 聊天主区
MessageItem 消息渲染(Markdown)
SourceCard 来源可视化
FeedbackButtons 反馈收集
InputBox 输入 + 过滤
LoadingDots Loading 动画
Toast 错误提示
EmptyState 空状态引导

这些不是"技术难点"------ 都是你做了多年的"前端活儿"。

但正是这些,把"RAG 系统"变成了"用户愿意用的产品"。

关键心法:

AI 时代,前端更值钱了------

因为:

  • 后端差异越来越小:都用同样的 LLM、同样的 RAG
  • 前端体验差异巨大:同样的功能,用户体验千差万别
  • "AI 产品"的核心竞争力是"体验":不是"技术"

你在前端上的积累------ 是 AI 时代最稀缺的能力。

从今天起,你不仅是"AI 开发者",更是"AI 产品设计师"。

Day 55 完成度:✅

明日预告(Day 56)

  • RAG 项目实战(五):部署上线
  • Docker 化前后端
  • Nginx 反代 + SSE 流式
  • CI/CD 自动部署
  • 上线检查清单
  • 从"本地能跑"到"公网可访问"

最后

如果这篇对你有用,点个赞让我知道有人在看。

评论区互动: 你的 RAG 前端长什么样?做了什么"体验优化"?欢迎分享截图或者描述。

有问题评论区见,我们第 56 天继续。

100 天,第 56 天见。


附录:系列目录

第一阶段:工程基础(已完成 ✅)

阶段 天数 内容
Python 基础 01-15 语法 + 命令行助手
后端工程化 16-30 数据库/测试/FastAPI/Docker/上线

第二阶段:LLM 应用(已完成 ✅)

阶段 天数 内容
LLM 全链路 31-45 调用/流式/工具/结构化/Prompt/成本/多模型/前端

第三阶段:RAG(进行中 🎯)

阶段 天数 内容
RAG 基础 46-51 入门 + Embedding + 向量库 + 切分 + 评估 ✅
项目实战 52-54 知识库 + 生成层 + 多轮对话 ✅
项目实战 55 前端完善(本篇) ✅
项目实战 56 部署上线
RAG 进阶 57-60 上下文压缩 / 多跳推理 / 优化

第四阶段:Agent 进阶(Day 61-80)

第五阶段:完整项目(Day 81-100)

55 天已过,45 天继续。

一起从切图仔变成 Agent 开发者。

相关推荐
geovindu1 小时前
python: KNeighborsClassifier K
开发语言·后端·python·算法
mattleeee1 小时前
Python脚本超时重试机制设计:失败立即重试,最多3次
python·超时·重试机制
笨鸟先飞的橘猫1 小时前
SLG 后端实战(一):基础建模与行军模拟
python·游戏程序
Thanks_ks3 小时前
接口限流是怎么实现的:从固定窗口计数讲到滑动窗口日志
redis·python·限流·滑动窗口·漏桶·令牌桶·固定窗口
choicesages4 小时前
跑通不等于跑对:公开评论抓取里三处不报错的坐标问题
爬虫·python·数据清洗·数据质量·去重
鲸渔5 小时前
【AI Agent系列课程33-FastAPI 基础07】自动文档与接口调试:Swagger UI 和 ReDoc 入门
python·ui·fastapi·ai编程
Nor.na6 小时前
dateutil 4.0.0 之前,闰年的第 366 天落回 12 月 30 日
python
aifannihao7 小时前
AI 学习第 27 课:重排救不回没召回的答案,四个静默坑
python·scikit-learn·学习路线·rag·重排序
Wellijohn7 小时前
`s += x` 到底是 O(n) 还是 O(n²)?我把 CPython 的字符串拼接拆开测了一遍
后端·python·性能优化