o
    ȳg                     @   s\   d Z ddlmZmZmZ ddlZddlmZ ddlm	Z	m
Z
mZ dZdZG dd	 d	e	ZdS )
zUtil that calls Google Books.    )DictListOptionalNget_from_dict_or_env)	BaseModel
ConfigDictmodel_validator   z+https://www.googleapis.com/books/v1/volumesc                   @   s   e Zd ZU dZdZee ed< eZ	e
ed< eddZedded	ed
efddZded
efddZdeded
efddZded
efddZdS )GoogleBooksAPIWrappera  Wrapper around Google Books API.

    To use, you should have a Google Books API key available.
    This wrapper will use the Google Books API to conduct searches and
    fetch books based on a query passed in by the agents. By default,
    it will return the top-k results.

    The response for each book will contain the book title, author name, summary, and
    a source link.
    Ngoogle_books_api_keytop_k_resultsforbid)extrabefore)modevaluesreturnc                 C   s   t |dd}||d< |S )z,Validate that api key exists in environment.r   GOOGLE_BOOKS_API_KEYr   )clsr   r    r   f/var/www/html/chatdoc2/venv/lib/python3.10/site-packages/langchain_community/utilities/google_books.pyvalidate_environment    s
   z*GoogleBooksAPIWrapper.validate_environmentqueryc                 C   sx   d|fd| j fd| jff}tjt|d}| }|jdkr2|j}|di dd}d	| d
| S | ||dg S )Nq
maxResultskey)params   errormessagezInternal failurez)Unable to retrieve books got status code : items)r   r   requestsgetGOOGLE_BOOKS_API_URLjsonstatus_code_format)selfr   r   responser&   coder   r   r   r   run+   s   
zGoogleBooksAPIWrapper.runbooksc              	   C   s   |sd| S dt | d| d}g }|| d}|D ]7}|d }|d }| |d }	|d	 }
|d
 }| d| d|	 d|
 d}|d| 7 }|| |d7 }qd|S )Nz.Sorry no books could be found for your query: z	Here are z" suggestions for books related to :   
volumeInfotitleauthorsdescriptioninfoLinkz. "z" by r!   
zYou can read more at z

)lenappend_format_authorsjoin)r)   r   r-   startresultsibookinfor1   r2   summarysourcedescr   r   r   r(   @   s"   




zGoogleBooksAPIWrapper._formatr2   c                 C   s2   t |dkr
|d S dd|d d |d S )Nr/   r   z	{} and {}z, )r6   formatr9   )r)   r2   r   r   r   r8   Y   s   z%GoogleBooksAPIWrapper._format_authors)__name__
__module____qualname____doc__r   r   str__annotations__GOOGLE_BOOKS_MAX_ITEM_SIZEr   intr   model_configr	   classmethodr   r   r,   r   r(   r8   r   r   r   r   r      s   
 	r   )rG   typingr   r   r   r#   langchain_core.utilsr   pydanticr   r   r	   rJ   r%   r   r   r   r   r   <module>   s    