|
| 1 | +# flake8: noqa |
| 2 | +from dataclasses import dataclass, field |
| 3 | +from typing import Any, Dict, Generator, List, Optional |
| 4 | + |
| 5 | +import arxiv |
| 6 | +import json |
| 7 | +from arxiv import SortCriterion, SortOrder |
| 8 | +from ms_agent.tools.search.search_base import (BaseResult, SearchRequest, |
| 9 | + SearchResponse, SearchResult) |
| 10 | + |
| 11 | + |
| 12 | +class ArxivSearchRequest(SearchRequest): |
| 13 | + """ |
| 14 | + A class representing a search request to ArXiv. |
| 15 | + """ |
| 16 | + |
| 17 | + def __init__(self, |
| 18 | + query: str = None, |
| 19 | + num_results: Optional[int] = 10, |
| 20 | + sort_strategy: SortCriterion = SortCriterion.Relevance, |
| 21 | + sort_order: SortOrder = SortOrder.Descending): |
| 22 | + """ |
| 23 | + Initialize ArxivSearchRequest with search parameters. |
| 24 | +
|
| 25 | + Args: |
| 26 | + query: The search query string |
| 27 | + num_results: Number of results to return, default is 10 |
| 28 | + sort_strategy: The strategy to sort results, default is relevance |
| 29 | + sort_order: The order of sorting, default is descending |
| 30 | + """ |
| 31 | + super().__init__(query=query, num_results=num_results) |
| 32 | + self.sort_strategy = sort_strategy |
| 33 | + self.sort_order = sort_order |
| 34 | + |
| 35 | + def to_dict(self) -> Dict[str, Any]: |
| 36 | + """ |
| 37 | + Convert the request parameters to a dictionary. |
| 38 | +
|
| 39 | + Returns: |
| 40 | + Dict[str, Any]: The parameters as a dictionary |
| 41 | + """ |
| 42 | + return { |
| 43 | + 'query': self.query, |
| 44 | + 'max_results': self.num_results, |
| 45 | + 'sort_by': self.sort_strategy, |
| 46 | + 'sort_order': self.sort_order |
| 47 | + } |
| 48 | + |
| 49 | + def to_json(self) -> Dict[str, Any]: |
| 50 | + """ |
| 51 | + Convert the request parameters to a JSON string. |
| 52 | +
|
| 53 | + Returns: |
| 54 | + Dict[str, Any]: The parameters as a JSON string |
| 55 | + """ |
| 56 | + return json.dumps( |
| 57 | + { |
| 58 | + 'query': self.query, |
| 59 | + 'max_results': self.num_results, |
| 60 | + 'sort_strategy': self.sort_strategy.value, |
| 61 | + 'sort_order': self.sort_order.value |
| 62 | + }, |
| 63 | + ensure_ascii=False) |
| 64 | + |
| 65 | + |
| 66 | +class ArxivSearchResult(SearchResult): |
| 67 | + """ArXiv search result implementation.""" |
| 68 | + |
| 69 | + def __init__(self, |
| 70 | + query: str, |
| 71 | + arguments: Dict[str, Any] = None, |
| 72 | + response: List['arxiv.Result'] = None): |
| 73 | + """ |
| 74 | + Initialize ArxivSearchResult. |
| 75 | +
|
| 76 | + Args: |
| 77 | + query: The original search query string |
| 78 | + arguments: The arguments used for the search |
| 79 | + response: The raw results returned by the search |
| 80 | + """ |
| 81 | + super().__init__(query, arguments, response) |
| 82 | + self.arguments = self._process_arguments() |
| 83 | + self.response = self._process_results() |
| 84 | + |
| 85 | + def _process_results(self) -> SearchResponse: |
| 86 | + """ |
| 87 | + Process the raw results into a standardized format. |
| 88 | +
|
| 89 | + Returns: |
| 90 | + SearchResponse: Processed search results |
| 91 | + """ |
| 92 | + if isinstance(self.response, Generator): |
| 93 | + self.response = list(self.response) |
| 94 | + |
| 95 | + if not self.response: |
| 96 | + print( |
| 97 | + '***Warning: No search results found. This may happen because ' |
| 98 | + 'Arxiv\'s search functionality relies on precise metadata matching (e.g., title, ' |
| 99 | + 'author, abstract keywords) rather than the full-text indexing and complex ' |
| 100 | + 'ranking algorithms used by search engines like Google, or the semantic search ' |
| 101 | + 'capabilities of some neural search engines. The search query rewritten by the ' |
| 102 | + 'model may not align perfectly with Arxiv\'s metadata-driven engine. For a more ' |
| 103 | + 'robust and stable search experience, consider configuring an advanced search ' |
| 104 | + 'provider (such as Exa, SerpApi, etc.) in the `conf.yaml` file.' |
| 105 | + ) |
| 106 | + return SearchResponse(results=[]) |
| 107 | + |
| 108 | + processed = [] |
| 109 | + for res in self.response: |
| 110 | + if not isinstance(res, arxiv.Result): |
| 111 | + print( |
| 112 | + f'***Warning: Result {res} is not an instance of arxiv.Result.' |
| 113 | + ) |
| 114 | + continue |
| 115 | + |
| 116 | + processed.append( |
| 117 | + BaseResult( |
| 118 | + url=getattr(res, 'pdf_url', None) |
| 119 | + or getattr(res, 'entry_id', None), |
| 120 | + id=getattr(res, 'entry_id', None), |
| 121 | + title=getattr(res, 'title', None), |
| 122 | + highlights=None, |
| 123 | + highlight_scores=None, |
| 124 | + summary=getattr(res, 'summary', None), |
| 125 | + markdown=None)) |
| 126 | + |
| 127 | + return SearchResponse(results=processed) |
| 128 | + |
| 129 | + def _process_arguments(self) -> Dict[str, Any]: |
| 130 | + """Process the search arguments to be JSON serializable.""" |
| 131 | + return { |
| 132 | + 'query': |
| 133 | + self.query, |
| 134 | + 'max_results': |
| 135 | + self.arguments.get('max_results', None), |
| 136 | + 'sort_strategy': |
| 137 | + self.arguments.get('sort_strategy', SortCriterion.Relevance).value, |
| 138 | + 'sort_order': |
| 139 | + self.arguments.get('sort_order', SortOrder.Descending).value |
| 140 | + } |
0 commit comments