Coverage for app / tools / web / models.py: 100%

88 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1""" 

2Provider-neutral data types for the web tools. 

3 

4Every search provider normalises its native payload into ``SearchResult`` so 

5filtering, ranking, caching and formatting are written once — adding a 

6provider means writing one adapter, not touching the pipeline. 

7""" 

8 

9from __future__ import annotations 

10 

11import re 

12from dataclasses import dataclass, field 

13from enum import Enum 

14 

15# What a search's locale may be: an ISO 3166-1 alpha-2 country, and an ISO 639 

16# language with an optional subtag (Brave's en-gb, zh-hans, pt-br). Providers 

17# put both into their requests, and ddgs builds a host name from the 

18# language (https://{lang}.wikipedia.org), so a free string there points 

19# svc-ai at any host. 

20COUNTRY_CODE = re.compile(r"[A-Za-z]{2}") 

21LANGUAGE_CODE = re.compile(r"[A-Za-z]{2,3}(?:-[A-Za-z]{2,4})?") 

22 

23 

24class SearchType(str, Enum): 

25 """Result verticals the ``web_search`` tool can query.""" 

26 

27 TEXT = "text" 

28 NEWS = "news" 

29 IMAGES = "images" 

30 VIDEOS = "videos" 

31 

32 

33class Freshness(str, Enum): 

34 """Maximum age of results. Providers map these to their own codes.""" 

35 

36 DAY = "day" 

37 WEEK = "week" 

38 MONTH = "month" 

39 YEAR = "year" 

40 

41 @classmethod 

42 def parse(cls, value: object) -> Freshness | None: 

43 """Lenient parse: accepts canonical values plus common aliases. 

44 

45 LLMs frequently emit provider-style codes ('pw', 'w') or phrases 

46 ('past_week', '7d'); rejecting those would waste a tool call. 

47 """ 

48 if value is None or isinstance(value, cls): 

49 return value 

50 key = str(value).strip().lower().replace("-", "_").replace(" ", "_") 

51 if not key: 

52 return None 

53 return _FRESHNESS_ALIASES.get(key) 

54 

55 

56_FRESHNESS_ALIASES: dict[str, Freshness] = { 

57 **{ 

58 alias: Freshness.DAY 

59 for alias in ("day", "d", "pd", "24h", "1d", "past_day", "today") 

60 }, 

61 **{alias: Freshness.WEEK for alias in ("week", "w", "pw", "7d", "past_week")}, 

62 **{ 

63 alias: Freshness.MONTH 

64 for alias in ("month", "m", "pm", "30d", "31d", "past_month") 

65 }, 

66 **{alias: Freshness.YEAR for alias in ("year", "y", "py", "365d", "past_year")}, 

67} 

68 

69 

70class SafeSearch(str, Enum): 

71 OFF = "off" 

72 MODERATE = "moderate" 

73 STRICT = "strict" 

74 

75 

76class ProviderName(str, Enum): 

77 BRAVE = "brave" 

78 DUCKDUCKGO = "duckduckgo" 

79 

80 

81@dataclass(frozen=True, slots=True) 

82class SearchRequest: 

83 """A fully-resolved query, as sent to a provider. 

84 

85 ``query`` already carries any ``site:`` restriction; ``count`` is the 

86 over-fetch size (the tool trims to the caller's ``max_results`` after 

87 filtering and ranking). Frozen + hashable so it doubles as a cache key. 

88 """ 

89 

90 query: str 

91 search_type: SearchType = SearchType.TEXT 

92 count: int = 10 

93 freshness: Freshness | None = None 

94 country: str = "GB" 

95 language: str = "en" 

96 safesearch: SafeSearch = SafeSearch.MODERATE 

97 

98 def __post_init__(self) -> None: 

99 if not COUNTRY_CODE.fullmatch(self.country): 

100 raise ValueError(f"country {self.country!r} is not a two-letter code") 

101 if not LANGUAGE_CODE.fullmatch(self.language): 

102 raise ValueError(f"language {self.language!r} is not a language code") 

103 

104 

105@dataclass(frozen=True, slots=True) 

106class SearchResult: 

107 """One normalised search hit. ``url`` is always the landing page.""" 

108 

109 title: str 

110 url: str 

111 snippet: str = "" 

112 extra_snippets: tuple[str, ...] = () 

113 source: str = "" # publisher / site name 

114 published: str | None = None # ISO date (YYYY-MM-DD) when known 

115 age: str | None = None # provider's relative age, e.g. "2 days ago" 

116 image_url: str | None = None # images: the image file itself 

117 width: int | None = None 

118 height: int | None = None 

119 duration: str | None = None # videos 

120 creator: str | None = None # videos: channel / uploader 

121 

122 

123class FailureReason(str, Enum): 

124 """Why a provider could not answer — what the tool tells the model and 

125 an operator reads in ``/health``, in place of the provider's own text.""" 

126 

127 QUOTA = "quota" 

128 RATE_LIMITED = "rate_limited" 

129 AUTH = "auth" 

130 REFUSED = "refused" 

131 TIMEOUT = "timeout" 

132 NETWORK = "network" 

133 UNSUPPORTED = "unsupported" 

134 ERROR = "error" 

135 

136 

137class AttemptOutcome(str, Enum): 

138 """What became of asking one provider.""" 

139 

140 ANSWERED = "answered" 

141 EMPTY = "empty" 

142 FAILED = "failed" 

143 # Not asked: the call ran out of its time budget first. 

144 SKIPPED = "skipped" 

145 

146 

147@dataclass(frozen=True, slots=True) 

148class ProviderAttempt: 

149 """One provider asked for one search, and what it said.""" 

150 

151 provider: ProviderName 

152 search_type: SearchType 

153 outcome: AttemptOutcome 

154 reason: FailureReason | None = None 

155 returned: int = 0 

156 

157 

158@dataclass(frozen=True, slots=True) 

159class SearchResponse: 

160 results: tuple[SearchResult, ...] 

161 provider: ProviderName 

162 # Set when the provider spell-corrected the query. 

163 altered_query: str | None = None 

164 # Every provider asked for this response, in order: those that failed or 

165 # answered with nothing before the one that answered (or last said none). 

166 attempts: tuple[ProviderAttempt, ...] = field(default_factory=tuple) 

167 # Served from the in-process cache rather than a provider. 

168 cached: bool = False