Ë
    aQbjzH  ã                   ó  — d Z ddlZddlmZmZmZmZmZmZ ddl	Z
ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ dd	lmZmZmZmZmZmZmZmZmZmZ dd
l m!Z! dZ"dZ#e› d�Z$e› d�Z%e› d�Z&e› d�Z'e› d�Z(dZ) G d„ de«      Z*y)zÌMySQL-backed vector store for embeddings and semantic document retrieval.

Provides a VectorStore implementation persisting documents, metadata, and
embeddings in MySQL, plus similarity search utilities.
é    N)ÚAnyÚIterableÚListÚOptionalÚSequenceÚUnion)ÚDocument)Ú
Embeddings)ÚVectorStore)ÚPrivateAttr)ÚMyEmbeddings)
ÚVAR_NAME_SPACEÚatomic_transactionÚdelete_sql_tableÚexecute_sqlÚextend_sql_tableÚformat_value_sqlÚget_random_nameÚis_table_emptyÚsource_schemaÚtable_exists)ÚMySQLConnectionAbstractzHello world!Úexternal_sourcez
.embeddingz.contextz.context_mapz.retrieval_infoz.optionsÚinternal_ai_id_c                   ó(  ‡ — e Zd ZU dZ e«       Zeed<    e«       Ze	ed<    e«       Z
eed<    e«       Zee   ed<    e«       Zeed<    e«       Zeed<   	 d#d	ed
ee	   ddfˆ fd„Zdedee   fd„Zd$d„Zd#deee      deddfd„Zd$d„Z	 	 d%dee   deee      deee      dedee   f
d„Ze	 	 d%dee   d
e	deee      d	edef
d„«       Z	 d#dee    dee   dee   fd„Z!	 d&dedededee    fd„Z"d'd„Z#de$e%df   d e$e&df   d!e$e'df   ddfd"„Z(ˆ xZ)S )(ÚMyVectorStorea­  
    MySQL-backed vector store for handling embeddings and semantic document retrieval.

    Supports adding, deleting, and searching high-dimensional vector representations
    of documents using efficient storage and HeatWave ML similarity search procedures.

    Supports use as a context manager: when used in a `with` statement, all backing
    tables/data are deleted automatically when the block exits (even on exception).

    Attributes:
        db_connection (MySQLConnectionAbstract): Active MySQL database connection.
        embedder (Embeddings): Embeddings generator for computing vector representations.
        schema_name (str): SQL schema for table storage.
        table_name (Optional[str]): Name of the active table backing the store
            (or None until created).
        embedding_dimension (int): Size of embedding vectors stored.
        next_id (int): Internal counter for unique document ID generation.
    Ú_db_connectionÚ	_embedderÚ_schema_nameÚ_table_nameÚ_embedding_dimensionÚ_next_idNÚdb_connectionÚembedderÚreturnc                 óî   •— t         ‰| �  «        d| _        t        |«      | _        |xs t        |«      | _        || _        d| _        t        | j                  j                  t        «      «      | _        y)añ  
        Initialize a MyVectorStore with a database connection and embedding generator.

        Args:
            db_connection: MySQL database connection for all vector operations.
            embedder: Embeddings generator used for creating and querying embeddings.

        Raises:
            ValueError: If the schema name is not valid
            DatabaseError:
                If a database connection issue occurs.
                If an operational error occurs during execution.
        r   N)ÚsuperÚ__init__r"   r   r   r   r   r   r    ÚlenÚembed_queryÚBASIC_EMBEDDING_QUERYr!   )Úselfr#   r$   Ú	__class__s      €úN/var/www/html/venv/lib/python3.12/site-packages/mysql/ai/genai/vector_store.pyr(   zMyVectorStore.__init__d   sg   ø€ ô$ 	‰ÑÔØˆŒä)¨-Ó8ˆÔØ!Ò@¤\°-Ó%@ˆŒØ+ˆÔØ*.ˆÔô %(Ø�N‰N×&Ñ&Ô'<Ó=ó%
ˆÕ!ó    Únum_idsc                 ó    — t        | j                  | j                  |z   «      D �cg c]  }d|› �‘Œ	 }}| xj                  |z  c_        |S c c}w )zä
        Generate a batch of unique internal document IDs for vector storage.

        Args:
            num_ids: Number of IDs to create.

        Returns:
            List of sequentially numbered internal string IDs.
        r   )Úranger"   )r,   r0   ÚiÚidss       r.   Ú_get_idszMyVectorStore._get_ids„   sT   € ô ,1°·±ÀÇÁÐPWÑ@WÓ+Xö
Ø&'ˆo˜a˜SÒ!ð
ˆð 
ð 	�Š˜Ñ �Øˆ
ùò	
s   ¦Ac                 óú   ‡ ‡— ‰ j                   €at        ‰ j                  «      5 Št        ˆˆ fd„«      }d‰ j                  › d|› d�}t        ‰|‰ j                  f¬«       |‰ _         ddd«       yy# 1 sw Y   yxY w)a²  
        Create a backing SQL table for storing vectors if not already created.

        Returns:
            None

        Raises:
            DatabaseError:
                If a database connection issue occurs.
                If an operational error occurs during execution.

        Notes:
            The table name is randomized to avoid collisions.
            Schema includes content, metadata, and embedding vector.
        Nc                 ó4   •— t        ‰‰j                  | «       S ©N)r   r   )Ú
table_nameÚcursorr,   s    €€r.   ú<lambda>z2MyVectorStore._make_vector_store.<locals>.<lambda>§   s   ø€ ¬<Ø × 1Ñ 1°:ó,ð (€ r/   z
                CREATE TABLE ú.a	   (
                    `id` VARCHAR(128) NOT NULL,
                    `content` TEXT,
                    `metadata` JSON DEFAULT NULL,
                    `embed` vector(%s),
                    PRIMARY KEY (`id`)
                ) ENGINE=InnoDB;
                ©Úparams)r    r   r   r   r   r   r!   )r,   r9   Úcreate_table_stmtr:   s   `  @r.   Ú_make_vector_storez MyVectorStore._make_vector_store”   s˜   ù€ ð  ×ÑÐ#Ü# D×$7Ñ$7Ó8ð .¸FÜ,ôó�
ð)Ø"×/Ñ/Ð0°°*°ð >ð%Ð!ô ØÐ-°t×7PÑ7PÐ6Rõð $.�Ô ÷).ð .ð $÷.ð .ús   ¤AA1Á1A:r4   Ú_c           
      ó   — t        | j                  «      5 }|r1|D ],  }t        |d| j                  › d| j                  › d�|f¬«       Œ. t        || j                  | j                  «      r| j                  «        ddd«       y# 1 sw Y   yxY w)a#  
        Delete documents by ID. Optionally deletes the vector table if empty after deletions.

        Args:
            ids: Optional sequence of document IDs to delete. If None, no action is taken.

        Returns:
            None

        Raises:
            DatabaseError:
                If a database connection issue occurs.
                If an operational error occurs during execution.

        Notes:
            If the backing table is empty after deletions, the table is dropped and
            table_name is set to None.
        zDELETE FROM r<   ú WHERE id = %sr=   N)r   r   r   r   r    r   Ú
delete_all)r,   r4   rA   r:   Ú_ids        r.   ÚdeletezMyVectorStore.delete»   s�   € ô&   × 3Ñ 3Ó4ð 
	"¸ÙØò �CÜØØ& t×'8Ñ'8Ð&9¸¸4×;KÑ;KÐ:LÈNÐ[Ø #˜vöðô ˜f d×&7Ñ&7¸×9IÑ9IÔJØ—‘Ô!÷
	"÷ 
	"ñ 
	"ús   –A%BÂBc                 óÂ   — | j                   �Gt        | j                  «      5 }t        || j                  | j                   «       d| _         ddd«       yy# 1 sw Y   yxY w)zc
        Delete and drop the entire vector store table.

        Returns:
            None
        N)r    r   r   r   r   )r,   r:   s     r.   rD   zMyVectorStore.delete_allÚ   s_   € ð ×ÑÐ'Ü# D×$7Ñ$7Ó8ð (¸FÜ  ¨×):Ñ):¸D×<LÑ<LÔMØ#'�Ô ÷(ð (ð (÷(ð (ús   ¢)AÁAÚtextsÚ	metadatasc                 ó¾   — t        |«      }t        ||xs i gt        |«      z  «      D ��cg c]  \  }}t        ||¬«      ‘Œ }}}| j	                  ||¬«      S c c}}w )ap  
        Add a batch of text strings and corresponding metadata to the vector store.

        Args:
            texts: List of strings to embed and store.
            metadatas: Optional list of metadata dicts (one per text).
            ids: Optional custom document IDs.

        Returns:
            List of document IDs corresponding to the added texts.

        Raises:
            DatabaseError:
                If a database connection issue occurs.
                If an operational error occurs during execution.

        Notes:
            If metadatas is None, an empty dict is assigned to each document.
        )Úpage_contentÚmetadata)r4   )ÚlistÚzipr)   r	   Úadd_documents)r,   rH   rI   r4   rA   ÚtextÚmetaÚ	documentss           r.   Ú	add_textszMyVectorStore.add_textsæ   sk   € ô4 �U“ˆô " %¨Ò)G°r°d¼SÀ»ZÑ6GÓH÷
á��dô  $°Ö6ð
ˆ	ñ 
ð ×!Ñ! )°Ð!Ó5Ð5ùó	
s   ¬Ac                 óp   — |€t        d«      ‚t        |«      } | ||¬«      }|j                  ||¬«       |S )a‚  
        Construct and populate a MyVectorStore instance from raw texts and metadata.

        Args:
            texts: List of strings to vectorize and store.
            embedder: Embeddings generator to use.
            metadatas: Optional list of metadata dicts per text.
            db_connection: Active MySQL connection.

        Returns:
            Instance of MyVectorStore containing the added texts.

        Raises:
            ValueError: If db_connection is not provided.
            DatabaseError:
                If a database connection issue occurs.
                If an operational error occurs during execution.
        z@db_connection must be specified to create a MyVectorStore object)r#   r$   )rI   )Ú
ValueErrorrM   rS   )ÚclsrH   r$   rI   r#   Úinstances         r.   Ú
from_textszMyVectorStore.from_texts  sI   € ð4 Ð ÜØRóð ô �U“ˆá ]¸XÔFˆØ×Ñ˜5¨IÐÔ6àˆr/   rR   c           	      óœ  — |r=t        |«      t        |«      k7  r&dt        |«      › dt        |«      › d�}t        |«      ‚t        |«      dkD  r| j                  «        ng S |€| j                  t        |«      «      }|D �cg c]  }|j                  ‘Œ }}| j
                  j                  |«      }t        j                  «       }||d<   ||d<   ||d<   |D �cg c]  }|j                  ‘Œ c}|d	<   t        | j                  «      5 }t        || j                  | j                  |dd
i¬«       ddd«       |S c c}w c c}w # 1 sw Y   |S xY w)a«  
        Embed and store Document objects as high-dimensional vectors with metadata.

        Args:
            documents: List of Document objects (each with 'page_content' and 'metadata').
            ids: Optional list of explicit document IDs. Must match the length of documents.

        Returns:
            List of document IDs stored.

        Raises:
            ValueError: If provided IDs do not match the number of documents.
            DatabaseError:
                If a database connection issue occurs.
                If an operational error occurs during execution.

        Notes:
            Automatically creates the backing table if it does not exist.
        z.ids must be the same length as documents. Got z	 ids and z documents.r   NÚidÚcontentÚembedrL   zstring_to_vector(%s))Úcol_name_to_placeholder_string)r)   rU   r@   r5   rK   r   Úembed_documentsÚpdÚ	DataFramerL   r   r   r   r   r    )	r,   rR   r4   ÚmsgÚdocr[   ÚvectorsÚdfr:   s	            r.   rO   zMyVectorStore.add_documents.  sH  € ñ, ”3�s“8œs 9›~Ò-ðÜ˜3“x�j 	¬#¨i«.Ð)9¸ðFð ô ˜S“/Ð!äˆy‹>˜AÒØ×#Ñ#Õ%àˆIàˆ;Ø—-‘-¤ I£Ó/ˆCà/8Ö9¨�3×#Ó#Ð9ˆÐ9Ø—.‘.×0Ñ0°Ó9ˆä�\‰\‹^ˆØˆˆ4‰Øˆˆ9‰Øˆˆ7‰Ø2;Ö<¨3˜#Ÿ,›,Ò<ˆˆ:‰ä × 3Ñ 3Ó4ð 	¸ÜØØ×!Ñ!Ø× Ñ ØØ07Ð9OÐ/Põ÷	ð ˆ
ùò% :ùò =÷	ð ˆ
ús   ÂD7ÃD<Ä'EÅEÚqueryÚkÚkwargsc                 ó¶  — | j                   €g S | j                  j                  |«      }t        | j                  «      5 }t        |dt        › d�t        |«      g¬«       |j                  dd«      }|j                  dd«      |j                  d	d
«      |j                  dd«      dœ}t        |«      \  }}	dt        › d| j                  › d| j                   › d|› d|› dt        › dt        › dt        › d�}
t        ||
|g|	¢¬«       t        |dt        › �«       g }t        j                  |j!                  «       d   «      }|D ]~  }t        |d| j                  › d| j                   › d�|d   f¬«       |j!                  «       \  }}}||dœ}|�t        j                  |«      |d<   t#        di |¤Ž}|j%                  |«       Œ€ |cddd«       S # 1 sw Y   yxY w)aä  
        Search for and return the most similar documents in the store to the given query.

        Args:
            query: String query to embed and use for similarity search.
            k: Number of top documents to return.
            kwargs: options to pass to ML_SIMILARITY_SEARCH. Currently supports
                distance_metric, max_distance, percentage_distance, and segment_overlap

        Returns:
            List of Document objects, ordered from most to least similar.

        Raises:
            DatabaseError:
                If provided kwargs are invalid or unsupported.
                If a database connection issue occurs.
                If an operational error occurs during execution.

        Implementation Notes:
            - Calls ML similarity search within MySQL using stored procedures.
            - Retrieves IDs, content, and metadata for search matches.
            - Parsing and retrieval for context results are handled via intermediate JSONs.
        NzSET @z = string_to_vector(%s)r=   Údistance_metricÚCOSINEÚmax_distanceg333333ã?Úpercentage_distanceg      4@Úsegment_overlapr   )rk   rl   rm   z=
            CALL sys.ML_SIMILARITY_SEARCH(
                @z3,
                JSON_ARRAY(
                    'r<   zÛ'
                ),
                JSON_OBJECT(
                    "segment", "content",
                    "segment_embedding", "embed",
                    "document_name", "id"
                ),
                zR,
                %s,
                NULL,
                NULL,
                z,
                @z
            )
            zSELECT @z"SELECT id, content, metadata FROM rC   Údocument_name)rZ   rK   rL   © )r    r   r*   r   r   r   ÚVAR_EMBEDDINGÚstrÚgetr   r   ÚVAR_CONTEXTÚVAR_CONTEXT_MAPÚVAR_RETRIEVAL_INFOÚjsonÚloadsÚfetchoner	   Úappend)r,   re   rf   rg   Ú	embeddingr:   ri   Úretrieval_optionsÚretrieval_options_placeholderÚretrieval_options_paramsÚsimilarity_search_queryÚresultsÚcontext_mapsÚcontextÚdoc_idr[   rL   Údoc_argsrb   s                      r.   Úsimilarity_searchzMyVectorStore.similarity_searchg  s?  € ð: ×ÑÐ#ØˆIà—N‘N×.Ñ.¨uÓ5ˆ	ä × 3Ñ 3Ó4ð H	¸äØØœ�Ð&=Ð>Ü˜I›Ð'õð %Ÿj™jÐ):¸HÓEˆOà &§
¡
¨>¸3Ó ?Ø'-§z¡zÐ2GÈÓ'NØ#)§:¡:Ð.?ÀÓ#Cñ!Ðô GWØ!óGÑCÐ)Ð+Cð+ä�ð !à×'Ñ'Ð(¨¨$×*:Ñ*:Ð);ð <ð �ð ð /Ð/ð 0Ü�ð Ü!Ð"ð #Ü$Ð%ð &ð%'Ð#ô, ØØ'Ø'ÐCÐ*BÐCõô
 ˜ (¬?Ð*;Ð <Ô=àˆGäŸ:™: f§o¡oÓ&7¸Ñ&:Ó;ˆLØ'ò $�ÜØð Ø $× 1Ñ 1Ð2°!°D×4DÑ4DÐ3Eð F(ð(ð $ OÑ4Ð6õð -3¯O©OÓ,=Ñ)�˜ ð !Ø$+ñ�ð Ð'Ü+/¯:©:°hÓ+?�H˜ZÑ(äÑ* Ñ*�Ø—‘˜sÕ#ð)$ð, ÷QH	÷ H	ò H	ús   ¿FGÇGc                 ó   — | S )aÃ  
        Enter the runtime context related to this vector store instance.

        Returns:
            The current MyVectorStore object, allowing use within a `with` statement block.

        Usage Notes:
            - Intended for use in a `with` statement to ensure automatic
              cleanup of resources.
            - No special initialization occurs during context entry, but enables
              proper context-managed lifecycle.

        Example:
            with MyVectorStore(db_connection, embedder) as vectorstore:
                vectorstore.add_texts([...])
                # Vector store is active within this block.
            # All storage and resources are now cleaned up.
        ro   )r,   s    r.   Ú	__enter__zMyVectorStore.__enter__Ó  s	   € ð& ˆr/   Úexc_typeÚexc_valÚexc_tbc                 ó$   — | j                  «        y)aÄ  
        Exit the runtime context for the vector store, ensuring all storage
        resources are cleaned up.

        Args:
            exc_type: The exception type, if any exception occurred in the context block.
            exc_val: The exception value, if any exception occurred in the context block.
            exc_tb:  The traceback object, if any exception occurred in the context block.

        Returns:
            None: Indicates that exceptions are never suppressed; they will propagate as normal.

        Implementation Notes:
            - Automatically deletes all vector store data and backing tables via `delete_all()`
            upon exiting the context.
            - This cleanup occurs whether the block exits normally or due to an exception.
            - Does not suppress exceptions; errors in the context block will continue to propagate.
            - Use when the vector store lifecycle is intended to be temporary or scoped.

        Example:
            with MyVectorStore(db_connection, embedder) as vectorstore:
                vectorstore.add_texts([...])
                # Vector store is active within this block.
            # All storage and resources are now cleaned up.
        N)rD   )r,   r‡   rˆ   r‰   s       r.   Ú__exit__zMyVectorStore.__exit__è  s   € ð> 	�‰Õr/   r8   )r%   N)NN)é   )r%   r   )*Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   Ú__annotations__r   r
   r   rq   r    r   r!   Úintr"   r(   rM   r5   r@   r   r   rF   rD   r   Údictr   rS   Úclassmethodr   rX   r	   rO   r„   r†   r   ÚtypeÚBaseExceptionÚobjectr‹   Ú__classcell__)r-   s   @r.   r   r   I   s0  ø… ññ& /:«m€NÐ+Ó;Ù'›M€IˆzÓ)Ù#›€L�#Ó%Ù!,£€K�˜#‘Ó.Ù +£Ð˜#Ó-Ù“M€HˆcÓ!ð
 *.ñ
à.ð
ð ˜:Ñ&ð
ð 
õ	
ð@ ð ¨¨S©	ó ó %.ñN"˜( 8¨C¡=Ñ1ð "¸sð "Àtó "ó>
(ð +/Ø#'ñ	 6à˜‰}ð 6ð ˜D ™JÑ'ð 6ð �d˜3‘iÑ ð	 6ð
 ð 6ð 
ˆc‰ó 6ðD ð
 +/Ø15ñ#à˜‰}ð#ð ð#ð ˜D ™JÑ'ð	#ð
 /ð#ð 
ò#ó ð#ðL ;?ñ7Ø˜h™ð7Ø.2°3©ið7à	ˆc‰ó7ðx ñjàðjð ðjð ð	jð
 
ˆh‰ójóXð*à˜˜d˜
Ñ#ðð �} dÐ*Ñ+ðð �f˜d�lÑ#ð	ð
 
÷r/   r   )+r�   rv   Útypingr   r   r   r   r   r   Úpandasr_   Úlangchain_core.documentsr	   Úlangchain_core.embeddingsr
   Úlangchain_core.vectorstoresr   Úpydanticr   Úmysql.ai.genai.embeddingr   Úmysql.ai.utilsr   r   r   r   r   r   r   r   r   r   Úmysql.connector.abstractsr   r+   ÚEMBEDDING_SOURCErp   rs   rt   ru   ÚVAR_OPTIONSÚID_SPACEr   ro   r/   r.   ú<module>r¥      sœ   ðñ:ó ç A× Aã å -Ý 0Ý 3Ý  å 1÷÷ ÷ õ >à&Ð Ø$Ð à!Ð" *Ð-€ØÐ  Ð)€Ø#Ð$ LÐ1€Ø&Ð' Ð7Ð ØÐ  Ð)€à€ô~�Kõ ~r/   