"use client"; import { useRef, useState } from "react"; import { useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { Check, Code2, Copy, ImageIcon, Search, Upload, X } from "lucide-react"; import { toast } from "sonner"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form"; import { Popover, PopoverContent, PopoverTrigger, } from "@/components/ui/popover"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, } from "@/components/ui/tooltip"; import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"; import { type FilterBuilderHandle } from "./filter-builder"; import { RetrievalParamsFields } from "./retrieval-params-fields"; import { assembleRetrievalConfiguration } from "./assemble-retrieval-configuration"; import { useI18n } from "@/i18n/i18n-context"; import { retrievalSchema, type RetrievalInput } from "@/schemas/retrieval"; import type { KnowledgeBase } from "@/types/knowledge-base"; import type { RetrievalQuery, RetrievalRequest } from "@/types/retrieval"; interface RetrievalFormProps { knowledgeBaseName: string; knowledgeBase?: KnowledgeBase; onSubmit: (request: RetrievalRequest) => void; isLoading?: boolean; } /** * Pure assembler shared by the submit path and the request-preview panel. * Centralising it guarantees the JSON shown to the user matches the body * actually sent to the API; earlier versions drifted apart and silently * dropped strategy-specific sub-objects like `modelConfiguration`. * * Delegates the `retrievalConfiguration` core to * `assembleRetrievalConfiguration` so the chat homepage (which needs the * exact same shape but scopes it globally across mounts) stays in lockstep * with this form. */ export function assembleRetrievalRequest( knowledgeBaseName: string, v: RetrievalInput, filter: Record | undefined, ): RetrievalRequest { const config = assembleRetrievalConfiguration(v, undefined) ?? {}; if (filter) config.filter = filter; const retrievalQuery: RetrievalQuery = v.queryType === "IMAGE" && v.imageInput ? { type: "IMAGE" as const, imageBase64: v.imageInput, ...(v.query ? { text: v.query } : {}), } : { type: "TEXT" as const, text: v.query ?? "" }; const req: RetrievalRequest = { knowledgeBaseName, retrievalQuery, }; if (v.subspace?.length) req.subspace = v.subspace; if (Object.keys(config).length > 0) req.retrievalConfiguration = config; return req; } /** * Compute the default form values from a knowledge base configuration. Shared * with the QA playground so the rerank parameter defaults stay consistent * between the two forms. */ export function retrievalDefaultsFromKB( knowledgeBaseName: string, knowledgeBase?: KnowledgeBase, ): RetrievalInput { const kbSearchType = knowledgeBase?.retrievalConfiguration?.searchType ?? [ "DENSE_VECTOR", ]; const kbRerank = knowledgeBase?.retrievalConfiguration?.rerankingConfiguration; const kbDense = knowledgeBase?.retrievalConfiguration?.denseVectorSearchConfiguration; const kbFullText = knowledgeBase?.retrievalConfiguration?.fullTextSearchConfiguration; const kbRrf = kbRerank?.rrfConfiguration; const kbWeight = kbRerank?.weightConfiguration; const kbModel = kbRerank?.modelConfiguration; const kbHybrid = kbSearchType.includes("DENSE_VECTOR") && kbSearchType.includes("FULL_TEXT"); const kbRerankType: "RRF" | "WEIGHT" | "MODEL" = kbRerank?.type === "RRF" || kbRerank?.type === "WEIGHT" ? kbHybrid ? kbRerank.type : "MODEL" : kbRerank?.type === "MODEL" ? "MODEL" : "WEIGHT"; const kbDenseTopK = kbDense?.numberOfResults ?? kbRerank?.numberOfResults ?? 20; const kbFullTextTopK = kbFullText?.numberOfResults ?? kbRerank?.numberOfResults ?? 20; const kbRerankTopK = kbRerank?.numberOfResults ?? 20; return { knowledgeBaseName, queryType: "TEXT" as const, query: "", imageInput: "", subspace: [], topK: kbRerankTopK, denseTopK: kbDenseTopK, fullTextTopK: kbFullTextTopK, rerankTopK: kbRerankTopK, searchType: kbSearchType, rerankType: kbRerankType, rrfK: kbRrf?.k ?? 60, rrfDenseWeight: kbRrf?.denseVectorSearchWeight ?? 0.5, rrfFullTextWeight: kbRrf?.fullTextSearchWeight ?? 0.5, weightDense: kbWeight?.denseVectorSearchWeight ?? 0.5, weightFullText: kbWeight?.fullTextSearchWeight ?? 0.5, modelProvider: kbModel?.provider ?? "bailian", modelName: kbModel?.model ?? "gte-rerank-v2", }; } /** * Compact "developer tool" affordance for the retrieval form: an icon * button at the form's top-right corner that opens a popover preview of * the assembled request body. The user can hover for a tooltip, click to * see the JSON, and copy it to the clipboard from the popover header. * * Replaces the previous inline collapsible panel that ate vertical * space in the form column even when collapsed and read like a primary * affordance instead of a secondary inspection helper. */ function RequestPreviewButton({ buildRequestJson, }: { buildRequestJson: () => Record; }) { const { t } = useI18n(); const [open, setOpen] = useState(false); const [copied, setCopied] = useState(false); // Snapshot the current form values whenever the popover opens so the // displayed JSON does not flicker as the user clicks around inside it. const json = open ? JSON.stringify(buildRequestJson(), null, 2) : ""; const handleCopy = async () => { try { await navigator.clipboard.writeText(json); setCopied(true); toast.success(t("retrieval.form.copiedRequestBody")); setTimeout(() => setCopied(false), 1500); } catch { toast.error(t("retrieval.form.copyFailed")); } }; return ( {t("retrieval.form.viewCopyRequestBody")}
{t("retrieval.form.requestBodyPreview")}
          {json}
        
); } export function RetrievalForm({ knowledgeBaseName, knowledgeBase, onSubmit, isLoading, }: RetrievalFormProps) { const { t } = useI18n(); const filterRef = useRef(null); const fileInputRef = useRef(null); const [fileName, setFileName] = useState(""); const [isDragging, setIsDragging] = useState(false); const form = useForm({ resolver: zodResolver(retrievalSchema), defaultValues: retrievalDefaultsFromKB(knowledgeBaseName, knowledgeBase), }); function handleSubmit(values: RetrievalInput) { const filter = filterRef.current?.getFilter(); onSubmit(assembleRetrievalRequest(knowledgeBaseName, values, filter)); } // Build the request preview JSON on demand. The preview and the submit // path both delegate to `assembleRetrievalRequest` so the JSON shown always // matches the body actually sent. const buildRequestJson = (): Record => { const values = form.getValues(); const filter = filterRef.current?.getFilter(); return assembleRetrievalRequest( knowledgeBaseName, values, filter, ) as unknown as Record; }; const isMultimodal = knowledgeBase?.multimodal === true; const queryType = form.watch("queryType") ?? "TEXT"; // Force TEXT mode for non-multimodal KBs const effectiveQueryType = isMultimodal ? queryType : "TEXT"; return (

{t("retrieval.form.title")}

{isMultimodal && ( ( {t("retrieval.form.queryType")} { if (v && v !== field.value) { field.onChange(v); // Clear both inputs on type switch to avoid stale values form.setValue("query", ""); form.setValue("imageInput", ""); } }} className="grid w-full grid-cols-2 gap-0 overflow-hidden rounded-lg border border-border bg-[hsl(var(--muted)/0.4)] p-0 sm:max-w-md" > TEXT IMAGE )} /> )} {effectiveQueryType === "TEXT" ? ( ( {t("retrieval.form.queryContent")}
)} /> ) : ( <> {/* Image file upload */} { const acceptedTypes = [ "image/jpeg", "image/png", "image/webp", "image/bmp", "image/tiff", ]; const handleFile = (file: File) => { if (!acceptedTypes.includes(file.type)) { toast.error(t("retrieval.form.unsupportedFormat")); return; } const reader = new FileReader(); reader.onload = () => { field.onChange(reader.result as string); setFileName(file.name || "pasted-image"); }; reader.onerror = () => { toast.error(t("retrieval.form.imageReadFailed")); }; reader.readAsDataURL(file); }; const handleRemove = () => { field.onChange(""); setFileName(""); if (fileInputRef.current) { fileInputRef.current.value = ""; } }; const handlePaste = (e: React.ClipboardEvent) => { const items = e.clipboardData?.items; if (!items) return; for (const item of Array.from(items)) { if (item.type.startsWith("image/")) { e.preventDefault(); const file = item.getAsFile(); if (file) handleFile(file); return; } } }; return ( {t("retrieval.form.imageInput")}
{ const file = e.target.files?.[0]; if (file) handleFile(file); }} /> {!field.value ? (
fileInputRef.current?.click()} onDragOver={(e) => { e.preventDefault(); setIsDragging(true); }} onDragLeave={() => setIsDragging(false)} onDrop={(e) => { e.preventDefault(); setIsDragging(false); const file = e.dataTransfer.files[0]; if (file) handleFile(file); }} className={`border-2 border-dashed rounded-lg p-8 flex flex-col items-center gap-3 cursor-pointer transition-colors ${ isDragging ? "border-primary bg-accent/50" : "border-border hover:border-primary/50 hover:bg-accent/50" }`} >

{t("retrieval.form.dropImageHere")}

{t("retrieval.form.supportedFormats")}

) : ( /* 已选择态 - 悬停遮罩式 */
{/* 图片预览区域 */}
{t("retrieval.form.selectedImageAlt")} {/* 悬停遮罩 + 操作按钮 */}
{/* 底部文件信息栏 */}
{fileName}
)}
); }} /> {/* Supplementary text */} ( {t("retrieval.form.supplementaryText")} )} /> )} ); }