Skip to content
The Chat Archive
gpt-4-0314· OpenAI WildChat-4.8M (AI2)

замени mongodb на sqlite3: from typing import Tuple import sys import importlib.util…

  1. User

    замени mongodb на sqlite3: from typing import Tuple import sys import importlib.util from pymongo import MongoClient

    Указываем адрес и порт MongoDB-сервера

    class Environment: def init(self, client: MongoClient): # Подключаемся к базе данных self.db = client['environment']

        # Получаем доступ к коллекции
        self.plugins = self.db['plugins']
    
    def _add_plugin(self, plugin: dict) -> None:
        # Добавление документа в коллекцию
        self.plugins.insert_one(plugin)
    
    
    def add_plugin(self, title: str, repository_level: str, description: str, list_command: list, path: str) -> Tuple[bool, str]:
        """
        Adds a new plugin to the system.
    
        Args:
            title (str): The title of the plugin.
            description (str): The description of the plugin.
            list_command (list): The list of commands associated with the plugin.
            path (str): The path to the plugin file.
    
        Returns:
            Tuple[bool, str]: A tuple containing a boolean indicating whether the plugin was successfully added
            and a message describing the result.
        """
        plugin = {
            'title': title,
            'repository_level': repository_level,
            'description': description,
            'list_command': list_command,
            'path': path
        }
        try:
            self._add_plugin(plugin)
        except Exception as e:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            traceback_details = {
                'filename': exc_traceback.tb_frame.f_code.co_filename,
                'lineno': exc_traceback.tb_lineno,
                'name': exc_traceback.tb_frame.f_code.co_name,
                'type': exc_type.__name__,
                'message': str(exc_value)
            }
            del(exc_type, exc_value, exc_traceback)
            # for key, value in traceback_details.items():
            #     print("{}: {}".format(key, value))
            return False, str(traceback_details.items())
        else:
            return True, 'Plugin was successfully added.'
    def _search_plugin_path(self, search_filter: dict) -> str:
        # Выполняем поиск документов
        try:
            search_results = list(self.plugins.find(search_filter))
        except Exception as e:
            print("An error occurred:", e)
        else:
            print(search_results)
        # Возвращаем путь к документу по его команде
        path = search_results[0]['path']
        return path
    
    def search_plugin_path(self, command: str) -> str:
        search_filter = {'list_command': {'$in': [command]}}
        return self._search_plugin_path(search_filter)
    
    def get_all_plugins(self, repository_level: str) -> list:
        search_filter = {'repository_level': repository_level}
        return self._search_plugin_path(search_filter)
    
    # def get_plugin_module(self, path: str) -> object:
    #     # Импортируем модуль по пути
    #     spec = importlib.util.spec_from_file_location(path, path)
    #     module = importlib.util.module_from_spec(spec)
    #     spec.loader.exec_module(module)
    #     return module
    

    Пример данных для добавления

    plugin = {

    'title': 'system_help',

    'description': 'System help plugin, for looking up system help.',

    'list_command': ['sys help', 'system help'],

    'path': 'plugins/repo/based/system_help/'}

  2. Assistant

    from typing import Tuple import sys import importlib.util import sqlite3

    class Environment: def init(self, db_path: str): # Подключаемся к базе данных Sqlite self.conn = sqlite3.connect(db_path) self.cur = self.conn.cursor()

        # Создаем таблицу для хранения плагинов (если еще не создана)
        self.cur.execute("""
            CREATE TABLE IF NOT EXISTS plugins (
                id INTEGER PRIMARY KEY,
                title TEXT,
                repository_level TEXT,
                description TEXT,
                list_command TEXT,
                path TEXT
            )
        """)
        self.conn.commit()
    
    def _add_plugin(self, plugin: dict) -> None:
        # Добавление записи в таблицу плагинов
        query = f"""
            INSERT INTO plugins (title, repository_level, description, list_command, path)
            VALUES (?, ?, ?, ?, ?)
        """
        self.cur.execute(query, (
            plugin['title'],
            plugin['repository_level'],
            plugin['description'],
            ','.join(plugin['list_command']),
            plugin['path']
        ))
        self.conn.commit()
    
    def add_plugin(self, title: str, repository_level: str, description: str, list_command: list, path: str) -> Tuple[bool, str]:
        """
        Adds a new plugin to the system.
    
        Args:
            title (str): The title of the plugin.
            description (str): The description of the plugin.
            list_command (list): The list of commands associated with the plugin.
            path (str): The path to the plugin file.
    
        Returns:
            Tuple[bool, str]: A tuple containing a boolean indicating whether the plugin was successfully added
            and a message describing the result.
        """
        plugin = {
            'title': title,
            'repository_level': repository_level,
            'description': description,
            'list_command': list_command,
            'path': path
        }
        try:
            self._add_plugin(plugin)
        except Exception as e:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            traceback_details = {
                'filename': exc_traceback.tb_frame.f_code.co_filename,
                'lineno': exc_traceback.tb_lineno,
                'name': exc_traceback.tb_frame.f_code.co_name,
                'type': exc_type.__name__,
                'message': str(exc_value)
            }
            del(exc_type, exc_value, exc_traceback)
            # for key, value in traceback_details.items():
            #     print("{}: {}".format(key, value))
            return False, str(traceback_details.items())
        else:
            return True, 'Plugin was successfully added.'
    
    def _search_plugin_path(self, search_filter: str) -> str:
        # Выполняем поиск записей
        try:
            self.cur.execute(f"SELECT * FROM plugins WHERE list_command LIKE '%{search_filter}%'")
            search_results = self.cur.fetchall()
        except Exception as e:
            print("An error occurred:", e)
        else:
            print(search_results)
        # Возвращаем путь к записи по его команде
        path = search_results[0][5]
        return path
    
    def search_plugin_path(self, command: str) -> str:
        return self._search_plugin_path(command)
    
    def get_all_plugins(self, repository_level: str) -> list:
        return self._search_plugin_path(repository_level)
    

    Пример данных для добавления

    plugin = {

    'title': 'system_help',

    'description': 'System help plugin, for looking up system help.',

    'list_command': ['sys help', 'system help'],

    'path': 'plugins/repo/based/system_help/'}