Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e8dd9c0476 | ||
|
|
24ad222266 | ||
|
|
18458c7e87 |
@@ -92,6 +92,7 @@ ENV_RETAIN_MAX_COMPLETION_TOKENS = "HINDSIGHT_API_RETAIN_MAX_COMPLETION_TOKENS"
|
||||
ENV_RETAIN_CHUNK_SIZE = "HINDSIGHT_API_RETAIN_CHUNK_SIZE"
|
||||
ENV_RETAIN_EXTRACT_CAUSAL_LINKS = "HINDSIGHT_API_RETAIN_EXTRACT_CAUSAL_LINKS"
|
||||
ENV_RETAIN_EXTRACTION_MODE = "HINDSIGHT_API_RETAIN_EXTRACTION_MODE"
|
||||
ENV_RETAIN_CUSTOM_INSTRUCTIONS = "HINDSIGHT_API_RETAIN_CUSTOM_INSTRUCTIONS"
|
||||
ENV_RETAIN_OBSERVATIONS_ASYNC = "HINDSIGHT_API_RETAIN_OBSERVATIONS_ASYNC"
|
||||
|
||||
# Observations settings (consolidated knowledge from facts)
|
||||
@@ -168,8 +169,9 @@ DEFAULT_MENTAL_MODEL_REFRESH_CONCURRENCY = 8 # Max concurrent mental model refr
|
||||
DEFAULT_RETAIN_MAX_COMPLETION_TOKENS = 64000 # Max tokens for fact extraction LLM call
|
||||
DEFAULT_RETAIN_CHUNK_SIZE = 3000 # Max chars per chunk for fact extraction
|
||||
DEFAULT_RETAIN_EXTRACT_CAUSAL_LINKS = True # Extract causal links between facts
|
||||
DEFAULT_RETAIN_EXTRACTION_MODE = "concise" # Extraction mode: "concise" or "verbose"
|
||||
RETAIN_EXTRACTION_MODES = ("concise", "verbose") # Allowed extraction modes
|
||||
DEFAULT_RETAIN_EXTRACTION_MODE = "concise" # Extraction mode: "concise", "verbose", or "custom"
|
||||
RETAIN_EXTRACTION_MODES = ("concise", "verbose", "custom") # Allowed extraction modes
|
||||
DEFAULT_RETAIN_CUSTOM_INSTRUCTIONS = None # Custom extraction guidelines (only used when mode="custom")
|
||||
DEFAULT_RETAIN_OBSERVATIONS_ASYNC = False # Run observation generation async (after retain completes)
|
||||
|
||||
# Observations defaults (consolidated knowledge from facts)
|
||||
@@ -328,6 +330,7 @@ class HindsightConfig:
|
||||
retain_chunk_size: int
|
||||
retain_extract_causal_links: bool
|
||||
retain_extraction_mode: str
|
||||
retain_custom_instructions: str | None
|
||||
retain_observations_async: bool
|
||||
|
||||
# Observations settings (consolidated knowledge from facts)
|
||||
@@ -431,6 +434,7 @@ class HindsightConfig:
|
||||
retain_extraction_mode=_validate_extraction_mode(
|
||||
os.getenv(ENV_RETAIN_EXTRACTION_MODE, DEFAULT_RETAIN_EXTRACTION_MODE)
|
||||
),
|
||||
retain_custom_instructions=os.getenv(ENV_RETAIN_CUSTOM_INSTRUCTIONS) or DEFAULT_RETAIN_CUSTOM_INSTRUCTIONS,
|
||||
retain_observations_async=os.getenv(
|
||||
ENV_RETAIN_OBSERVATIONS_ASYNC, str(DEFAULT_RETAIN_OBSERVATIONS_ASYNC)
|
||||
).lower()
|
||||
|
||||
@@ -432,34 +432,15 @@ def _chunk_conversation(turns: list[dict], max_chars: int) -> list[str]:
|
||||
# FACT EXTRACTION PROMPTS
|
||||
# =============================================================================
|
||||
|
||||
# Concise extraction prompt (default) - selective, high-quality facts
|
||||
CONCISE_FACT_EXTRACTION_PROMPT = """Extract SIGNIFICANT facts from text. Be SELECTIVE - only extract facts worth remembering long-term.
|
||||
# Base prompt template (shared by concise and custom modes)
|
||||
# Uses {extraction_guidelines} placeholder for mode-specific instructions
|
||||
_BASE_FACT_EXTRACTION_PROMPT = """Extract SIGNIFICANT facts from text. Be SELECTIVE - only extract facts worth remembering long-term.
|
||||
|
||||
LANGUAGE REQUIREMENT: Detect the language of the input text. All extracted facts, entity names, descriptions, and other output MUST be in the SAME language as the input. Do not translate to another language.
|
||||
|
||||
{fact_types_instruction}
|
||||
|
||||
══════════════════════════════════════════════════════════════════════════
|
||||
SELECTIVITY - CRITICAL (Reduces 90% of unnecessary output)
|
||||
══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
ONLY extract facts that are:
|
||||
✅ Personal info: names, relationships, roles, background
|
||||
✅ Preferences: likes, dislikes, habits, interests (e.g., "Alice likes coffee")
|
||||
✅ Significant events: milestones, decisions, achievements, changes
|
||||
✅ Plans/goals: future intentions, deadlines, commitments
|
||||
✅ Expertise: skills, knowledge, certifications, experience
|
||||
✅ Important context: projects, problems, constraints
|
||||
✅ Sensory/emotional details: feelings, sensations, perceptions that provide context
|
||||
✅ Observations: descriptions of people, places, things with specific details
|
||||
|
||||
DO NOT extract:
|
||||
❌ Generic greetings: "how are you", "hello", pleasantries without substance
|
||||
❌ Pure filler: "thanks", "sounds good", "ok", "got it", "sure"
|
||||
❌ Process chatter: "let me check", "one moment", "I'll look into it"
|
||||
❌ Repeated info: if already stated, don't extract again
|
||||
|
||||
CONSOLIDATE related statements into ONE fact when possible.
|
||||
{extraction_guidelines}
|
||||
|
||||
══════════════════════════════════════════════════════════════════════════
|
||||
FACT FORMAT - BE CONCISE
|
||||
@@ -507,7 +488,33 @@ ENTITIES
|
||||
══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
Include: people names, organizations, places, key objects, abstract concepts (career, friendship, etc.)
|
||||
Always include "user" when fact is about the user.
|
||||
Always include "user" when fact is about the user.{examples}"""
|
||||
|
||||
# Concise mode guidelines
|
||||
_CONCISE_GUIDELINES = """══════════════════════════════════════════════════════════════════════════
|
||||
SELECTIVITY - CRITICAL (Reduces 90% of unnecessary output)
|
||||
══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
ONLY extract facts that are:
|
||||
✅ Personal info: names, relationships, roles, background
|
||||
✅ Preferences: likes, dislikes, habits, interests (e.g., "Alice likes coffee")
|
||||
✅ Significant events: milestones, decisions, achievements, changes
|
||||
✅ Plans/goals: future intentions, deadlines, commitments
|
||||
✅ Expertise: skills, knowledge, certifications, experience
|
||||
✅ Important context: projects, problems, constraints
|
||||
✅ Sensory/emotional details: feelings, sensations, perceptions that provide context
|
||||
✅ Observations: descriptions of people, places, things with specific details
|
||||
|
||||
DO NOT extract:
|
||||
❌ Generic greetings: "how are you", "hello", pleasantries without substance
|
||||
❌ Pure filler: "thanks", "sounds good", "ok", "got it", "sure"
|
||||
❌ Process chatter: "let me check", "one moment", "I'll look into it"
|
||||
❌ Repeated info: if already stated, don't extract again
|
||||
|
||||
CONSOLIDATE related statements into ONE fact when possible."""
|
||||
|
||||
# Concise mode examples
|
||||
_CONCISE_EXAMPLES = """
|
||||
|
||||
══════════════════════════════════════════════════════════════════════════
|
||||
EXAMPLES
|
||||
@@ -533,6 +540,20 @@ QUALITY OVER QUANTITY
|
||||
|
||||
Ask: "Would this be useful to recall in 6 months?" If no, skip it."""
|
||||
|
||||
# Assembled concise prompt (backward compatible - exact same output as before)
|
||||
CONCISE_FACT_EXTRACTION_PROMPT = _BASE_FACT_EXTRACTION_PROMPT.format(
|
||||
fact_types_instruction="{fact_types_instruction}",
|
||||
extraction_guidelines=_CONCISE_GUIDELINES,
|
||||
examples=_CONCISE_EXAMPLES,
|
||||
)
|
||||
|
||||
# Custom prompt uses same base but without examples
|
||||
CUSTOM_FACT_EXTRACTION_PROMPT = _BASE_FACT_EXTRACTION_PROMPT.format(
|
||||
fact_types_instruction="{fact_types_instruction}",
|
||||
extraction_guidelines="{custom_instructions}",
|
||||
examples="", # No examples for custom mode
|
||||
)
|
||||
|
||||
|
||||
# Verbose extraction prompt - detailed, comprehensive facts (legacy mode)
|
||||
VERBOSE_FACT_EXTRACTION_PROMPT = """Extract facts from text into structured format with FIVE required dimensions - BE EXTREMELY DETAILED.
|
||||
@@ -680,6 +701,12 @@ async def _extract_facts_from_chunk(
|
||||
Note: event_date parameter is kept for backward compatibility but not used in prompt.
|
||||
The LLM extracts temporal information from the context string instead.
|
||||
"""
|
||||
import logging
|
||||
|
||||
from openai import BadRequestError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
memory_bank_context = f"\n- Your name: {agent_name}" if agent_name and extract_opinions else ""
|
||||
|
||||
# Determine which fact types to extract based on the flag
|
||||
@@ -698,13 +725,27 @@ async def _extract_facts_from_chunk(
|
||||
extract_causal_links = config.retain_extract_causal_links
|
||||
|
||||
# Select base prompt based on extraction mode
|
||||
if extraction_mode == "verbose":
|
||||
if extraction_mode == "custom":
|
||||
# Custom mode: inject user-provided guidelines
|
||||
if not config.retain_custom_instructions:
|
||||
logger.warning(
|
||||
"extraction_mode='custom' but HINDSIGHT_API_RETAIN_CUSTOM_INSTRUCTIONS not set. "
|
||||
"Falling back to 'concise' mode."
|
||||
)
|
||||
base_prompt = CONCISE_FACT_EXTRACTION_PROMPT
|
||||
prompt = base_prompt.format(fact_types_instruction=fact_types_instruction)
|
||||
else:
|
||||
base_prompt = CUSTOM_FACT_EXTRACTION_PROMPT
|
||||
prompt = base_prompt.format(
|
||||
fact_types_instruction=fact_types_instruction,
|
||||
custom_instructions=config.retain_custom_instructions,
|
||||
)
|
||||
elif extraction_mode == "verbose":
|
||||
base_prompt = VERBOSE_FACT_EXTRACTION_PROMPT
|
||||
prompt = base_prompt.format(fact_types_instruction=fact_types_instruction)
|
||||
else:
|
||||
base_prompt = CONCISE_FACT_EXTRACTION_PROMPT
|
||||
|
||||
# Format the prompt with fact types instruction
|
||||
prompt = base_prompt.format(fact_types_instruction=fact_types_instruction)
|
||||
prompt = base_prompt.format(fact_types_instruction=fact_types_instruction)
|
||||
|
||||
# Build the full prompt with or without causal relationships section
|
||||
# Select appropriate response schema based on extraction mode and causal links
|
||||
@@ -717,12 +758,6 @@ async def _extract_facts_from_chunk(
|
||||
else:
|
||||
response_schema = FactExtractionResponseNoCausal
|
||||
|
||||
import logging
|
||||
|
||||
from openai import BadRequestError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Retry logic for JSON validation errors
|
||||
max_retries = 2
|
||||
last_error = None
|
||||
|
||||
@@ -213,6 +213,7 @@ def main():
|
||||
retain_chunk_size=config.retain_chunk_size,
|
||||
retain_extract_causal_links=config.retain_extract_causal_links,
|
||||
retain_extraction_mode=config.retain_extraction_mode,
|
||||
retain_custom_instructions=config.retain_custom_instructions,
|
||||
retain_observations_async=config.retain_observations_async,
|
||||
enable_observations=config.enable_observations,
|
||||
consolidation_batch_size=config.consolidation_batch_size,
|
||||
|
||||
@@ -2082,3 +2082,117 @@ def test_recall_result_model_empty_construction():
|
||||
assert result.chunks == {}, "Should have empty chunks"
|
||||
|
||||
logger.info("✓ RecallResult empty construction works correctly")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_custom_extraction_mode():
|
||||
"""
|
||||
Test that custom extraction mode uses custom guidelines from env variable.
|
||||
|
||||
This test verifies that when HINDSIGHT_API_RETAIN_EXTRACTION_MODE=custom and
|
||||
HINDSIGHT_API_RETAIN_CUSTOM_INSTRUCTIONS is set, the fact extraction uses the
|
||||
custom guidelines while keeping structural parts intact.
|
||||
"""
|
||||
import os
|
||||
from hindsight_api import LLMConfig
|
||||
from hindsight_api.engine.retain.fact_extraction import extract_facts_from_text
|
||||
from hindsight_api.config import clear_config_cache
|
||||
|
||||
# Save original env vars
|
||||
original_mode = os.getenv("HINDSIGHT_API_RETAIN_EXTRACTION_MODE")
|
||||
original_instructions = os.getenv("HINDSIGHT_API_RETAIN_CUSTOM_INSTRUCTIONS")
|
||||
|
||||
try:
|
||||
# Set custom extraction mode with challenging language-specific guidelines
|
||||
os.environ["HINDSIGHT_API_RETAIN_EXTRACTION_MODE"] = "custom"
|
||||
os.environ["HINDSIGHT_API_RETAIN_CUSTOM_INSTRUCTIONS"] = """ONLY extract facts that are in ITALIAN language.
|
||||
|
||||
DO NOT extract:
|
||||
❌ Facts in English
|
||||
❌ Facts in any other language besides Italian
|
||||
|
||||
If the text contains both Italian and English content, extract ONLY the Italian facts."""
|
||||
|
||||
# Clear config cache to pick up new env vars
|
||||
clear_config_cache()
|
||||
|
||||
# Test content with BOTH Italian (should extract) and English (should NOT extract) facts
|
||||
# This is a much harder test than filtering greetings
|
||||
text = """
|
||||
The team discussed the new architecture. We will use microservices.
|
||||
|
||||
Il database PostgreSQL ha ridotto la latenza delle query del 60%.
|
||||
Alice ha suggerito di usare il connection pooling per migliorare le prestazioni.
|
||||
|
||||
Bob mentioned that the API endpoint is ready for testing.
|
||||
The deployment pipeline has been updated to use Kubernetes.
|
||||
|
||||
Marco ha completato la revisione del codice e ha approvato le modifiche.
|
||||
Il sistema di autenticazione è stato migrato a OAuth 2.0.
|
||||
"""
|
||||
|
||||
llm_config = LLMConfig.for_memory()
|
||||
|
||||
facts, _, _ = await extract_facts_from_text(
|
||||
text=text,
|
||||
event_date=datetime(2024, 1, 15, tzinfo=timezone.utc),
|
||||
context="team meeting notes",
|
||||
llm_config=llm_config,
|
||||
agent_name="TestUser"
|
||||
)
|
||||
|
||||
logger.info(f"\nExtracted {len(facts)} facts with custom mode (Italian only):")
|
||||
for i, fact in enumerate(facts):
|
||||
logger.info(f" {i+1}. {fact.fact}")
|
||||
|
||||
assert len(facts) > 0, "Should extract at least one Italian fact"
|
||||
|
||||
# All facts text
|
||||
all_facts_text = " ".join([f.fact for f in facts])
|
||||
|
||||
# Should HAVE Italian content
|
||||
italian_keywords = ["postgresql", "latenza", "query", "alice", "connection pooling", "prestazioni",
|
||||
"marco", "revisione", "codice", "autenticazione", "oauth"]
|
||||
has_italian = any(keyword in all_facts_text.lower() for keyword in italian_keywords)
|
||||
assert has_italian, f"Should extract Italian facts. Got: {all_facts_text}"
|
||||
|
||||
# Should NOT have English-only content
|
||||
# These are facts that appear ONLY in English sections
|
||||
english_only_keywords = ["microservices", "bob", "api endpoint", "testing", "deployment pipeline", "kubernetes"]
|
||||
|
||||
# Check if facts contain English-only content (this would be wrong)
|
||||
facts_lower = all_facts_text.lower()
|
||||
found_english_only = [kw for kw in english_only_keywords if kw in facts_lower]
|
||||
|
||||
if found_english_only:
|
||||
logger.warning(f"⚠ Found English-only keywords in facts: {found_english_only}")
|
||||
logger.warning(f" Facts: {all_facts_text}")
|
||||
logger.warning(f" This may indicate the LLM is not strictly following language-specific custom guidelines")
|
||||
# Log but don't fail - LLM behavior can vary
|
||||
else:
|
||||
logger.info("✓ Successfully extracted only Italian facts, ignored English facts")
|
||||
|
||||
# At least verify we have some Italian indicators
|
||||
italian_indicators = ["latenza", "prestazioni", "revisione", "codice", "autenticazione"]
|
||||
italian_count = sum(1 for ind in italian_indicators if ind in facts_lower)
|
||||
|
||||
assert italian_count >= 1, \
|
||||
f"Should extract facts with Italian words. Found {italian_count} Italian indicators in: {all_facts_text}"
|
||||
|
||||
logger.info("✓ Custom extraction mode works with language-specific guidelines")
|
||||
logger.info(f"✓ Extracted {len(facts)} Italian facts, found {italian_count} Italian indicators")
|
||||
|
||||
finally:
|
||||
# Restore original env vars
|
||||
if original_mode is not None:
|
||||
os.environ["HINDSIGHT_API_RETAIN_EXTRACTION_MODE"] = original_mode
|
||||
else:
|
||||
os.environ.pop("HINDSIGHT_API_RETAIN_EXTRACTION_MODE", None)
|
||||
|
||||
if original_instructions is not None:
|
||||
os.environ["HINDSIGHT_API_RETAIN_CUSTOM_INSTRUCTIONS"] = original_instructions
|
||||
else:
|
||||
os.environ.pop("HINDSIGHT_API_RETAIN_CUSTOM_INSTRUCTIONS", None)
|
||||
|
||||
# Clear cache again to restore original config
|
||||
clear_config_cache()
|
||||
|
||||
@@ -319,7 +319,8 @@ Controls the retain (memory ingestion) pipeline.
|
||||
|----------|-------------|---------|
|
||||
| `HINDSIGHT_API_RETAIN_MAX_COMPLETION_TOKENS` | Max completion tokens for fact extraction LLM calls | `64000` |
|
||||
| `HINDSIGHT_API_RETAIN_CHUNK_SIZE` | Max characters per chunk for fact extraction. Larger chunks extract fewer LLM calls but may lose context. | `3000` |
|
||||
| `HINDSIGHT_API_RETAIN_EXTRACTION_MODE` | Fact extraction mode: `concise` (selective, fewer high-quality facts) or `verbose` (detailed, more facts) | `concise` |
|
||||
| `HINDSIGHT_API_RETAIN_EXTRACTION_MODE` | Fact extraction mode: `concise`, `verbose`, or `custom` | `concise` |
|
||||
| `HINDSIGHT_API_RETAIN_CUSTOM_INSTRUCTIONS` | Custom extraction guidelines (only used when mode is `custom`) | - |
|
||||
| `HINDSIGHT_API_RETAIN_EXTRACT_CAUSAL_LINKS` | Extract causal relationships between facts | `true` |
|
||||
|
||||
#### Extraction Modes
|
||||
@@ -330,6 +331,31 @@ The extraction mode controls how aggressively facts are extracted from content:
|
||||
|
||||
- **`verbose`**: Detailed extraction that captures every piece of information with maximum verbosity. Produces more facts with extensive detail but slower performance and higher token usage.
|
||||
|
||||
- **`custom`**: Inject your own extraction guidelines while keeping the structural parts of the prompt (output format, coreference resolution, temporal handling, etc.) intact. Useful for A/B testing different extraction strategies or domain-specific customization.
|
||||
|
||||
**Example: Custom Extraction Mode**
|
||||
|
||||
```bash
|
||||
# Set mode to custom
|
||||
export HINDSIGHT_API_RETAIN_EXTRACTION_MODE=custom
|
||||
|
||||
# Define custom guidelines (multi-line is fine)
|
||||
export HINDSIGHT_API_RETAIN_CUSTOM_INSTRUCTIONS="ONLY extract facts that are:
|
||||
✅ Technical decisions and their rationale
|
||||
✅ Architecture patterns and design choices
|
||||
✅ Performance metrics and benchmarks
|
||||
✅ Code reviews and feedback
|
||||
|
||||
DO NOT extract:
|
||||
❌ Generic greetings or pleasantries
|
||||
❌ Process chatter (\"let me check\", \"one moment\")
|
||||
❌ Repeated information already captured
|
||||
|
||||
CONSOLIDATE related technical discussions into ONE fact when possible.
|
||||
|
||||
Ask yourself: 'Would this technical context be useful in 6 months?' If no, skip it."
|
||||
```
|
||||
|
||||
### Observations (Experimental)
|
||||
|
||||
Observations are consolidated knowledge synthesized from facts. This feature is experimental and disabled by default.
|
||||
|
||||
Reference in New Issue
Block a user