diff --git a/README.md b/README.md index dfa7c1a5..3a14b00a 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,8 @@ Also check our sibling project, [OllamaHub](https://ollamahub.com/), where you c - 👍👎 **RLHF Annotation**: Empower your messages by rating them with thumbs up and thumbs down, facilitating the creation of datasets for Reinforcement Learning from Human Feedback (RLHF). Utilize your messages to train or fine-tune models, all while ensuring the confidentiality of locally saved data. +- 🏷️ **Conversation Tagging**: Effortlessly categorize and locate specific chats for quick reference and streamlined data collection. + - 📥🗑️ **Download/Delete Models**: Easily download or remove models directly from the web UI. - ⬆️ **GGUF File Model Creation**: Effortlessly create Ollama models by uploading GGUF files directly from the web UI. Streamlined process with options to upload from your machine or download GGUF files from Hugging Face. diff --git a/backend/apps/web/models/chats.py b/backend/apps/web/models/chats.py index bc4659de..4895740d 100644 --- a/backend/apps/web/models/chats.py +++ b/backend/apps/web/models/chats.py @@ -60,23 +60,23 @@ class ChatTitleIdResponse(BaseModel): class ChatTable: - def __init__(self, db): self.db = db db.create_tables([Chat]) - def insert_new_chat(self, user_id: str, - form_data: ChatForm) -> Optional[ChatModel]: + def insert_new_chat(self, user_id: str, form_data: ChatForm) -> Optional[ChatModel]: id = str(uuid.uuid4()) chat = ChatModel( **{ "id": id, "user_id": user_id, - "title": form_data.chat["title"] if "title" in - form_data.chat else "New Chat", + "title": form_data.chat["title"] + if "title" in form_data.chat + else "New Chat", "chat": json.dumps(form_data.chat), "timestamp": int(time.time()), - }) + } + ) result = Chat.create(**chat.model_dump()) return chat if result else None @@ -109,25 +109,37 @@ class ChatTable: except: return None - def get_chat_lists_by_user_id(self, - user_id: str, - skip: int = 0, - limit: int = 50) -> List[ChatModel]: + def get_chat_lists_by_user_id( + self, user_id: str, skip: int = 0, limit: int = 50 + ) -> List[ChatModel]: return [ - ChatModel(**model_to_dict(chat)) for chat in Chat.select().where( - Chat.user_id == user_id).order_by(Chat.timestamp.desc()) + ChatModel(**model_to_dict(chat)) + for chat in Chat.select() + .where(Chat.user_id == user_id) + .order_by(Chat.timestamp.desc()) # .limit(limit) # .offset(skip) ] - def get_all_chats_by_user_id(self, user_id: str) -> List[ChatModel]: + def get_chat_lists_by_chat_ids( + self, chat_ids: List[str], skip: int = 0, limit: int = 50 + ) -> List[ChatModel]: return [ - ChatModel(**model_to_dict(chat)) for chat in Chat.select().where( - Chat.user_id == user_id).order_by(Chat.timestamp.desc()) + ChatModel(**model_to_dict(chat)) + for chat in Chat.select() + .where(Chat.id.in_(chat_ids)) + .order_by(Chat.timestamp.desc()) ] - def get_chat_by_id_and_user_id(self, id: str, - user_id: str) -> Optional[ChatModel]: + def get_all_chats_by_user_id(self, user_id: str) -> List[ChatModel]: + return [ + ChatModel(**model_to_dict(chat)) + for chat in Chat.select() + .where(Chat.user_id == user_id) + .order_by(Chat.timestamp.desc()) + ] + + def get_chat_by_id_and_user_id(self, id: str, user_id: str) -> Optional[ChatModel]: try: chat = Chat.get(Chat.id == id, Chat.user_id == user_id) return ChatModel(**model_to_dict(chat)) @@ -142,8 +154,7 @@ class ChatTable: def delete_chat_by_id_and_user_id(self, id: str, user_id: str) -> bool: try: - query = Chat.delete().where((Chat.id == id) - & (Chat.user_id == user_id)) + query = Chat.delete().where((Chat.id == id) & (Chat.user_id == user_id)) query.execute() # Remove the rows, return number of rows removed. return True diff --git a/backend/apps/web/models/tags.py b/backend/apps/web/models/tags.py new file mode 100644 index 00000000..c14658cf --- /dev/null +++ b/backend/apps/web/models/tags.py @@ -0,0 +1,206 @@ +from pydantic import BaseModel +from typing import List, Union, Optional +from peewee import * +from playhouse.shortcuts import model_to_dict + +import json +import uuid +import time + +from apps.web.internal.db import DB + +#################### +# Tag DB Schema +#################### + + +class Tag(Model): + id = CharField(unique=True) + name = CharField() + user_id = CharField() + data = TextField(null=True) + + class Meta: + database = DB + + +class ChatIdTag(Model): + id = CharField(unique=True) + tag_name = CharField() + chat_id = CharField() + user_id = CharField() + timestamp = DateField() + + class Meta: + database = DB + + +class TagModel(BaseModel): + id: str + name: str + user_id: str + data: Optional[str] = None + + +class ChatIdTagModel(BaseModel): + id: str + tag_name: str + chat_id: str + user_id: str + timestamp: int + + +#################### +# Forms +#################### + + +class ChatIdTagForm(BaseModel): + tag_name: str + chat_id: str + + +class TagChatIdsResponse(BaseModel): + chat_ids: List[str] + + +class ChatTagsResponse(BaseModel): + tags: List[str] + + +class TagTable: + def __init__(self, db): + self.db = db + db.create_tables([Tag, ChatIdTag]) + + def insert_new_tag(self, name: str, user_id: str) -> Optional[TagModel]: + id = str(uuid.uuid4()) + tag = TagModel(**{"id": id, "user_id": user_id, "name": name}) + try: + result = Tag.create(**tag.model_dump()) + if result: + return tag + else: + return None + except Exception as e: + return None + + def get_tag_by_name_and_user_id( + self, name: str, user_id: str + ) -> Optional[TagModel]: + try: + tag = Tag.get(Tag.name == name, Tag.user_id == user_id) + return TagModel(**model_to_dict(tag)) + except Exception as e: + return None + + def add_tag_to_chat( + self, user_id: str, form_data: ChatIdTagForm + ) -> Optional[ChatIdTagModel]: + tag = self.get_tag_by_name_and_user_id(form_data.tag_name, user_id) + if tag == None: + tag = self.insert_new_tag(form_data.tag_name, user_id) + + id = str(uuid.uuid4()) + chatIdTag = ChatIdTagModel( + **{ + "id": id, + "user_id": user_id, + "chat_id": form_data.chat_id, + "tag_name": tag.name, + "timestamp": int(time.time()), + } + ) + try: + result = ChatIdTag.create(**chatIdTag.model_dump()) + if result: + return chatIdTag + else: + return None + except: + return None + + def get_tags_by_user_id(self, user_id: str) -> List[TagModel]: + tag_names = [ + ChatIdTagModel(**model_to_dict(chat_id_tag)).tag_name + for chat_id_tag in ChatIdTag.select() + .where(ChatIdTag.user_id == user_id) + .order_by(ChatIdTag.timestamp.desc()) + ] + + return [ + TagModel(**model_to_dict(tag)) + for tag in Tag.select().where(Tag.name.in_(tag_names)) + ] + + def get_tags_by_chat_id_and_user_id( + self, chat_id: str, user_id: str + ) -> List[TagModel]: + tag_names = [ + ChatIdTagModel(**model_to_dict(chat_id_tag)).tag_name + for chat_id_tag in ChatIdTag.select() + .where((ChatIdTag.user_id == user_id) & (ChatIdTag.chat_id == chat_id)) + .order_by(ChatIdTag.timestamp.desc()) + ] + + return [ + TagModel(**model_to_dict(tag)) + for tag in Tag.select().where(Tag.name.in_(tag_names)) + ] + + def get_chat_ids_by_tag_name_and_user_id( + self, tag_name: str, user_id: str + ) -> Optional[ChatIdTagModel]: + return [ + ChatIdTagModel(**model_to_dict(chat_id_tag)) + for chat_id_tag in ChatIdTag.select() + .where((ChatIdTag.user_id == user_id) & (ChatIdTag.tag_name == tag_name)) + .order_by(ChatIdTag.timestamp.desc()) + ] + + def count_chat_ids_by_tag_name_and_user_id( + self, tag_name: str, user_id: str + ) -> int: + return ( + ChatIdTag.select() + .where((ChatIdTag.tag_name == tag_name) & (ChatIdTag.user_id == user_id)) + .count() + ) + + def delete_tag_by_tag_name_and_chat_id_and_user_id( + self, tag_name: str, chat_id: str, user_id: str + ) -> bool: + try: + query = ChatIdTag.delete().where( + (ChatIdTag.tag_name == tag_name) + & (ChatIdTag.chat_id == chat_id) + & (ChatIdTag.user_id == user_id) + ) + res = query.execute() # Remove the rows, return number of rows removed. + print(res) + + tag_count = self.count_chat_ids_by_tag_name_and_user_id(tag_name, user_id) + if tag_count == 0: + # Remove tag item from Tag col as well + query = Tag.delete().where( + (Tag.name == tag_name) & (Tag.user_id == user_id) + ) + query.execute() # Remove the rows, return number of rows removed. + + return True + except Exception as e: + print("delete_tag", e) + return False + + def delete_tags_by_chat_id_and_user_id(self, chat_id: str, user_id: str) -> bool: + tags = self.get_tags_by_chat_id_and_user_id(chat_id, user_id) + + for tag in tags: + self.delete_tag_by_tag_name_and_chat_id_and_user_id( + tag.tag_name, chat_id, user_id + ) + + return True + + +Tags = TagTable(DB) diff --git a/backend/apps/web/routers/chats.py b/backend/apps/web/routers/chats.py index e97e1473..29214229 100644 --- a/backend/apps/web/routers/chats.py +++ b/backend/apps/web/routers/chats.py @@ -16,6 +16,15 @@ from apps.web.models.chats import ( Chats, ) + +from apps.web.models.tags import ( + TagModel, + ChatIdTagModel, + ChatIdTagForm, + ChatTagsResponse, + Tags, +) + from utils.utils import ( bearer_scheme, ) @@ -65,6 +74,42 @@ async def create_new_chat(form_data: ChatForm, user=Depends(get_current_user)): ) +############################ +# GetAllTags +############################ + + +@router.get("/tags/all", response_model=List[TagModel]) +async def get_all_tags(user=Depends(get_current_user)): + try: + tags = Tags.get_tags_by_user_id(user.id) + return tags + except Exception as e: + print(e) + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT() + ) + + +############################ +# GetChatsByTags +############################ + + +@router.get("/tags/tag/{tag_name}", response_model=List[ChatTitleIdResponse]) +async def get_user_chats_by_tag_name( + tag_name: str, user=Depends(get_current_user), skip: int = 0, limit: int = 50 +): + chat_ids = [ + chat_id_tag.chat_id + for chat_id_tag in Tags.get_chat_ids_by_tag_name_and_user_id(tag_name, user.id) + ] + + print(chat_ids) + + return Chats.get_chat_lists_by_chat_ids(chat_ids, skip, limit) + + ############################ # GetChatById ############################ @@ -115,6 +160,88 @@ async def delete_chat_by_id(id: str, user=Depends(get_current_user)): return result +############################ +# GetChatTagsById +############################ + + +@router.get("/{id}/tags", response_model=List[TagModel]) +async def get_chat_tags_by_id(id: str, user=Depends(get_current_user)): + tags = Tags.get_tags_by_chat_id_and_user_id(id, user.id) + + if tags != None: + return tags + else: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND + ) + + +############################ +# AddChatTagById +############################ + + +@router.post("/{id}/tags", response_model=Optional[ChatIdTagModel]) +async def add_chat_tag_by_id( + id: str, form_data: ChatIdTagForm, user=Depends(get_current_user) +): + tags = Tags.get_tags_by_chat_id_and_user_id(id, user.id) + + if form_data.tag_name not in tags: + tag = Tags.add_tag_to_chat(user.id, form_data) + + if tag: + return tag + else: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail=ERROR_MESSAGES.NOT_FOUND, + ) + else: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT() + ) + + +############################ +# DeleteChatTagById +############################ + + +@router.delete("/{id}/tags", response_model=Optional[bool]) +async def delete_chat_tag_by_id( + id: str, form_data: ChatIdTagForm, user=Depends(get_current_user) +): + result = Tags.delete_tag_by_tag_name_and_chat_id_and_user_id( + form_data.tag_name, id, user.id + ) + + if result: + return result + else: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND + ) + + +############################ +# DeleteAllChatTagsById +############################ + + +@router.delete("/{id}/tags/all", response_model=Optional[bool]) +async def delete_all_chat_tags_by_id(id: str, user=Depends(get_current_user)): + result = Tags.delete_tags_by_chat_id_and_user_id(id, user.id) + + if result: + return result + else: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND + ) + + ############################ # DeleteAllChats ############################ diff --git a/src/lib/apis/chats/index.ts b/src/lib/apis/chats/index.ts index 0eddf5b4..7c515f11 100644 --- a/src/lib/apis/chats/index.ts +++ b/src/lib/apis/chats/index.ts @@ -93,6 +93,68 @@ export const getAllChats = async (token: string) => { return res; }; +export const getAllChatTags = async (token: string) => { + let error = null; + + const res = await fetch(`${WEBUI_API_BASE_URL}/chats/tags/all`, { + method: 'GET', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + ...(token && { authorization: `Bearer ${token}` }) + } + }) + .then(async (res) => { + if (!res.ok) throw await res.json(); + return res.json(); + }) + .then((json) => { + return json; + }) + .catch((err) => { + error = err; + console.log(err); + return null; + }); + + if (error) { + throw error; + } + + return res; +}; + +export const getChatListByTagName = async (token: string = '', tagName: string) => { + let error = null; + + const res = await fetch(`${WEBUI_API_BASE_URL}/chats/tags/tag/${tagName}`, { + method: 'GET', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + ...(token && { authorization: `Bearer ${token}` }) + } + }) + .then(async (res) => { + if (!res.ok) throw await res.json(); + return res.json(); + }) + .then((json) => { + return json; + }) + .catch((err) => { + error = err; + console.log(err); + return null; + }); + + if (error) { + throw error; + } + + return res; +}; + export const getChatById = async (token: string, id: string) => { let error = null; @@ -192,6 +254,141 @@ export const deleteChatById = async (token: string, id: string) => { return res; }; +export const getTagsById = async (token: string, id: string) => { + let error = null; + + const res = await fetch(`${WEBUI_API_BASE_URL}/chats/${id}/tags`, { + method: 'GET', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + ...(token && { authorization: `Bearer ${token}` }) + } + }) + .then(async (res) => { + if (!res.ok) throw await res.json(); + return res.json(); + }) + .then((json) => { + return json; + }) + .catch((err) => { + error = err; + + console.log(err); + return null; + }); + + if (error) { + throw error; + } + + return res; +}; + +export const addTagById = async (token: string, id: string, tagName: string) => { + let error = null; + + const res = await fetch(`${WEBUI_API_BASE_URL}/chats/${id}/tags`, { + method: 'POST', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + ...(token && { authorization: `Bearer ${token}` }) + }, + body: JSON.stringify({ + tag_name: tagName, + chat_id: id + }) + }) + .then(async (res) => { + if (!res.ok) throw await res.json(); + return res.json(); + }) + .then((json) => { + return json; + }) + .catch((err) => { + error = err; + + console.log(err); + return null; + }); + + if (error) { + throw error; + } + + return res; +}; + +export const deleteTagById = async (token: string, id: string, tagName: string) => { + let error = null; + + const res = await fetch(`${WEBUI_API_BASE_URL}/chats/${id}/tags`, { + method: 'DELETE', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + ...(token && { authorization: `Bearer ${token}` }) + }, + body: JSON.stringify({ + tag_name: tagName, + chat_id: id + }) + }) + .then(async (res) => { + if (!res.ok) throw await res.json(); + return res.json(); + }) + .then((json) => { + return json; + }) + .catch((err) => { + error = err; + + console.log(err); + return null; + }); + + if (error) { + throw error; + } + + return res; +}; +export const deleteTagsById = async (token: string, id: string) => { + let error = null; + + const res = await fetch(`${WEBUI_API_BASE_URL}/chats/${id}/tags/all`, { + method: 'DELETE', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + ...(token && { authorization: `Bearer ${token}` }) + } + }) + .then(async (res) => { + if (!res.ok) throw await res.json(); + return res.json(); + }) + .then((json) => { + return json; + }) + .catch((err) => { + error = err; + + console.log(err); + return null; + }); + + if (error) { + throw error; + } + + return res; +}; + export const deleteAllChats = async (token: string) => { let error = null; diff --git a/src/lib/components/chat/ShareChatModal.svelte b/src/lib/components/chat/ShareChatModal.svelte new file mode 100644 index 00000000..b6c10df3 --- /dev/null +++ b/src/lib/components/chat/ShareChatModal.svelte @@ -0,0 +1,38 @@ + + + +
+ + +
+
or
+ + +
+
+
diff --git a/src/lib/components/common/Modal.svelte b/src/lib/components/common/Modal.svelte index 0fb3f8bd..b292b910 100644 --- a/src/lib/components/common/Modal.svelte +++ b/src/lib/components/common/Modal.svelte @@ -8,7 +8,9 @@ let mounted = false; const sizeToWidth = (size) => { - if (size === 'sm') { + if (size === 'xs') { + return 'w-[16rem]'; + } else if (size === 'sm') { return 'w-[30rem]'; } else { return 'w-[40rem]'; diff --git a/src/lib/components/layout/Navbar.svelte b/src/lib/components/layout/Navbar.svelte index bd52bd9b..3fc0ffa0 100644 --- a/src/lib/components/layout/Navbar.svelte +++ b/src/lib/components/layout/Navbar.svelte @@ -5,11 +5,21 @@ import { getChatById } from '$lib/apis/chats'; import { chatId, modelfiles } from '$lib/stores'; + import ShareChatModal from '../chat/ShareChatModal.svelte'; export let initNewChat: Function; export let title: string = 'Ollama Web UI'; export let shareEnabled: boolean = false; + export let tags = []; + export let addTag: Function; + export let deleteTag: Function; + + let showShareChatModal = false; + + let tagName = ''; + let showTagInput = false; + const shareChat = async () => { const chat = (await getChatById(localStorage.token, $chatId)).chat; console.log('share', chat); @@ -51,18 +61,34 @@ saveAs(blob, `chat-${chat.title}.txt`); }; + + const addTagHandler = () => { + // if (!tags.find((e) => e.name === tagName)) { + // tags = [ + // ...tags, + // { + // name: JSON.parse(JSON.stringify(tagName)) + // } + // ]; + // } + + addTag(tagName); + tagName = ''; + showTagInput = false; + }; + diff --git a/src/lib/components/layout/Sidebar.svelte b/src/lib/components/layout/Sidebar.svelte index 927d87d6..afd4b0e5 100644 --- a/src/lib/components/layout/Sidebar.svelte +++ b/src/lib/components/layout/Sidebar.svelte @@ -6,9 +6,14 @@ import { goto, invalidateAll } from '$app/navigation'; import { page } from '$app/stores'; - import { user, chats, settings, showSettings, chatId } from '$lib/stores'; + import { user, chats, settings, showSettings, chatId, tags } from '$lib/stores'; import { onMount } from 'svelte'; - import { deleteChatById, getChatList, updateChatById } from '$lib/apis/chats'; + import { + deleteChatById, + getChatList, + getChatListByTagName, + updateChatById + } from '$lib/apis/chats'; let show = false; let navElement; @@ -28,6 +33,12 @@ } await chats.set(await getChatList(localStorage.token)); + + tags.subscribe(async (value) => { + if (value.length === 0) { + await chats.set(await getChatList(localStorage.token)); + } + }); }); const loadChat = async (id) => { @@ -281,6 +292,29 @@ + {#if $tags.length > 0} +
+ + {#each $tags as tag} + + {/each} +
+ {/if} +
{#each $chats.filter((chat) => { if (search === '') { diff --git a/src/lib/stores/index.ts b/src/lib/stores/index.ts index c7d8f5e6..7880235c 100644 --- a/src/lib/stores/index.ts +++ b/src/lib/stores/index.ts @@ -10,6 +10,7 @@ export const theme = writable('dark'); export const chatId = writable(''); export const chats = writable([]); +export const tags = writable([]); export const models = writable([]); export const modelfiles = writable([]); diff --git a/src/routes/(app)/+layout.svelte b/src/routes/(app)/+layout.svelte index 39ae0eea..c7839d93 100644 --- a/src/routes/(app)/+layout.svelte +++ b/src/routes/(app)/+layout.svelte @@ -20,7 +20,8 @@ models, modelfiles, prompts, - documents + documents, + tags } from '$lib/stores'; import { REQUIRED_OLLAMA_VERSION, WEBUI_API_BASE_URL } from '$lib/constants'; @@ -29,6 +30,7 @@ import { checkVersion } from '$lib/utils'; import ShortcutsModal from '$lib/components/chat/ShortcutsModal.svelte'; import { getDocs } from '$lib/apis/documents'; + import { getAllChatTags } from '$lib/apis/chats'; let ollamaVersion = ''; let loaded = false; @@ -106,6 +108,7 @@ await modelfiles.set(await getModelfiles(localStorage.token)); await prompts.set(await getPrompts(localStorage.token)); await documents.set(await getDocs(localStorage.token)); + await tags.set(await getAllChatTags(localStorage.token)); modelfiles.subscribe(async () => { // should fetch models diff --git a/src/routes/(app)/+page.svelte b/src/routes/(app)/+page.svelte index 93b50a32..9507579c 100644 --- a/src/routes/(app)/+page.svelte +++ b/src/routes/(app)/+page.svelte @@ -6,11 +6,28 @@ import { goto } from '$app/navigation'; import { page } from '$app/stores'; - import { models, modelfiles, user, settings, chats, chatId, config } from '$lib/stores'; + import { + models, + modelfiles, + user, + settings, + chats, + chatId, + config, + tags as _tags + } from '$lib/stores'; import { copyToClipboard, splitStream } from '$lib/utils'; import { generateChatCompletion, cancelChatCompletion, generateTitle } from '$lib/apis/ollama'; - import { createNewChat, getChatList, updateChatById } from '$lib/apis/chats'; + import { + addTagById, + createNewChat, + deleteTagById, + getAllChatTags, + getChatList, + getTagsById, + updateChatById + } from '$lib/apis/chats'; import { queryVectorDB } from '$lib/apis/rag'; import { generateOpenAIChatCompletion } from '$lib/apis/openai'; @@ -47,6 +64,7 @@ }, {}); let chat = null; + let tags = []; let title = ''; let prompt = ''; @@ -181,6 +199,7 @@ }, messages: messages, history: history, + tags: [], timestamp: Date.now() }); await chats.set(await getChatList(localStorage.token)); @@ -673,6 +692,34 @@ } }; + const getTags = async () => { + return await getTagsById(localStorage.token, $chatId).catch(async (error) => { + return []; + }); + }; + + const addTag = async (tagName) => { + const res = await addTagById(localStorage.token, $chatId, tagName); + tags = await getTags(); + + chat = await updateChatById(localStorage.token, $chatId, { + tags: tags + }); + + _tags.set(await getAllChatTags(localStorage.token)); + }; + + const deleteTag = async (tagName) => { + const res = await deleteTagById(localStorage.token, $chatId, tagName); + tags = await getTags(); + + chat = await updateChatById(localStorage.token, $chatId, { + tags: tags + }); + + _tags.set(await getAllChatTags(localStorage.token)); + }; + const setChatTitle = async (_chatId, _title) => { if (_chatId === $chatId) { title = _title; @@ -691,7 +738,7 @@ }} /> - 0} {initNewChat} /> + 0} {initNewChat} {tags} {addTag} {deleteTag} />
diff --git a/src/routes/(app)/c/[id]/+page.svelte b/src/routes/(app)/c/[id]/+page.svelte index 412c332e..206b7398 100644 --- a/src/routes/(app)/c/[id]/+page.svelte +++ b/src/routes/(app)/c/[id]/+page.svelte @@ -6,11 +6,29 @@ import { goto } from '$app/navigation'; import { page } from '$app/stores'; - import { models, modelfiles, user, settings, chats, chatId, config } from '$lib/stores'; + import { + models, + modelfiles, + user, + settings, + chats, + chatId, + config, + tags as _tags + } from '$lib/stores'; import { copyToClipboard, splitStream, convertMessagesToHistory } from '$lib/utils'; import { generateChatCompletion, generateTitle } from '$lib/apis/ollama'; - import { createNewChat, getChatById, getChatList, updateChatById } from '$lib/apis/chats'; + import { + addTagById, + createNewChat, + deleteTagById, + getAllChatTags, + getChatById, + getChatList, + getTagsById, + updateChatById + } from '$lib/apis/chats'; import { queryVectorDB } from '$lib/apis/rag'; import { generateOpenAIChatCompletion } from '$lib/apis/openai'; @@ -49,6 +67,7 @@ }, {}); let chat = null; + let tags = []; let title = ''; let prompt = ''; @@ -97,6 +116,7 @@ }); if (chat) { + tags = await getTags(); const chatContent = chat.chat; if (chatContent) { @@ -688,6 +708,34 @@ await chats.set(await getChatList(localStorage.token)); }; + const getTags = async () => { + return await getTagsById(localStorage.token, $chatId).catch(async (error) => { + return []; + }); + }; + + const addTag = async (tagName) => { + const res = await addTagById(localStorage.token, $chatId, tagName); + tags = await getTags(); + + chat = await updateChatById(localStorage.token, $chatId, { + tags: tags + }); + + _tags.set(await getAllChatTags(localStorage.token)); + }; + + const deleteTag = async (tagName) => { + const res = await deleteTagById(localStorage.token, $chatId, tagName); + tags = await getTags(); + + chat = await updateChatById(localStorage.token, $chatId, { + tags: tags + }); + + _tags.set(await getAllChatTags(localStorage.token)); + }; + onMount(async () => { if (!($settings.saveChatHistory ?? true)) { await goto('/'); @@ -713,6 +761,9 @@ goto('/'); }} + {tags} + {addTag} + {deleteTag} />