accrue 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- accrue/__init__.py +77 -0
- accrue/core/__init__.py +40 -0
- accrue/core/cache.py +178 -0
- accrue/core/checkpoint.py +184 -0
- accrue/core/config.py +169 -0
- accrue/core/enricher.py +213 -0
- accrue/core/exceptions.py +101 -0
- accrue/core/hooks.py +114 -0
- accrue/data/__init__.py +7 -0
- accrue/data/fields.py +229 -0
- accrue/pipeline/__init__.py +5 -0
- accrue/pipeline/pipeline.py +1192 -0
- accrue/providers.py +22 -0
- accrue/py.typed +0 -0
- accrue/schemas/__init__.py +16 -0
- accrue/schemas/base.py +68 -0
- accrue/schemas/enrichment.py +13 -0
- accrue/schemas/field_spec.py +40 -0
- accrue/schemas/grounding.py +67 -0
- accrue/steps/__init__.py +13 -0
- accrue/steps/base.py +69 -0
- accrue/steps/function.py +83 -0
- accrue/steps/llm.py +612 -0
- accrue/steps/prompt_builder.py +258 -0
- accrue/steps/providers/__init__.py +13 -0
- accrue/steps/providers/anthropic.py +388 -0
- accrue/steps/providers/base.py +176 -0
- accrue/steps/providers/google.py +195 -0
- accrue/steps/providers/openai.py +580 -0
- accrue/steps/schema_builder.py +105 -0
- accrue/utils/__init__.py +5 -0
- accrue/utils/logger.py +162 -0
- accrue/utils/web_search.py +140 -0
- accrue-1.0.0.dist-info/METADATA +207 -0
- accrue-1.0.0.dist-info/RECORD +37 -0
- accrue-1.0.0.dist-info/WHEEL +4 -0
- accrue-1.0.0.dist-info/licenses/LICENSE +21 -0
accrue/__init__.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Accrue — Enrichment Pipeline Engine.
|
|
2
|
+
|
|
3
|
+
A programmatic enrichment engine built on composable, column-oriented
|
|
4
|
+
pipeline steps with Pydantic validation, checkpointing, and async concurrency.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
# Set up default logging when package is imported
|
|
8
|
+
from .utils.logger import setup_logging
|
|
9
|
+
|
|
10
|
+
setup_logging(level="WARNING", format_type="console", include_timestamp=False)
|
|
11
|
+
|
|
12
|
+
# Public API
|
|
13
|
+
from .core import (
|
|
14
|
+
Enricher,
|
|
15
|
+
EnrichmentConfig,
|
|
16
|
+
EnrichmentError,
|
|
17
|
+
FieldValidationError,
|
|
18
|
+
PipelineError,
|
|
19
|
+
RowError,
|
|
20
|
+
StepError,
|
|
21
|
+
)
|
|
22
|
+
from .core.hooks import (
|
|
23
|
+
EnrichmentHooks,
|
|
24
|
+
PipelineEndEvent,
|
|
25
|
+
PipelineStartEvent,
|
|
26
|
+
RowCompleteEvent,
|
|
27
|
+
StepEndEvent,
|
|
28
|
+
StepStartEvent,
|
|
29
|
+
)
|
|
30
|
+
from .pipeline import Pipeline, PipelineResult
|
|
31
|
+
from .schemas.base import CostSummary
|
|
32
|
+
from .schemas.field_spec import FieldSpec
|
|
33
|
+
from .schemas.grounding import GroundingConfig
|
|
34
|
+
from .steps import FunctionStep, LLMStep, Step, StepContext, StepResult
|
|
35
|
+
from .steps.providers.base import BatchCapableLLMClient, BatchRequest, BatchResult
|
|
36
|
+
from .utils.web_search import web_search
|
|
37
|
+
|
|
38
|
+
__version__ = "1.0.0"
|
|
39
|
+
__author__ = "Accrue Team"
|
|
40
|
+
|
|
41
|
+
__all__ = [
|
|
42
|
+
# Primary API
|
|
43
|
+
"Pipeline",
|
|
44
|
+
"PipelineResult",
|
|
45
|
+
"LLMStep",
|
|
46
|
+
"FunctionStep",
|
|
47
|
+
"EnrichmentConfig",
|
|
48
|
+
# Hooks
|
|
49
|
+
"EnrichmentHooks",
|
|
50
|
+
"PipelineStartEvent",
|
|
51
|
+
"PipelineEndEvent",
|
|
52
|
+
"StepStartEvent",
|
|
53
|
+
"StepEndEvent",
|
|
54
|
+
"RowCompleteEvent",
|
|
55
|
+
# Step protocol
|
|
56
|
+
"Step",
|
|
57
|
+
"StepContext",
|
|
58
|
+
"StepResult",
|
|
59
|
+
# Schemas
|
|
60
|
+
"FieldSpec",
|
|
61
|
+
"GroundingConfig",
|
|
62
|
+
# Utilities
|
|
63
|
+
"web_search",
|
|
64
|
+
# Batch API
|
|
65
|
+
"BatchCapableLLMClient",
|
|
66
|
+
"BatchRequest",
|
|
67
|
+
"BatchResult",
|
|
68
|
+
# Results & errors
|
|
69
|
+
"CostSummary",
|
|
70
|
+
"RowError",
|
|
71
|
+
"EnrichmentError",
|
|
72
|
+
"FieldValidationError",
|
|
73
|
+
"StepError",
|
|
74
|
+
"PipelineError",
|
|
75
|
+
# Internal runner (power users)
|
|
76
|
+
"Enricher",
|
|
77
|
+
]
|
accrue/core/__init__.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Core functionality for the Accrue enrichment tool."""
|
|
2
|
+
|
|
3
|
+
from .cache import CacheManager
|
|
4
|
+
from .checkpoint import CheckpointData, CheckpointManager
|
|
5
|
+
from .config import EnrichmentConfig
|
|
6
|
+
from .enricher import Enricher
|
|
7
|
+
from .exceptions import (
|
|
8
|
+
EnrichmentError,
|
|
9
|
+
FieldValidationError,
|
|
10
|
+
PipelineError,
|
|
11
|
+
RowError,
|
|
12
|
+
StepError,
|
|
13
|
+
)
|
|
14
|
+
from .hooks import (
|
|
15
|
+
EnrichmentHooks,
|
|
16
|
+
PipelineEndEvent,
|
|
17
|
+
PipelineStartEvent,
|
|
18
|
+
RowCompleteEvent,
|
|
19
|
+
StepEndEvent,
|
|
20
|
+
StepStartEvent,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"CacheManager",
|
|
25
|
+
"Enricher",
|
|
26
|
+
"CheckpointManager",
|
|
27
|
+
"CheckpointData",
|
|
28
|
+
"EnrichmentConfig",
|
|
29
|
+
"EnrichmentError",
|
|
30
|
+
"FieldValidationError",
|
|
31
|
+
"StepError",
|
|
32
|
+
"PipelineError",
|
|
33
|
+
"RowError",
|
|
34
|
+
"EnrichmentHooks",
|
|
35
|
+
"PipelineStartEvent",
|
|
36
|
+
"PipelineEndEvent",
|
|
37
|
+
"StepStartEvent",
|
|
38
|
+
"StepEndEvent",
|
|
39
|
+
"RowCompleteEvent",
|
|
40
|
+
]
|
accrue/core/cache.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""CacheManager — SQLite-backed input-hash cache for pipeline steps.
|
|
2
|
+
|
|
3
|
+
Per-step-per-row caching with SHA-256 keys. Uses WAL mode for
|
|
4
|
+
concurrent access. Single `.accrue/cache.db` file, zero new deps.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import json
|
|
11
|
+
import sqlite3
|
|
12
|
+
import time
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class CacheManager:
|
|
18
|
+
"""SQLite-backed cache for step results.
|
|
19
|
+
|
|
20
|
+
Each entry is keyed by a SHA-256 hash of the step's input
|
|
21
|
+
(row data, prior results, field specs, model, temperature, etc.).
|
|
22
|
+
TTL expiry is lazy — checked on ``get()``, bulk-cleaned via
|
|
23
|
+
``cleanup_expired()``.
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
cache_dir: Directory for ``cache.db``. Created if absent.
|
|
27
|
+
ttl: Time-to-live in seconds. 0 = no expiry.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
def __init__(self, cache_dir: str = ".accrue", ttl: int = 3600) -> None:
|
|
31
|
+
self._cache_dir = Path(cache_dir)
|
|
32
|
+
self._ttl = ttl
|
|
33
|
+
self._conn: sqlite3.Connection | None = None
|
|
34
|
+
|
|
35
|
+
def _ensure_connection(self) -> sqlite3.Connection:
|
|
36
|
+
if self._conn is not None:
|
|
37
|
+
return self._conn
|
|
38
|
+
|
|
39
|
+
self._cache_dir.mkdir(parents=True, exist_ok=True)
|
|
40
|
+
db_path = self._cache_dir / "cache.db"
|
|
41
|
+
|
|
42
|
+
self._conn = sqlite3.connect(str(db_path))
|
|
43
|
+
self._conn.execute("PRAGMA journal_mode=WAL")
|
|
44
|
+
self._conn.execute("PRAGMA synchronous=NORMAL")
|
|
45
|
+
self._conn.execute("PRAGMA cache_size=-8000") # 8 MB
|
|
46
|
+
|
|
47
|
+
self._conn.execute("""
|
|
48
|
+
CREATE TABLE IF NOT EXISTS cache (
|
|
49
|
+
key TEXT PRIMARY KEY,
|
|
50
|
+
step_name TEXT NOT NULL,
|
|
51
|
+
value TEXT NOT NULL,
|
|
52
|
+
created_at REAL NOT NULL,
|
|
53
|
+
expires_at REAL
|
|
54
|
+
)
|
|
55
|
+
""")
|
|
56
|
+
self._conn.execute("CREATE INDEX IF NOT EXISTS idx_step ON cache(step_name)")
|
|
57
|
+
self._conn.execute("CREATE INDEX IF NOT EXISTS idx_expires ON cache(expires_at)")
|
|
58
|
+
self._conn.commit()
|
|
59
|
+
return self._conn
|
|
60
|
+
|
|
61
|
+
def get(self, key: str) -> dict | None:
|
|
62
|
+
"""Look up a cached value by key. Returns None on miss or expiry."""
|
|
63
|
+
conn = self._ensure_connection()
|
|
64
|
+
row = conn.execute("SELECT value, expires_at FROM cache WHERE key = ?", (key,)).fetchone()
|
|
65
|
+
|
|
66
|
+
if row is None:
|
|
67
|
+
return None
|
|
68
|
+
|
|
69
|
+
value_json, expires_at = row
|
|
70
|
+
if expires_at is not None and time.time() > expires_at:
|
|
71
|
+
conn.execute("DELETE FROM cache WHERE key = ?", (key,))
|
|
72
|
+
conn.commit()
|
|
73
|
+
return None
|
|
74
|
+
|
|
75
|
+
return json.loads(value_json)
|
|
76
|
+
|
|
77
|
+
def set(self, key: str, step_name: str, value: dict) -> None:
|
|
78
|
+
"""Store a value in the cache."""
|
|
79
|
+
conn = self._ensure_connection()
|
|
80
|
+
now = time.time()
|
|
81
|
+
expires_at = (now + self._ttl) if self._ttl > 0 else None
|
|
82
|
+
|
|
83
|
+
conn.execute(
|
|
84
|
+
"INSERT OR REPLACE INTO cache (key, step_name, value, created_at, expires_at) "
|
|
85
|
+
"VALUES (?, ?, ?, ?, ?)",
|
|
86
|
+
(key, step_name, json.dumps(value, default=str), now, expires_at),
|
|
87
|
+
)
|
|
88
|
+
conn.commit()
|
|
89
|
+
|
|
90
|
+
def delete_step(self, step_name: str) -> int:
|
|
91
|
+
"""Delete all cache entries for a step. Returns count deleted."""
|
|
92
|
+
conn = self._ensure_connection()
|
|
93
|
+
cursor = conn.execute("DELETE FROM cache WHERE step_name = ?", (step_name,))
|
|
94
|
+
conn.commit()
|
|
95
|
+
return cursor.rowcount
|
|
96
|
+
|
|
97
|
+
def delete_all(self) -> int:
|
|
98
|
+
"""Delete all cache entries. Returns count deleted."""
|
|
99
|
+
conn = self._ensure_connection()
|
|
100
|
+
cursor = conn.execute("DELETE FROM cache")
|
|
101
|
+
conn.commit()
|
|
102
|
+
return cursor.rowcount
|
|
103
|
+
|
|
104
|
+
def cleanup_expired(self) -> int:
|
|
105
|
+
"""Remove all expired entries. Returns count deleted."""
|
|
106
|
+
conn = self._ensure_connection()
|
|
107
|
+
cursor = conn.execute(
|
|
108
|
+
"DELETE FROM cache WHERE expires_at IS NOT NULL AND expires_at < ?",
|
|
109
|
+
(time.time(),),
|
|
110
|
+
)
|
|
111
|
+
conn.commit()
|
|
112
|
+
return cursor.rowcount
|
|
113
|
+
|
|
114
|
+
def close(self) -> None:
|
|
115
|
+
"""Close the database connection."""
|
|
116
|
+
if self._conn is not None:
|
|
117
|
+
self._conn.close()
|
|
118
|
+
self._conn = None
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
# ---------------------------------------------------------------------------
|
|
122
|
+
# Cache key computation
|
|
123
|
+
# ---------------------------------------------------------------------------
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def canonical_json(obj: Any) -> str:
|
|
127
|
+
"""Deterministic JSON: sorted keys, compact separators, str fallback."""
|
|
128
|
+
return json.dumps(obj, sort_keys=True, separators=(",", ":"), default=str)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def compute_cache_key(**components: Any) -> str:
|
|
132
|
+
"""SHA-256 hex digest of canonical JSON of *components*."""
|
|
133
|
+
payload = canonical_json(components)
|
|
134
|
+
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _compute_step_cache_key(
|
|
138
|
+
step: Any,
|
|
139
|
+
row: dict[str, Any],
|
|
140
|
+
prior_results: dict[str, Any],
|
|
141
|
+
step_fields: dict[str, Any],
|
|
142
|
+
) -> str:
|
|
143
|
+
"""Build the cache key for a step + row, duck-typing the step.
|
|
144
|
+
|
|
145
|
+
LLMStep has ``model`` and ``temperature``; FunctionStep has ``cache_version``.
|
|
146
|
+
"""
|
|
147
|
+
if getattr(step, "model", None) is not None:
|
|
148
|
+
# LLMStep path
|
|
149
|
+
system_prompt = getattr(step, "_custom_system_prompt", None) or ""
|
|
150
|
+
system_prompt_header = getattr(step, "_system_prompt_header", None) or ""
|
|
151
|
+
# Include grounding config in cache key when present
|
|
152
|
+
grounding_cfg = getattr(step, "_grounding_config", None)
|
|
153
|
+
grounding_hash = ""
|
|
154
|
+
if grounding_cfg is not None:
|
|
155
|
+
grounding_hash = hashlib.sha256(
|
|
156
|
+
grounding_cfg.model_dump_json().encode("utf-8")
|
|
157
|
+
).hexdigest()
|
|
158
|
+
return compute_cache_key(
|
|
159
|
+
step_name=step.name,
|
|
160
|
+
row=row,
|
|
161
|
+
prior_results=prior_results,
|
|
162
|
+
field_specs=step_fields,
|
|
163
|
+
model=step.model,
|
|
164
|
+
temperature=getattr(step, "temperature", None),
|
|
165
|
+
system_prompt_hash=hashlib.sha256(system_prompt.encode("utf-8")).hexdigest(),
|
|
166
|
+
system_prompt_header_hash=hashlib.sha256(
|
|
167
|
+
system_prompt_header.encode("utf-8")
|
|
168
|
+
).hexdigest(),
|
|
169
|
+
grounding_hash=grounding_hash,
|
|
170
|
+
)
|
|
171
|
+
else:
|
|
172
|
+
# FunctionStep path
|
|
173
|
+
return compute_cache_key(
|
|
174
|
+
step_name=step.name,
|
|
175
|
+
row=row,
|
|
176
|
+
prior_results=prior_results,
|
|
177
|
+
cache_version=getattr(step, "cache_version", None),
|
|
178
|
+
)
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"""Per-step checkpoint manager for column-oriented pipeline execution.
|
|
2
|
+
|
|
3
|
+
Saves pipeline progress after each step completes across all rows.
|
|
4
|
+
Single JSON file per data_identifier + category.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import time
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import TYPE_CHECKING, Any
|
|
14
|
+
|
|
15
|
+
from ..utils.logger import get_logger
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from .config import EnrichmentConfig
|
|
19
|
+
|
|
20
|
+
logger = get_logger(__name__)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class CheckpointData:
|
|
25
|
+
"""Snapshot of pipeline progress loaded from a checkpoint file."""
|
|
26
|
+
|
|
27
|
+
timestamp: float
|
|
28
|
+
category: str
|
|
29
|
+
total_rows: int
|
|
30
|
+
fields_dict: dict[str, dict[str, Any]]
|
|
31
|
+
completed_steps: list[str]
|
|
32
|
+
step_results: dict[str, list[dict[str, Any]]]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class CheckpointManager:
|
|
36
|
+
"""Manages per-step checkpoint files for pipeline execution.
|
|
37
|
+
|
|
38
|
+
After each step finishes (across all rows), the full pipeline
|
|
39
|
+
state is written to a single JSON file. On resume, completed
|
|
40
|
+
steps are skipped and their results are fed into downstream
|
|
41
|
+
dependency routing.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
def __init__(self, config: EnrichmentConfig) -> None:
|
|
45
|
+
self._enabled = config.enable_checkpointing
|
|
46
|
+
self._auto_resume = config.auto_resume
|
|
47
|
+
self._checkpoint_dir: Path | None = None
|
|
48
|
+
|
|
49
|
+
raw_dir = config.checkpoint_dir
|
|
50
|
+
if raw_dir is not None:
|
|
51
|
+
self._checkpoint_dir = Path(raw_dir)
|
|
52
|
+
|
|
53
|
+
# -- path helpers ----------------------------------------------------
|
|
54
|
+
|
|
55
|
+
def _get_path(self, data_identifier: str, category: str) -> Path:
|
|
56
|
+
base_dir = self._checkpoint_dir or Path.cwd()
|
|
57
|
+
base_dir.mkdir(parents=True, exist_ok=True)
|
|
58
|
+
|
|
59
|
+
safe_id = "".join(c if c.isalnum() or c in ("-", "_") else "_" for c in data_identifier)
|
|
60
|
+
safe_cat = "".join(c if c.isalnum() or c in ("-", "_") else "_" for c in category)
|
|
61
|
+
return base_dir / f"{safe_id}_{safe_cat}_checkpoint.json"
|
|
62
|
+
|
|
63
|
+
# -- public API ------------------------------------------------------
|
|
64
|
+
|
|
65
|
+
def save_step(
|
|
66
|
+
self,
|
|
67
|
+
data_identifier: str,
|
|
68
|
+
category: str,
|
|
69
|
+
step_name: str,
|
|
70
|
+
step_row_results: list[dict[str, Any]],
|
|
71
|
+
total_rows: int,
|
|
72
|
+
fields_dict: dict[str, dict[str, Any]],
|
|
73
|
+
existing_completed: list[str],
|
|
74
|
+
existing_results: dict[str, list[dict[str, Any]]],
|
|
75
|
+
) -> bool:
|
|
76
|
+
"""Write full pipeline state to disk after a step completes.
|
|
77
|
+
|
|
78
|
+
Returns True on success or when checkpointing is disabled (no-op).
|
|
79
|
+
"""
|
|
80
|
+
if not self._enabled:
|
|
81
|
+
return True
|
|
82
|
+
|
|
83
|
+
# Merge the newly completed step into existing state
|
|
84
|
+
completed = list(existing_completed) + [step_name]
|
|
85
|
+
results = dict(existing_results)
|
|
86
|
+
results[step_name] = step_row_results
|
|
87
|
+
|
|
88
|
+
payload = {
|
|
89
|
+
"timestamp": time.time(),
|
|
90
|
+
"category": category,
|
|
91
|
+
"total_rows": total_rows,
|
|
92
|
+
"fields_dict": fields_dict,
|
|
93
|
+
"completed_steps": completed,
|
|
94
|
+
"step_results": results,
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
try:
|
|
98
|
+
path = self._get_path(data_identifier, category)
|
|
99
|
+
with open(path, "w") as f:
|
|
100
|
+
json.dump(payload, f, indent=2, default=str)
|
|
101
|
+
logger.info(f"Checkpoint saved after step '{step_name}': {path}")
|
|
102
|
+
return True
|
|
103
|
+
except Exception as e:
|
|
104
|
+
logger.error(f"Failed to save checkpoint: {e}")
|
|
105
|
+
return False
|
|
106
|
+
|
|
107
|
+
def load(self, data_identifier: str, category: str) -> CheckpointData | None:
|
|
108
|
+
"""Load checkpoint if enabled, auto_resume is on, file exists, and category matches."""
|
|
109
|
+
if not self._enabled or not self._auto_resume:
|
|
110
|
+
return None
|
|
111
|
+
|
|
112
|
+
path = self._get_path(data_identifier, category)
|
|
113
|
+
if not path.exists():
|
|
114
|
+
return None
|
|
115
|
+
|
|
116
|
+
try:
|
|
117
|
+
with open(path) as f:
|
|
118
|
+
raw = json.load(f)
|
|
119
|
+
|
|
120
|
+
if raw.get("category") != category:
|
|
121
|
+
logger.warning(
|
|
122
|
+
f"Checkpoint category mismatch: expected '{category}', "
|
|
123
|
+
f"got '{raw.get('category')}'"
|
|
124
|
+
)
|
|
125
|
+
return None
|
|
126
|
+
|
|
127
|
+
data = CheckpointData(
|
|
128
|
+
timestamp=raw["timestamp"],
|
|
129
|
+
category=raw["category"],
|
|
130
|
+
total_rows=raw["total_rows"],
|
|
131
|
+
fields_dict=raw["fields_dict"],
|
|
132
|
+
completed_steps=raw["completed_steps"],
|
|
133
|
+
step_results=raw["step_results"],
|
|
134
|
+
)
|
|
135
|
+
logger.info(
|
|
136
|
+
f"Checkpoint loaded: {len(data.completed_steps)} steps completed "
|
|
137
|
+
f"({', '.join(data.completed_steps)})"
|
|
138
|
+
)
|
|
139
|
+
return data
|
|
140
|
+
except Exception as e:
|
|
141
|
+
logger.error(f"Failed to load checkpoint: {e}")
|
|
142
|
+
return None
|
|
143
|
+
|
|
144
|
+
def cleanup(self, data_identifier: str, category: str) -> bool:
|
|
145
|
+
"""Remove checkpoint file after successful pipeline completion."""
|
|
146
|
+
if not self._enabled:
|
|
147
|
+
return True
|
|
148
|
+
|
|
149
|
+
try:
|
|
150
|
+
path = self._get_path(data_identifier, category)
|
|
151
|
+
if path.exists():
|
|
152
|
+
path.unlink()
|
|
153
|
+
logger.info(f"Checkpoint cleaned up: {path}")
|
|
154
|
+
return True
|
|
155
|
+
except Exception as e:
|
|
156
|
+
logger.error(f"Failed to cleanup checkpoint: {e}")
|
|
157
|
+
return False
|
|
158
|
+
|
|
159
|
+
def list_checkpoints(self) -> dict[str, dict[str, Any]]:
|
|
160
|
+
"""Scan checkpoint_dir for ``*_checkpoint.json`` files."""
|
|
161
|
+
checkpoints: dict[str, dict[str, Any]] = {}
|
|
162
|
+
|
|
163
|
+
if not self._enabled:
|
|
164
|
+
return checkpoints
|
|
165
|
+
|
|
166
|
+
scan_dir = self._checkpoint_dir or Path.cwd()
|
|
167
|
+
if not scan_dir.exists():
|
|
168
|
+
return checkpoints
|
|
169
|
+
|
|
170
|
+
for path in scan_dir.glob("*_checkpoint.json"):
|
|
171
|
+
try:
|
|
172
|
+
with open(path) as f:
|
|
173
|
+
raw = json.load(f)
|
|
174
|
+
checkpoints[path.stem] = {
|
|
175
|
+
"path": str(path),
|
|
176
|
+
"category": raw.get("category"),
|
|
177
|
+
"total_rows": raw.get("total_rows"),
|
|
178
|
+
"completed_steps": raw.get("completed_steps", []),
|
|
179
|
+
"timestamp": raw.get("timestamp"),
|
|
180
|
+
}
|
|
181
|
+
except Exception as e:
|
|
182
|
+
logger.warning(f"Failed to read checkpoint {path}: {e}")
|
|
183
|
+
|
|
184
|
+
return checkpoints
|
accrue/core/config.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Unified configuration for the Accrue enrichment tool.
|
|
3
|
+
|
|
4
|
+
Defaults are tuned for fast processing on OpenAI Tier 2+ accounts.
|
|
5
|
+
For Tier 1 accounts, reduce max_workers to 5-10.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class EnrichmentConfig:
|
|
15
|
+
"""
|
|
16
|
+
Configuration for enrichment pipelines.
|
|
17
|
+
|
|
18
|
+
Defaults are optimized for speed on typical API tier accounts.
|
|
19
|
+
Adjust max_workers based on your provider's rate limits.
|
|
20
|
+
|
|
21
|
+
Rate limit guidance (OpenAI GPT-4.1 nano/mini):
|
|
22
|
+
- Tier 1 ($5 spend): max_workers=5-10 (500 RPM, 200K TPM)
|
|
23
|
+
- Tier 2 ($50 spend): max_workers=20-50 (5K RPM, 2M TPM)
|
|
24
|
+
- Tier 3+ ($100+): max_workers=50-100 (5K+ RPM, 4M+ TPM)
|
|
25
|
+
- Tier 5 ($1K+): max_workers=100-200 (30K RPM, 150M TPM)
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
# === LLM Configuration ===
|
|
29
|
+
max_tokens: int = 4000
|
|
30
|
+
"""Maximum tokens for LLM output."""
|
|
31
|
+
|
|
32
|
+
temperature: float = 0.2
|
|
33
|
+
"""LLM temperature. Low (0.1-0.3) is best for structured enrichment."""
|
|
34
|
+
|
|
35
|
+
# === Concurrency ===
|
|
36
|
+
max_workers: int = 10
|
|
37
|
+
"""Concurrent rows per step (asyncio.Semaphore bound).
|
|
38
|
+
Real-world production uses 20-30. Default 10 is safe for Tier 1-2."""
|
|
39
|
+
|
|
40
|
+
# === Fields ===
|
|
41
|
+
overwrite_fields: bool = False
|
|
42
|
+
"""Whether to overwrite existing field values in the DataFrame."""
|
|
43
|
+
|
|
44
|
+
# === Reliability ===
|
|
45
|
+
max_retries: int = 3
|
|
46
|
+
"""Maximum retry attempts for API errors (429, 500, timeouts)."""
|
|
47
|
+
|
|
48
|
+
retry_base_delay: float = 1.0
|
|
49
|
+
"""Base delay for exponential backoff on API errors (seconds).
|
|
50
|
+
Actual delay: base_delay * 2^attempt + jitter."""
|
|
51
|
+
|
|
52
|
+
on_error: str = "continue"
|
|
53
|
+
"""Error handling mode: 'continue' collects errors and returns partial results,
|
|
54
|
+
'raise' fails fast on the first row error."""
|
|
55
|
+
|
|
56
|
+
# === Logging ===
|
|
57
|
+
log_level: str = "INFO"
|
|
58
|
+
"""Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)."""
|
|
59
|
+
|
|
60
|
+
enable_progress_bar: bool = True
|
|
61
|
+
"""Show tqdm progress bar during pipeline execution."""
|
|
62
|
+
|
|
63
|
+
# === Checkpointing ===
|
|
64
|
+
enable_checkpointing: bool = False
|
|
65
|
+
"""Save results after each step completes for crash recovery."""
|
|
66
|
+
|
|
67
|
+
checkpoint_dir: str | None = None
|
|
68
|
+
"""Directory for checkpoint files. None = temp directory."""
|
|
69
|
+
|
|
70
|
+
auto_resume: bool = True
|
|
71
|
+
"""Automatically resume from checkpoint on re-run."""
|
|
72
|
+
|
|
73
|
+
# === Caching ===
|
|
74
|
+
enable_caching: bool = False
|
|
75
|
+
"""Enable input-hash cache to skip redundant API calls."""
|
|
76
|
+
|
|
77
|
+
cache_ttl: int = 3600
|
|
78
|
+
"""Cache time-to-live in seconds."""
|
|
79
|
+
|
|
80
|
+
cache_dir: str = ".accrue"
|
|
81
|
+
"""Directory for cache.db."""
|
|
82
|
+
|
|
83
|
+
checkpoint_interval: int = 0
|
|
84
|
+
"""Save partial step progress every N rows. 0 = disabled."""
|
|
85
|
+
|
|
86
|
+
# === Batch API ===
|
|
87
|
+
batch_poll_interval: float = 60.0
|
|
88
|
+
"""Seconds between batch job status checks."""
|
|
89
|
+
|
|
90
|
+
batch_timeout: float = 86400.0
|
|
91
|
+
"""Maximum seconds to wait for a batch job to complete (default: 24h)."""
|
|
92
|
+
|
|
93
|
+
batch_max_requests: int = 50000
|
|
94
|
+
"""Maximum requests per batch submission. Larger sets are auto-chunked."""
|
|
95
|
+
|
|
96
|
+
# === Validation ===
|
|
97
|
+
def __post_init__(self):
|
|
98
|
+
if not 0.0 <= self.temperature <= 2.0:
|
|
99
|
+
raise ValueError(f"temperature must be between 0.0 and 2.0, got {self.temperature}")
|
|
100
|
+
if self.max_tokens <= 0:
|
|
101
|
+
raise ValueError(f"max_tokens must be positive, got {self.max_tokens}")
|
|
102
|
+
if self.max_workers <= 0:
|
|
103
|
+
raise ValueError(f"max_workers must be positive, got {self.max_workers}")
|
|
104
|
+
if self.max_retries < 0:
|
|
105
|
+
raise ValueError(f"max_retries must be non-negative, got {self.max_retries}")
|
|
106
|
+
if self.cache_ttl < 0:
|
|
107
|
+
raise ValueError(f"cache_ttl must be non-negative, got {self.cache_ttl}")
|
|
108
|
+
if self.checkpoint_interval < 0:
|
|
109
|
+
raise ValueError(
|
|
110
|
+
f"checkpoint_interval must be non-negative, got {self.checkpoint_interval}"
|
|
111
|
+
)
|
|
112
|
+
if self.batch_poll_interval <= 0:
|
|
113
|
+
raise ValueError(
|
|
114
|
+
f"batch_poll_interval must be positive, got {self.batch_poll_interval}"
|
|
115
|
+
)
|
|
116
|
+
if self.batch_timeout <= 0:
|
|
117
|
+
raise ValueError(f"batch_timeout must be positive, got {self.batch_timeout}")
|
|
118
|
+
if self.batch_max_requests <= 0:
|
|
119
|
+
raise ValueError(f"batch_max_requests must be positive, got {self.batch_max_requests}")
|
|
120
|
+
|
|
121
|
+
# === Presets ===
|
|
122
|
+
@classmethod
|
|
123
|
+
def for_development(cls) -> "EnrichmentConfig":
|
|
124
|
+
"""Low concurrency, verbose logging, caching on. Safe for Tier 1 accounts."""
|
|
125
|
+
return cls(
|
|
126
|
+
max_workers=5,
|
|
127
|
+
temperature=0.2,
|
|
128
|
+
enable_progress_bar=True,
|
|
129
|
+
log_level="DEBUG",
|
|
130
|
+
enable_caching=True,
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
@classmethod
|
|
134
|
+
def for_production(cls) -> "EnrichmentConfig":
|
|
135
|
+
"""High concurrency with caching and checkpointing. For Tier 2+ accounts."""
|
|
136
|
+
return cls(
|
|
137
|
+
max_workers=30,
|
|
138
|
+
temperature=0.2,
|
|
139
|
+
enable_checkpointing=True,
|
|
140
|
+
enable_caching=True,
|
|
141
|
+
checkpoint_interval=100,
|
|
142
|
+
max_retries=5,
|
|
143
|
+
log_level="INFO",
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
@classmethod
|
|
147
|
+
def for_server(cls) -> "EnrichmentConfig":
|
|
148
|
+
"""Async server context (FastAPI). No progress bars, high concurrency."""
|
|
149
|
+
return cls(
|
|
150
|
+
max_workers=30,
|
|
151
|
+
temperature=0.2,
|
|
152
|
+
enable_progress_bar=False,
|
|
153
|
+
max_retries=5,
|
|
154
|
+
log_level="WARNING",
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
@classmethod
|
|
158
|
+
def for_batch(cls) -> "EnrichmentConfig":
|
|
159
|
+
"""Batch API execution with caching. For cost-optimised large datasets."""
|
|
160
|
+
return cls(
|
|
161
|
+
max_workers=10,
|
|
162
|
+
temperature=0.2,
|
|
163
|
+
enable_caching=True,
|
|
164
|
+
enable_checkpointing=True,
|
|
165
|
+
batch_poll_interval=60.0,
|
|
166
|
+
batch_timeout=86400.0,
|
|
167
|
+
max_retries=5,
|
|
168
|
+
log_level="INFO",
|
|
169
|
+
)
|