
    7|h!                         d Z ddlZddlZddlmZmZmZmZ ddlZddl	m
Z
 ddlmZmZmZmZ  G d d      Z G d d	e      Zy)
zWChain that calls SerpAPI.

Heavily borrowed from https://github.com/ofirpress/self-ask
    N)AnyDictOptionalTuple)get_from_dict_or_env)	BaseModel
ConfigDictFieldmodel_validatorc                   (    e Zd ZdZddZdeddfdZy)HiddenPrintszContext manager to hide prints.returnNc                 t    t         j                  | _        t        t        j
                  d      t         _        y)zOpen file to pipe stdout to.wN)sysstdout_original_stdoutopenosdevnull)selfs    d/var/www/html/test/engine/venv/lib/python3.12/site-packages/langchain_community/utilities/serpapi.py	__enter__zHiddenPrints.__enter__   s      #

"**c*
    _c                 j    t         j                  j                          | j                  t         _        y)z$Close file that stdout was piped to.N)r   r   closer   )r   r   s     r   __exit__zHiddenPrints.__exit__   s    

**
r   )r   N)__name__
__module____qualname____doc__r   r   r    r   r   r   r      s    )+
+3 +4 +r   r   c                   D   e Zd ZU dZdZeed<    eddddd	      Ze	ed
<   dZ
ee   ed<   dZeej                     ed<    edd      Z ed      ededefd              ZdededefdZdededefdZdede	fdZdede	fdZdedeeef   fdZede	defd       Zy)SerpAPIWrappera  Wrapper around SerpAPI.

    To use, you should have the ``google-search-results`` python package installed,
    and the environment variable ``SERPAPI_API_KEY`` set with your API key, or pass
    `serpapi_api_key` as a named parameter to the constructor.

    Example:
        .. code-block:: python

            from langchain_community.utilities import SerpAPIWrapper
            serpapi = SerpAPIWrapper()
    Nsearch_enginegooglez
google.comusen)enginegoogle_domainglhl)defaultparamsserpapi_api_key
aiosessionTforbid)arbitrary_types_allowedextrabefore)modevaluesr   c                 r    t        |dd      }||d<   	 ddlm} ||d<   |S # t        $ r t        d      w xY w)z?Validate that api key and python package exists in environment.r0   SERPAPI_API_KEYr   )GoogleSearchr&   zdCould not import serpapi python package. Please install it with `pip install google-search-results`.)r   serpapir:   ImportError)clsr7   r0   r:   s       r   validate_environmentz#SerpAPIWrapper.validate_environment<   sa     /%'8
 %4 !	,&2F?#   	N 	s   ! 6querykwargsc                 ^   K   | j                  | j                  |       d{         S 7 w)z1Run query through SerpAPI and parse result async.N)_process_responsearesultsr   r?   r@   s      r   arunzSerpAPIWrapper.arunO   s&     %%DMM%,@&@AA&@s    -+	-c                 B    | j                  | j                  |            S )z+Run query through SerpAPI and parse result.)rB   resultsrD   s      r   runzSerpAPIWrapper.runS   s    %%dll5&9::r   c                     | j                  |      }t               5  | j                  |      }|j                         }ddd       |S # 1 sw Y   S xY w)z4Run query through SerpAPI and return the raw result.N)
get_paramsr   r&   get_dict)r   r?   r/   searchress        r   rG   zSerpAPIWrapper.resultsW   sO    '^ 	$''/F//#C	$ 
	$ 
s   "AAc                    K   dt         t        t        t        t        f   f   f fd} |       \  }} j                  sst	        j
                         4 d{   }|j                  ||      4 d{   }|j                          d{   }ddd      d{    ddd      d{    S  j                  j                  ||      4 d{   }|j                          d{   }ddd      d{    |S 7 7 7 z7 l# 1 d{  7  sw Y   |xY w7 s# 1 d{  7  sw Y   S xY w7 c7 M7 ?# 1 d{  7  sw Y   S xY ww)zFUse aiohttp to run query through SerpAPI and return the results async.r   c                  |    j                        } d| d<   j                  rj                  | d<   d| d<   d}|| fS )Npythonsourceserp_api_keyjsonoutputzhttps://serpapi.com/search)rJ   r0   )r/   urlr?   r   s     r   construct_url_and_paramsz9SerpAPIWrapper.aresults.<locals>.construct_url_and_paramsb   sM    __U+F'F8##)-)=)=~&%F8.C;r   N)r/   )r   strr   r1   aiohttpClientSessiongetrS   )r   r?   rV   rU   r/   sessionresponserM   s   ``      r   rC   zSerpAPIWrapper.aresults_   sD    	%T#s(^0C*D 	 /0V,,. 0 0'";;s6;: 0 0h (/C0 00 0 
 **3v*> , ,($MMO+, , 
00/0 0 0 00 0 0 0 
,+, , , , 
s   AEDED$6D7D$:DD	DD$DD$#E.D"/'ED:EE .D</E 3E>D>?ED$	DD$D	DD	D$"E$D7*D-+D72	E<E >E EE	EEc                 D    | j                   |d}i | j                  |}|S )zGet parameters for SerpAPI.)api_keyq)r0   r/   )r   r?   _paramsr/   s       r   rJ   zSerpAPIWrapper.get_paramsv   s1     ++
 ,DKK+7+r   rM   c           	      $
   d| j                         v rt        d| d          d| j                         v r| d   | d<   d| j                         v r| d   }t        |t              r|d   }d|j                         v r|d   S d|j                         v r|d   S d|j                         v r|d   S d	|j                         v r|d	   S i }|j	                         D ]C  \  }}t        |t        t
        f      rt        |t              r|j                  d
      r?|||<   E t        |      S d| j                         v r| d   dd S d| j                         v r| d   S d| j                         v r| d   S d| j                         v r| d   S d| j                         v rd| d   j                         v r| d   d   S d| j                         v r d| d   d   j                         v r| d   dd S d| j                         v r| d   S d| j                         v rd| d   j                         v r| d   d   S d| j                         v rd| d   j                         v r| d   d   S d| j                         v r:d| d   d   j                         v r"t        | d   dd D cg c]  }|d   	 c}      S g }d| j                         v r| d   }d|v r|d   nd}d|j                         v r|j                  |d          |j	                         D ]|  \  }}t        |t              st        |t              s(|d vs-|j                  d!      r?|j                  d"      rQ|j                  d
      rc|j                  | d#| d$| d%       ~ | j                  d&g       D ]  }	d|	j                         v r|j                  |	d          *d	|	j                         v r|j                  |	d	          Qd'|	j                         v r|j                  |	d'          xd(|	j                         v r|j                  |	d(          d)|	j                         v s|j                  |	d)           d*| j                         v r|j                  | d*          d+| v rt        | d+   t              r|| d+   z  }d+| j                         v r?t        | d+   t
              r,d,| d+   j                         v r|j                  | d+   d,          t        |      dkD  rt        |      S y-c c}w ).zProcess response from SerpAPI.errorzGot error from SerpAPI: answer_box_list
answer_boxr   resultanswersnippetsnippet_highlighted_wordshttpevents_resultsN
   sports_resultstop_storiesnews_resultsjobs_resultsjobsshopping_resultstitle   questions_and_answerspopular_destinationsdestinations
top_sightssightsimages_results	thumbnailknowledge_graph description)rr   r}   _stick_link z: .organic_resultsrich_snippetrich_snippet_tablelinkbuying_guidelocal_resultsplaceszNo good search result found)keys
ValueError
isinstancelistitemsdictrW   
startswithappendendswithrZ   len)
rM   rd   rf   keyvalueitemsnippetsr{   rr   organic_results
             r   rB   z SerpAPIWrapper._process_response   s4    chhj 7G~FGG
* #$5 6C388:%\*J*d+']
:??,,!(++Z__..!(++joo//!),,,
0AA!"=>>","2"2"4 ,JC%edD\:"5#.53C3CF3K&+s	,
 6{"+'("--+'((chhj(}%%sxxz)~&&sxxz)fN8K8P8P8R.R~&v..#((*,31215::<<)*2A..$
2.//"chhj0#&<"="B"B"DD-.~>>SXXZ'HL8I8N8N8P,P|$X..
*s#34Q7<<>>c:J6KCR6PQd[)QRR
*!"34O07?0JOG,PRE 4 4 66 >?-335 	@
UsC("5#.#;;LL2LL1!,,V4OOugQse2eWA$>?	@ "gg&7< 
	8NN//11y 9:,0C0C0EE/J KL>#6#6#88~ >?%)<)<)>>/C DE>..00v 67
	8 SXXZ'OOC/0c!j_1Et&LO,,Hsxxz)3/6C05577OOC0:;x=1x= 0Y Rs   T)r   r    r!   r"   r&   r   __annotations__r
   r/   r   r0   r   rW   r1   rX   rY   r	   model_configr   classmethodr   r>   rE   rH   rG   rC   rJ   staticmethodrB   r#   r   r   r%   r%      s8    M3)	
FD  &*OXc])26J../6 $L
 (#$ 3   $"B Bs Bs B; ; ; ;S T C D . S#X  b1t b1 b1 b1r   r%   )r"   r   r   typingr   r   r   r   rX   langchain_core.utilsr   pydanticr   r	   r
   r   r   r%   r#   r   r   <module>r      s<   
 
 
 - -  5 B B+ +E1Y E1r   