Skip to content

tenets.core.instiller Package

Instiller module for managing and injecting tenets.

The instiller system handles the lifecycle of tenets (guiding principles) and their strategic injection into generated context to maintain consistency across AI interactions.

Classes

InjectionPosition

Bases: Enum

Where to inject tenets in the context.

Attributes

TOPclass-attributeinstance-attribute
Python
TOP = 'top'
BOTTOMclass-attributeinstance-attribute
Python
BOTTOM = 'bottom'
STRATEGICclass-attributeinstance-attribute
Python
STRATEGIC = 'strategic'
DISTRIBUTEDclass-attributeinstance-attribute
Python
DISTRIBUTED = 'distributed'

TenetInjector

Python
TenetInjector(config: Optional[Dict[str, Any]] = None)

Handles strategic injection of tenets into context.

Initialize the injector.

PARAMETERDESCRIPTION
config

Injection configuration

TYPE:Optional[Dict[str, Any]]DEFAULT:None

Attributes

configinstance-attribute
Python
config = config or {}
loggerinstance-attribute
Python
logger = get_logger(__name__)
min_distance_betweeninstance-attribute
Python
min_distance_between = get('min_distance_between', 1000)
prefer_natural_breaksinstance-attribute
Python
prefer_natural_breaks = get('prefer_natural_breaks', True)
reinforce_at_endinstance-attribute
Python
reinforce_at_end = get('reinforce_at_end', True)

Functions

inject_tenets
Python
inject_tenets(content: str, tenets: List[Tenet], format: str = 'markdown', context_metadata: Optional[Dict[str, Any]] = None) -> Tuple[str, Dict[str, Any]]

Inject tenets into content.

PARAMETERDESCRIPTION
content

The content to inject into

TYPE:str

tenets

List of tenets to inject

TYPE:List[Tenet]

format

Content format (markdown, xml, json)

TYPE:strDEFAULT:'markdown'

context_metadata

Metadata about the context

TYPE:Optional[Dict[str, Any]]DEFAULT:None

RETURNSDESCRIPTION
Tuple[str, Dict[str, Any]]

Tuple of (modified content, injection metadata)

calculate_optimal_injection_count
Python
calculate_optimal_injection_count(content_length: int, available_tenets: int, max_token_increase: int = 1000) -> int

Calculate optimal number of tenets to inject.

PARAMETERDESCRIPTION
content_length

Current content length

TYPE:int

available_tenets

Number of available tenets

TYPE:int

max_token_increase

Maximum allowed token increase

TYPE:intDEFAULT:1000

RETURNSDESCRIPTION
int

Optimal number of tenets to inject

inject_into_context_result
Python
inject_into_context_result(context_result: ContextResult, tenets: List[Tenet]) -> ContextResult

Inject tenets into a ContextResult object.

PARAMETERDESCRIPTION
context_result

The context result to modify

TYPE:ContextResult

tenets

Tenets to inject

TYPE:List[Tenet]

RETURNSDESCRIPTION
ContextResult

Modified context result

InstillationResultdataclass

Python
InstillationResult(tenets_instilled: List[Tenet], injection_positions: List[Dict[str, Any]], token_increase: int, strategy_used: str, session: Optional[str] = None, timestamp: datetime = datetime.now(), success: bool = True, error_message: Optional[str] = None, metrics: Optional[Dict[str, Any]] = None, complexity_score: float = 0.0, skip_reason: Optional[str] = None)

Result of a tenet instillation operation.

ATTRIBUTEDESCRIPTION
tenets_instilled

List of tenets that were instilled

TYPE:List[Tenet]

injection_positions

Where tenets were injected

TYPE:List[Dict[str, Any]]

token_increase

Number of tokens added

TYPE:int

strategy_used

Injection strategy that was used

TYPE:str

session

Session identifier if any

TYPE:Optional[str]

timestamp

When instillation occurred

TYPE:datetime

success

Whether instillation succeeded

TYPE:bool

error_message

Error message if failed

TYPE:Optional[str]

metrics

Additional metrics from the operation

TYPE:Optional[Dict[str, Any]]

complexity_score

Complexity score of the context

TYPE:float

skip_reason

Reason if injection was skipped

TYPE:Optional[str]

Attributes

tenets_instilledinstance-attribute
Python
tenets_instilled: List[Tenet]
injection_positionsinstance-attribute
Python
injection_positions: List[Dict[str, Any]]
token_increaseinstance-attribute
Python
token_increase: int
strategy_usedinstance-attribute
Python
strategy_used: str
sessionclass-attributeinstance-attribute
Python
session: Optional[str] = None
timestampclass-attributeinstance-attribute
Python
timestamp: datetime = field(default_factory=now)
successclass-attributeinstance-attribute
Python
success: bool = True
error_messageclass-attributeinstance-attribute
Python
error_message: Optional[str] = None
metricsclass-attributeinstance-attribute
Python
metrics: Optional[Dict[str, Any]] = None
complexity_scoreclass-attributeinstance-attribute
Python
complexity_score: float = 0.0
skip_reasonclass-attributeinstance-attribute
Python
skip_reason: Optional[str] = None

Functions

to_dict
Python
to_dict() -> Dict[str, Any]

Convert to dictionary for serialization.

Instiller

Python
Instiller(config: TenetsConfig)

Main orchestrator for tenet instillation with smart injection.

The Instiller manages the entire process of injecting tenets into context, including: - Tracking injection history per session - Analyzing context complexity - Determining optimal injection frequency - Selecting appropriate tenets - Applying injection strategies - Recording metrics and effectiveness

It supports multiple injection modes: - Always: Inject into every context - Periodic: Inject every Nth distillation - Adaptive: Smart injection based on complexity and session - Manual: Only inject when explicitly requested

Initialize the Instiller.

PARAMETERDESCRIPTION
config

Configuration object

TYPE:TenetsConfig

Attributes

configinstance-attribute
Python
config = config
loggerinstance-attribute
Python
logger = get_logger(__name__)
managerinstance-attribute
Python
manager = TenetManager(config)
injectorinstance-attribute
Python
injector = TenetInjector(injection_config)
complexity_analyzerinstance-attribute
Python
complexity_analyzer = ComplexityAnalyzer(config)
metrics_trackerinstance-attribute
Python
metrics_tracker = MetricsTracker()
session_historiesinstance-attribute
Python
session_histories: Dict[str, InjectionHistory] = {}
system_instruction_injectedinstance-attribute
Python
system_instruction_injected: Dict[str, bool] = {}

Functions

inject_system_instruction
Python
inject_system_instruction(content: str, format: str = 'markdown', session: Optional[str] = None) -> Tuple[str, Dict[str, Any]]

Inject system instruction (system prompt) according to config.

Behavior: - If system instruction is disabled or empty, return unchanged. - If session provided and once-per-session is enabled, inject only on first distill. - If no session, inject on every distill. - Placement controlled by system_instruction_position. - Formatting controlled by system_instruction_format.

Returns modified content and metadata about injection.

instill
Python
instill(context: Union[str, ContextResult], session: Optional[str] = None, force: bool = False, strategy: Optional[str] = None, max_tenets: Optional[int] = None, check_frequency: bool = True, inject_system_instruction: Optional[bool] = None) -> Union[str, ContextResult]

Instill tenets into context with smart injection.

PARAMETERDESCRIPTION
context

Context to inject tenets into

TYPE:Union[str, ContextResult]

session

Session identifier for tracking

TYPE:Optional[str]DEFAULT:None

force

Force injection regardless of frequency settings

TYPE:boolDEFAULT:False

strategy

Override injection strategy

TYPE:Optional[str]DEFAULT:None

max_tenets

Override maximum tenets

TYPE:Optional[int]DEFAULT:None

check_frequency

Whether to check injection frequency

TYPE:boolDEFAULT:True

RETURNSDESCRIPTION
Union[str, ContextResult]

Modified context with tenets injected (if applicable)

get_session_stats
Python
get_session_stats(session: str) -> Dict[str, Any]

Get statistics for a specific session.

PARAMETERDESCRIPTION
session

Session identifier

TYPE:str

RETURNSDESCRIPTION
Dict[str, Any]

Dictionary of session statistics

get_all_session_stats
Python
get_all_session_stats() -> Dict[str, Dict[str, Any]]

Get statistics for all sessions.

RETURNSDESCRIPTION
Dict[str, Dict[str, Any]]

Dictionary mapping session IDs to stats

analyze_effectiveness
Python
analyze_effectiveness(session: Optional[str] = None) -> Dict[str, Any]

Analyze the effectiveness of tenet instillation.

PARAMETERDESCRIPTION
session

Optional session to analyze

TYPE:Optional[str]DEFAULT:None

RETURNSDESCRIPTION
Dict[str, Any]

Dictionary with analysis results and recommendations

export_instillation_history
Python
export_instillation_history(output_path: Path, format: str = 'json', session: Optional[str] = None) -> None

Export instillation history to file.

PARAMETERDESCRIPTION
output_path

Path to output file

TYPE:Path

format

Export format (json or csv)

TYPE:strDEFAULT:'json'

session

Optional session filter

TYPE:Optional[str]DEFAULT:None

RAISESDESCRIPTION
ValueError

If format is not supported

reset_session_history
Python
reset_session_history(session: str) -> bool

Reset injection history for a session.

PARAMETERDESCRIPTION
session

Session identifier

TYPE:str

RETURNSDESCRIPTION
bool

True if reset, False if session not found

clear_cache
Python
clear_cache() -> None

Clear the results cache.

TenetManager

Python
TenetManager(config: TenetsConfig)

Manages tenets throughout their lifecycle.

Initialize the tenet manager.

PARAMETERDESCRIPTION
config

Tenets configuration

TYPE:TenetsConfig

Attributes

configinstance-attribute
Python
config = config
loggerinstance-attribute
Python
logger = get_logger(__name__)
storage_pathinstance-attribute
Python
storage_path = Path(cache_dir) / 'tenets'
db_pathinstance-attribute
Python
db_path = storage_path / 'tenets.db'

Functions

add_tenet
Python
add_tenet(content: Union[str, Tenet], priority: Union[str, Priority] = 'medium', category: Optional[Union[str, TenetCategory]] = None, session: Optional[str] = None, author: Optional[str] = None) -> Tenet

Add a new tenet.

PARAMETERDESCRIPTION
content

The guiding principle text or a Tenet object

TYPE:Union[str, Tenet]

priority

Priority level (low, medium, high, critical)

TYPE:Union[str, Priority]DEFAULT:'medium'

category

Category for organization

TYPE:Optional[Union[str, TenetCategory]]DEFAULT:None

session

Bind to specific session

TYPE:Optional[str]DEFAULT:None

author

Who created the tenet

TYPE:Optional[str]DEFAULT:None

RETURNSDESCRIPTION
Tenet

The created Tenet

get_tenet
Python
get_tenet(tenet_id: str) -> Optional[Tenet]

Get a specific tenet by ID.

PARAMETERDESCRIPTION
tenet_id

Tenet ID (can be partial)

TYPE:str

RETURNSDESCRIPTION
Optional[Tenet]

The Tenet or None if not found

list_tenets
Python
list_tenets(pending_only: bool = False, instilled_only: bool = False, session: Optional[str] = None, category: Optional[Union[str, TenetCategory]] = None) -> List[Dict[str, Any]]

List tenets with filtering.

PARAMETERDESCRIPTION
pending_only

Only show pending tenets

TYPE:boolDEFAULT:False

instilled_only

Only show instilled tenets

TYPE:boolDEFAULT:False

session

Filter by session binding

TYPE:Optional[str]DEFAULT:None

category

Filter by category

TYPE:Optional[Union[str, TenetCategory]]DEFAULT:None

RETURNSDESCRIPTION
List[Dict[str, Any]]

List of tenet dictionaries

get_pending_tenets
Python
get_pending_tenets(session: Optional[str] = None) -> List[Tenet]

Get all pending tenets.

PARAMETERDESCRIPTION
session

Filter by session

TYPE:Optional[str]DEFAULT:None

RETURNSDESCRIPTION
List[Tenet]

List of pending Tenet objects

remove_tenet
Python
remove_tenet(tenet_id: str) -> bool

Remove a tenet.

PARAMETERDESCRIPTION
tenet_id

Tenet ID (can be partial)

TYPE:str

RETURNSDESCRIPTION
bool

True if removed, False if not found

instill_tenets
Python
instill_tenets(session: Optional[str] = None, force: bool = False) -> Dict[str, Any]

Instill pending tenets.

PARAMETERDESCRIPTION
session

Target session

TYPE:Optional[str]DEFAULT:None

force

Re-instill even if already instilled

TYPE:boolDEFAULT:False

RETURNSDESCRIPTION
Dict[str, Any]

Dictionary with results

get_tenets_for_injection
Python
get_tenets_for_injection(context_length: int, session: Optional[str] = None, max_tenets: int = 5) -> List[Tenet]

Get tenets ready for injection into context.

PARAMETERDESCRIPTION
context_length

Current context length in tokens

TYPE:int

session

Current session

TYPE:Optional[str]DEFAULT:None

max_tenets

Maximum number of tenets to return

TYPE:intDEFAULT:5

RETURNSDESCRIPTION
List[Tenet]

List of tenets to inject

export_tenets
Python
export_tenets(format: str = 'yaml', session: Optional[str] = None, include_archived: bool = False) -> str

Export tenets to YAML or JSON.

PARAMETERDESCRIPTION
format

Export format (yaml or json)

TYPE:strDEFAULT:'yaml'

session

Filter by session

TYPE:Optional[str]DEFAULT:None

include_archived

Include archived tenets

TYPE:boolDEFAULT:False

RETURNSDESCRIPTION
str

Serialized tenets

import_tenets
Python
import_tenets(file_path: Union[str, Path], session: Optional[str] = None, override_priority: Optional[Priority] = None) -> int

Import tenets from file.

PARAMETERDESCRIPTION
file_path

Path to import file

TYPE:Union[str, Path]

session

Bind imported tenets to session

TYPE:Optional[str]DEFAULT:None

override_priority

Override priority for all imported tenets

TYPE:Optional[Priority]DEFAULT:None

RETURNSDESCRIPTION
int

Number of tenets imported

create_collection
Python
create_collection(name: str, description: str = '', tenet_ids: Optional[List[str]] = None) -> TenetCollection

Create a collection of related tenets.

PARAMETERDESCRIPTION
name

Collection name

TYPE:str

description

Collection description

TYPE:strDEFAULT:''

tenet_ids

IDs of tenets to include

TYPE:Optional[List[str]]DEFAULT:None

RETURNSDESCRIPTION
TenetCollection

The created TenetCollection

analyze_tenet_effectiveness
Python
analyze_tenet_effectiveness() -> Dict[str, Any]

Analyze effectiveness of tenets.

RETURNSDESCRIPTION
Dict[str, Any]

Analysis of tenet usage and effectiveness

Modules