* feat: entity labels * feat: entity labels — optional, free_values, multi_value, UI polish Completes the entity labels system: **Schema & extraction** - Dynamic Pydantic Labels model per fact: each group becomes a typed field (Literal | None, list[Literal], str | None, or list[str]) - `optional: bool` flag per group — non-optional enum fields appear in JSON schema required array so structured-output providers enforce them - `free_values: bool` flag per group — accepts any LLM-generated string instead of a predefined enum; example values shown as hints in prompt - New `is_label_entity()` helper for labels-only mode filtering that handles both enum lookup and free_values key-prefix matching - Sentinel rejection: "None"/"null"/"n/a" strings dropped in post-processing **BM25 / dense retrieval** - `text_signals` column on memory_units: entity names + date tokens for enriched BM25 indexing without polluting stored fact text - Dense embedding includes occurred_end when it differs from occurred_start - Alembic migration z1u2v3w4x5y6 (merge revision fixing two heads) **UI (bank-config-view)** - Shadcn Switch replaces custom Toggle for both entity-labels and observations - Shadcn Checkbox for multi/optional/free_values per group - Input heights bumped to h-8 throughout the editor - "Label Groups" → "Entity Labels", "Free-form entities" → "Entities" - Free-text groups show "Example hints" banner in values section **Tests (45 unit + 3 LLM integration)** - build_labels_model: single, multi, mixed, free_values optional/required/multi - is_label_entity: enum match, free_values prefix match, no false positives - Post-processing: null/absent/string-None/free_values/sentinels/multi-value - Schema: labels in required, structured object, no labels when unconfigured - LLM integration: single-value enum, multi-value enum, free_values retain **Docs** - retain.md: new Entity Labels section covering groups, flags, examples - configuration.md: retain_free_form_entities env var + entity_labels note * fix(tests): update hierarchical fields count for entity_labels additions entity_labels and retain_free_form_entities are hierarchical fields, bumping the expected count from 11 to 13. * fix(migration): rename text_signals revision to avoid collision with main Main branch claimed z1u2v3w4x5y6 for observation_scopes. Rename our text_signals migration to a2b3c4d5e6f7, chaining after z1u2v3w4x5y6. * refactor(entity-labels): simplify free_values — always str|None, no multi - free_values groups always produce str | None (multi_value and optional flags are ignored for free text groups — always optional, never multi) - Prompt section for free_values groups shows only key + description, no values list (users put examples in the description instead) - UI: section title "Entities", toggle "Free Form Entities", replace per-group checkboxes with a type dropdown (Enum / Free text); only show multi checkbox and values list when type is Enum - Update tests to reflect new behaviour * refactor(entity-labels): replace free_values/multi_value booleans with type field - LabelGroup now uses type: "value" | "multi-values" | "text" instead of free_values/multi_value boolean pair - Backward-compat migration converts legacy dicts automatically - Rename retain_free_form_entities → entities_allow_free_form throughout - Update UI dropdown to show Single value / Multi-values / Free text - Remove separate multi checkbox (captured by type selection) - Update docs examples and configuration.md - Update all tests to use new field names * fix(migration): backfill observation_scopes column for DBs with swapped z1u2v3w4x5y6 Local DBs that had z1u2v3w4x5y6 applied when it referred to the old text_signals migration (before it was renamed to a2b3c4d5e6f7) won't have observation_scopes in their memory_units table. This migration adds the column with IF NOT EXISTS so it's a no-op on clean installs. * feat(entity-labels): add tag field to auto-populate memory unit tags from labels When a LabelGroup has tag=True, extracted key:value entities for that group are automatically written to the memory unit's tags array. This lets entity labels double as tags, enabling immediate filtering via the existing tags/tags_match API params with no extra infrastructure. - Add tag: bool = False to LabelGroup - _inject_label_tags() helper called in both sync and batch extraction paths - UI: add Tag checkbox per label group row - Docs: document the new tag field - Tests: 4 new unit tests covering all tag injection paths * style: ruff format migration file * fix(migration): fix multiple alembic heads after rebase — point text_signals after nullable_event_date * fix(clients): update timestamp field to use Timestamp wrapper type after timestamp=unset feature * style: ruff format agent.py * fix(docs): update Go quickstart example to use NullableTimestamp for timestamp field
111 lines
3.6 KiB
Python
111 lines
3.6 KiB
Python
"""
|
|
Entity processing for retain pipeline.
|
|
|
|
Handles entity extraction, resolution, and link creation for stored facts.
|
|
"""
|
|
|
|
import logging
|
|
|
|
from . import link_utils
|
|
from .types import EntityLink, ProcessedFact
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
async def process_entities_batch(
|
|
entity_resolver,
|
|
conn,
|
|
bank_id: str,
|
|
unit_ids: list[str],
|
|
facts: list[ProcessedFact],
|
|
log_buffer: list[str] = None,
|
|
user_entities_per_content: dict[int, list[dict]] = None,
|
|
entity_labels: list | None = None,
|
|
) -> list[EntityLink]:
|
|
"""
|
|
Process entities for all facts and create entity links.
|
|
|
|
This function:
|
|
1. Extracts entity mentions from fact texts
|
|
2. Merges user-provided entities with LLM-extracted entities
|
|
3. Resolves entity names to canonical entities
|
|
4. Creates entity records in the database
|
|
5. Returns entity links ready for insertion
|
|
|
|
Args:
|
|
entity_resolver: EntityResolver instance for entity resolution
|
|
conn: Database connection
|
|
bank_id: Bank identifier
|
|
unit_ids: List of unit IDs (same length as facts)
|
|
facts: List of ProcessedFact objects
|
|
log_buffer: Optional buffer for detailed logging
|
|
user_entities_per_content: Dict mapping content_index to list of user-provided entities
|
|
|
|
Returns:
|
|
List of EntityLink objects for batch insertion
|
|
"""
|
|
if not unit_ids or not facts:
|
|
return []
|
|
|
|
if len(unit_ids) != len(facts):
|
|
raise ValueError(f"Mismatch between unit_ids ({len(unit_ids)}) and facts ({len(facts)})")
|
|
|
|
user_entities_per_content = user_entities_per_content or {}
|
|
|
|
# Extract data for link_utils function
|
|
fact_texts = [fact.fact_text for fact in facts]
|
|
# Use occurred_start if available, otherwise use mentioned_at for entity timestamps
|
|
fact_dates = [fact.occurred_start if fact.occurred_start is not None else fact.mentioned_at for fact in facts]
|
|
|
|
# Convert EntityRef objects to dict format and merge with user-provided entities
|
|
entities_per_fact = []
|
|
for fact in facts:
|
|
# Start with LLM-extracted entities
|
|
llm_entities = [{"text": entity.name, "type": "CONCEPT"} for entity in (fact.entities or [])]
|
|
|
|
# Get user entities for this content (use content_index from fact)
|
|
user_entities = user_entities_per_content.get(fact.content_index, [])
|
|
|
|
# Merge with case-insensitive deduplication
|
|
seen_texts = {e["text"].lower() for e in llm_entities}
|
|
for user_entity in user_entities:
|
|
if user_entity["text"].lower() not in seen_texts:
|
|
llm_entities.append(
|
|
{
|
|
"text": user_entity["text"],
|
|
"type": user_entity.get("type", "CONCEPT"),
|
|
}
|
|
)
|
|
seen_texts.add(user_entity["text"].lower())
|
|
|
|
entities_per_fact.append(llm_entities)
|
|
|
|
# Use existing link_utils function for entity processing
|
|
entity_links = await link_utils.extract_entities_batch_optimized(
|
|
entity_resolver,
|
|
conn,
|
|
bank_id,
|
|
unit_ids,
|
|
fact_texts,
|
|
"", # context (not used in current implementation)
|
|
fact_dates,
|
|
entities_per_fact,
|
|
log_buffer, # Pass log_buffer for detailed logging
|
|
entity_labels=entity_labels,
|
|
)
|
|
|
|
return entity_links
|
|
|
|
|
|
async def insert_entity_links_batch(conn, entity_links: list[EntityLink]) -> None:
|
|
"""
|
|
Insert entity links in batch.
|
|
|
|
Args:
|
|
conn: Database connection
|
|
entity_links: List of EntityLink objects
|
|
"""
|
|
if not entity_links:
|
|
return
|
|
|
|
await link_utils.insert_entity_links_batch(conn, entity_links)
|