agent#

class baf.core.agent.Agent(name, persist_sessions=False, user_profiles_path=None, agent_configurations_path=None)[source]#

Bases: object

The agent class.

Parameters:
  • name (str) – The agent’s name

  • persist_sessions (bool) – whether to persist sessions or not after restarting the agent

_name#

The agent name

Type:

str

_persist_sessions#

whether to persist sessions or not after restarting the agent

Type:

bool

_platforms#

The agent platforms

Type:

list[Platform]

_platforms_threads#

The threads where the platforms are run

Type:

list[threading.Thread]

_event_loop#

The event loop managing external events

Type:

asyncio.AbstractEventLoop

_event_thread#

The thread where the event loop is run

Type:

threading.Thread

_nlp_engine#

The agent NLP engine

Type:

NLPEngine

_config#

The agent configuration parameters

Type:

dict[str, Any]

_default_ic_config#

the intent classifier configuration used by default for the agent states

Type:

IntentClassifierConfiguration

_sessions#

The agent sessions

Type:

dict[str, Session]

_trained#

Whether the agent has been trained or not. It must be trained before it starts its execution.

Type:

bool

_monitoring_db#

The monitoring component of the agent that communicates with a database to store usage information for later visualization or analysis

Type:

MonitoringDB

states#

The agent states

Type:

list[State]

intents#

The agent intents

Type:

list[Intent]

entities#

The agent entities

Type:

list[Entity]

global_initial_states#

List of tuples of initial global states and their triggering intent

Type:

list[State, Intent]

global_state_component#

Dictionary of global state components, where key is initial global state and values is set of states in corresponding global component

Type:

dict[State, list[State]]

processors#

List of processors used by the agent

Type:

list[Processors]

_tools#

Tools registered on the agent and exposed to the predefined reasoning state. Keyed by tool name. Populated by add_tool() / new_tool() / load_tools(), the @agent.tool decorator, and indirectly by add_workspace() / new_workspace() (which register the universal list_directory / read_file and — when at least one workspace is writable — write_file / create_file / delete_file tools).

Type:

dict[str, Tool]

_skills#

Markdown-based playbooks the reasoning state injects into the system prompt. Keyed by skill name. Populated by add_skill() / new_skill() / load_skills().

Type:

dict[str, Skill]

_workspaces#

Filesystem workspaces the agent can browse and (when writable=True) modify through the universal workspace tools. Keyed by workspace name. Populated by add_workspace() / new_workspace().

Type:

dict[str, Workspace]

static _coerce_property_value(value, target_type)[source]#
_ensure_workspace_tools_registered()[source]#

Register the universal workspace tools.

Read tools (list_directory, read_file) are registered as soon as any workspace exists. Write tools (write_file, create_file, delete_file) are registered only once at least one workspace has writable=True — read-only-only setups never expose them to the LLM.

The tool callables themselves live in baf.library.tool.workspace_tools. This method only owns the gating policy (which family to expose, when) plus the dedup check. Idempotent — already-registered tools are skipped.

_flatten_yaml_properties(data, prefix='')[source]#
_get_session(session_id)[source]#

Get an agent session.

Parameters:

session_id (str) – the session id

Returns:

the session, if exists, or None

Return type:

Session or None

_init_global_states()[source]#

Initialise the global states and add the necessary transitions.

Go through all the global states and add transitions to every state to jump to the global states. Also add the transition to jump back to the previous state once the global state component has been completed.

_monitoring_db_delete_session(session)[source]#

Delete a session record from the monitoring database.

Parameters:

session (Session) – the session of the current user

_monitoring_db_get_last_state_of_session(session_id, platform)[source]#

Get the last state of a session from the monitoring database.

Parameters:
  • session_id (str) – The session ID to check.

  • platform (Platform) – The platform to check.

Returns:

The last state of the session if it exists, None otherwise.

Return type:

str | None

_monitoring_db_insert_chat(session, message)[source]#

Insert a message record into the monitoring database.

Parameters:

session (Session) – the session of the current user

_monitoring_db_insert_event(event)[source]#

Insert an event record into the monitoring database.

Parameters:

event (Event) – the event to insert into the database

_monitoring_db_insert_intent_prediction(session, predicted_intent)[source]#

Insert an intent prediction record into the monitoring database.

Parameters:
_monitoring_db_insert_reasoning_event(session, kind, payload)[source]#

Insert a reasoning-state event (step or task-list snapshot) into the dedicated reasoning_step table. Synchronous on purpose so a subsequent link_pending_reasoning_events call sees the row.

_monitoring_db_insert_session(session)[source]#

Insert a session record into the monitoring database.

Parameters:

session (Session) – the session of the current user

_monitoring_db_insert_transition(session, transition)[source]#

Insert a transition record into the monitoring database.

Parameters:

session (Session) – the session of the current user

Attach reasoning events with chat_id IS NULL to the most recent chat row for session. Best-effort, called at the end of every reasoning loop.

_monitoring_db_load_session_variables(session)[source]#

Load the session variables (private data dictionary) from the monitoring database.

Parameters:

session (Session) – The session to load the variables for.

_monitoring_db_select_reasoning_events(session, until_timestamp=None)[source]#

Fetch all reasoning events for a session, in chronological order.

_monitoring_db_session_exists(session_id, platform)[source]#

Check if a session with the given session_id exists in the monitoring database.

Parameters:
  • session_id (str) – The session ID to check.

  • platform (Platform) – The platform to check.

Returns:

True if the session exists in the database, False otherwise

Return type:

bool

_monitoring_db_store_session_variables(session)[source]#

Store the session variables (private data dictionary) in the monitoring database.

Parameters:

session (Session) – The session to store the variables for.

_new_session(session_id, platform, username=None, session_name=None)[source]#

Create a new session for the agent.

Parameters:
  • session_id (str) – the session id

  • platform (Platform) – the platform where the session is to be created and used

  • username (str) – the name of the session user (optional)

  • session_name (str) – the name of the session (optional)

Returns:

the session

Return type:

Session

_resolve_workspace(name=None)[source]#

Look up a workspace by name, or pick the only one when name is None.

Raises a ValueError (which the Tool wrapper turns into an LLM-readable ERROR string) on missing or ambiguous lookups.

_run_platforms()[source]#

Start the execution of the agent platforms

_stop_platforms()[source]#

Stop the execution of the agent platforms

add_entity(entity)[source]#

Add an entity to the agent.

Parameters:

entity (Entity) – the entity to add

Returns:

the added entity

Return type:

Entity

add_intent(intent)[source]#

Add an intent to the agent.

Parameters:

intent (Intent) – the intent to add

Returns:

the added intent

Return type:

Intent

add_skill(skill)[source]#

Add an already-constructed Skill to the agent.

Mirrors add_intent(). Use new_skill() to skip the explicit Skill(...) construction (especially convenient for loading from a .md file path).

Parameters:

skill (Skill) – the skill to register.

Returns:

the registered skill.

Return type:

Skill

add_tool(tool)[source]#

Add an already-constructed Tool to the agent.

Mirrors add_intent(): the caller builds the wrapper, this method registers it. Use new_tool() when you want to skip the explicit Tool(...) construction.

Parameters:

tool (Tool) – the tool wrapper to register.

Returns:

the registered tool wrapper.

Return type:

Tool

add_workspace(workspace)[source]#

Add an already-constructed Workspace to the agent.

The first call also registers the universal list_directory / read_file tools, and — if at least one registered workspace has writable=True — the write_file / create_file / delete_file tools.

Mirrors add_intent(). Use new_workspace() to skip the explicit Workspace(...) construction.

Parameters:

workspace (Workspace) – the workspace to register.

Returns:

the registered workspace.

Return type:

Workspace

Raises:

ValueError – if a workspace with the same name is already registered.

property agent_configurations#

Return loaded agent configurations mapped by profile/user key.

close_session(session_id)[source]#

Delete an existing agent session.

Parameters:

session_id (str) – the session id

property config#

The agent configuration parameters.

Type:

dict[str, Any]

delete_session(session_id)[source]#

Delete an existing agent session.

Parameters:

session_id (str) – the session id

get_or_create_session(session_id, platform, username=None, session_name=None)[source]#
get_property(prop)[source]#

Get an agent property’s value

Parameters:

prop (Property) – the property to get its value

Returns:

the property value, or None

Return type:

Any

initial_state()[source]#

Get the agent’s initial state. It can be None if it has not been set.

Returns:

the initial state of the agent, if exists

Return type:

State or None

load_agent_configurations(path)[source]#

Load agent configurations from a JSON file.

Expected format: a mapping where keys represent profile/user identifiers and values are the corresponding agent configuration objects.

load_properties(path)[source]#

Read a properties file and store its properties in the agent configuration.

Supported formats are YAML (.yaml, .yml).

See baf/test/examples/config.yaml in the repository for a complete example of an agent configuration file.

Parameters:

path (str) – the path to the properties file

load_skills(folder)[source]#

Register every *.md file in folder (non-recursive) as a skill.

Parameters:

folder (str) – path to a folder containing markdown files.

Returns:

the skills that were registered.

Return type:

list[Skill]

load_tools(path)[source]#

Load every public top-level callable from a Python module or folder of modules.

path may be a single .py file or a folder (non-recursive). For each module, every callable whose name does not start with _ is registered as a tool. Callables imported from other modules are skipped — only those defined in the loaded module are considered, so importing helpers in tools.py does not pollute the tool registry.

Parameters:

path (str) – path to a .py file or to a folder containing them.

Returns:

the tools that were registered (may be empty).

Return type:

list[Tool]

load_user_profiles(path)[source]#

Load user profiles from a JSON file and store data.

property name#

The agent name.

Type:

str

new_entity(name, base_entity=False, entries=None, description=None)[source]#

Create a new entity in the agent.

Parameters:
  • name (str) – the entity name. It must be unique in the agent

  • base_entity (bool) – whether the entity is a base entity or not (i.e. a custom entity)

  • entries (dict[str, list[str]] or None) – the entity entries

  • description (str or None) – a description of the entity, optional

Returns:

the entity

Return type:

Entity

new_intent(name, training_sentences=None, parameters=None, description=None)[source]#

Create a new intent in the agent.

Parameters:
  • name (str) – the intent name. It must be unique in the agent

  • training_sentences (list[str] or None) – the intent’s training sentences

  • parameters (list[IntentParameter] or None) – the intent parameters, optional

  • description (str or None) – a description of the intent, optional

Returns:

the intent

Return type:

Intent

new_skill(source, name=None, description=None)[source]#

Build a Skill and register it.

source is either a path to an existing .md file (loaded via Skill.from_file()) or a literal markdown string. The path detection is automatic.

Parameters:
  • source (str) – path to a .md file or the markdown content as a string.

  • name (str) – override the skill name (otherwise taken from frontmatter, a leading H1, or the filename stem).

  • description (str) – override the description (otherwise taken from frontmatter).

Returns:

the registered skill.

Return type:

Skill

new_state(name, initial=False, ic_config=None)[source]#

Create a new state in the agent.

Parameters:
  • name (str) – the state name. It must be unique in the agent.

  • initial (bool) – whether the state is initial or not. An agent must have 1 initial state.

  • ic_config (IntentClassifierConfiguration or None) – the intent classifier configuration for the state. If None is provided, the agent’s default one will be assigned to the state.

Returns:

the state

Return type:

State

new_tool(fn, name=None, description=None)[source]#

Build a Tool from a callable and register it.

See baf.reasoning.tool.Tool for the auto-introspection rules.

Parameters:
  • fn (Callable) – the function to expose. May be a bound method.

  • name (str) – override the tool’s public name. Defaults to fn.__name__.

  • description (str) – override the description shown to the LLM. Defaults to the first line of fn.__doc__.

Returns:

the registered tool wrapper.

Return type:

Tool

new_workspace(path, name='workspace', description=None, writable=True, max_read_bytes=200000)[source]#

Build a Workspace and register it.

Parameters:
  • path (str) – the workspace root path.

  • name (str) – the workspace identifier the LLM passes as the workspace tool argument. Must be unique within the agent.

  • description (str) – a short human-readable explanation of what the workspace contains. Strongly recommended — without it the LLM only sees the name and root path and may not realise it should browse the workspace.

  • writable (bool) – whether mutating operations are allowed on this workspace (write_file / create_file / delete_file). Defaults to True.

  • max_read_bytes (int) – cap on read_file output, in bytes.

Returns:

the registered workspace.

Return type:

Workspace

property nlp_engine#

The agent NLP engine.

Type:

NLPEngine

process(session, message, is_user_message)[source]#

Runs the agent processors in a message.

Only processors that process messages of the same type as the given message will be run. If the message to process is a user message, only processors that process user messages will be run. If the message to process is an agent message, only processors that process agent messages will be run.

Parameters:
  • session (Session) – the current session

  • message (Any) – the message to be processed

  • is_user_message (bool) – indicates whether the message is a user message (True) or an agent message (False)

Returns:

the processed message

Return type:

Any

receive_event(event)[source]#

Receive an external event from a platform.

Receiving an event and send it to all the applicable sessions of the agent

Parameters:

event (Event) – the received event

reset(session_id)[source]#

Reset the agent current state and memory for the specified session. Then, restart the agent again for this session.

Parameters:

session_id (str) – the session to reset

Returns:

the reset session, or None if the provided session_id does not exist

Return type:

Session or None

run(train=True, sleep=True)[source]#

Start the execution of the agent.

Parameters:
  • train (bool) – whether to train the agent or not

  • sleep (bool) – whether to sleep after running the agent or not, which means that this function will not return

set_agent_configurations(configurations)[source]#

Set agent configurations programmatically.

Parameters:

configurations (dict[str, Any] | None) – mapping of profile/user keys to config objects.

set_default_ic_config(ic_config)[source]#

Set the default intent classifier configuration.

Parameters:

ic_config (IntentClassifierConfiguration) – the intent classifier configuration

set_global_fallback_body(body)[source]#

Set the fallback body for all agent states.

The fallback body is a state’s callable function that will be run whenever necessary to handle unexpected scenarios (e.g. when no intent is matched, the current state’s fallback is run). This method simply sets the same fallback body to all agent states.

Parameters:

body (Callable[[Session], None]) – the fallback body

set_property(prop, value)[source]#

Set an agent property.

Parameters:
  • prop (Property) – the property to set

  • value (Any) – the property value

set_user_profiles(profiles)[source]#

Set user profiles programmatically.

stop()[source]#

Stop the agent execution.

tool(fn=None, *, name=None, description=None)[source]#

Decorator form of new_tool().

Usable bare (@agent.tool) or with arguments (@agent.tool(name='x')).

train()[source]#

Train the agent.

The agent training is done before its execution.

use_a2a_platform()[source]#

Use the :class: ~baf.platforms.a2a.a2a_platform.A2APlatform on this agent.

Returns:

the A2A platform

Return type:

A2APlatform

use_db_handler()[source]#

Use the DBHandler on this agent.

DB connections are established lazily, when the first query is executed.

Returns:

the database handler

Return type:

DBHandler

use_github_platform()[source]#

Use the GitHubPlatform on this agent.

Returns:

the GitHub platform

Return type:

GitHubPlatform

use_gitlab_platform()[source]#

Use the GitLabPlatform on this agent.

Returns:

the GitLab platform

Return type:

GitLabPlatform

use_telegram_platform()[source]#

Use the TelegramPlatform on this agent.

Returns:

the telegram platform

Return type:

TelegramPlatform

use_websocket_platform(use_ui=True, authenticate_users=False)[source]#

Use the WebSocketPlatform on this agent.

Parameters:
  • use_ui (bool) – if true, the default UI will be run to use this platform

  • authenticate_users (bool) – whether to enable user persistence and authentication. Requires streamlit database configuration. Default is False

Returns:

the websocket platform

Return type:

WebSocketPlatform

property user_profiles#

Return loaded user profiles data, or None if not set.