Coverage for app / common / settings.py: 99%

109 statements  

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

1from functools import lru_cache 

2from typing import Literal 

3 

4from pydantic import field_validator 

5from pydantic_settings import BaseSettings 

6 

7# Environments where service-to-service auth is mandatory and a missing secret 

8# must hard-fail startup rather than silently run unauthenticated. 

9STRICT_ENVIRONMENTS = {"staging", "stage", "production", "prod"} 

10 

11# Engines the keyless ddgs web-search fallback may scrape. Every engine in 

12# this list receives the user's query verbatim, so the default is deliberately 

13# narrow: privacy-oriented or independent indexes (DuckDuckGo, Brave, Mojeek — 

14# UK-based) plus Wikipedia. Google, Bing, Yahoo, Yandex and Grokipedia are 

15# excluded; ddgs's own "auto" enables all of them. Only 'duckduckgo' exists 

16# for news/images/videos, so those categories resolve to it. 

17DEFAULT_DDGS_BACKEND = "duckduckgo,brave,mojeek,wikipedia" 

18 

19# Identify the fetcher honestly rather than impersonating a browser, so site 

20# operators can recognise, contact, or block it. 

21DEFAULT_URL_FETCH_USER_AGENT = ( 

22 "Mozilla/5.0 (compatible; CHAINR-Agent/1.0; +https://datachainr.com/bot)" 

23) 

24 

25# Values that mean "deliberately not configured" for an optional credential. 

26# SSM cannot store an empty string and the deploy script refuses anything left 

27# as CHANGE_ME, so an optional key needs a real value that reads as "off" — 

28# otherwise the placeholder is truthy and gets used as a real credential. 

29# Mirrors app.services.dashboards.market.DISABLED_VALUES in svc-core. 

30DISABLED_VALUES = {"", "none", "disabled", "off", "unset", "change_me"} 

31 

32 

33class Settings(BaseSettings): 

34 app_name: str = "CHAIN-R" 

35 

36 # Server 

37 port: int = 5000 

38 environment: str = "development" 

39 

40 # Internal service-to-service auth. svc-ai verifies tokens minted by 

41 # svc-core (audience "svc-ai"). When the secret is unset, verification is 

42 # skipped (legacy / migration); a warning is logged at startup. 

43 INTERNAL_JWT_SECRET: str | None = None 

44 # Previous secret, accepted during a rotation overlap (zero-downtime). 

45 INTERNAL_JWT_SECRET_PREVIOUS: str | None = None 

46 INTERNAL_JWT_AUDIENCE: str = "svc-ai" 

47 

48 # CORS. svc-ai is an *internal* service reached only over the private backend 

49 # network (svc-core -> svc-ai, server to server); no browser calls it 

50 # directly, so the allowlist is empty by default. Escape hatch only — 

51 # comma-separated browser origins, should a deployment ever expose it. 

52 CORS_ALLOWED_ORIGINS: str = "" 

53 

54 # The model that triages every agent run (route and task shape), as 

55 # "provider/model". Empty: the agent's own model. A cheaper model here 

56 # saves a call's worth of cost on agents that run on a dear one — adopt 

57 # it only once the gold datasets show the answers hold (the platform 

58 # benchmark re-runs CHAINR Bot when this changes; it is in /health's 

59 # fingerprint). Used only for agents on the same provider: triage reads 

60 # the whole request, and must not send it to a provider the agent (or a 

61 # routing rule) never chose. A model this deployment cannot reach falls 

62 # back to the agent's own, with a warning, rather than failing the turn. 

63 TRIAGE_MODEL: str = "" 

64 

65 # Strict tool use (app/tools/wire.py): on a Bedrock route whose 

66 # ``strict_tools`` flag is set, bind each tool whose schema the platform 

67 # wrote with ``toolSpec.strict``, so its arguments are decoded to its 

68 # schema. On since the live probe (app/diagnostics/structured_probe.py, 

69 # 20 October 2026) found gpt-oss-120b and Qwen3 235B accept strict tool 

70 # sets with no compile cost a turn would notice and no recompile when a 

71 # set changes; the flag is set on those routes only. ``false`` binds every 

72 # tool as it is. In /health's fingerprint, so changing it re-runs CHAINR 

73 # Bot's benchmark. 

74 STRICT_BUILTIN_TOOLS: bool = True 

75 

76 # How this deployment reaches models (app.services.inference_routes): 

77 # "direct" — the vendors' own APIs and keys (local development); or 

78 # "bedrock" — Amazon Bedrock in BEDROCK_REGION, one AWS bill and UK/EU 

79 # inference where a model is offered there. The catalogue is the same 

80 # either way; its prices, regions and availability follow the backend. 

81 INFERENCE_BACKEND: str = "direct" 

82 BEDROCK_REGION: str = "eu-west-2" 

83 # Whose models this AWS account may use on Bedrock: "all", or the vendors 

84 # by name, comma-separated ("amazon,openai"). AWS grants model access per 

85 # account; a vendor left out has its routes marked unavailable and refused 

86 # with a reason, rather than offered and failing on AccessDenied. 

87 BEDROCK_MODEL_ACCESS: str = "all" 

88 

89 # The deployment's spending ceiling (app.services.spend_guard): no model 

90 # call starts once today's (UTC) or this month's metered spend has 

91 # reached it. Unset means the default ($15 a day, $150 a month) — never 

92 # unlimited; "off" lifts one. 

93 LLM_DAILY_CEILING_USD: str = "" 

94 LLM_MONTHLY_CEILING_USD: str = "" 

95 

96 # Postgres 

97 POSTGRES_USER: str = "postgres" 

98 POSTGRES_PASSWORD: str = "postgres" 

99 POSTGRES_HOST: str = "postgres" 

100 POSTGRES_PORT: int = 5432 

101 POSTGRES_DB: str = "svc_ai" 

102 

103 # Qdrant 

104 qdrant_url: str = "http://qdrant:6333" 

105 qdrant_api_key: str | None = None 

106 

107 # MinIO 

108 minio_endpoint: str = "minio:9000" 

109 minio_access_key: str 

110 minio_secret_key: str 

111 minio_secure: bool = False 

112 

113 # Embeddings. The model follows INFERENCE_BACKEND (app.services.embeddings): 

114 # OpenAI's on "direct", Amazon Titan on "bedrock". Titan takes one text 

115 # per request and Bedrock throttles it per request, so two settings pace 

116 # it across the process (svc-ai runs one uvicorn worker): 

117 # - EMBEDDING_RPM_QUOTA: the account's on-demand requests-per-minute quota 

118 # for the embedding model in this region, from Service Quotas (Titan 

119 # Text Embeddings V2 in London: 6,000, checked 9 October 2026). svc-ai 

120 # sends at most embeddings.QUOTA_SHARE of it; 0 turns pacing off. 

121 # - EMBEDDING_CONCURRENCY: requests in flight, enough to reach that pace 

122 # (about 80 a second at ~100 ms each). 

123 EMBEDDING_RPM_QUOTA: int = 6000 

124 EMBEDDING_CONCURRENCY: int = 8 

125 

126 # Docling 

127 docling_url: str = "http://docling:5001" 

128 

129 # Neo4j 

130 neo4j_uri: str = "bolt://neo4j:7687" 

131 neo4j_auth: str = "neo4j/chainr_dev" 

132 

133 @property 

134 def neo4j_user(self) -> str: 

135 return self.neo4j_auth.split("/")[0] 

136 

137 @property 

138 def neo4j_password(self) -> str: 

139 return self.neo4j_auth.split("/", 1)[1] 

140 

141 # LLM keys — LiteLLM reads these automatically 

142 openai_api_key: str | None = None 

143 anthropic_api_key: str | None = None 

144 groq_api_key: str | None = None 

145 

146 # Verbose LiteLLM wire logging (full request/response payloads). Opt-in 

147 # only: prompts routinely reach hundreds of KB (catalogs, graph node 

148 # context, evaluator drafts), and serialising them on every call is a 

149 # real CPU/event-loop cost that has destabilised the service under load. 

150 litellm_debug: bool = False 

151 

152 # ── MCP (Model Context Protocol) ──────────────────────────────────── 

153 # Per-server connection budget when discovering/loading tools. One slow 

154 # or unreachable server must never stall inference — past the deadline 

155 # the server is skipped and the agent degrades to its builtin toolset. 

156 mcp_connect_timeout_s: float = 15.0 

157 # MCP as a whole is off in every environment (app.mcp.MCP_AVAILABLE, a 

158 # constant, not a setting); these only shape it once that changes. 

159 # 

160 # stdio MCP servers run as subprocesses INSIDE the svc-ai container, so 

161 # the command field is code execution for anyone who can save an MCP 

162 # server config. The allowlist names launchers, not what they run — `npx` 

163 # and `uvx` fetch and execute any package — so it is no sandbox. The 

164 # interpreters (`python -c`, `node -e`) are left off because they need 

165 # no package at all. Comma-separated. 

166 mcp_stdio_allowed_commands: str = "npx,uvx" 

167 # Master switch for the stdio transport, off by default: stdio belongs in 

168 # an isolated sidecar, not in the container holding the provider keys. 

169 mcp_stdio_enabled: bool = False 

170 

171 # ── Web search / url_fetch ────────────────────────────────────────── 

172 # "auto" uses the Brave Search API when BRAVE_SEARCH_API_KEY is set and 

173 # the keyless DuckDuckGo (ddgs) scraper otherwise. Brave is an official 

174 # API over an independent index; ddgs scrapes several public engines, is 

175 # frequently rate-limited, and shares queries with every engine it 

176 # scrapes — acceptable only as a fallback. 

177 web_search_provider: Literal["auto", "brave", "duckduckgo"] = "auto" 

178 brave_search_api_key: str | None = None 

179 # When the primary provider errors (quota, outage) or lacks a result 

180 # type, retry on DuckDuckGo. Disable where queries must never leave the 

181 # contracted provider. 

182 web_search_fallback_enabled: bool = True 

183 # Comma-separated engines the ddgs fallback may scrape. Each one receives 

184 # the user's query, so the default excludes Google/Bing/Yahoo/Yandex; 

185 # "auto" opts back in to every engine ddgs supports. 

186 web_search_ddgs_backend: str = DEFAULT_DDGS_BACKEND 

187 # Locale defaults — per-agent tool config may override. 

188 web_search_country: str = "GB" # ISO 3166-1 alpha-2 

189 web_search_language: str = "en" # ISO 639-1 

190 web_search_safesearch: Literal["off", "moderate", "strict"] = "moderate" 

191 web_search_timeout_s: float = 10.0 

192 # How long one search may spend across the chain: an engine that fails 

193 # or answers with nothing hands on to the next until this has passed. 

194 web_search_call_budget_s: float = 25.0 

195 # In-process result cache: parallel graph nodes and evaluator retries 

196 # re-issue identical queries. 0 disables. 

197 web_search_cache_ttl_s: float = 600.0 

198 web_search_cache_size: int = 512 

199 # url_fetch download cap — protects memory from huge/binary responses. 

200 url_fetch_max_bytes: int = 10 * 1024 * 1024 

201 # Sent by url_fetch. Point the URL at your own bot page when deploying. 

202 url_fetch_user_agent: str = DEFAULT_URL_FETCH_USER_AGENT 

203 # The product token robots.txt rules are matched against for website 

204 # knowledge crawls — the name a site operator writes in ``User-agent:``. 

205 # Must appear in url_fetch_user_agent so the two identify the same bot. 

206 web_knowledge_robots_token: str = "CHAINR-Agent" 

207 # The most a document imported from a URL into a file source may be 

208 # (``knowledge/web.fetch_document``): held whole in memory to hand to 

209 # svc-core, so below svc-core's upload limit. 

210 knowledge_import_max_bytes: int = 25 * 1024 * 1024 

211 

212 # Images a document shows (``app/documents/images.py``): fetched once when 

213 # ``render_document`` runs, re-encoded and stored, then drawn in the PDF 

214 # and the document card. Off: every image stays its alt text. 

215 document_images_enabled: bool = True 

216 # The most one image may download, and the most its stored copy may be. 

217 document_image_max_bytes: int = 8 * 1024 * 1024 

218 document_image_max_stored_bytes: int = 2 * 1024 * 1024 

219 # Refused before decoding beyond this many pixels (a decompression bomb 

220 # is a small file that decodes to gigabytes). 

221 document_image_max_pixels: int = 40_000_000 

222 # The longest edge a stored copy keeps. 

223 document_image_max_edge_px: int = 1600 

224 # Per image, and for all a document's images together. 

225 document_image_fetch_timeout_s: float = 10.0 

226 document_image_budget_s: float = 30.0 

227 document_image_concurrency: int = 4 

228 # The width Wikimedia is asked to render a file at — one of its standard 

229 # thumbnail steps, which it serves from cache. 

230 document_image_wikimedia_width: int = 1280 

231 

232 @field_validator("brave_search_api_key", mode="before") 

233 @classmethod 

234 def _blank_disabled_key(cls, v): 

235 """Treat an explicit "off" value as no key at all. 

236 

237 Provider selection is ``if not key``, so without this a placeholder 

238 like "none" would be taken for a real key and every search would hit 

239 Brave with an invalid credential instead of falling back. 

240 """ 

241 if isinstance(v, str) and v.strip().lower() in DISABLED_VALUES: 

242 return None 

243 return v 

244 

245 @property 

246 def mcp_stdio_command_allowlist(self) -> set[str]: 

247 return { 

248 c.strip() for c in self.mcp_stdio_allowed_commands.split(",") if c.strip() 

249 } 

250 

251 class Config: 

252 env_file = ".env" 

253 extra = "ignore" 

254 

255 @property 

256 def POSTGRES_URL_FULL(self) -> str: 

257 return f"postgresql+psycopg2://{self.POSTGRES_USER}:{self.POSTGRES_PASSWORD}@{self.POSTGRES_HOST}:{self.POSTGRES_PORT}/{self.POSTGRES_DB}" 

258 

259 @property 

260 def is_development(self) -> bool: 

261 return self.environment in ("development", "dev", "local") 

262 

263 @property 

264 def internal_auth_active(self) -> bool: 

265 return bool(self.INTERNAL_JWT_SECRET) 

266 

267 @property 

268 def strict_auth(self) -> bool: 

269 return self.environment.lower() in STRICT_ENVIRONMENTS 

270 

271 

272@lru_cache 

273def get_settings(): 

274 settings = Settings() 

275 if settings.strict_auth: 

276 if not settings.INTERNAL_JWT_SECRET: 

277 raise ValueError( 

278 f"INTERNAL_JWT_SECRET must be set in {settings.environment} for " 

279 "service-to-service authentication" 

280 ) 

281 if len(settings.INTERNAL_JWT_SECRET) < 32: 

282 raise ValueError("INTERNAL_JWT_SECRET must be at least 32 characters") 

283 return settings