So I have a bunch of text documents all over my computer that I have built up over many…
- User
So I have a bunch of text documents all over my computer that I have built up over many years, even decades, lots of files of random notes, things I keep track of, designs, files filled with text prompts for LLMs or ones filled with text prompts for stable diffusion(text-to-image generative AI diffusion models), there is documents that contain wildcards, for example colors.txt that when included in a prompt for a text-to-image model, will pull in one random line from that file, in the example I gave it would be a random color, like red, blue, yellow etc, also some that might contain scraped info on a Stable Diffusion AI model from a website, including example prompts, a link and the description of the model given by the author. Point is, I have a lot of text documents that I want to organize into a database, so I can sort, search, filter and organize using a REACT based front end, with a FastAPI backend, using SQLAlchemy and Pydantic.
What I would like, is a suitable design for the database model, and any other details or considerations for such a system.
- Assistant
- User
When I mentioned searching, I did mean a Full-Text Search of the documents, I am fine with using tagging as well however. I want a flexible system, and I want to be able to add new "documents" directly into the database, so rather then creating documents outside of this REACT UI, I instead use the REACT UI itself to directly add new documents, they could range in size from quick little notes, all the way to a full document that I keep coming back to and modifying, all within the REACT UI(which obviously sends the changes through the FastAPI backend, with the backend being responsible for database changes)
- Assistant
- User
Are PostgreSQL and Elasticsearch the only options for this? And since you mention Elasticsearch as a "search service", it sounds like this isn't something I can run locally alongside the backend server? It seems like a remote service run by a company that I would need an account, and maybe even pay for.
- Assistant
- User
My preference is SQLite, however, the requirement is to be able to perform a search which would return all matching documents, fully searching the entire contents of every document, but I also want to store the files, probably within the database itself, rather then externally, because as I said, I want to be able to just add new "documents" for tasks such as quick note taking, or more intensive tasks such as design documents or if I wanted to write software documentation or even research papers. I don't want to have to then save out an extra file for every entry I make, and I want to avoid making new documents on my HDD, as my current workflow is to create a document, such as the one I am using to store this conversation:
AIDILI Talk with GPT4 2023-12-22.txt, and now I have a massive folder filled with text files, which, while I can search using Visual Studio Code, it is messy and I want all my notes and other documents in one UI, I currently have 5 separate Visual Studio Code windows open pointed at different folders, some are code projects, so those are fine, but the ones I point at storing LLM chats, or LLM prompts, or another one I have pointed at all my wildcard files for Stable Diffusion, which contain files containing full prompts, or categorized word lists. This is my reasoning for this, and because I am also working on a more broad organization tool using FastAPI for a backend, with REACT for the front end, I would want to include a page dedicated for all my documentation, searching, which includes fuzzy searching, the idea of having a versioning system and a backup in case of failure would also be great functionality I want. Right now my FastAPI backend is using SQLite, it was desirable to keep it self-contained, rather than needing several services, and once I complete my app, I intend to build out the REACT side to then be directly served by the FastAPI server, so then I only need to run one server to access everything. - Assistant
- User
I would like to see FastAPI endpoints for use by the REACT frontend, and I want to see the implementation for versioning, as well as at least an example REACT .jsx page incorporating browsing, searching, editing and creating new documents, or adding documents from existing files.(So, uploading) I also want the categories and tagging systems as before.
- Assistant
- User
Sorry if I asked for too much in one go, my intent was to get the full details, and I am fine with splitting it up into smaller parts, if you like, given the entire system we planned out in mind, we will focus on one part at a time, these are the documents we want:
For FastAPI:
- document_routes.py - The FastAPI endpoints for document creation, adding, updating and deleting, as well as being able to get lists of past versions of a document, or get the past versions of the documents themselves, changing what the "current" version is, in the case of reverting to an older version, and searching documents or getting all documents.
- crud.py - The Database requests themselves, to act as an intermediate between the endpoints and the database itself
- database.py - The core database, should be a fairly small file that just initializes SQLAlchemy and the DB
- models.py - The actual database models
For REACT:
- /src/components/ - This is a folder, if you think we can add components that can be reused elsewhere and not specific to the document management, we can create standalone components here
- Assistant
- User
This is why I said we should do it bit by bit, sorry I didn't tell you where to start, I assumed you would pick just one file to do before continuing, and for the REACT frontend, I just want the functionality, I can worry about design and style after the functionality is complete.
Ok, let's take a look at what you did so far, database.py is a short file, and fairly straight forward, I would say that is complete. As for models.py, it looks good, personally I would remove content from the Document, since it is already included in DocumentVersion, however, we also need some way of selecting what the "current version" of a document is, but I am not sure if creating a circular loop with having Document then point back at DocumentVersion, but that is the only change I can see happening there. Since we need to address something, I will just leave it at that to let you address it, then I will direct you further.
- Assistant
- User
Ok, that seems acceptable to me, let's continue shall we? For crud.py, you left out most of the implementation details, I would like you to address this before we continue.
- Assistant
- User
Ah, yes, my mistake for not including schemas.py, I will address it before we do the endpoints, also, I am fine with just the raw functionality being in place, we can handle exception handling, etc later on, just focusing on the core functionality first, however, I would like to see you continue the crud.py to include the crud functions for managing tags, categories, and anything else required for this document system.
- Assistant
- User
Ah, yes, I would like to utilize FTS5, I know it doesn't support the features of a full-fledged search engine like Elasticsearch, but I assume it is still more robust than using SQLAlchemy .contains(), if you could make all the required changes to crud.py to incorporate FTS5 instead I would appreciate it, including the full crud function for those that change, but only include the crud functions that require changes.
- Assistant
- User
I appreciate you going back and correcting the models.py as well, thank you for that, I think what we have is fine now, so let's move on to what I missed before, the schemas.py for Pydantic validation.
- Assistant
- User
Awesome, now I think the only thing left on the FastAPI side is to create the endpoints themselves, to supply full functionality, so let us proceed with a fully functioning set of endpoints in document_routers.py.
- Assistant
- User
You are amazing, I think that is everything we need for the FastAPI backend side, anything else might just be minor tweaks or error checking, and then later I can add more robust error checking or adding anything we overlooked or if things change later.
So, I think we can move on to the REACT frontend, again, I do not care about the design or styling of the components, I just want all the functionality provided by the FastAPI backend, to be accessible in a REACT frontend page, first, we need to determine what parts of the page might be best broken into their own generic component files, like maybe the document editor could be a separate component stored in the components folder, so that I can use that functionality elsewhere in my REACT front end later on. Remember, we are just deciding on the files we want to work on, so just think it through step-by-step based on the FastAPI endpoints and the functionality required, and then list the required files, and I will guide you through each file in turn.
- Assistant
- User
Ok great, it might be best to start with utilities, especially ones where we have a clear functionality goal in mind, let's start with the apiClient.js
- Assistant
- User
Great! Now let's do DocumentEditor.jsx
- Assistant
The
DocumentEditor.jsxcomponent will be a text editor intended to allow users to create or update document contents. For the sake of simplicity and demonstration, I will use a basic HTML . In a production environment, you would likely replace this with a rich text editor like Draft.js or CKEditor, as mentioned earlier. - User
As I said, don't stress too much over styling for now, the only styling should be based around specific layout or functionality, so that is fine. I would like to see a more feature filled editor, could you give an example of the most widely used rich text editor for the DocumentEditor.jsx?
- Assistant
- User
Ok great, I will take a look at this closer in the future, for now, let's move on to SearchBar.jsx
- Assistant
The
SearchBar.jsxcomponent will be a simple input field dedicated to submitting search queries. To keep things flexible, the component will accept a callback function as a prop, which will be invoked with the search term whenever the user submits a search. - User
We don't need the example as we will be including it within the main page, but, moving on, next up in the list is the component TagSelector.jsx
- Assistant
- User
Ok great, we still have CategoriesSelector.jsx, VersionHistory.jsx and DocumentList.jsx, but I think we might revisit those components later, what I want you to focus on now is putting it all together in the main scene component, documents.jsx, using these custom components and the apiClient.js to create the full picture of the document editor, again, just focusing on the raw functionality, with basic layouts, we don't need to worry about any fancy CSS or styling.
- Assistant
- User
Ok, slight issue, error with adding a new document:
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: documents.current_version_id [SQL: INSERT INTO documents (current_version_id, title) VALUES (?, ?) RETURNING id, created_at, updated_at] - Assistant
- User
The not null error specifically points at the db.commit() line just below db.add(new_document), before it was db.flush(), because we are not assigning a current_version_id anywhere before then, we also won't get the new_document.id until we commit it, which I assume means we also cannot create the document version before the document to first get the document_version_id either.
- Assistant
- User
Ok, not going to lie, I am a bit confused on this one, I think it has to do with the changes recommended for FTS5, this is the error:
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: document_versions.id [SQL: INSERT INTO document_versions (document_id, content) VALUES (?, ?) RETURNING id, created_at, updated_at]Which refers to the flush in the create versions crud function:
def _document_version_create(document_id: int, content: str, db: Session) -> models.DocumentVersion: new_version = models.DocumentVersion(document_id=document_id, content=content) # Insert into the FTS table fts_version = models.DocumentVersionFTS(id=new_version.id, content=content) db.add(new_version) db.add(fts_version) db.flush() return new_versionAnd just as reference, this is my current DocumentVersion model:
class DocumentVersion(Base): __tablename__ = 'document_versions' id: Mapped[int] = mapped_column(Integer, primary_key=True) document_id: Mapped[int] = mapped_column(Integer, ForeignKey('documents.id')) content: Mapped[str] = mapped_column(Text) created_at = mapped_column(DateTime(timezone=True), server_default=func.now()) updated_at = mapped_column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now()) @declared_attr def __table_args__(cls): return ( {'sqlite_with_rowid': False}, # This is important for FTS5 tables ) - Assistant
- User
I am now getting this error:
File "D:\AI Generation\Projects\ai-webui\aidili-fastreact\backend\database\models.py", line 648, in __table_args__ return (Index('ix_document_versions_fts', 'content', sqlite_using='FTS5'),) File "D:\AI Generation\Projects\ai-webui\aidili-fastreact\backend\venv\lib\site-packages\sqlalchemy\sql\schema.py", line 5219, in __init__ self._validate_dialect_kwargs(dialect_kw) File "D:\AI Generation\Projects\ai-webui\aidili-fastreact\backend\venv\lib\site-packages\sqlalchemy\sql\base.py", line 621, in _validate_dialect_kwargs raise exc.ArgumentError( sqlalchemy.exc.ArgumentError: Argument 'sqlite_using' is not accepted by dialect 'sqlite' on behalf of <class 'sqlalchemy.sql.schema.Index'>Pointing at the DocumentVersionFTS model
- Assistant
- User
I mean, you already have how I was trying to use them before, I have two crud functions, one for creating the document version:
def _document_version_create(document_id: int, content: str, db: Session) -> models.DocumentVersion: new_version = models.DocumentVersion(document_id=document_id, content=content) db.add(new_version) db.flush() # Ensures new_version.id is populated # Now create an entry in the FTS table with the new version ID fts_version = models.DocumentVersionFTS(id=new_version.id) db.add(fts_version) # No need to flush here, as the main purpose was to get the ID for new_version return new_versionAnd one for searching:
def documents_search(query: str, db: Session) -> List[models.Document]: """Full-text search functionality using FTS5.""" # To search the FTS table, use the match operation provided by the FTS5 extension fts_version_ids = db.query(models.DocumentVersionFTS.id).filter( func.fts5(models.DocumentVersionFTS.__tablename__, None, query) ).all() document_ids = [vid.id for vid in fts_version_ids] # Now that we have the version IDs, let’s fetch the corresponding documents # Note: This assumes that the document’s current_version_id is synchronized with the FTS table documents = db.query(models.Document).filter( models.Document.current_version_id.in_(document_ids) ).all() return documents - Assistant
- User
Ok, looks like creating a document(and thus document version) works fine now, but searching gave this error:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: document_versions_fts [SQL: SELECT rowid FROM document_versions_fts WHERE document_versions_fts MATCH ?]This is after I had to correct an error requiring the use of using text():
def documents_search(query: str, db: Session) -> List[models.Document]: """Full-text search functionality using FTS5.""" matched_Versions = db.execute( _sql.text("""SELECT rowid FROM document_versions_fts WHERE document_versions_fts MATCH :query"""), {"query": query} ).fetchall() document_ids = [row['rowid'] for row in matched_Versions] # Now that we have the version IDs, let’s fetch the corresponding documents # Note: This assumes that the document’s current_version_id is synchronized with the FTS table documents = db.query(models.Document).filter( models.Document.current_version_id.in_(document_ids) ).all() return documentsIt points specifically at that db.execute()
- Assistant
The error you're encountering indicates that SQLite can't find the
document_versions_ftscolumn when performing the match operation. This error message is somewhat misleading because is actually the name of the table and not a column. - User
When trying to search, I am getting this error:
File "D:\AI Generation\Projects\ai-webui\aidili-fastreact\backend\database\crud.py", line 534, in documents_search matched_Versions = db.execute( File "D:\AI Generation\Projects\ai-webui\aidili-fastreact\backend\venv\lib\site-packages\sqlalchemy\orm\session.py", line 2308, in execute return self._execute_internal( File "D:\AI Generation\Projects\ai-webui\aidili-fastreact\backend\venv\lib\site-packages\sqlalchemy\orm\session.py", line 2199, in _execute_internal result = conn.execute( File "D:\AI Generation\Projects\ai-webui\aidili-fastreact\backend\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1416, in execute return meth( File "D:\AI Generation\Projects\ai-webui\aidili-fastreact\backend\venv\lib\site-packages\sqlalchemy\sql\elements.py", line 516, in _execute_on_connection return connection._execute_clauseelement( File "D:\AI Generation\Projects\ai-webui\aidili-fastreact\backend\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1639, in _execute_clauseelement ret = self._execute_context( File "D:\AI Generation\Projects\ai-webui\aidili-fastreact\backend\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1848, in _execute_context return self._exec_single_context( File "D:\AI Generation\Projects\ai-webui\aidili-fastreact\backend\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1988, in _exec_single_context self._handle_dbapi_exception( File "D:\AI Generation\Projects\ai-webui\aidili-fastreact\backend\venv\lib\site-packages\sqlalchemy\engine\base.py", line 2343, in _handle_dbapi_exception raise sqlalchemy_exception.with_traceback(exc_info[2]) from e File "D:\AI Generation\Projects\ai-webui\aidili-fastreact\backend\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1969, in _exec_single_context self.dialect.do_execute( File "D:\AI Generation\Projects\ai-webui\aidili-fastreact\backend\venv\lib\site-packages\sqlalchemy\engine\default.py", line 922, in do_execute cursor.execute(statement, parameters) sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) unable to use function MATCH in the requested context [SQL: SELECT rowid FROM document_versions_fts WHERE content MATCH ?] [parameters: ('mofa',)] (Background on this error at: https://sqlalche.me/e/20/e3q8) - Assistant
- User
I ran that command on the sqlite database file I created with my FastAPI app:
CREATE VIRTUAL TABLE IF NOT EXISTS document_versions_fts USING FTS5(content);I used SQliteStudio, it finished in 0.0 seconds with rows affected: 0. I saw no errors or any other messages, the document_versions_fts table didn't appear to change, I assume it just, did not run because it already existed... - Assistant
- User
I am getting close, I now have the table created properly, and I believe it is being filled properly, however I still have an issue with search:
File "D:\AI Generation\Projects\ai-webui\aidili-fastreact\backend\routers\documents.py", line 49, in search_docs results = crud.documents_search(query=query, db=db) File "D:\AI Generation\Projects\ai-webui\aidili-fastreact\backend\database\crud.py", line 542, in documents_search document_ids = [row['docid'] for row in matched_Versions] File "D:\AI Generation\Projects\ai-webui\aidili-fastreact\backend\database\crud.py", line 542, in <listcomp> document_ids = [row['docid'] for row in matched_Versions] File "lib\\sqlalchemy\\cyextension\\resultproxy.pyx", line 48, in sqlalchemy.cyextension.resultproxy.BaseRow.__getitem__ TypeError: tuple indices must be integers or slices, not strI am not quite sure of the error, this is the code for my crud function:
def documents_search(query: str, db: Session) -> List[models.Document]: """Full-text search functionality using FTS5.""" matched_versions = db.execute( _sql.text("""SELECT docid FROM document_versions_fts WHERE content MATCH :query"""), {"query": query} ).fetchall() document_ids = [row['docid'] for row in matched_versions] # Now that we have the version IDs, let’s fetch the corresponding documents # Note: This assumes that the document’s current_version_id is synchronized with the FTS table documents = db.query(models.Document).filter( models.Document.current_version_id.in_(document_ids) ).all() return documents - Assistant
The error message "TypeError: tuple indices must be integers or slices, not str" indicates that the result rows returned by
db.execute()are being treated as tuples, not dictionaries. When you use the method with SQLAlchemy's , you get back a list of tuples, with each tuple representing a row from the result set. - User
ok, using row[0] seems to work fine, now a quick question, as a final follow up, the DocumentVersion(and the FTS version) has the content column, which contains the main documents contents, but looking back at the simple non-FTS search you gave me earlier, it included searching not just content, but also the documents title, I am assuming it would require reworking to include title in the FTS search?
- Assistant
- User
Ok, going back to the REACT components, let's create the DocumentList.jsx
- Assistant
- User
We have a slight problem with selecting a document for edit, probably saving too, I changed the element a little so it only shows when editing:
{editDocument ? ( <DocumentEditor initialContent={editDocument ? editDocument.content : ''} onSave={handleSaveDocument} onCancel={handleCancelEditing} />) : (<></>)}The issue is, the document itself doesn't contain the content, instead, the document json returned looks like this:
{ "title": "Did this work?", "id": 2, "current_version_id": 2, "created_at": "2023-12-22T07:01:20", "updated_at": "2023-12-22T07:01:20", "versions": [ { "content": "Did this mofa work?!", "id": 2, "created_at": "2023-12-22T07:01:20" } ], "tags": [], "categories": [] }Which means we need to get the current versions content...
- Assistant
You're right; based on the structure of the document JSON you've shared, the
contentof the document is nested within the array. The field indicates which version is the active one, but in this setup, you need to actually access that version's content.