Skip to content

Commit

Permalink
feat: add advanced setting & ai markdown support #198 #202
Browse files Browse the repository at this point in the history
  • Loading branch information
Blinko committed Nov 30, 2024
1 parent ad53a06 commit d6cac1e
Show file tree
Hide file tree
Showing 17 changed files with 327 additions and 58 deletions.
5 changes: 4 additions & 1 deletion public/locales/ar/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -172,5 +172,8 @@
"if-you-have-a-lot-of-notes-you-may-consume-a-certain-number-of-tokens": "إذا كان لديك الكثير من الملاحظات فقد تستهلك عددًا معينًا من الرموز المميزة",
"force-rebuild": "إعادة بناء القوة",
"force-rebuild-embedding-index": "ستؤدي إعادة البناء القسري إلى إعادة بناء جميع البيانات التي تمت فهرستها بالكامل",
"embedding-model-description": "يجب إعادة بناء الفهرس بعد تبديل النماذج المدمجة"
"embedding-model-description": "يجب إعادة بناء الفهرس بعد تبديل النماذج المدمجة",
"top-k-description": "الحد الأقصى لعدد المستندات التي تم إرجاعها في النهاية",
"embedding-score-description": "عادة ما تكون عتبة التشابه للاستعلامات هي مجموع المسافة الإقليدية",
"embedding-lambda-description": "معلمة ترجيح تنوع نتائج الاستعلامات"
}
5 changes: 4 additions & 1 deletion public/locales/de/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -163,5 +163,8 @@
"embedding-model": "Einbettungsmodell",
"force-rebuild": "Force Rebuild",
"force-rebuild-embedding-index": "Erzwungener Neuaufbau stellt alle Daten wieder her, die vollständig indiziert wurden.",
"embedding-model-description": "Der Index muss nach einem Wechsel des eingebetteten Modells neu aufgebaut werden"
"embedding-model-description": "Der Index muss nach einem Wechsel des eingebetteten Modells neu aufgebaut werden",
"top-k-description": "Maximale Anzahl von Dokumenten, die zurückgegeben werden",
"embedding-score-description": "Die Ähnlichkeitsschwelle für Abfragen ist im Allgemeinen der euklidische Summenabstand",
"embedding-lambda-description": "Abfrageergebnis Diversität Gewichtungsparameter"
}
5 changes: 4 additions & 1 deletion public/locales/en/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -168,5 +168,8 @@
"embedding-model": "Embedding Model",
"force-rebuild": "Force Rebuild",
"force-rebuild-embedding-index": "Forced rebuild will rebuild all data that has been indexed completely",
"embedding-model-description": "The index must be rebuilt after switching embedded models"
"embedding-model-description": "The index must be rebuilt after switching embedded models",
"top-k-description": "Maximum number of documents eventually returned",
"embedding-score-description": "The similarity threshold for queries is generally the Euclidean sum distance",
"embedding-lambda-description": "Query Result Diversity Weighting Parameter"
}
5 changes: 4 additions & 1 deletion public/locales/es/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -163,5 +163,8 @@
"if-you-have-a-lot-of-notes-you-may-consume-a-certain-number-of-tokens": "Si tienes muchos billetes puedes consumir un número determinado de fichas",
"force-rebuild": "Reconstrucción forzosa",
"force-rebuild-embedding-index": "La reconstrucción forzada reconstruirá por completo todos los datos indexados.",
"embedding-model-description": "El índice debe reconstruirse después de cambiar de modelo integrado."
"embedding-model-description": "El índice debe reconstruirse después de cambiar de modelo integrado.",
"top-k-description": "Número máximo de documentos devueltos",
"embedding-score-description": "El umbral de similitud de las consultas suele ser la distancia de la suma euclídea",
"embedding-lambda-description": "Resultado de la consulta Parámetro de ponderación de la diversidad"
}
5 changes: 4 additions & 1 deletion public/locales/fr/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -164,5 +164,8 @@
"if-you-have-a-lot-of-notes-you-may-consume-a-certain-number-of-tokens": "Si vous avez beaucoup de notes, vous pouvez consommer un certain nombre de jetons.",
"force-rebuild": "Reconstruction des forces",
"force-rebuild-embedding-index": "La reconstruction forcée reconstruit toutes les données qui ont été complètement indexées.",
"embedding-model-description": "L'index doit être reconstruit après avoir changé de modèle intégré."
"embedding-model-description": "L'index doit être reconstruit après avoir changé de modèle intégré.",
"top-k-description": "Nombre maximum de documents éventuellement renvoyés",
"embedding-score-description": "Le seuil de similarité pour les requêtes est généralement la distance de la somme euclidienne",
"embedding-lambda-description": "Résultat de la requête Paramètre de pondération de la diversité"
}
5 changes: 4 additions & 1 deletion public/locales/ja/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -161,5 +161,8 @@
"embedding-model": "埋め込みモデル",
"force-rebuild": "フォース・リビルド",
"force-rebuild-embedding-index": "強制再構築は、インデックスが作成されたすべてのデータを完全に再構築します。",
"embedding-model-description": "組み込みモデルを切り替えた後は、インデックスを再構築する必要があります。"
"embedding-model-description": "組み込みモデルを切り替えた後は、インデックスを再構築する必要があります。",
"top-k-description": "最終的に返される文書の最大数",
"embedding-score-description": "クエリの類似度閾値は一般的にユークリッド和距離である。",
"embedding-lambda-description": "クエリ結果の多様性重み付けパラメータ"
}
5 changes: 4 additions & 1 deletion public/locales/ko/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -163,5 +163,8 @@
"embedding-model": "임베딩 모델",
"force-rebuild": "강제 재구축",
"force-rebuild-embedding-index": "강제 재구축은 인덱싱된 모든 데이터를 완전히 재구축합니다.",
"embedding-model-description": "임베디드 모델을 전환한 후 인덱스를 다시 작성해야 합니다."
"embedding-model-description": "임베디드 모델을 전환한 후 인덱스를 다시 작성해야 합니다.",
"top-k-description": "최종적으로 반환되는 최대 문서 수",
"embedding-score-description": "쿼리의 유사성 임계값은 일반적으로 유클리드 합 거리입니다.",
"embedding-lambda-description": "쿼리 결과 다양성 가중치 매개변수"
}
4 changes: 3 additions & 1 deletion public/locales/pt/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -162,5 +162,7 @@
"embedding-model": "Modelo de incorporação",
"force-rebuild": "Reconstrução da força",
"force-rebuild-embedding-index": "A reconstrução forçada irá reconstruir completamente todos os dados que foram indexados",
"embedding-model-description": "O índice deve ser reconstruído após a mudança de modelos incorporados"
"embedding-model-description": "O índice deve ser reconstruído após a mudança de modelos incorporados",
"top-k-description": "Número máximo de documentos eventualmente devolvidos",
"embedding-lambda-description": "Resultado da consulta Parâmetro de ponderação da diversidade"
}
5 changes: 4 additions & 1 deletion public/locales/ru/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -164,5 +164,8 @@
"embedding-model": "Модель встраивания",
"force-rebuild": "Восстановление сил",
"force-rebuild-embedding-index": "Принудительная перестройка полностью перестроит все данные, которые были проиндексированы.",
"embedding-model-description": "Индекс должен быть перестроен после переключения встроенных моделей"
"embedding-model-description": "Индекс должен быть перестроен после переключения встроенных моделей",
"top-k-description": "Максимальное количество возвращаемых документов",
"embedding-score-description": "Порогом сходства для запросов обычно является расстояние, равное евклидовой сумме",
"embedding-lambda-description": "Весовой параметр разнообразия результатов запросов"
}
5 changes: 4 additions & 1 deletion public/locales/zh-TW/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -164,5 +164,8 @@
"if-you-have-a-lot-of-notes-you-may-consume-a-certain-number-of-tokens": "如果您有大量笔记,您可能会消耗一定数量的代币",
"force-rebuild": "强制重建",
"force-rebuild-embedding-index": "强制重建将完全重建已编制索引的所有数据",
"embedding-model-description": "切换嵌入式模型后必须重建索引"
"embedding-model-description": "切换嵌入式模型后必须重建索引",
"top-k-description": "最终返回文件的最大数量",
"embedding-score-description": "查询的相似性阈值通常是欧氏总和距离",
"embedding-lambda-description": "查询结果多样性加权参数"
}
5 changes: 4 additions & 1 deletion public/locales/zh/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -165,5 +165,8 @@
"if-you-have-a-lot-of-notes-you-may-consume-a-certain-number-of-tokens": "如果您有大量笔记,您可能会消耗一定数量的代币",
"force-rebuild": "强制重建",
"force-rebuild-embedding-index": "强制重建将完全重建已索引的所有数据",
"embedding-model-description": "切换嵌入式模型后必须重建索引"
"embedding-model-description": "切换嵌入式模型后必须重建索引",
"top-k-description": "最终返回文件的最大数量",
"embedding-score-description": "查询的相似性阈值通常是欧氏总和距离",
"embedding-lambda-description": "查询结果多样性加权参数"
}
79 changes: 54 additions & 25 deletions src/components/BlinkoAi/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,15 @@ import Link from "next/link";
import DraggableDiv from "../Common/DragContainer";
import dayjs from "@/lib/dayjs";
import { FilesAttachmentRender } from "../Common/AttachmentRender";
import { MarkdownRender } from "../Common/MarkdownRender";
import { ResizableWrapper } from "../Common/ResizableWrapper";
import { router } from "@/server/trpc";
import { useRouter } from "next/router";

export const BlinkoAiChat = observer(() => {
const ai = RootStore.Get(AiStore)
const user = RootStore.Get(UserStore)
const router = useRouter()
const scrollAreaRef = useRef<ScrollAreaHandles>(null);
const { t } = useTranslation()
useEffect(() => {
Expand All @@ -31,16 +36,16 @@ export const BlinkoAiChat = observer(() => {
onBottom={() => { }}
ref={scrollAreaRef}
key='BlinkoAiChat'
className={`mx-1 w-full !h-[500px] md:!h-[360px]`}>
className={`mx-1 w-full flex-1`}>
{
ai.chatHistory.list.length == 0 && <div className="font-bold mt-5 select-none text-desc">
<Image src="/single-logo.svg" className="ml-[-8px]" width={40} />
<Icon icon="fxemoji:smallsmile" width="24" height="24" />
{t('hi-user-name-i-can-search-for-the-notes-for-you-how-can-i-help-you-today', { name: user.name })}
</div>
}
{ai.chatHistory.list?.map((i, index) => {
return <div className="flex flex-col w-full gap-2">
{i.role == 'user' && <div className="text-center text-desc">{dayjs(i.createAt).fromNow()}</div>}
{i.role == 'user' && <div className="text-center text-desc mt-2">{dayjs(i.createAt).fromNow()}</div>}
{
i.role == 'user' && <div className="ml-auto max-w-[80%] mb-2 bg-primary text-primary-foreground p-2 rounded-xl">
{i.content}
Expand All @@ -55,25 +60,43 @@ export const BlinkoAiChat = observer(() => {
<div className="flex items-center gap-1">
<div className='text-desc'>Thinking</div>
<Icon icon="eos-icons:three-dots-loading" width="20" height="20" />
</div> : i.content
</div> :
<>
{ai.isAnswering && index === ai.chatHistory.list.length - 1 ? (
<div className="whitespace-pre-wrap">{i.content}</div>
) : (
<MarkdownRender content={i.content} disableOverflowing />
)}
</>
}
</div>
{
(ai.chatHistory.list?.length == index + 1) && <div className="flex flex-col gap-1">
{ai.relationNotes?.list?.map(note => {
return <Link onClick={e => {
e.stopPropagation()
}} href={`/detail?id=${note.id}`} className="w-[90%] flex flex-col gap-1 justify-center cursor-pointer blinko-tag" style={{ fontSize: '11px' }}>
<div className="flex items-center gap-1">
<Icon className="min-w-[15px]" icon="uim:arrow-up-left" width="15" height="15" />
{note.content && <div className="truncate ">{note.content}</div>}
</div>
(!!i.relationNotes?.length && i.relationNotes.length > 0) && <div className="flex flex-col gap-1">
{i.relationNotes?.map(note => {
return <div className="flex flex-col gap-1">
{
note.attachments && note.attachments.length > 0 && <div className="text-foreground">
<FilesAttachmentRender preview files={note.attachments ?? []} />
note.content && <Link onClick={e => {
e.stopPropagation()
}} href={`/detail?id=${note.id}`} className="w-[90%] flex flex-col gap-1 justify-center cursor-pointer blinko-tag" style={{ fontSize: '11px' }}>
<div className="flex items-center gap-1">
<Icon className="min-w-[15px]" icon="uim:arrow-up-left" width="15" height="15" />
<div className="truncate ">{note.content}</div>
</div>
</Link>
}
{
!!note.attachments && note.attachments.length > 0 &&
<div className="cursor-pointer hover:bg-hover rounded-md px-2 pb-2" onClick={e => {
router.push(`/detail?id=${note.id}`)
}}>
{
<div className="text-foreground">
<FilesAttachmentRender preview files={note.attachments ?? []} />
</div>
}
</div>
}
</Link>
</div>
})}
</div>
}
Expand All @@ -83,7 +106,7 @@ export const BlinkoAiChat = observer(() => {
</div>
})}
</ScrollArea>
<div className="flex gap-2 mt-auto w-full ">
<div className="flex gap-2 mt-auto w-full pt-2">
<div className="relative w-full pb-4 md:pb-0">
<Textarea
className="w-[78%]"
Expand Down Expand Up @@ -118,11 +141,15 @@ export const BlinkoAiChat = observer(() => {
</div>

<div onClick={e => {
if (ai.aiSearchText == '') return
ai.completionsStream()
ai.aiSearchText = ''
}} className={`${ai.aiSearchText == '' ? 'opacity-30 select-none' : ''} cursor-pointer hover:opacity-70 transition-all rounded-full bg-primary text-primary-foreground`}>
<Icon icon="uil:arrow-up" width="26" height="26" />
if (ai.isAnswering) {
ai.abort()
} else {
if (ai.aiSearchText == '') return
ai.completionsStream()
ai.aiSearchText = ''
}
}} className={`${ai.aiSearchText == '' && !ai.isAnswering ? 'opacity-30 select-none' : ''} cursor-pointer hover:opacity-70 transition-all rounded-full bg-primary text-primary-foreground w-[26px] h-[26px]`}>
{ai.isAnswering ? <Icon icon="fluent:record-stop-12-filled" width="26" height="26" /> : <Icon icon="uil:arrow-up" width="26" height="26" />}
</div>
</div>
</div>
Expand Down Expand Up @@ -160,9 +187,11 @@ export const BlinkoAi = observer(() => {
<Icon icon="mingcute:ai-line" width="20" height="20" />
</motion.div>
</PopoverTrigger>
<PopoverContent>
<div className="h-[420px] w-[420px]">
<BlinkoAiChat />
<PopoverContent className="p-0">
<div className="overflow-visible">
<ResizableWrapper id="BlinkoAiChat">
<BlinkoAiChat />
</ResizableWrapper>
</div>
</PopoverContent>
</Popover> : <BlinkoAiButton />
Expand Down
Loading

0 comments on commit d6cac1e

Please sign in to comment.