import { JSONValue } from "ai"; import { useState } from "react"; import { Button } from "../button"; import { DocumentPreview } from "../document-preview"; import FileUploader from "../file-uploader"; import { Input } from "../input"; import UploadImagePreview from "../upload-image-preview"; import { ChatHandler } from "./chat.interface"; import { useFile } from "./hooks/use-file"; import { LlamaCloudSelector } from "./widgets/LlamaCloudSelector"; const ALLOWED_EXTENSIONS = ["png", "jpg", "jpeg", "csv", "pdf", "txt", "docx"]; export default function ChatInput( props: Pick< ChatHandler, | "isLoading" | "input" | "onFileUpload" | "onFileError" | "handleSubmit" | "handleInputChange" | "messages" | "setInput" | "append" > & { requestParams?: any; }, ) { const { imageUrl, setImageUrl, uploadFile, files, removeDoc, reset, getAnnotations, } = useFile(); const [requestData, setRequestData] = useState(); // default submit function does not handle including annotations in the message // so we need to use append function to submit new message with annotations const handleSubmitWithAnnotations = ( e: React.FormEvent, annotations: JSONValue[] | undefined, ) => { e.preventDefault(); props.append!( { content: props.input, role: "user", createdAt: new Date(), annotations, }, { data: requestData }, ); props.setInput!(""); }; const onSubmit = (e: React.FormEvent) => { const annotations = getAnnotations(); if (annotations.length) { handleSubmitWithAnnotations(e, annotations); return reset(); } props.handleSubmit(e, { data: requestData }); }; const handleUploadFile = async (file: File) => { if (imageUrl || files.length > 0) { alert("同一时刻只能上传一个文件。"); return; } try { await uploadFile(file, props.requestParams); props.onFileUpload?.(file); } catch (error: any) { props.onFileError?.(error.message); } }; return (
{imageUrl && ( setImageUrl(null)} /> )} {files.length > 0 && (
{files.map((file) => ( removeDoc(file)} /> ))}
)}