import os import gradio as gr from context.dbloader import SQLiteContextLoader from…
- User
import os import gradio as gr from context.db_loader import SQLiteContextLoader from models.gpt4o import ModelClient
class NeuroRavenApp: def init(self): self.system_prompt = None self.current_theme = None self.client = ModelClient() self.context_loader = SQLiteContextLoader()
self.conversation_themes = self.get_conversation_themes() if "Без контекста" not in self.conversation_themes: self.conversation_themes.append("Без контекста") @staticmethod def get_conversation_themes(docs_path='docs'): # Получаем список всех директорий в указанном пути return [name for name in os.listdir(docs_path) if os.path.isdir(os.path.join(docs_path, name))] def handle_query(self, message, history, context_theme, should_save): # Сохранение сообщения в базу данных, если чекбокс активирован if should_save and isinstance(self.context_loader, SQLiteContextLoader): if context_theme == "Без контекста": return "Невозможно сохранить сообщение для текущей темы..." self.context_loader.save_message(context_theme, message) self.current_theme = None return "Сообщение сохранено в контекст!" if context_theme != self.current_theme: context = self.context_loader.load_context(context_theme) if context: self.system_prompt = f"Отвечай на вопросы беря информацию из контекста: \n{context}" else: self.system_prompt = "You are a helpful assistant." self.current_theme = context_theme response = self.client.get_response( message=message, history=history, sys_prompt=self.system_prompt ) return response def launch_app(self): gr.ChatInterface( self.handle_query, chatbot=gr.Chatbot(height=500), textbox=gr.Textbox(placeholder="Напиши свой вопрос", container=False, scale=7), title="NeuroRaven", theme="soft", retry_btn=None, clear_btn="Clear", additional_inputs=[ gr.Dropdown(self.conversation_themes, label="Выбери тему контекста", value="Без контекста"), gr.Checkbox(label="Сохранить сообщение", value=False) ], css="footer{display:none !important}" ).launch(server_name="192.168.0.105", server_port=7846)if name == "main": app = NeuroRavenApp() app.launch_app()
Как мне переделать код чтобы получать conversation_themes из json файла который будет расположен в проекте?
- Assistant
Чтобы изменить код для загрузки
conversation_themesиз JSON файла вместо получения их из директорий, вам нужно внести изменения в методget_conversation_themes. Предположим, что у вас есть JSON файл, назовем егоconversation_themes.json, который будет содержать массив строк, представляющих темы. Вот как вы можете изменить код:-
Добавьте импорт для работы с JSON:
import json -
Измените метод
get_conversation_themes, чтобы он загружал данные из JSON файла:@staticmethod def get_conversation_themes(json_path='conversation_themes.json'): try: with open(json_path, 'r', encoding='utf-8') as file: themes = json.load(file) if isinstance(themes, list): return themes else: print("The JSON file does not contain a list.") return [] except (FileNotFoundError, json.JSONDecodeError) as e: print(f"Error loading conversation themes from {json_path}: {e}") return []
-