Skip to content

Latest commit

 

History

History
440 lines (298 loc) · 10.3 KB

File metadata and controls

440 lines (298 loc) · 10.3 KB

Aifeels API Reference

Complete API documentation for the Aifeels library.

Core Classes

EmotionalState

Main class for managing emotional state.

from aifeels import EmotionalState

state = EmotionalState(
    frustration=0.0,  # Optional, default: 0.0
    trust=0.0,        # Optional, default: 0.0
    urgency=0.0,      # Optional, default: 0.0
    stress=0.0,       # Optional, default: 0.0
    caution=0.0       # Optional, default: 0.0
)

Attributes

Attribute Type Range Description
frustration float 0.0-1.0 Accumulated setbacks and failures
trust float 0.0-1.0 Confidence in own capabilities
urgency float 0.0-1.0 Time pressure and priority
stress float 0.0-1.0 Cognitive load and resource constraints
caution float 0.0-1.0 Need for verification and care
last_update_time float - Unix timestamp of last update
history List[StateTransition] - List of state transitions

Methods

process_event(event: Event, apply_decay: bool = True) -> None

Process an event and update emotional state.

Parameters:

  • event (Event): The event to process
  • apply_decay (bool): Whether to apply decay before processing (default: True)

Example:

from aifeels.events import StandardEvents

state.process_event(StandardEvents.TASK_FAILED)
get_current_state(apply_decay: bool = True) -> Dict[str, float]

Get current emotional state as a dictionary.

Parameters:

  • apply_decay (bool): Whether to apply decay before returning (default: True)

Returns:

  • Dictionary mapping emotion names to current values

Example:

current = state.get_current_state()
# {'frustration': 0.3, 'trust': 0.0, 'urgency': 0.0, 'stress': 0.1, 'caution': 0.0}
recommended_action(apply_decay: bool = True) -> str

Get recommended action based on current state.

Parameters:

  • apply_decay (bool): Whether to apply decay before selecting action (default: True)

Returns:

  • Action string: 'escalate_to_human', 'request_confirmation', 'increase_caution', or 'continue_autonomy'

Example:

action = state.recommended_action()
if action == 'escalate_to_human':
    # Stop and get human help
    pass
get_action_recommendation(apply_decay: bool = True) -> ActionRecommendation

Get detailed action recommendation with reasoning.

Parameters:

  • apply_decay (bool): Whether to apply decay before selecting action (default: True)

Returns:

  • ActionRecommendation object with action, reason, and triggered_by

Example:

rec = state.get_action_recommendation()
print(rec.action)        # Action.ESCALATE_TO_HUMAN
print(rec.reason)        # "High frustration level..."
print(rec.triggered_by)  # {'frustration': 0.9}
reset() -> None

Reset all emotional primitives to 0.0 and clear history.

Example:

state.reset()
get_history() -> List[StateTransition]

Get complete history of state transitions.

Returns:

  • List of StateTransition objects in chronological order

Example:

history = state.get_history()
for transition in history:
    print(transition.event_name, transition.deltas)

Event System

Event

Represents an event that affects emotional state.

from aifeels.events import Event

event = Event(
    name="custom:my_event",
    deltas={"frustration": 0.1, "stress": 0.2}
)

Attributes

Attribute Type Description
name str Unique event identifier (with namespace)
deltas Dict[str, float] Emotional state changes

Note: Events are immutable (frozen).

StandardEvents

Class containing all 13 standard events defined in Aifeels v0.1.0.

Events

Task Lifecycle:

  • StandardEvents.TASK_STARTED
  • StandardEvents.TASK_COMPLETED
  • StandardEvents.TASK_FAILED
  • StandardEvents.TASK_BLOCKED

User Interaction:

  • StandardEvents.USER_FEEDBACK_POSITIVE
  • StandardEvents.USER_FEEDBACK_NEGATIVE
  • StandardEvents.USER_INTERVENTION_REQUIRED
  • StandardEvents.USER_INTERVENTION_COMPLETED

System Events:

  • StandardEvents.RESOURCE_CONSTRAINT
  • StandardEvents.UNCERTAINTY_DETECTED
  • StandardEvents.CONFIDENCE_INCREASED
  • StandardEvents.DEADLINE_APPROACHING
  • StandardEvents.IDLE_TIME

Methods

get_all_events() -> Dict[str, Event]

Get all standard events as a dictionary.

Returns:

  • Dictionary mapping event names to Event objects

Example:

events = StandardEvents.get_all_events()
print(len(events))  # 13
get_event_by_name(name: str) -> Event

Retrieve a standard event by its name.

Parameters:

  • name (str): The event name (e.g., 'std:task_failed')

Returns:

  • The Event object

Raises:

  • ValueError: If event name is not found

Example:

event = StandardEvents.get_event_by_name('std:task_failed')

Decay System

DecayCalculator

Calculates temporal decay for emotional primitives.

Constants

Constant Value Description
DECAY_RATE 0.05 Amount of decay per interval
DECAY_INTERVAL 300.0 Interval in seconds (5 minutes)

Methods

calculate_decay(current_value: float, last_update_time: float, current_time: float | None = None) -> float

Calculate decayed value based on elapsed time.

Parameters:

  • current_value (float): Current emotional primitive value (0.0-1.0)
  • last_update_time (float): Unix timestamp of last update
  • current_time (float | None): Unix timestamp to calculate decay to (defaults to now)

Returns:

  • Decayed value, clamped to [0.0, 1.0]

Example:

from aifeels.decay import DecayCalculator
import time

value = 0.5
start_time = time.time()
end_time = start_time + 300  # 5 minutes later

decayed = DecayCalculator.calculate_decay(value, start_time, end_time)
print(decayed)  # 0.45 (0.5 - 0.05)
apply_decay_to_state(state: Dict[str, float], last_update_time: float, current_time: float | None = None) -> Dict[str, float]

Apply decay to all primitives in a state dictionary.

Parameters:

  • state (Dict[str, float]): Dictionary of emotion names to values
  • last_update_time (float): Unix timestamp of last update
  • current_time (float | None): Unix timestamp to calculate decay to (defaults to now)

Returns:

  • New state dictionary with decayed values

Action System

Action

Enum of possible actions.

from aifeels.actions import Action

Action.ESCALATE_TO_HUMAN       # 'escalate_to_human'
Action.REQUEST_CONFIRMATION    # 'request_confirmation'
Action.INCREASE_CAUTION        # 'increase_caution'
Action.CONTINUE_AUTONOMY       # 'continue_autonomy'

ActionRecommendation

Recommendation for action based on emotional state.

Attributes

Attribute Type Description
action Action The recommended action
reason str Human-readable explanation
triggered_by Dict[str, float] Emotional primitives that triggered this

ActionSelector

Selects appropriate actions based on emotional state thresholds.

Constants

Constant Value Description
ESCALATE_THRESHOLD 0.8 Frustration threshold for escalation
CONFIRM_THRESHOLD 0.7 Frustration threshold for confirmation
CAUTION_THRESHOLD 0.7 Caution threshold for increased care

Methods

select_action(state: Dict[str, float]) -> ActionRecommendation

Select the appropriate action based on emotional state.

Parameters:

  • state (Dict[str, float]): Dictionary of emotion names to values

Returns:

  • ActionRecommendation with selected action and explanation

Example:

from aifeels.actions import ActionSelector

state = {"frustration": 0.9, "trust": 0.2, "urgency": 0.5, "stress": 0.3, "caution": 0.1}
rec = ActionSelector.select_action(state)
print(rec.action)  # Action.ESCALATE_TO_HUMAN
get_action_precedence() -> list[Action]

Get the list of actions in precedence order.

Returns:

  • List of actions from highest to lowest priority

Data Models

StateTransition

Record of a single state transition.

Attributes

Attribute Type Description
timestamp float Unix timestamp when transition occurred
event_name str Name of the event that triggered the transition
deltas Dict[str, float] Changes applied to emotional primitives
state_before Dict[str, float] State values before the transition
state_after Dict[str, float] State values after the transition

MCP Server

Server Functions

start_server(port: int = 8080) -> None

Start the Aifeels MCP server.

Parameters:

  • port (int): Port number (currently unused for stdio server)

main() -> None

Main entry point for the aifeels-mcp command.

MCP Tools

The MCP server provides these tools:

  1. get_emotional_state

    • Get current emotional state
    • Parameters: apply_decay (bool)
  2. process_event

    • Process an event
    • Parameters: event_name (str)
  3. get_recommended_action

    • Get recommended action
    • Parameters: apply_decay (bool)
  4. reset_emotional_state

    • Reset all primitives to 0.0
    • Parameters: none
  5. get_state_history

    • Get complete history
    • Parameters: none

Type Hints

All public APIs include complete type hints for use with mypy and other type checkers.

from aifeels import EmotionalState
from aifeels.events import Event

# Type checking works
def process_failure(state: EmotionalState) -> str:
    state.process_event(StandardEvents.TASK_FAILED)
    return state.recommended_action()

Pydantic Models

All data classes use Pydantic for runtime validation:

from aifeels import EmotionalState

# Validation happens automatically
state = EmotionalState(frustration=1.5)  # Raises ValidationError
state = EmotionalState(frustration=-0.1)  # Raises ValidationError
state = EmotionalState(frustration=0.5)   # OK

Version Information

import aifeels

print(aifeels.__version__)  # '0.1.0'

Further Reading