hyb
2025-12-30 5e753a15ff53faab2261a53367e44d38caf87041
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
Ë
WñúhsHãó—dZddlZddlmZmZmZmZmZmZddl    Z
ddl m Z ddl mZddlmZddlmZddlmZdd    lmZmZmZmZmZmZmZmZmZmZdd
l m!Z!d Z"d Z#e›d Z$e›dZ%e›dZ&e›dZ'e›dZ(dZ)Gd„de«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 ó(‡—eZdZUdZe«Zeed<e«Ze    ed<e«Z
e ed<e«Z e e ed<e«Zeed<e«Zeed<    d#d    ed
e e    d dfˆfd „ Zd ed ee fd„Zd$d„Zd#de ee ded dfd„Zd$d„Z        d%dee de eede ee ded ee f
d„Ze        d%dee d
e    de eed    ed ef
d„«Z    d#dee dee d ee fd„Z!    d&de deded ee fd„Z"d'd„Z#de$e%dfd e$e&dfd!e$e'dfd dfd"„Z(ˆxZ)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|«|_|xs t |«|_||_d|_t|j jt««|_ 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.
        rN) ÚsuperÚ__init__r"rrr rrr ÚlenÚ embed_queryÚBASIC_EMBEDDING_QUERYr!)Úselfr#r$Ú    __class__s   €úNH:\Change_password\venv_build\Lib\site-packages\mysql/ai/genai/vector_store.pyr(zMyVectorStore.__init__dsgø€ô$    ‰ÑÔØˆŒ ä)¨-Ó8ˆÔØ!Ò@¤\°-Ó%@ˆŒØ+ˆÔØ*.ˆÔô%(Ø N‰N× &Ñ &Ô'<Ó =ó%
ˆÕ!óÚnum_idscó —t|j|j|z«Dcgc]}d|›‘Œ    }}|xj|z c_|Scc}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_idszMyVectorStore._get_ids„sT€ô,1°·±ÀÇ Á ÐPWÑ@WÓ+Xö
Ø&'ˆo˜a˜SÒ !ð
ˆð
ð      Š ˜Ñ  ؈
ùò    
s¦ A cóú‡‡—‰j€at‰j«5Štˆˆfd„«}d‰j›d|›d}t ‰|‰j f¬«|‰_ddd«yy#1swYyxYw)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)rr)Ú
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 rrrrrr!)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 ¤AA1Á1A:r4Ú_c
ó —t|j«5}|r1|D],}t|d|j›d|j›d|f¬«Œ.t ||j|j«r|j «ddd«y#1swYyxYw)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)rrrrr rÚ
delete_all)r,r4rAr:Ú_ids     r.ÚdeletezMyVectorStore.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|_ddd«yy#1swYyxYw)zc
        Delete and drop the entire vector store table.
 
        Returns:
            None
        N)r rrrr)r,r:s  r.rDzMyVectorStore.delete_allÚs_€ð × Ñ Ð 'Ü# D×$7Ñ$7Ó8ð (¸FÜ  ¨×):Ñ):¸D×<LÑ<LÔMØ#'Ô ÷ (ð (ð (÷ (ð (ús ¢)AÁAÚtextsÚ    metadatasc ó¾—t|«}t||xsigt|«z«Dcgc]\}}t||¬«‘Œ}}}|j    ||¬«Scc}}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,rHrIr4rAÚtextÚmetaÚ    documentss        r.Ú    add_textszMyVectorStore.add_textsæsk€ô4U“ ˆô" %¨Ò)G°r°d¼SÀ»ZÑ6GÓH÷
ᐐdô  $°Ö 6ð
ˆ    ñ
ð×!Ñ! )°Ð!Ó5Ð5ùó    
s¬Acóp—|€ td«‚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)Ú
ValueErrorrMrS)ÚclsrHr$rIr#Úinstances      r.Ú
from_textszMyVectorStore.from_textssI€ð4 Ð  ÜØRóð ôU“ ˆá ]¸XÔFˆØ×ј5¨IÐÔ6àˆr/rRc    óœ—|r=t|«t|«k7r&dt|«›dt|«›d}t|«‚t|«dkDr|j«ngS|€|jt|««}|Dcgc]}|j‘Œ}}|j
j |«}tj«}||d<||d<||d<|Dcgc]}|j‘Œc}|d    <t|j«5}t||j|j|dd
i¬ «ddd«|Scc}wcc}w#1swY|SxYw) 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.rNÚidÚcontentÚembedrLzstring_to_vector(%s))Úcol_name_to_placeholder_string)r)rUr@r5rKrÚembed_documentsÚpdÚ    DataFramerLrrrrr )    r,rRr4ÚmsgÚdocr[ÚvectorsÚdfr:s             r.rOzMyVectorStore.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€gS|jj|«}t|j«5}t |dt ›dt|«g¬«|jdd«}|jdd«|jd    d
«|jd d «d œ}t|«\}}    dt ›d|j›d|j›d|›d|›dt›dt›dt›d}
t ||
|g|    ¢¬«t |dt›«g} tj|j!«d «} | D]~} t |d|j›d|j›d| df¬«|j!«\}}}||dœ}|tj|«|d<t#di|¤Ž}| j%|«Œ€| cddd«S#1swYyxYw)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.
        NzSET @z = string_to_vector(%s)r=Údistance_metricÚCOSINEÚ max_distanceg333333ã?Úpercentage_distanceg4@Úsegment_overlapr)rkrlrmz=
            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
            )
            zSELECT @z"SELECT id, content, metadata FROM rCÚ document_name)rZrKrL©)r rr*rrrÚ VAR_EMBEDDINGÚstrÚgetrrÚ VAR_CONTEXTÚVAR_CONTEXT_MAPÚVAR_RETRIEVAL_INFOÚjsonÚloadsÚfetchoner    Úappend)r,rerfrgÚ    embeddingr:riÚretrieval_optionsÚretrieval_options_placeholderÚretrieval_options_paramsÚsimilarity_search_queryÚresultsÚ context_mapsÚcontextÚdoc_idr[rLÚdoc_argsrbs                   r.Úsimilarity_searchzMyVectorStore.similarity_searchgs?€ð: × Ñ Ð #؈Ià—N‘N×.Ñ.¨uÓ5ˆ    ä  × 3Ñ 3Ó 4ðH    ¸ä ØØœ Ð&=Ð>ܘI›Ð'õ ð %Ÿj™jÐ):¸HÓEˆOà &§
¡
¨>¸3Ó ?Ø'-§z¡zÐ2GÈÓ'NØ#)§:¡:Ð.?ÀÓ#Cñ!Ð ô GWØ!ó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Õ#ð) $ð,÷QH    ÷H    òH    ús ¿FGÇGcó—|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__zMyVectorStore.__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__zMyVectorStore.__exit__ès€ð>     ‰Õr/r8)r%N)NN)é)r%r )*Ú__name__Ú
__module__Ú __qualname__Ú__doc__r rrÚ__annotations__rr
rrqr rr!Úintr"r(rMr5r@rrrFrDrÚdictrrSÚ classmethodr rXr    rOr„r†rÚtypeÚ BaseExceptionÚobjectr‹Ú __classcell__)r-s@r.rrIs0ø…ññ&/:«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ÚtypingrrrrrrÚpandasr_Úlangchain_core.documentsr    Úlangchain_core.embeddingsr
Úlangchain_core.vectorstoresr Úpydanticr Úmysql.ai.genai.embeddingr Úmysql.ai.utilsrrrrrrrrrrÚmysql.connector.abstractsrr+ÚEMBEDDING_SOURCErprsrtruÚ VAR_OPTIONSÚID_SPACError/r.ú<module>r¥sœðñ:ó  çA×Aãå-Ý0Ý3Ý å1÷ ÷ ÷ õ>à&ÐØ$Ðà!Ð" *Ð-€ ØÐ  Ð)€ Ø#Ð$ LÐ1€Ø&Ð' Ð7ÐØÐ  Ð)€ à €ô~Kõ~r/