Utilities API
Supporting utilities for theme discovery, LLM management, and graph operations.
Theme Registry
scinr.newton.utils.theme_registry.ThemeRegistry
Scans models/ recursively to discover theme folders and build a theme tree.
A folder is a theme iff it contains a catalog.py. Nested theme folders (sub-themes) are supported to any depth.
build_catalog_block
Build the plain-text model catalog block to inject into LLM decision prompts.
Format
Available annotation models:
-
ClassName — First line of docstring Fields: field1: str, field2: int | None
-
ContainerClass [list container] — Description Fields: items: list[ItemClass] Each item (ItemClass): field1: str, field2: str
This format is readable by all LLM families (Claude, OpenAI, Kimi, GLM, etc.)
and replaces the previous XML
build_theme_section_for_extraction_prompt
Builds the
Called once at extraction startup; the result is static for the duration of the run (themes do not change at runtime).
find_best_theme
Return the most specific available ThemeNode for detected_path.
Resolution order (most to least specific): 1. Exact match for the full detected path 2. Progressively shorter path prefixes 3. "default" theme (if available) 4. First registered theme (emergency fallback)
Examples:
detected_path="structural_specs/pharmaceutical/ema" → tries "structural_specs/pharmaceutical/ema" → not found → tries "structural_specs/pharmaceutical" → not found → tries "structural_specs" → FOUND, returns it
detected_path="unknown_theme" → tries "unknown_theme" → not found → falls back to "default"
get_all_theme_paths
Returns all registered theme paths sorted alphabetically.
Used by the extraction pipeline to build a dynamic Literal type for structured output validation.
get_all_valid_model_classes
Return sorted list of ALL valid model class names across ALL themes.
get_neo4j_theme_structure
Return the full theme tree as a list of dicts for graph ingestion.
Each dict has
path — str, e.g. "structural_specs/nta" name — str, e.g. "nta" parent_path — str | None (parent theme path, or None if top-level) model_names — list[str] of selectable class names
get_theme_list_for_prompt
Build a formatted list of available themes for injection into the classification prompt.
Example output
- default: Generic fallback for content that does not fit a specific domain
- pharmaceutical: Pharmaceutical drug development documents following ICH CTD Module 3
- structural_specs: Documents that prescribe how other documents must be structured
LLM Utilities
scinr.newton.utils.llm_factory
utils/llm_factory.py — Deprecated. Use scinr_config instead.
This module exists for backward compatibility only.
Retry Utilities
scinr.newton.utils.llm_retry
utils/llm_retry.py — Generic LLM retry with exponential backoff.
Handles rate-limiting and transient errors from any LangChain-compatible LLM provider (AWS Bedrock, OpenAI, Anthropic, Ollama, etc.).
with_bedrock_retry
async
with_bedrock_retry(
coro_fn: Callable[[], Awaitable[Any]],
max_retries: int = _MAX_RETRIES,
) -> Any
Deprecated alias for with_llm_retry. Use with_llm_retry instead.
with_llm_retry
async
Execute an async LLM call with exponential backoff on retryable errors.
Parameters
coro_fn: Zero-argument async callable that invokes the LLM. max_retries: Maximum number of retry attempts (default 6).
Returns
Any The return value of coro_fn() on success.
Raises
The last exception if all retries are exhausted.
scinr.newton.graph.neo4j.retry
graph/neo4j/retry.py — Two-phase retry wrapper for transient Neo4j errors.
Neo4j can raise transient errors (e.g. DeadlockDetected, LockClientStopped, ServiceUnavailable / defunct connection) under write contention or parallel read overload. Without a retry mechanism, concurrent document ingestion would fail immediately on the first lock conflict or socket reset.
Public API
result = await with_neo4j_retry(lambda: session.run(...))
result = with_neo4j_retry_sync(lambda: session.run(...)) # sync mirror,
# for use inside asyncio.to_thread() worker threads
The wrapper uses a two-phase retry strategy:
Phase 1 — Exponential backoff with full jitter, capped at 60 s (7 attempts). Phase 2 — Fixed 60 s plateau, 5 additional attempts.
Total: 12 retry attempts maximum (~6.8 min worst-case wait). Non-transient exceptions are re-raised immediately without retrying.
BASE_DELAY
module-attribute
Initial wait in seconds; doubles each exponential attempt.
EXP_RETRIES
module-attribute
Number of exponential-backoff attempts (attempts 0–6, delays 1 s → 60 s).
MAX_DELAY_EXP
module-attribute
Upper cap on the exponential back-off delay and fixed plateau delay (seconds).
PLATEAU_RETRIES
module-attribute
Number of fixed-plateau attempts after the exponential phase (60 s each).
TOTAL_RETRIES
module-attribute
Maximum total retry attempts after the initial failure (12).
with_neo4j_retry
async
with_neo4j_retry(
coro_fn: Callable[[], Coroutine[Any, Any, T]],
*,
exp_retries: int = EXP_RETRIES,
plateau_retries: int = PLATEAU_RETRIES,
base_delay: float = BASE_DELAY,
max_delay_exp: float = MAX_DELAY_EXP,
) -> T
Await coro_fn() with two-phase retry on transient Neo4j errors.
Parameters
coro_fn:
A zero-argument callable that returns an awaitable (e.g.
lambda: session.run(...)). It is called fresh on every attempt
so that a new coroutine object is created each time.
exp_retries:
Number of exponential-backoff retry attempts (Phase 1).
plateau_retries:
Number of fixed-plateau retry attempts after the exponential phase
(Phase 2).
base_delay:
Base wait time in seconds for the exponential phase.
max_delay_exp:
Cap on the exponential delay and the fixed plateau delay (seconds).
Returns
T Whatever coro_fn() returns on success.
Raises
Exception Re-raises the last transient exception once all retries are exhausted, or immediately re-raises any non-transient exception.
with_neo4j_retry_sync
with_neo4j_retry_sync(
fn: Callable[[], T],
*,
exp_retries: int = EXP_RETRIES,
plateau_retries: int = PLATEAU_RETRIES,
base_delay: float = BASE_DELAY,
max_delay_exp: float = MAX_DELAY_EXP,
) -> T
Synchronous mirror of with_neo4j_retry(): uses time.sleep() instead of asyncio.sleep(). Designed to run inside an asyncio.to_thread() worker thread (no event loop of its own) — must never await.
Parameters
fn:
A zero-argument callable that returns a value synchronously (e.g.
lambda: session.run(...)). It is called fresh on every attempt.
exp_retries:
Number of exponential-backoff retry attempts (Phase 1).
plateau_retries:
Number of fixed-plateau retry attempts after the exponential phase
(Phase 2).
base_delay:
Base wait time in seconds for the exponential phase.
max_delay_exp:
Cap on the exponential delay and the fixed plateau delay (seconds).
Returns
T Whatever fn() returns on success.
Raises
Exception Re-raises the last transient exception once all retries are exhausted, or immediately re-raises any non-transient exception.
Concurrency
scinr.newton.utils.graph_concurrency
utils/graph_concurrency.py — Compatibility shim for the graph-store concurrency semaphore.
The semaphore logic lives in config.py alongside get_llm_semaphore() and reset_llm_semaphore(). This module re-exports those functions so that callers (annotation/nodes.py, entity_extraction/nodes.py) can import them from a stable path.
To configure concurrency, call configure(graph_concurrency=N) followed by reset_graph_semaphore() before running annotation or entity extraction stages.
get_graph_semaphore
Return (creating if needed) the global asyncio.Semaphore for graph-store session concurrency.
The semaphore bounds the number of concurrent graph-store sessions during annotation (Stage 3) and entity extraction (Stage 4), for any graph backend (Neo4j or SQL). It is created lazily on the first call using the graph_concurrency value from ScinrConfig.
To change the concurrency at runtime, call configure(graph_concurrency=N) followed by reset_graph_semaphore() before running the relevant stages.
The deprecated module scinr.newton.utils.neo4j_concurrency (get_neo4j_semaphore, reset_neo4j_semaphore) still works with a DeprecationWarning and is removed in 0.7.0.
Logging
scinr.newton.utils.logging_config
utils/logging_config.py — Logging setup for scinr-ingest.
Library mode (default)
When called without arguments, only a console handler is added — no files are created, no directories are touched. This is the correct behaviour for a library: the application that uses scinr-ingest is responsible for configuring file logging if it wants it.
File logging
When log_dir is provided (e.g. Path("logs")), two rotating
daily-folder file handlers are added in addition to the console handler:
<log_dir>/
└── YYYY-MM-DD/
├── scinr.log ← INFO+, retained 30 days
└── scinr.errors.log ← ERROR+ only, retained 90 days
Usage::
# Library — console only, no files:
from scinr.newton.utils.logging_config import setup_logging
setup_logging()
# Application — console + daily file rotation under ./logs/:
setup_logging(log_dir=Path("logs"))
Credential redaction
Every handler installed here formats through :class:RedactingFormatter, which
masks connection-string passwords and the configured secrets in the final
line — message, arguments and traceback alike. Applications that install their
own handlers should use it too, or call :func:redact_handlers once after
configuring logging::
handler.setFormatter(RedactingFormatter("%(asctime)s %(message)s"))
redact_handlers() # or: wrap whatever formatters the root handlers have
RedactingFormatter
Bases: Formatter
A :class:logging.Formatter that scrubs credentials from the output.
Redacts the fully formatted record (message, arguments, exception
traceback and stack info), so a driver error echoing a connection URI is
masked even when it is only logged through logger.exception.
Pass wrapped= to keep an existing formatter (e.g. a JSON one) and only
add the redaction on top of its output.
redact_handlers
Make every handler of logger (the root logger by default) redact credentials.
Each handler's current formatter is wrapped in a :class:RedactingFormatter,
so its format is kept. Idempotent. Applications that configure their own
logging should call this once after doing so.
setup_logging
Configure logging for scinr-ingest.
Parameters
log_dir:
Directory under which dated sub-folders and log files are created.
When None (the default), only a console handler is configured —
no files or directories are created. Pass an explicit path (e.g.
Path("logs")) to enable file logging.
Credential Redaction
scinr.newton.utils.redaction
utils/redaction.py — Scrub credentials out of text before it leaves the process.
Connection strings carry their credentials inline
(mongodb://user:secret@host), and both our own messages and some driver
errors echo them back. Anything that turns a connection string or an exception
into text that is logged or handed to a caller — a log line, a
StageResult.errors entry, an exception message — should go through here.
Public API
redact_uri(uri)
Mask the password of one known connection string, keeping the user and host
so the message is still useful for debugging.
redact_secrets(text)
Scrub free text: mask the userinfo password of every scheme://user:pw@
it contains, plus any literal occurrence of the configured secrets
(Neo4j password, MongoDB URI password, SQL URL password, Mistral API key).
redact_secrets
Return text with every credential it may contain replaced by ***.
Masks the password of every scheme://user:password@ URI in the text,
then any literal occurrence (raw or URL-decoded) of the currently configured
Neo4j password, MongoDB URI password, SQL URL password and Mistral API key.
redact_uri
Return uri with the password in its userinfo replaced by ***.
mongodb://app:s3cr3t@db1:27017,db2:27017/?authSource=admin becomes
mongodb://app:***@db1:27017,db2:27017/?authSource=admin.
The split is on the last @ of the whole string, so a password with
unescaped reserved characters (/, ?, @) is still fully masked.