o
    ȳg%                     @   sr   d Z ddlZddlZddlZddlmZmZmZmZm	Z	 ddl
mZ ddlmZmZ eeZG dd deZdS )zUtil that calls Arxiv.    N)AnyDictIteratorListOptional)Document)	BaseModelmodel_validatorc                   @   s  e Zd ZU dZeed< eed< dZeed< dZeed< dZ	e
ed	< d
Zeed< dZe
ed< dZee ed< dede
f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e fddZdedefddZdedee fddZdedee fd d!Zd"S )#ArxivAPIWrappera
  Wrapper around ArxivAPI.

    To use, you should have the ``arxiv`` python package installed.
    https://lukasschwab.me/arxiv.py/index.html
    This wrapper will use the Arxiv API to conduct searches and
    fetch document summaries. By default, it will return the document summaries
    of the top-k results.
    If the query is in the form of arxiv identifier
    (see https://info.arxiv.org/help/find/index.html), it will return the paper
    corresponding to the arxiv identifier.
    It limits the Document content by doc_content_chars_max.
    Set doc_content_chars_max=None if you don't want to limit the content size.

    Attributes:
        top_k_results: number of the top-scored document used for the arxiv tool
        ARXIV_MAX_QUERY_LENGTH: the cut limit on the query used for the arxiv tool.
        continue_on_failure (bool): If True, continue loading other URLs on failure.
        load_max_docs: a limit to the number of loaded documents
        load_all_available_meta:
            if True: the `metadata` of the loaded Documents contains all available
            meta info (see https://lukasschwab.me/arxiv.py/index.html#Result),
            if False: the `metadata` contains only the published date, title,
            authors and summary.
        doc_content_chars_max: an optional cut limit for the length of a document's
            content

    Example:
        .. code-block:: python

            from langchain_community.utilities.arxiv import ArxivAPIWrapper
            arxiv = ArxivAPIWrapper(
                top_k_results = 3,
                ARXIV_MAX_QUERY_LENGTH = 300,
                load_max_docs = 3,
                load_all_available_meta = False,
                doc_content_chars_max = 40000
            )
            arxiv.run("tree of thought llm")
    arxiv_searcharxiv_exceptions   top_k_resultsi,  ARXIV_MAX_QUERY_LENGTHFcontinue_on_failured   load_max_docsload_all_available_metai  doc_content_chars_maxqueryreturnc                 C   sV   d}|d| j   D ]}t||}|s dS |dusJ |d|ks( dS qdS )z(Check if a query is an arxiv identifier.z,\d{2}(0[1-9]|1[0-2])\.\d{4,5}(v\d+|)|\d{7}.*NFr   T)r   splitrematchgroup)selfr   arxiv_identifier_pattern
query_itemmatch_result r   _/var/www/html/chatdoc2/venv/lib/python3.10/site-packages/langchain_community/utilities/arxiv.pyis_arxiv_identifier@   s   z#ArxivAPIWrapper.is_arxiv_identifierbefore)modevaluesc                 C   sN   zddl }|j|d< |j|j|jf|d< |j|d< W |S  ty&   tdw )z7Validate that the python package exists in environment.r   Nr   r   arxiv_resultzRCould not import arxiv python package. Please install it with `pip install arxiv`.)arxivSearch
ArxivErrorUnexpectedEmptyPageError	HTTPErrorResultImportError)clsr$   r&   r   r   r    validate_environmentL   s   
z$ArxivAPIWrapper.validate_environmentc                 C   s@   |  |r| j| | jd S | j|d| j | jd S )z6Helper function to fetch arxiv results based on query.)id_listmax_resultsN)r0   )r!   r   r   r   resultsr   r   r   r   r   r    _fetch_resultsa   s   

zArxivAPIWrapper._fetch_resultsc              
   C   sj   z|  |}W n$ | jy+ } ztd|  td| dgW  Y d}~S d}~ww dd |D }|S )aL  
        Performs an arxiv search and returns list of
        documents, with summaries as the content.

        If an error occurs or no documents found, error text
        is returned instead. Wrapper for
        https://lukasschwab.me/arxiv.py/index.html#Search

        Args:
            query: a plaintext search query
        Arxiv exception: )page_contentNc                 S   s@   g | ]}t |j|j|j |jd dd |jD ddqS ), c                 s       | ]}|j V  qd S Nname.0ar   r   r    	<genexpr>       zCArxivAPIWrapper.get_summaries_as_docs.<locals>.<listcomp>.<genexpr>)zEntry ID	PublishedTitleAuthorsr5   metadata)r   summaryentry_idupdateddatetitlejoinauthorsr<   resultr   r   r    
<listcomp>~   s    
z9ArxivAPIWrapper.get_summaries_as_docs.<locals>.<listcomp>)r3   r   loggererrorr   r   r   r1   exdocsr   r   r    get_summaries_as_docsk   s   
z%ArxivAPIWrapper.get_summaries_as_docsc              
   C   sz   z|  |}W n  | jy' } ztd|  d| W  Y d}~S d}~ww dd |D }|r;d|d| j S dS )a  
        Performs an arxiv search and A single string
        with the publish date, title, authors, and summary
        for each article separated by two newlines.

        If an error occurs or no documents found, error text
        is returned instead. Wrapper for
        https://lukasschwab.me/arxiv.py/index.html#Search

        Args:
            query: a plaintext search query
        r4   Nc                 S   sD   g | ]}d |j   d|j dddd |jD  d|j qS )zPublished: z
Title: z

Authors: r6   c                 s   r7   r8   r9   r;   r   r   r    r>      r?   z1ArxivAPIWrapper.run.<locals>.<listcomp>.<genexpr>z

Summary: )rG   rH   rI   rJ   rK   rE   rL   r   r   r    rN      s    z'ArxivAPIWrapper.run.<locals>.<listcomp>z

zNo good Arxiv Result was found)r3   r   rO   rP   rJ   r   rQ   r   r   r    run   s   zArxivAPIWrapper.runc                 C   s   t | |S )a  
        Run Arxiv search and get the article texts plus the article meta information.
        See https://lukasschwab.me/arxiv.py/index.html#Search

        Returns: a list of documents with the document.page_content in text format

        Performs an arxiv search, downloads the top k results as PDFs, loads
        them as Documents, and returns them in a List.

        Args:
            query: a plaintext search query
        )list	lazy_loadr2   r   r   r    load   s   zArxivAPIWrapper.loadc                 c   s   zddl }W n ty   tdw z|dddd}| |}W n | jy> } ztd| W Y d}~dS d}~ww |D ]}z%| }||}d	dd	 |D }W d   n1 sbw   Y  W n6 t
|j jfy }	 zt|	 W Y d}	~	qAd}	~	w ty }
 z| jrt|
 W Y d}
~
qA|
d}
~
ww | jr|jt|j |j|j|j|j|jd
d |jD d}ni }t|j |jd	dd	 |jD |jd|}t|d| j |dV  t !| qAdS )a  
        Run Arxiv search and get the article texts plus the article meta information.
        See https://lukasschwab.me/arxiv.py/index.html#Search

        Returns: documents with the document.page_content in text format

        Performs an arxiv search, downloads the top k results as PDFs, loads
        them as Documents, and returns them.

        Args:
            query: a plaintext search query
        r   NzGPyMuPDF package not found, please install it with `pip install pymupdf`: -zError on arxiv: %sc                 s   s    | ]}|  V  qd S r8   )get_text)r<   pager   r   r    r>      s    z,ArxivAPIWrapper.lazy_load.<locals>.<genexpr>c                 S   s   g | ]}|j qS r   )href)r<   linkr   r   r    rN      s    z-ArxivAPIWrapper.lazy_load.<locals>.<listcomp>)rF   published_first_timecommentjournal_refdoiprimary_category
categorieslinksr6   c                 s   r7   r8   r9   r;   r   r   r    r>      r?   )r@   rA   rB   SummaryrC   )"fitzr,   replacer3   r   rO   debugdownload_pdfopenrJ   FileNotFoundErrorFileDataError	Exceptionr   rP   r   rF   str	publishedrH   ra   rb   rc   rd   re   rf   rG   rI   rK   rE   r   r   osremove)r   r   rh   r1   rR   rM   doc_file_namedoc_filetextf_exeextra_metadatarD   r   r   r    rW      sv   

zArxivAPIWrapper.lazy_loadN)__name__
__module____qualname____doc__r   __annotations__r   intr   r   boolr   r   r   r   rp   r!   r	   classmethodr   r.   r3   r   r   rT   rU   rX   r   rW   r   r   r   r    r
      s&   
 (
! r
   )r}   loggingrr   r   typingr   r   r   r   r   langchain_core.documentsr   pydanticr   r	   	getLoggerrz   rO   r
   r   r   r   r    <module>   s    
