Merge branch 'dhk-2' into 'master'
推荐问题接口添加 See merge request knowledge-base-bj/deerflow-server!11
This commit is contained in:
commit
bf98713a55
15 files changed
+746
-29
No files matched your search
@@ -80,35 +80,15 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from "../ui/dropdown-menu";
|
||||
|
||||
import { useRecommendedQuestions } from "@/core/recommended-questions/hooks";
|
||||
|
||||
|
||||
import { useThread } from "./messages/context";
|
||||
import { ModeHoverGuide } from "./mode-hover-guide";
|
||||
import { Tooltip } from "./tooltip";
|
||||
|
||||
type InputMode = "flash" | "thinking" | "pro" | "ultra";
|
||||
|
||||
// 推荐问题列表 — 可自由配置 title(卡片标题)和 content(发送给对话的内容)
|
||||
const RECOMMENDED_QUESTIONS: { title: string; content: string }[] = [
|
||||
{
|
||||
title: "市场分析报告",
|
||||
content: "请帮我写一份关于当前 AI 市场的详细分析报告,包括市场规模、主要玩家和发展趋势。",
|
||||
},
|
||||
{
|
||||
title: "制定学习计划",
|
||||
content: "请帮我制定一个为期 3 个月的 Python 编程学习计划,从基础到进阶,每周安排具体任务。",
|
||||
},
|
||||
{
|
||||
title: "代码审查建议",
|
||||
content: "请帮我审查代码,找出潜在的问题、性能瓶颈以及改进建议,并给出修改示例。",
|
||||
},
|
||||
{
|
||||
title: "数据分析方案",
|
||||
content: "请帮我设计一个用于分析用户行为数据的方案,包括数据收集、处理和可视化策略。",
|
||||
},
|
||||
{
|
||||
title: "文章润色优化",
|
||||
content: "请帮我润色以下文章,使其更加流畅、专业,并保持原意不变。",
|
||||
},
|
||||
];
|
||||
|
||||
function getResolvedMode(
|
||||
mode: InputMode | undefined,
|
||||
@@ -185,6 +165,8 @@ export function InputBox({
|
||||
null,
|
||||
);
|
||||
|
||||
const { questions: recommendedQuestions } = useRecommendedQuestions();
|
||||
|
||||
useEffect(() => {
|
||||
if (models.length === 0) {
|
||||
return;
|
||||
@@ -461,11 +443,11 @@ export function InputBox({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isNewThread && searchParams.get("mode") !== "skill" && (
|
||||
{isNewThread && searchParams.get("mode") !== "skill" && recommendedQuestions.length > 0 && (
|
||||
<div className="flex flex-wrap justify-center gap-2.5 px-4 mb-[10px]">
|
||||
{RECOMMENDED_QUESTIONS.map((q) => (
|
||||
{recommendedQuestions.map((q) => (
|
||||
<button
|
||||
key={q.title}
|
||||
key={q.id}
|
||||
type="button"
|
||||
className="rounded-full border border-[#e4e4e7] bg-white px-4 py-2 text-sm text-[#18181b] shadow-none transition-colors hover:bg-[#f4f4f5] cursor-pointer"
|
||||
onClick={() => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { ChevronsUpDown, Settings2Icon, SettingsIcon } from "lucide-react";
|
||||
import { ChevronsUpDown, MessageSquarePlusIcon, Settings2Icon, SettingsIcon } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import {
|
||||
@@ -19,6 +19,8 @@ import {
|
||||
} from "@/components/ui/sidebar";
|
||||
import { useI18n } from "@/core/i18n/hooks";
|
||||
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import { SettingsDialog } from "./settings";
|
||||
|
||||
function NavMenuButtonContent({
|
||||
@@ -42,6 +44,7 @@ function NavMenuButtonContent({
|
||||
}
|
||||
|
||||
export function WorkspaceNavMenu() {
|
||||
const navigate = useNavigate();
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
const [settingsDefaultSection, setSettingsDefaultSection] = useState<
|
||||
"appearance" | "memory" | "tools" | "skills" | "notification" | "about"
|
||||
@@ -88,6 +91,14 @@ export function WorkspaceNavMenu() {
|
||||
<Settings2Icon />
|
||||
{t.common.settings}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() =>
|
||||
navigate("/page/workspace/settings/recommended-questions")
|
||||
}
|
||||
>
|
||||
<MessageSquarePlusIcon />
|
||||
推荐问题配置
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator />
|
||||
</DropdownMenuContent>
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { apiFetch } from "@/core/api";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
|
||||
import type {
|
||||
CreateQuestionRequest,
|
||||
RecommendedQuestion,
|
||||
UpdateQuestionRequest,
|
||||
} from "./index";
|
||||
|
||||
const BASE = () => `${getBackendBaseURL()}/api/recommended-questions`;
|
||||
|
||||
export async function listRecommendedQuestions(): Promise<RecommendedQuestion[]> {
|
||||
const res = await apiFetch(BASE());
|
||||
if (!res.ok) throw new Error(`Failed to load questions: ${res.statusText}`);
|
||||
const data = (await res.json()) as { questions: RecommendedQuestion[] };
|
||||
return data.questions;
|
||||
}
|
||||
|
||||
export async function createRecommendedQuestion(
|
||||
body: CreateQuestionRequest,
|
||||
): Promise<RecommendedQuestion> {
|
||||
const res = await apiFetch(BASE(), {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = (await res.json().catch(() => ({}))) as { detail?: string };
|
||||
throw new Error(err.detail ?? `Failed to create question: ${res.statusText}`);
|
||||
}
|
||||
return res.json() as Promise<RecommendedQuestion>;
|
||||
}
|
||||
|
||||
export async function updateRecommendedQuestion(
|
||||
id: string,
|
||||
body: UpdateQuestionRequest,
|
||||
): Promise<RecommendedQuestion> {
|
||||
const res = await apiFetch(`${BASE()}/${id}`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = (await res.json().catch(() => ({}))) as { detail?: string };
|
||||
throw new Error(err.detail ?? `Failed to update question: ${res.statusText}`);
|
||||
}
|
||||
return res.json() as Promise<RecommendedQuestion>;
|
||||
}
|
||||
|
||||
export async function deleteRecommendedQuestion(id: string): Promise<void> {
|
||||
const res = await apiFetch(`${BASE()}/${id}`, { method: "DELETE" });
|
||||
if (!res.ok) throw new Error(`Failed to delete question: ${res.statusText}`);
|
||||
}
|
||||
|
||||
export async function reorderRecommendedQuestions(
|
||||
ids: string[],
|
||||
): Promise<RecommendedQuestion[]> {
|
||||
const res = await apiFetch(`${getBackendBaseURL()}/api/recommended-questions-reorder`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ ids }),
|
||||
});
|
||||
if (!res.ok) throw new Error(`Failed to reorder questions: ${res.statusText}`);
|
||||
const data = (await res.json()) as { questions: RecommendedQuestion[] };
|
||||
return data.questions;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import {
|
||||
createRecommendedQuestion,
|
||||
deleteRecommendedQuestion,
|
||||
listRecommendedQuestions,
|
||||
reorderRecommendedQuestions,
|
||||
updateRecommendedQuestion,
|
||||
} from "./api";
|
||||
import type { CreateQuestionRequest, UpdateQuestionRequest } from "./index";
|
||||
|
||||
const QK = ["recommended-questions"] as const;
|
||||
|
||||
export function useRecommendedQuestions() {
|
||||
const { data, isLoading, error } = useQuery({
|
||||
queryKey: QK,
|
||||
queryFn: listRecommendedQuestions,
|
||||
});
|
||||
return { questions: data ?? [], isLoading, error };
|
||||
}
|
||||
|
||||
export function useCreateRecommendedQuestion() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (body: CreateQuestionRequest) => createRecommendedQuestion(body),
|
||||
onSuccess: () => void qc.invalidateQueries({ queryKey: QK }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateRecommendedQuestion() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: ({ id, body }: { id: string; body: UpdateQuestionRequest }) =>
|
||||
updateRecommendedQuestion(id, body),
|
||||
onSuccess: () => void qc.invalidateQueries({ queryKey: QK }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteRecommendedQuestion() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (id: string) => deleteRecommendedQuestion(id),
|
||||
onSuccess: () => void qc.invalidateQueries({ queryKey: QK }),
|
||||
});
|
||||
}
|
||||
|
||||
export function useReorderRecommendedQuestions() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (ids: string[]) => reorderRecommendedQuestions(ids),
|
||||
onSuccess: () => void qc.invalidateQueries({ queryKey: QK }),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
export interface RecommendedQuestion {
|
||||
id: string;
|
||||
title: string;
|
||||
content: string;
|
||||
sort_order: number;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
export interface CreateQuestionRequest {
|
||||
title: string;
|
||||
content: string;
|
||||
sort_order?: number;
|
||||
}
|
||||
|
||||
export interface UpdateQuestionRequest {
|
||||
title?: string;
|
||||
content?: string;
|
||||
sort_order?: number;
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import {
|
||||
GripVerticalIcon,
|
||||
Loader2Icon,
|
||||
PencilIcon,
|
||||
PlusIcon,
|
||||
Trash2Icon,
|
||||
} from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import {
|
||||
useCreateRecommendedQuestion,
|
||||
useDeleteRecommendedQuestion,
|
||||
useRecommendedQuestions,
|
||||
useReorderRecommendedQuestions,
|
||||
useUpdateRecommendedQuestion,
|
||||
} from "@/core/recommended-questions/hooks";
|
||||
import type { RecommendedQuestion } from "@/core/recommended-questions";
|
||||
|
||||
type DialogState =
|
||||
| { mode: "add" }
|
||||
| { mode: "edit"; question: RecommendedQuestion }
|
||||
| null;
|
||||
|
||||
export default function RecommendedQuestionsPage() {
|
||||
const { questions, isLoading, error } = useRecommendedQuestions();
|
||||
const createMutation = useCreateRecommendedQuestion();
|
||||
const updateMutation = useUpdateRecommendedQuestion();
|
||||
const deleteMutation = useDeleteRecommendedQuestion();
|
||||
const reorderMutation = useReorderRecommendedQuestions();
|
||||
|
||||
const [dialog, setDialog] = useState<DialogState>(null);
|
||||
const [formTitle, setFormTitle] = useState("");
|
||||
const [formContent, setFormContent] = useState("");
|
||||
const [deleteTarget, setDeleteTarget] = useState<RecommendedQuestion | null>(null);
|
||||
|
||||
// drag state
|
||||
const [dragIndex, setDragIndex] = useState<number | null>(null);
|
||||
const [dragOverIndex, setDragOverIndex] = useState<number | null>(null);
|
||||
|
||||
function openAdd() {
|
||||
setFormTitle("");
|
||||
setFormContent("");
|
||||
setDialog({ mode: "add" });
|
||||
}
|
||||
|
||||
function openEdit(q: RecommendedQuestion) {
|
||||
setFormTitle(q.title);
|
||||
setFormContent(q.content);
|
||||
setDialog({ mode: "edit", question: q });
|
||||
}
|
||||
|
||||
function closeDialog() {
|
||||
setDialog(null);
|
||||
}
|
||||
|
||||
async function handleSave() {
|
||||
const title = formTitle.trim();
|
||||
const content = formContent.trim();
|
||||
if (!title || !content) {
|
||||
toast.error("标题和内容不能为空");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (dialog?.mode === "add") {
|
||||
await createMutation.mutateAsync({
|
||||
title,
|
||||
content,
|
||||
sort_order: questions.length,
|
||||
});
|
||||
toast.success("问题已添加");
|
||||
} else if (dialog?.mode === "edit") {
|
||||
await updateMutation.mutateAsync({
|
||||
id: dialog.question.id,
|
||||
body: { title, content },
|
||||
});
|
||||
toast.success("问题已更新");
|
||||
}
|
||||
closeDialog();
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : "操作失败");
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDelete(q: RecommendedQuestion) {
|
||||
try {
|
||||
await deleteMutation.mutateAsync(q.id);
|
||||
setDeleteTarget(null);
|
||||
toast.success("问题已删除");
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : "删除失败");
|
||||
}
|
||||
}
|
||||
|
||||
function handleDragStart(index: number) {
|
||||
setDragIndex(index);
|
||||
}
|
||||
|
||||
function handleDragOver(e: React.DragEvent, index: number) {
|
||||
e.preventDefault();
|
||||
setDragOverIndex(index);
|
||||
}
|
||||
|
||||
async function handleDrop(toIndex: number) {
|
||||
if (dragIndex === null || dragIndex === toIndex) {
|
||||
setDragIndex(null);
|
||||
setDragOverIndex(null);
|
||||
return;
|
||||
}
|
||||
const next = [...questions];
|
||||
const [moved] = next.splice(dragIndex, 1);
|
||||
next.splice(toIndex, 0, moved!);
|
||||
setDragIndex(null);
|
||||
setDragOverIndex(null);
|
||||
try {
|
||||
await reorderMutation.mutateAsync(next.map((q) => q.id));
|
||||
} catch {
|
||||
toast.error("排序保存失败");
|
||||
}
|
||||
}
|
||||
|
||||
const isSaving =
|
||||
createMutation.isPending ||
|
||||
updateMutation.isPending ||
|
||||
deleteMutation.isPending ||
|
||||
reorderMutation.isPending;
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-2xl flex-col gap-6 px-6 py-10">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold">推荐问题配置</h1>
|
||||
<p className="text-muted-foreground mt-1 text-sm">
|
||||
管理首页展示的推荐问题,点击后直接发送到对话。拖拽可调整顺序。
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={openAdd} className="shrink-0" disabled={isLoading}>
|
||||
<PlusIcon className="mr-1.5 size-4" />
|
||||
添加问题
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-16">
|
||||
<Loader2Icon className="text-muted-foreground size-6 animate-spin" />
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="text-destructive flex flex-col items-center gap-2 rounded-xl border border-dashed py-16 text-sm">
|
||||
<p>加载失败:{error.message}</p>
|
||||
</div>
|
||||
) : questions.length === 0 ? (
|
||||
<div className="text-muted-foreground flex flex-col items-center gap-3 rounded-xl border border-dashed py-16 text-sm">
|
||||
<p>暂无推荐问题</p>
|
||||
<Button variant="outline" size="sm" onClick={openAdd}>
|
||||
<PlusIcon className="mr-1.5 size-4" />
|
||||
添加第一个问题
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{questions.map((q, index) => (
|
||||
<div
|
||||
key={q.id}
|
||||
draggable
|
||||
onDragStart={() => handleDragStart(index)}
|
||||
onDragOver={(e) => handleDragOver(e, index)}
|
||||
onDrop={() => handleDrop(index)}
|
||||
onDragEnd={() => {
|
||||
setDragIndex(null);
|
||||
setDragOverIndex(null);
|
||||
}}
|
||||
className={`flex items-start gap-3 rounded-xl border bg-white px-4 py-3.5 transition-colors ${
|
||||
dragOverIndex === index && dragIndex !== index
|
||||
? "border-blue-400 bg-blue-50"
|
||||
: "border-[#e4e4e7]"
|
||||
}`}
|
||||
>
|
||||
<GripVerticalIcon className="text-muted-foreground/40 mt-0.5 size-4 shrink-0 cursor-grab active:cursor-grabbing" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-sm font-medium text-[#18181b]">
|
||||
{q.title}
|
||||
</div>
|
||||
<div className="text-muted-foreground mt-0.5 line-clamp-2 text-xs">
|
||||
{q.content}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-7"
|
||||
onClick={() => openEdit(q)}
|
||||
disabled={isSaving}
|
||||
>
|
||||
<PencilIcon className="size-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="text-destructive hover:text-destructive size-7"
|
||||
onClick={() => setDeleteTarget(q)}
|
||||
disabled={isSaving}
|
||||
>
|
||||
<Trash2Icon className="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 添加 / 编辑弹窗 */}
|
||||
<Dialog open={dialog !== null} onOpenChange={(o) => !o && closeDialog()}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{dialog?.mode === "add" ? "添加推荐问题" : "编辑推荐问题"}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="flex flex-col gap-4 py-2">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<p className="text-sm font-medium">卡片标题</p>
|
||||
<Input
|
||||
placeholder="例:市场分析报告"
|
||||
value={formTitle}
|
||||
onChange={(e) => setFormTitle(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<p className="text-sm font-medium">发送内容</p>
|
||||
<Textarea
|
||||
placeholder="点击卡片后实际发送给 AI 的消息内容"
|
||||
rows={4}
|
||||
value={formContent}
|
||||
onChange={(e) => setFormContent(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={closeDialog} disabled={isSaving}>
|
||||
取消
|
||||
</Button>
|
||||
<Button onClick={handleSave} disabled={isSaving}>
|
||||
{isSaving && <Loader2Icon className="mr-1.5 size-4 animate-spin" />}
|
||||
{dialog?.mode === "add" ? "添加" : "保存"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* 删除确认弹窗 */}
|
||||
<Dialog
|
||||
open={deleteTarget !== null}
|
||||
onOpenChange={(o) => !o && setDeleteTarget(null)}
|
||||
>
|
||||
<DialogContent className="sm:max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>确认删除</DialogTitle>
|
||||
</DialogHeader>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
确定要删除「{deleteTarget?.title}」吗?此操作不可撤销。
|
||||
</p>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setDeleteTarget(null)}
|
||||
disabled={isSaving}
|
||||
>
|
||||
取消
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
disabled={isSaving}
|
||||
onClick={() => deleteTarget && handleDelete(deleteTarget)}
|
||||
>
|
||||
{deleteMutation.isPending && (
|
||||
<Loader2Icon className="mr-1.5 size-4 animate-spin" />
|
||||
)}
|
||||
删除
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import AgentChatPage from "./AgentChatPage";
|
||||
import NewAgentPage from "./NewAgentPage";
|
||||
import ScheduledTaskRunDetailPage from "./ScheduledTaskRunDetailPage";
|
||||
import ScheduledTasksPage from "./ScheduledTasksPage";
|
||||
import RecommendedQuestionsPage from "./RecommendedQuestionsPage";
|
||||
|
||||
function WorkspaceLayout({
|
||||
children,
|
||||
@@ -143,6 +144,14 @@ export default function WorkspaceRoutes({
|
||||
</WorkspaceLayout>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="settings/recommended-questions"
|
||||
element={
|
||||
<WorkspaceLayout {...layoutProps}>
|
||||
<RecommendedQuestionsPage />
|
||||
</WorkspaceLayout>
|
||||
}
|
||||
/>
|
||||
</Routes>
|
||||
);
|
||||
}
|
||||
@@ -30,6 +30,7 @@ from app.gateway.routers import (
|
||||
mcp,
|
||||
memory,
|
||||
models,
|
||||
recommended_questions,
|
||||
runs,
|
||||
scheduled_tasks,
|
||||
skills,
|
||||
@@ -485,6 +486,9 @@ This gateway provides custom endpoints for models, MCP configuration, skills, an
|
||||
# Agents API is mounted at /api/agents
|
||||
app.include_router(agents.router)
|
||||
|
||||
# Recommended Questions API is mounted at /api/recommended-questions
|
||||
app.include_router(recommended_questions.router)
|
||||
|
||||
# Suggestions API is mounted at /api/threads/{thread_id}/suggestions
|
||||
app.include_router(suggestions.router)
|
||||
|
||||
|
||||
@@ -94,6 +94,10 @@ async def langgraph_runtime(app: FastAPI) -> AsyncGenerator[None, None]:
|
||||
|
||||
app.state.agent_store = make_agent_store(sf)
|
||||
|
||||
from deerflow.persistence.recommended_questions import make_recommended_question_store
|
||||
|
||||
app.state.recommended_question_store = make_recommended_question_store(sf)
|
||||
|
||||
# Run event store (has its own factory with config-driven backend selection)
|
||||
run_events_config = getattr(config, "run_events", None)
|
||||
app.state.run_event_store = make_run_event_store(run_events_config)
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
from . import artifacts, assistants_compat, mcp, models, skills, suggestions, thread_runs, threads, uploads
|
||||
from . import artifacts, assistants_compat, mcp, models, recommended_questions, skills, suggestions, thread_runs, threads, uploads
|
||||
|
||||
__all__ = ["artifacts", "assistants_compat", "mcp", "models", "skills", "suggestions", "threads", "thread_runs", "uploads"]
|
||||
__all__ = ["artifacts", "assistants_compat", "mcp", "models", "recommended_questions", "skills", "suggestions", "threads", "thread_runs", "uploads"]
|
||||
@@ -0,0 +1,101 @@
|
||||
"""CRUD API for recommended questions."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix="/api", tags=["recommended-questions"])
|
||||
|
||||
|
||||
class RecommendedQuestionResponse(BaseModel):
|
||||
id: str
|
||||
title: str
|
||||
content: str
|
||||
sort_order: int = 0
|
||||
created_at: datetime | str | None = None
|
||||
updated_at: datetime | str | None = None
|
||||
|
||||
|
||||
class RecommendedQuestionsListResponse(BaseModel):
|
||||
questions: list[RecommendedQuestionResponse]
|
||||
|
||||
|
||||
class RecommendedQuestionCreateRequest(BaseModel):
|
||||
title: str = Field(..., min_length=1, max_length=256)
|
||||
content: str = Field(..., min_length=1)
|
||||
sort_order: int = Field(default=0)
|
||||
|
||||
|
||||
class RecommendedQuestionUpdateRequest(BaseModel):
|
||||
title: str | None = Field(default=None, max_length=256)
|
||||
content: str | None = None
|
||||
sort_order: int | None = None
|
||||
|
||||
|
||||
class ReorderRequest(BaseModel):
|
||||
ids: list[str] = Field(..., description="Question IDs in the desired order")
|
||||
|
||||
|
||||
def _get_store(request: Request):
|
||||
store = getattr(request.app.state, "recommended_question_store", None)
|
||||
if store is None:
|
||||
raise HTTPException(status_code=503, detail="Recommended question store not available")
|
||||
return store
|
||||
|
||||
|
||||
@router.get("/recommended-questions", response_model=RecommendedQuestionsListResponse)
|
||||
async def list_recommended_questions(request: Request) -> RecommendedQuestionsListResponse:
|
||||
store = _get_store(request)
|
||||
rows = await store.list_all()
|
||||
return RecommendedQuestionsListResponse(questions=[RecommendedQuestionResponse(**r) for r in rows])
|
||||
|
||||
|
||||
@router.post("/recommended-questions", response_model=RecommendedQuestionResponse, status_code=201)
|
||||
async def create_recommended_question(request: Request, body: RecommendedQuestionCreateRequest) -> RecommendedQuestionResponse:
|
||||
store = _get_store(request)
|
||||
data = {
|
||||
"id": str(uuid4()),
|
||||
"title": body.title.strip(),
|
||||
"content": body.content.strip(),
|
||||
"sort_order": body.sort_order,
|
||||
}
|
||||
row = await store.create(data)
|
||||
return RecommendedQuestionResponse(**row)
|
||||
|
||||
|
||||
@router.put("/recommended-questions/{question_id}", response_model=RecommendedQuestionResponse)
|
||||
async def update_recommended_question(request: Request, question_id: str, body: RecommendedQuestionUpdateRequest) -> RecommendedQuestionResponse:
|
||||
store = _get_store(request)
|
||||
data: dict = {}
|
||||
if body.title is not None:
|
||||
data["title"] = body.title.strip()
|
||||
if body.content is not None:
|
||||
data["content"] = body.content.strip()
|
||||
if body.sort_order is not None:
|
||||
data["sort_order"] = body.sort_order
|
||||
|
||||
row = await store.update(question_id, data)
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail="Question not found")
|
||||
return RecommendedQuestionResponse(**row)
|
||||
|
||||
|
||||
@router.delete("/recommended-questions/{question_id}", status_code=204)
|
||||
async def delete_recommended_question(request: Request, question_id: str) -> None:
|
||||
store = _get_store(request)
|
||||
deleted = await store.delete(question_id)
|
||||
if not deleted:
|
||||
raise HTTPException(status_code=404, detail="Question not found")
|
||||
|
||||
|
||||
@router.put("/recommended-questions-reorder", response_model=RecommendedQuestionsListResponse)
|
||||
async def reorder_recommended_questions(request: Request, body: ReorderRequest) -> RecommendedQuestionsListResponse:
|
||||
store = _get_store(request)
|
||||
rows = await store.reorder(body.ids)
|
||||
return RecommendedQuestionsListResponse(questions=[RecommendedQuestionResponse(**r) for r in rows])
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
"""Create recommended_questions table.
|
||||
|
||||
Revision ID: 20260514_01
|
||||
Revises: 20260513_02
|
||||
Create Date: 2026-05-14
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy import inspect
|
||||
|
||||
|
||||
revision = "20260514_01"
|
||||
down_revision = "20260513_02"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _has_table(table_name: str) -> bool:
|
||||
inspector = inspect(op.get_bind())
|
||||
return table_name in inspector.get_table_names()
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
if _has_table("recommended_questions"):
|
||||
return
|
||||
|
||||
op.create_table(
|
||||
"recommended_questions",
|
||||
sa.Column("id", sa.String(64), primary_key=True),
|
||||
sa.Column("title", sa.String(256), nullable=False),
|
||||
sa.Column("content", sa.Text(), nullable=False),
|
||||
sa.Column("sort_order", sa.Integer(), nullable=False, server_default="0"),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
|
||||
)
|
||||
op.create_index("ix_recommended_questions_sort_order", "recommended_questions", ["sort_order"])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
if _has_table("recommended_questions"):
|
||||
op.drop_table("recommended_questions")
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
"""Recommended questions persistence."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from deerflow.persistence.recommended_questions.model import RecommendedQuestionRow
|
||||
from deerflow.persistence.recommended_questions.sql import RecommendedQuestionRepository
|
||||
|
||||
__all__ = [
|
||||
"RecommendedQuestionRepository",
|
||||
"RecommendedQuestionRow",
|
||||
"make_recommended_question_store",
|
||||
]
|
||||
|
||||
|
||||
def make_recommended_question_store(session_factory):
|
||||
if session_factory is None:
|
||||
return None
|
||||
return RecommendedQuestionRepository(session_factory)
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
"""ORM model for recommended questions."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import DateTime, Integer, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from deerflow.persistence.base import Base
|
||||
|
||||
|
||||
class RecommendedQuestionRow(Base):
|
||||
__tablename__ = "recommended_questions"
|
||||
|
||||
id: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||
title: Mapped[str] = mapped_column(String(256), nullable=False)
|
||||
content: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, default=0, index=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=lambda: datetime.now(UTC))
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=lambda: datetime.now(UTC), onupdate=lambda: datetime.now(UTC))
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
"""SQLAlchemy-backed recommended questions repository."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
||||
|
||||
from deerflow.persistence.recommended_questions.model import RecommendedQuestionRow
|
||||
|
||||
|
||||
def _row_to_dict(row: RecommendedQuestionRow) -> dict[str, Any]:
|
||||
data = row.to_dict()
|
||||
for key in ("created_at", "updated_at"):
|
||||
value = data.get(key)
|
||||
if isinstance(value, datetime):
|
||||
data[key] = value.isoformat()
|
||||
return data
|
||||
|
||||
|
||||
class RecommendedQuestionRepository:
|
||||
def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:
|
||||
self._sf = session_factory
|
||||
|
||||
async def list_all(self) -> list[dict[str, Any]]:
|
||||
stmt = select(RecommendedQuestionRow).order_by(RecommendedQuestionRow.sort_order.asc(), RecommendedQuestionRow.created_at.asc())
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(stmt)
|
||||
return [_row_to_dict(row) for row in result.scalars()]
|
||||
|
||||
async def get(self, question_id: str) -> dict[str, Any] | None:
|
||||
async with self._sf() as session:
|
||||
row = await session.get(RecommendedQuestionRow, question_id)
|
||||
return _row_to_dict(row) if row is not None else None
|
||||
|
||||
async def create(self, data: dict[str, Any]) -> dict[str, Any]:
|
||||
now = datetime.now(UTC)
|
||||
row = RecommendedQuestionRow(
|
||||
id=data["id"],
|
||||
title=data["title"],
|
||||
content=data["content"],
|
||||
sort_order=data.get("sort_order", 0),
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
async with self._sf() as session:
|
||||
session.add(row)
|
||||
await session.commit()
|
||||
await session.refresh(row)
|
||||
return _row_to_dict(row)
|
||||
|
||||
async def update(self, question_id: str, data: dict[str, Any]) -> dict[str, Any] | None:
|
||||
async with self._sf() as session:
|
||||
row = await session.get(RecommendedQuestionRow, question_id)
|
||||
if row is None:
|
||||
return None
|
||||
for key in ("title", "content", "sort_order"):
|
||||
if key in data:
|
||||
setattr(row, key, data[key])
|
||||
row.updated_at = datetime.now(UTC)
|
||||
await session.commit()
|
||||
await session.refresh(row)
|
||||
return _row_to_dict(row)
|
||||
|
||||
async def delete(self, question_id: str) -> bool:
|
||||
async with self._sf() as session:
|
||||
row = await session.get(RecommendedQuestionRow, question_id)
|
||||
if row is None:
|
||||
return False
|
||||
await session.delete(row)
|
||||
await session.commit()
|
||||
return True
|
||||
|
||||
async def reorder(self, ordered_ids: list[str]) -> list[dict[str, Any]]:
|
||||
async with self._sf() as session:
|
||||
now = datetime.now(UTC)
|
||||
for index, question_id in enumerate(ordered_ids):
|
||||
row = await session.get(RecommendedQuestionRow, question_id)
|
||||
if row is not None:
|
||||
row.sort_order = index
|
||||
row.updated_at = now
|
||||
await session.commit()
|
||||
return await self.list_all()
|
||||
Reference in new issue
Block a user