Skip to content

tdfs4ds.impact_agent.agent

tdfs4ds.impact_agent.agent

The impact-study agent: code first, a model only for the advanced reading.

:func:run_study ALWAYS runs the deterministic order

resolve_scope -> study_change -> feature_chain (per affected feature) -> assistant_footprint

which is the whole study without any model. Only with agent=True and a model available, a bounded planner may add tool calls and questions to the consumer agent (IMPACT_AGENT_MAX_STEPS, IMPACT_AGENT_MAX_CONSUMER_CALLS), and one grounded call writes a narrative. Neither changes a verdict: the narrative is checked name by name against the model and a bullet naming anything the model does not hold is dropped.

The planner is a plain function planner(state, tool_catalog, llm, question) -> [{"tool", "args"}], so a LangGraph graph can replace it later without touching the tools. Typed output goes through tdfs4ds.agent.structured_output.with_structured_output; tracing through tdfs4ds.utils.tracing.run_callbacks. Nothing is ever written or run in the database.

_RANK module-attribute

_RANK = {'unaffected': 0, 'may_change': 1, 'values_change': 2, 'breaks': 3}

_BACKTICK module-attribute

_BACKTICK = re.compile('`([^`]+)`')

_IDENT module-attribute

_IDENT = re.compile('(?<![A-Za-z0-9_$#.])([A-Za-z_][\\w$#]*(?:\\.[A-Za-z_][\\w$#]*)?)(?![\\w$#])')

_CLAIMS module-attribute

_CLAIMS = (('empty', re.compile('\\bempty\\b|\\bno rows\\b|\\ball (?:its |the )?rows\\b|\\bloses? (?:its |all )?rows\\b', re.I), lambda e: any(w in e['text'] for w in ('empty', 'loses its rows', 'no rows'))), ('breaks', re.compile('\\bwill fail\\b|\\bfails?\\b|\\bbreaks?\\b|\\bbroken\\b', re.I), lambda e: 'breaks' in e['sev'] or 'fail' in e['text'] or 'no longer' in e['text']), ('identical', re.compile('\\bidentical\\b', re.I), lambda e: e['identical'] or 'unaffected' in e['sev'] or 'identical' in e['text'] or 'unchanged' in e['text']), ('differs', re.compile('\\bdiffers?\\b|\\bdifferent values\\b', re.I), lambda e: bool({'values_change', 'breaks'} & e['sev']) or e['differs'] or 'differ' in e['text'] or 'change' in e['text']))

_NEGATION module-attribute

_NEGATION = re.compile("(?:\\bnot|\\bnever|\\bno longer|n't|\\bwithout|\\bnothing)\\W+(?:\\w+\\W+){0,2}$", re.I)

_CONSUMER_OPINION module-attribute

_CONSUMER_OPINION = re.compile("consumer(?:'s| agent| assistant)|according to the consumer|consumer opinion|the consumer (?:says|said|thinks|reports|believes)", re.I)

_MEANING module-attribute

_MEANING = re.compile('\\bindicat\\w*|\\bmeans?\\b|\\bmeaning\\b|\\brepresent\\w*|\\bsignif\\w*|\\bhigher values?\\b|\\blower values?\\b|\\bhigher\\b.{0,30}\\b(?:risk|score)|\\bstands? for\\b', re.I)

_CLAUSE_SPLIT module-attribute

_CLAUSE_SPLIT = re.compile('[.;!?]+\\s+|\\s+(?:but|while|whereas|however)\\s+', re.I)

_PER_OBJECT module-attribute

_PER_OBJECT = ('identical', 'differs')

Ledger

An ordered list of entries. record adds one; entries is the JSON-able list.

entries instance-attribute

entries: List[Dict[str, Any]] = []

__init__

__init__()

record

record(tool: str, args: Optional[dict], result: Any, duration: float, source: str = 'code', error: Optional[str] = None, model: Optional[str] = None, skipped: bool = False) -> dict

count

count(*, tool: Optional[str] = None, source: Optional[str] = None) -> int

as_list

as_list() -> List[dict]

timed

with timed() as t: ... then t.seconds.

__enter__

__enter__()

__exit__

__exit__(*exc)

StudyState dataclass

What one study holds while it runs (the ImpactState of the design).

objects instance-attribute

objects: List[str]

new_sql class-attribute instance-attribute

new_sql: Optional[str] = None

dataset_change class-attribute instance-attribute

dataset_change: Optional[dict] = None

as_of class-attribute instance-attribute

as_of: Optional[str] = None

inputs class-attribute instance-attribute

inputs: Optional[dict] = None

targets class-attribute instance-attribute

targets: List[dict] = field(default_factory=list)

model class-attribute instance-attribute

model: Optional[dict] = None

footprint class-attribute instance-attribute

footprint: Optional[dict] = None

footprint_options class-attribute instance-attribute

footprint_options: Optional[dict] = None

ledger class-attribute instance-attribute

ledger: Ledger = field(default_factory=Ledger)

domains class-attribute instance-attribute

domains: Optional[List[str]] = None

thread_id class-attribute instance-attribute

thread_id: Optional[str] = None

consumer class-attribute instance-attribute

consumer: Optional[Callable] = None

consumer_budget class-attribute instance-attribute

consumer_budget: Any = None

consumer_timeout class-attribute instance-attribute

consumer_timeout: Optional[float] = None

consumer_answers class-attribute instance-attribute

consumer_answers: List[dict] = field(default_factory=list)

llm class-attribute instance-attribute

llm: Any = None

llm_name class-attribute instance-attribute

llm_name: Optional[str] = None

reviews class-attribute instance-attribute

reviews: List[dict] = field(default_factory=list)

review_skipped class-attribute instance-attribute

review_skipped: List[dict] = field(default_factory=list)

review_pool class-attribute instance-attribute

review_pool: List[dict] = field(default_factory=list)

__init__

__init__(objects: List[str], new_sql: Optional[str] = None, dataset_change: Optional[dict] = None, as_of: Optional[str] = None, inputs: Optional[dict] = None, targets: List[dict] = list(), model: Optional[dict] = None, footprint: Optional[dict] = None, footprint_options: Optional[dict] = None, ledger: Ledger = Ledger(), domains: Optional[List[str]] = None, thread_id: Optional[str] = None, consumer: Optional[Callable] = None, consumer_budget: Any = None, consumer_timeout: Optional[float] = None, consumer_answers: List[dict] = list(), llm: Any = None, llm_name: Optional[str] = None, reviews: List[dict] = list(), review_skipped: List[dict] = list(), review_pool: List[dict] = list()) -> None

_setting

_setting(name: str, default: int) -> int

_schemas

_schemas()

_typed_call

_typed_call(llm, schema, system: str, human: str, thread_id: Optional[str])

_summary

_summary(model: dict, footprint: Optional[dict] = None, consumer_answers: Optional[list] = None, reviews: Optional[list] = None) -> dict

The compact JSON the model calls see (the study's own facts, nothing else).

default_planner

default_planner(state: StudyState, catalog: List[dict], llm, question: Optional[str]) -> List[dict]

One typed call: which extra tools (and consumer questions) would sharpen the study.

known_names

known_names(model: dict, footprint: Optional[dict] = None) -> set

Every name the study holds (upper case, full and short forms).

verify_narrative

verify_narrative(bullets: List[str], known: set) -> Dict[str, Any]

Keep the bullets whose names are all in known; {"kept", "dropped": [{bullet, names}]}. Pure.

A name is a backticked text, or an identifier with an underscore or a dot (an object or column spelling); ordinary words are not checked.

_quoted_in_answers

_quoted_in_answers(text: str, answers: list) -> bool

True when the bullet is, or quotes (between quotation marks, 15+ characters), text of a consumer answer, compared on normalised text. Pure.

_short

_short(name) -> str

claim_basis

claim_basis(model: dict) -> Dict[str, dict]

What the study says about each named object: {name: {sev, text, identical, differs}}. Pure.

sev holds the severities, text the consequence / reason / explanation sentences (lower case), identical / differs what the measured comparison found for a column.

_word_in

_word_in(name: str, low: str) -> bool

_clauses

_clauses(text: str) -> List[tuple]

[(start, end)] spans of the clauses of text (split on sentence ends, ';', 'but', 'while').

_claim_check

_claim_check(text: str, basis: Dict[str, dict]) -> Optional[str]

None when every strong claim of text about a named object is backed by the study, else the reason.

'identical' and 'differs' claims are checked for EVERY object the clause names: 'differs' is rejected when any of them was measured identical (and not differing), 'identical' when any of them differs. The other claims need one named object that backs them.

check_claims

check_claims(bullets: List[str], model: dict, consumer_answers: Optional[list] = None) -> Dict[str, Any]

The second check of the narrative, after the names: strong claims and consumer attribution.

A bullet is dropped ({"bullet", "names": [], "reason"}) when it makes a strong claim ('empty', 'no rows', 'all rows', 'will fail', 'breaks', 'identical', 'differs') that the severity, the consequence or the measure of the object it names does not back, or when it attributes an opinion to the consumer agent while no consumer answer exists. A kept bullet quoting the consumer agent gets the code severity of the objects it names appended. Pure.

_model_name

_model_name(llm) -> Optional[str]

The name of the model the impact agent uses (for the ledger).

_skip_reason

_skip_reason(state: StudyState, name: str, args: dict, T) -> Optional[str]

Why a planner step is not run (None = run it): unknown tool, no question, arguments that do not fit the tool's schema, or already done by the deterministic order.

write_narrative

write_narrative(state: StudyState, llm, question: Optional[str] = None) -> Dict[str, Any]

One grounded call; returns {"text", "dropped"} (text None when nothing survived).

_consumer_for_undocumented

_consumer_for_undocumented(state: StudyState) -> None

Ask the consumer agent about an undecided feature whose documentation is missing (budgeted by IMPACT_AGENT_MAX_CONSUMER_CALLS; its answer is evidence beside the review, never a fact).

_measure_study

_measure_study(state: StudyState, *, force: bool = False, options: Optional[dict] = None, say=None) -> None

Measure the proposed SQL on volatile tables and apply the result to state.model. Not a tool: the planner can never call it (the registry holds read-only tools only). Recorded in the ledger with source code; a refusal or a failure is recorded too, never raised.

run_study

run_study(objects, *, new_sql: Optional[str] = None, dataset_change: Optional[dict] = None, as_of=None, agent: bool = False, question: Optional[str] = None, progress: Optional[Callable[[str], None]] = None, inputs: Optional[dict] = None, llm=None, planner: Optional[Callable] = None, consumer: Optional[Callable] = None, footprint_options: Optional[dict] = None, domains: Optional[List[str]] = None, max_depth: int = 6, consumer_timeout: Optional[float] = None, measure: bool = False, measure_force: bool = False, measure_options: Optional[dict] = None) -> dict

Study the impact of a change at feature level; read only.

Returns the :func:tdfs4ds.impact.impact_of model (schema_version 2, with features, feature_edges, severity_counts) plus agent::

{"used": bool, "ledger": [...], "footprint": {...}, "narrative": str | None,
 "consumer_answers": [{"question", "answer"}], "skipped_reason": str | None,
 "narrative_dropped": [...], "steps": int}

inputs replaces the database reads (tests or a second run on the same reads); llm, planner and consumer replace the model, the planner and the consumer agent; footprint_options go to :func:tdfs4ds.impact_agent.footprint.assistant_footprint (readers, skills_folder, scenario_files, database). Raises ValueError like impact_of for an object that resolves to nothing or bad arguments.

measure (off by default, never chosen by the planner): with new_sql, compute the current and the proposed SELECT in full into two volatile tables of one session and compare them (:func:tdfs4ds.impact_measure.measure, gated by the EXPLAIN estimate and the process's execution log: measure_force runs it above the limits); the result is the model's measure key and is applied to the features (:func:tdfs4ds.impact_features.apply_measurement). measure_options go to measure (conn, cancel_event, entity_columns, reference).