
    Ng!                         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dS )
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dS )HiddenPrintszContext manager to hide prints.returnNc                 p    t           j        | _        t          t          j        d          t           _        dS )zOpen file to pipe stdout to.wN)sysstdout_original_stdoutopenosdevnull)selfs    a/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/utilities/serpapi.py	__enter__zHiddenPrints.__enter__   s#     #
"*c**


    _c                 d    t           j                                         | j        t           _        dS )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      sP        ))+ + + +
+3 +4 + + + + + +r   r   c                   r   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dS )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                     t          |dd          }||d<   	 ddlm} ||d<   n# t          $ r t          d          w xY w|S )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<   s     /%'8
 
 %4 !	,,,,,,&2F?## 	 	 	N  	
 s   $ >querykwargsc                 b   K   |                      |                     |           d{V           S )z1Run query through SerpAPI and parse result async.N)_process_responsearesultsr   r?   r@   s      r   arunzSerpAPIWrapper.arunO   s8      %%DMM%,@,@&@&@&@&@&@&@AAAr   c                 R    |                      |                     |                    S )z+Run query through SerpAPI and parse result.)rB   resultsrD   s      r   runzSerpAPIWrapper.runS   s"    %%dll5&9&9:::r   c                     |                      |          }t                      5  |                     |          }|                                }ddd           n# 1 swxY w Y   |S )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   s    ''^^ 	$ 	$''//F//##C	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 
s   *AA!Ac                    K   dt           t          t          t          t          f         f         f fd} |            \  }} j        st	          j                    4 d{V }|                    ||          4 d{V }|                                 d{V }ddd          d{V  n# 1 d{V swxY w Y   ddd          d{V  n# 1 d{V swxY w Y   n` j                            ||          4 d{V }|                                 d{V }ddd          d{V  n# 1 d{V swxY w Y   |S )zFUse aiohttp to run query through SerpAPI and return the results async.r   c                  p                                   } 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   sO    __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_   s     	%T#s(^0C*D 	 	 	 	 	 	 	 /.00V 	,,.. 0 0 0 0 0 0 0'";;s6;:: 0 0 0 0 0 0 0h (//////C0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 **3v*>> , , , , , , ,($MMOO++++++, , , , , , , , , , , , , , , , , , , , , , , , , , , 
sH   $CB/C/
B9	9C<B9	=C
CCD33
D= D=c                 0    | 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     +
 
 ,DK+7+r   rM   c           	         d|                                  v rt          d| d                    d|                                  v r| d         | d<   d|                                  v r| d         }t          |t                    r|d         }d|                                 v r|d         S d|                                 v r|d         S d|                                 v r|d         S d	|                                 v r|d	         S i }|                                D ]P\  }}t          |t          t
          f          s/t          |t                    r|                    d
          s|||<   Qt          |          S d|                                  v r| d         dd         S d|                                  v r| d         S d|                                  v r| d         S d|                                  v r| d         S d|                                  v r*d| d                                          v r| d         d         S d|                                  v r2d| d         d                                          v r| d         dd         S d|                                  v r| d         S d|                                  v r*d| d                                          v r| d         d         S d|                                  v r*d| d                                          v r| d         d         S d|                                  v rId| d         d                                          v r't          d | d         dd         D                       S g }d|                                  v r| d         }d|v r|d         nd}d |                                 v r|                    |d                     |                                D ]\  }}t          |t                    rvt          |t                    ra|d!vr]|	                    d"          sH|	                    d#          s3|                    d
          s|                    | d$| d%| d&           | 
                    d'g           D ]}d|                                 v r|                    |d                    4d	|                                 v r|                    |d	                    fd(|                                 v r|                    |d(                    d)|                                 v r|                    |d)                    d*|                                 v r|                    |d*                    d+|                                  v r|                    | d+                    d,| v r&t          | d,         t                    r|| d,         z  }d,|                                  v rXt          | d,         t
                    r=d-| d,                                          v r!|                    | d,         d-                    t          |          dk    rt          |          S d.S )/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	thumbnailc                     g | ]
}|d          S )rz   r#   ).0items     r   
<listcomp>z4SerpAPIWrapper._process_response.<locals>.<listcomp>   s    QQQd[)QQQr   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snippetsr   rr   organic_results	            r   rB   z SerpAPIWrapper._process_response   s    chhjj  FGFFGGG

** #$5 6C388::%%\*J*d++ +']
:??,,,,!(++Z__....!(++joo////!),,,
0A0AAA!"=>>","2"2"4"4 , ,JC%edD\:: ,"5#..,383C3CF3K3K, ',s6{{"++'("--++'((chhjj((}%%sxxzz))~&&sxxzz))fN8K8P8P8R8R.R.R~&v..#((**,,31215::<<<<)*2A2..$

22.//"chhjj00#&<"="B"B"D"DDD-.~>>SXXZZ''HL8I8N8N8P8P,P,P|$X..

**s#34Q7<<>>>>QQc:J6KCRC6PQQQRRR

**!"34O07?0J0JOG,,PRE 4 4 6 666 >???-3355 	@ 	@
UsC((@"5#..@ #;;;LL22 <LL11 < ",,V44 <
 OOu$>$>s$>$>e$>$>$>???!gg&7<< 
	8 
	8NN//1111y 9::::,0C0C0E0EEE/J KLLLL>#6#6#8#888~ >????%)<)<)>)>>>/C DEEEE>..0000v 6777SXXZZ''OOC/000c!!j_1Et&L&L!O,,Hsxxzz))3/66 *C0557777OOC0:;;;x==1x== 00r   )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%      s          M35)	
 
  FD    &*OXc])))26J./666: $  L
 _(###$ 3    [ $#"B Bs Bs B B B B; ; ; ; ; ; ;S T    C D    . S#X     b1t b1 b1 b1 b1 \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 5 5 5 5 5 B B B B B B B B B B B B+ + + + + + + +E1 E1 E1 E1 E1Y E1 E1 E1 E1 E1r   