
    dhF                    \   S SK Jr  S SKrS SKrS SKJrJrJrJrJ	r	J
r
Jr  S SKrS SKJr  S SKJrJr  S SKJrJr   S SKJr  S SKJr  S S	KJr  S S
KJr  S SKJr  \" 5       rSr Sr! " S S\5      r" " S S\"5      r# " S S\"5      r$ " S S5      r% " S S\5      r&g! \ a	    S SKJr   Nhf = f)    )annotationsN)AnyDictIterableListOptionalTupleType)func)JSONUUID)Sessionrelationship)declarative_base)Document)
Embeddings)get_from_dict_or_env)VectorStorei   	langchainc                  \    \ rS rSrSrSr\R                  " \" SS9S\	R                  S9r	Srg)	BaseModel   zBase model for all SQL stores.Tas_uuid)primary_keydefault N)__name__
__module____qualname____firstlineno____doc____abstract__
sqlalchemyColumnr   uuiduuid4__static_attributes__r       d/var/www/html/shao/venv/lib/python3.13/site-packages/langchain_community/vectorstores/pgembedding.pyr   r      s'    (LT$/T4::VDr)   r   c                      \ rS rSrSrSr\R                  " \R                  5      r	\R                  " \
5      r\" SSSS9r\SS j5       r\ S       SS
 jj5       rSrg	)CollectionStore$   zCollection store.langchain_pg_collectionEmbeddingStore
collectionT)back_populatespassive_deletesc                x    UR                  U 5      R                  U R                  U:H  5      R                  5       $ N)queryfilternamefirst)clssessionr7   s      r*   get_by_nameCollectionStore.get_by_name2   s.    }}S!((T)9:@@BBr)   Nc                    SnU R                  X5      nU(       a  XT4$ U " X#S9nUR                  U5        UR                  5         SnXT4$ )zn
Get or create a collection.
Returns [Collection, bool] where the bool is True if the collection was created.
F)r7   	cmetadataT)r;   addcommit)r9   r:   r7   r>   createdr0   s         r*   get_or_createCollectionStore.get_or_create6   sQ     __W3
&&d8
J""r)   r   )r:   r   r7   strreturnOptional['CollectionStore']r4   )r:   r   r7   rD   r>   Optional[dict]rE   zTuple['CollectionStore', bool])r   r   r    r!   r"   __tablename__r$   r%   Stringr7   r   r>   r   
embeddingsclassmethodr;   rB   r(   r   r)   r*   r,   r,   $   s    -MZ../D!!$'I#J C C 
 %)	## # "	#
 
(# #r)   r,   c                  v   \ rS rSrSrSr\R                  " \" SS9\R                  " \
R
                   S3SS95      r\" \
S	S
9r\R                  " \R                  " \R                  5      5      r\R                  " \R"                  SS9r\R                  " \SS9r\R                  " \R"                  SS9rSrg)r/   M   zEmbedding store.langchain_pg_embeddingTr   z.uuidCASCADE)ondeleterJ   )r1   )nullabler   N)r   r   r    r!   r"   rH   r$   r%   r   
ForeignKeyr,   collection_idr   r0   ARRAYREAL	embeddingrI   documentr   r>   	custom_idr(   r   r)   r*   r/   r/   M   s    ,M%%T,,-U3	
M olKJ!!*"2"2:??"CDI  !2!2TBH!!$6I !!*"3"3dCIr)   r/   c                  .    \ rS rSr% SrS\S'   S\S'   Srg)QueryResultc   zResult from a query.r/   floatdistancer   N)r   r   r    r!   r"   __annotations__r(   r   r)   r*   rZ   rZ   c   s    ""Or)   rZ   c                     \ rS rSrSr\SSS4             S S jjr  S!S jr\S"S j5       r	S#S jr
S!S	 jrS!S
 jrS!S jrS!S jrS\SSS4           S$S jjrS!S jrS%S jr\SS\S4                 S&S jj5       r            S'S jr  S(         S)S jjr  S*         S+S jjr  S*       S,S jjr  S*       S-S jjr  S*         S.S jjr\S\SS4                 S/S jj5       r\S\SS4               S0S jj5       r\\S4           S1S jj5       r\S2S j5       r\\SS4               S3S jj5       rSr g)4PGEmbeddingj   a  `Postgres` with the `pg_embedding` extension as a vector store.

pg_embedding uses sequential scan by default. but you can create a HNSW index
using the create_hnsw_index method.
- `connection_string` is a postgres connection string.
- `embedding_function` any embedding function implementing
    `langchain.embeddings.base.Embeddings` interface.
- `collection_name` is the name of the collection to use. (default: langchain)
    - NOTE: This is not the name of the table, but the name of the collection.
        The tables will be created when initializing the store (if not exists)
        So, make sure the user has the right permissions to create tables.
- `distance_strategy` is the distance strategy to use. (default: EUCLIDEAN)
    - `EUCLIDEAN` is the euclidean distance.
- `pre_delete_collection` if True, will delete the collection if it exists.
    (default: False)
    - Useful for testing.
NFc                    Xl         X l        X0l        X@l        XPl        U=(       d    [
        R                  " [        5      U l        U R                  5         g r4   )
connection_stringembedding_functioncollection_namecollection_metadatapre_delete_collectionlogging	getLoggerr   logger__post_init__)selfrc   rd   re   rf   rg   rj   s          r*   __init__PGEmbedding.__init__}   sE     "3"4.#6 %:"; 1 1( ;r)   c                    U R                  5       U l        U R                  5         U R                  5         U R	                  5         g r4   )connect_conncreate_hnsw_extensioncreate_tables_if_not_existscreate_collectionrl   s    r*   rk   PGEmbedding.__post_init__   s5     \\^
""$((* r)   c                    U R                   $ r4   )rd   ru   s    r*   rJ   PGEmbedding.embeddings   s    &&&r)   c                f    [         R                  " U R                  5      nUR                  5       nU$ r4   )r$   create_enginerc   rp   )rl   engineconns      r*   rp   PGEmbedding.connect   s)    ))$*@*@A~~r)   c                6    [        U R                  5       n[        R                  " S5      nUR	                  U5        UR                  5         S S S 5        g ! , (       d  f       g = f! [         a%  nU R                  R                  U5         S nAg S nAff = f)Nz(CREATE EXTENSION IF NOT EXISTS embedding)	r   rq   r$   textexecuter@   	Exceptionrj   	exception)rl   r:   	statementes       r*   rr   !PGEmbedding.create_hnsw_extension   sl    	%$&OO,VW		*  %$$  	%KK!!!$$	%s4   A) 8AA) 
A&"A) &A) )
B3BBc                    U R                   R                  5          [        R                  R	                  U R                   5        S S S 5        g ! , (       d  f       g = fr4   )rq   beginBasemetadata
create_allru   s    r*   rs   'PGEmbedding.create_tables_if_not_exists   s4    ZZMM$$TZZ0     *A
Ac                    U R                   R                  5          [        R                  R	                  U R                   5        S S S 5        g ! , (       d  f       g = fr4   )rq   r   r   r   drop_allru   s    r*   drop_tablesPGEmbedding.drop_tables   s4    ZZMM""4::.  r   c                    U R                   (       a  U R                  5         [        U R                  5       n[        R                  XR                  U R                  S9  S S S 5        g ! , (       d  f       g = f)N)r>   )rg   delete_collectionr   rq   r,   rB   re   rf   rl   r:   s     r*   rt   PGEmbedding.create_collection   sU    %%""$TZZ G))--9Q9Q *  !  s   )A))
A7i'        c           	     T   [         R                  " SR                  XX4U5      5      n [        U R                  5       nUR                  U5        UR                  5         S S S 5        [        S5        g ! , (       d  f       N= f! [         a  n[        SU 35         S nAg S nAff = f)NzCREATE INDEX IF NOT EXISTS langchain_pg_embedding_idx ON langchain_pg_embedding USING hnsw (embedding) WITH (maxelements = {}, dims = {}, m = {}, efconstruction = {}, efsearch = {});z.HNSW extension and index created successfully.z*Failed to create HNSW extension or index: )	r$   r   formatr   rq   r   r@   printr   )	rl   max_elementsdimsmef_construction	ef_searchcreate_index_queryr:   r   s	            r*   create_hnsw_indexPGEmbedding.create_hnsw_index   s     (__ A	J

	D$ 23  % BC	 %$
  	D>qcBCC	Ds.   B "A4 B 4
B>B 
B'B""B'c                T   U R                   R                  S5        [        U R                  5       nU R	                  U5      nU(       d%  U R                   R                  S5         S S S 5        g UR                  U5        UR                  5         S S S 5        g ! , (       d  f       g = f)NzTrying to delete collectionCollection not found)rj   debugr   rq   get_collectionwarningdeleter@   )rl   r:   r0   s      r*   r   PGEmbedding.delete_collection   sx    78TZZ G,,W5J##$:;	 ! 
 NN:&NN !  s   5B/!B
B'c                @    [         R                  XR                  5      $ r4   )r,   r;   re   r   s     r*   r   PGEmbedding.get_collection   s    **74H4HIIr)   c                   Uc-  U V	s/ sH!  n	[        [        R                  " 5       5      PM#     nn	U(       d  U V	s/ sH  n	0 PM     nn	U R                  U5      n
U " U
UUUS9nUR                  " SXXES.UD6  U$ s  sn	f s  sn	f )Nrc   re   rd   rg   )textsrJ   	metadatasidsr   )rD   r&   r'   get_connection_stringadd_embeddings)r9   r   rJ   rV   r   r   re   rg   kwargs_rc   stores               r*   _initialize_from_embeddings'PGEmbedding._initialize_from_embeddings   s     ;.34e3tzz|$eC4%*+UUI+55f=/+("7	
 	 	
)	
PV	
 % 5 ,s
   'A:A?c           	     d   [        U R                  5       nU R                  U5      nU(       d  [        S5      e[	        XX$5       H>  u  pp[        U
UU	US9nUR                  R                  U5        UR                  U5        M@     UR                  5         S S S 5        g ! , (       d  f       g = fNr   )rV   rW   r>   rX   )
r   rq   r   
ValueErrorzipr/   rJ   appendr?   r@   )rl   r   rJ   r   r   r   r:   r0   r   r   rV   idembedding_stores                r*   r   PGEmbedding.add_embeddings  s     TZZ G,,W5J !78814Uz1W-	"0'!& 	# %%,,_=O, 2X NN !  s   BB!!
B/c           	     T   Uc-  U Vs/ sH!  n[        [        R                  " 5       5      PM#     nnU R                  R	                  [        U5      5      nU(       d  U Vs/ sH  n0 PM     nn[        U R                  5       nU R                  U5      nU(       d  [        S5      e[        XXc5       H>  u  pp[        UU	U
US9nUR                  R                  U5        UR                  U5        M@     UR                  5         S S S 5        U$ s  snf s  snf ! , (       d  f       U$ = fr   )rD   r&   r'   rd   embed_documentslistr   rq   r   r   r   r/   rJ   r   r?   r@   )rl   r   r   r   r   r   rJ   r:   r0   r   r   rV   r   r   s                 r*   	add_textsPGEmbedding.add_texts  s    ;.34e3tzz|$eC4,,<<T%[I
%*+UUI+TZZ G,,W5J !78814Uz1W-	"0'!& 	# %%,,_=O, 2X NN ! 
- 5
 ,   
s   'D DBD
D'c                V    U R                   R                  US9nU R                  UUUS9$ )N)r   rV   kr6   )rd   embed_querysimilarity_search_by_vector)rl   r5   r   r6   r   rV   s         r*   similarity_searchPGEmbedding.similarity_search;  s>     ++77U7C	// 0 
 	
r)   c                \    U R                   R                  U5      nU R                  XBUS9nU$ Nr   )rd   r   &similarity_search_with_score_by_vector)rl   r5   r   r6   rV   docss         r*   similarity_search_with_score(PGEmbedding.similarity_search_with_scoreI  s;     ++77>	::V ; 
 r)   c           	        [        U R                  5       nU R                  U5      n[        R                  " S5      nUR                  U5        U(       d  [        S5      e[        R                  UR                  :H  nUGb  / nUR                  5        GHb  u  pSn[        U
[        5      (       a  U[        [        R                  U
5      ;   as  U
R                  5        VVs0 sH  u  p,UR                  5       U_M     nnn[        R                   U	   R"                  R%                  X   5      nUR'                  U5        M  [        U
[        5      (       ae  S[        [        R                  U
5      ;   aG  [        R                   U	   R"                  R)                  SU
S    S35      nUR'                  U5        GM(  [        R                   U	   R"                  [        U
5      :H  nUR'                  U5        GMe     [        R*                  " U/UQ76 nUR-                  [        [.        R0                  " [        R2                  R5                  S5      " U5      5      R7                  S5      5      R9                  U5      R;                  [.        R0                  " [        R2                  R5                  S5      " U5      5      R=                  5       5      R?                  W5      RA                  5       nS S S 5        W Vs/ sHP  n[C        UR                  RD                  UR                  R                   S9U RF                  b  URH                  OS	4PMR     nnU$ s  snnf ! , (       d  f       Nr= fs  snf )
NzSET enable_seqscan = offr   in	substring%z<->r]   )page_contentr   g        )%r   rq   r   r$   r   r   r   r/   rS   r&   items
isinstancedictmaprD   lowerr>   astextin_r   ilikeand_r5   r   absrV   oplabelr6   order_byasclimitallr   rW   rd   r]   )rl   rV   r   r6   r:   r0   set_enable_seqscan_stmt	filter_byfilter_clauseskeyvalueINvvalue_case_insensitivefilter_by_metadataresultsresultr   s                     r*   r   2PGEmbedding.similarity_search_with_score_by_vectorU  s    TZZ G,,W5J&0oo6P&Q#OO34 !788&44
GI!!#"(,,.JCB!%..2SYY9N3N5:[[]25BTQAGGIqL] / 2 .<-E-Ec-J-Q-Q-U-U26.* '--.@A#E400[C		5E 6 .<-E-Ec-J-Q-Q-W-Wk 2315.* '--.@A-;-E-E. &CJ./* '--.@A+ #1. 'OOIGG	 "HH^5588?	JKQQ" 	"HH^5588?	JKOOQ q I !v "	
 " !'!6!6!?!?#22<< $(#:#:#FC " 	 	
 _2 ! f	
s&   CM"M
>G0M:AM+M
M(c                Z    U R                  XUS9nU VVs/ sH  u  pgUPM	     snn$ s  snnf r   )r   )rl   rV   r   r6   r   docs_and_scoresdocr   s           r*   r   'PGEmbedding.similarity_search_by_vector  s;     EEV F 
 #22//222s   'c                j    UR                  [        U5      5      nU R                  " UUU4UUUUS.UD6$ )Nr   r   re   rg   )r   r   r   )	r9   r   rV   r   re   r   rg   r   rJ   s	            r*   
from_textsPGEmbedding.from_texts  sQ     ..tE{;
..	
  +"7	
 	
 		
r)   c                    U Vs/ sH  oS   PM	     n	nU Vs/ sH  oS   PM	     n
nU R                   " U	U
U4UUUUS.UD6$ s  snf s  snf )Nr      r   )r   )r9   text_embeddingsrV   r   re   r   rg   r   tr   rJ   s              r*   from_embeddingsPGEmbedding.from_embeddings  sq      //!1/$34OqdO
4..	
  +"7	
 	
 		
 04s
   AAc                :    U R                  U5      nU " UUUUS9nU$ )Nr   )r   )r9   rV   re   rg   r   rc   r   s          r*   from_existing_indexPGEmbedding.from_existing_index  s2      55f=/+("7	
 r)   c                @    [        USSS9nU(       d  [        S5      eU$ )Nrc   POSTGRES_CONNECTION_STRING)datar   env_keyz~Postgres connection string is requiredEither pass it as a parameteror set the POSTGRES_CONNECTION_STRING environment variable.)r   r   )r9   r   rc   s      r*   r   !PGEmbedding.get_connection_string  s6    !5#0"
 !N  ! r)   c           
         U Vs/ sH  owR                   PM     nnU Vs/ sH  owR                  PM     n	nU R                  U5      n
XS'   U R                  " SUUUU	UUS.UD6$ s  snf s  snf )Nrc   )r   rg   rV   r   r   re   r   )r   r   r   r   )r9   	documentsrV   re   r   rg   r   dr   r   rc   s              r*   from_documentsPGEmbedding.from_documents  s     *33A3)23AZZ	355f=&7"#~~ 
"7+
 
 	
 43s
   A#A()rq   rf   re   rc   rd   rj   rg   )rc   rD   rd   r   re   rD   rf   rG   rg   boolrj   zOptional[logging.Logger]rE   None)rE   r  )rE   r   )rE   zsqlalchemy.engine.Connection)r   intr   r  r   r  r   r  r   r  rE   r  )r:   r   rE   rF   )r   	List[str]rJ   List[List[float]]rV   r   r   Optional[List[dict]]r   Optional[List[str]]re   rD   rg   r  r   r   rE   r`   )r   r  rJ   r  r   z
List[dict]r   r  r   r   rE   r  )NN)
r   zIterable[str]r   r  r   r  r   r   rE   r  )   N)
r5   rD   r   r  r6   rG   r   r   rE   List[Document])r5   rD   r   r  r6   rG   rE   List[Tuple[Document, float]])rV   List[float]r   r  r6   rG   rE   r  )
rV   r  r   r  r6   rG   r   r   rE   r  )r9   Type[PGEmbedding]r   r  rV   r   r   r  re   rD   r   r  rg   r  r   r   rE   r`   )r   zList[Tuple[str, List[float]]]rV   r   r   r  re   rD   r   r  rg   r  r   r   rE   r`   )r9   r  rV   r   re   rD   rg   r  r   r   rE   r`   )r   zDict[str, Any]rE   rD   )r9   r  r	  r  rV   r   re   rD   r   r  rg   r  r   r   rE   r`   )!r   r   r    r!   r"   "_LANGCHAIN_DEFAULT_COLLECTION_NAMErm   rk   propertyrJ   rp   rr   rs   r   rt   ADA_TOKEN_COUNTr   r   r   rK   r   r   r   r   r   r   r   r   r   r  r   r  r(   r   r)   r*   r`   r`   j   s   ,  B.2&++/ ' 	
 ,  $ ) 
"!	! ' '
%1/ "#!DD D 	D
 D D 
D<J  +/#'A&+ & 	
 ( !   $  
 @ & 	
   
4 +/#'	 ( !	
  
F !%	

 
 	

 
 

" !%	

 
 	

 
&
 !%	CC C 	C
 
&CP !%	
3
3 
3 	
3
 
3 

3 
 +/A#'&+


 
 (	

 
 !
  $
 
 

 
. 
 +/A#'&+
6
 
 (	

 
 !
  $
 
 

 
0   B&+	   $	
  
 $ ! !  
  B#'&+

!
 
 	

 !
  $
 
 

 
r)   r`   )'
__future__r   rh   r&   typingr   r   r   r   r   r	   r
   r$   r   sqlalchemy.dialects.postgresqlr   r   sqlalchemy.ormr   r   r   ImportErrorsqlalchemy.ext.declarativelangchain_core.documentsr   langchain_core.embeddingsr   langchain_core.utilsr   langchain_core.vectorstoresr   r   r  r  r   r,   r/   rZ   r`   r   r)   r*   <module>r&     s    "   C C C   5 0</ . 0 5 3 %0 "W W&#i &#RDY D, i
+ i
y  <;<s   B B+*B+