spade package
Submodules
spade.agent module
- class spade.agent.Agent(jid: str, password: str, port: int = 5222, verify_security: bool = False)[source]
Bases:
object- add_behaviour(behaviour: BehaviourType, template: Optional[Template] = None) None[source]
Adds and starts a behaviour to the agent. If template is not None it is used to match new messages and deliver them to the behaviour.
- Args:
behaviour (Type[spade.behaviour.CyclicBehaviour]): the behaviour to be started template (spade.template.Template, optional): the template to match messages with (Default value = None)
- property avatar: str
Generates a unique avatar for the agent based on its JID. Uses Gravatar service with MonsterID option.
- Returns:
str: the url of the agent’s avatar
- static build_avatar_url(jid: str) str[source]
Static method to build a gravatar url with the agent’s JID
- Args:
jid (aioxmpp.JID): an XMPP identifier
- Returns:
str: a URL for the gravatar
- dispatch(msg: Message) List[Task][source]
Dispatch the message to every behaviour that is waiting for it using their templates match.
- Args:
msg (spade.message.Message): the message to dispatch.
- Returns:
list(asyncio.Future): a list of tasks for each message queuing in each matching behavior.
- get(name: str) Any[source]
Recovers a knowledge item from the agent’s knowledge base.
- Args:
name(str): name of the item
- Returns:
object: the object retrieved or None
- has_behaviour(behaviour: Type[CyclicBehaviour]) bool[source]
Checks if a behaviour is added to an agent.
- Args:
behaviour (Type[spade.behaviour.CyclicBehaviour]): the behaviour instance to check
- Returns:
bool: a boolean that indicates wether the behaviour is inside the agent.
- is_alive() bool[source]
Checks if the agent is alive.
- Returns:
bool: wheter the agent is alive or not
- property name: str
Returns the name of the agent (the string before the ‘@’)
- Returns:
str: the name of the agent (the string before the ‘@’)
- remove_behaviour(behaviour: Type[CyclicBehaviour]) None[source]
Removes a behaviour from the agent. The behaviour is first killed.
- Args:
behaviour (Type[spade.behaviour.CyclicBehaviour]): the behaviour instance to be removed
- set(name: str, value: Any)[source]
Stores a knowledge item in the agent knowledge base.
- Args:
name (str): name of the item value (object): value of the item
- set_container(container: Container) None[source]
Sets the container to which the agent is attached
- Args:
container (spade.container.Container): the container to be attached to
spade.behaviour module
- class spade.behaviour.CyclicBehaviour[source]
Bases:
objectThis behaviour is executed cyclically until it is stopped.
- async download_file(url: str, dest_path: Optional[str])[source]
Downloads a file from a 0363 slot (url) into the
dest_path(or execution dir if not provided)- Args:
url (str): URL of the slot to download. dest_path (str): Path to put the downloaded file. Must be an existing dir.
- async enqueue(message: Message) None[source]
Enqueues a message in the behaviour’s mailbox
- Args:
message (spade.message.Message): the message to be enqueued
- property exit_code: Any
Returns the exit_code of the behaviour. It only works when the behaviour is done or killed, otherwise it raises an exception.
- Returns:
object: the exit code of the behaviour
- Raises:
BehaviourNotFinishedException: if the behaviour is not yet finished
- get(name: str) Any[source]
Recovers a knowledge item from the agent’s knowledge base.
- Args:
name (str): name of the item
- Returns:
Any: the object retrieved or None
- is_done() bool[source]
Check if the behaviour is finished
- Returns:
bool: whether the behaviour is finished or not
- is_killed() bool[source]
Checks if the behaviour was killed by means of the kill() method.
- Returns:
bool: whether the behaviour is killed or not
- async join(timeout: Optional[float] = None) None[source]
Wait for the behaviour to complete
- Args:
timeout (Optional[float]): an optional timeout to wait to join (if None, the join is blocking)
- Returns:
None
- Raises:
TimeoutError: if the timeout is reached
- kill(exit_code: Optional[Any] = None) None[source]
Stops the behaviour
- Args:
exit_code (object, optional): the exit code of the behaviour (Default value = None)
- mailbox_size() int[source]
Checks if there is a message in the mailbox
- Returns:
int: the number of messages in the mailbox
- match(message: Message) bool[source]
Matches a message with the behaviour’s template
- Args:
message(spade.message.Message): the message to match with
- Returns:
bool: wheter the messaged matches or not
- async receive(timeout: Optional[float] = None) Optional[Message][source]
Receives a message for this behaviour. If timeout is not None it returns the message or “None” after timeout is done.
- Args:
timeout (float, optional): number of seconds until return
- Returns:
spade.message.Message: a Message or None
- async send(msg: Message) None[source]
Sends a message.
- Args:
msg (spade.message.Message): the message to be sent.
- async send_file(filename: str, input_file: Optional[IO[bytes]]) Optional[str][source]
Discovers the XEP 0363 service, and tries to send the file.
- Args:
filename (str): Path to the file to upload (or only the name if
input_fileis provided) input_file (IO[bytes]): Binary file stream on the file- Returns:
An url used to download the uploaded file (GET HTTP method)
- set(name: str, value: Any) None[source]
Stores a knowledge item in the agent knowledge base.
- Args:
name (str): name of the item value (Any): value of the item
- set_agent(agent) None[source]
Links behaviour with its owner agent
- Args:
agent (spade.agent.Agent): the agent who owns the behaviour
- class spade.behaviour.FSMBehaviour[source]
Bases:
CyclicBehaviourA behaviour composed of states (oneshotbehaviours) that may transition from one state to another.
- add_state(name: str, state: State, initial: bool = False) None[source]
Adds a new state to the FSM.
- Args:
name (str): the name of the state, which is used as its identifier. state (spade.behaviour.State): The state class initial (bool, optional): wether the state is the initial state or not. (Only one initial state is allowed) (Default value = False)
- add_transition(source: str, dest: str) None[source]
Adds a transition from one state to another.
- Args:
source (str): the name of the state from where the transition starts dest (str): the name of the state where the transition ends
- is_valid_transition(source: str, dest: str) bool[source]
Checks if a transitions is registered in the FSM
- Args:
source (str): the source state name dest (str): the destination state name
- Returns:
bool: wether the transition is valid or not
- class spade.behaviour.OneShotBehaviour[source]
Bases:
CyclicBehaviourThis behaviour is only executed once
- class spade.behaviour.PeriodicBehaviour(period: float, start_at: Optional[datetime] = None)[source]
Bases:
CyclicBehaviourThis behaviour is executed periodically with an interval
- property period: timedelta
Get the period.
- class spade.behaviour.State[source]
Bases:
OneShotBehaviourA state of a FSMBehaviour is a OneShotBehaviour
- set_next_state(state_name: str) None[source]
Set the state to transition to when this state is finished. state_name must be a valid state and the transition must be registered. If set_next_state is not called then current state is a final state.
- Args:
state_name (str): the name of the state to transition to
- class spade.behaviour.TimeoutBehaviour(start_at)[source]
Bases:
OneShotBehaviourThis behaviour is executed once at after specified datetime
- spade.behaviour.now(tz=None)
Returns new datetime object representing current time local to tz.
- tz
Timezone object.
If no tz is specified, uses local timezone.
spade.cli module
spade.container module
- class spade.container.Container[source]
Bases:
ContainerThe container class allows agents to exchange messages without using the XMPP socket if they are in the same process. The container is a singleton.
spade.fipa_message module
Module for creating and handling FIPA-ACL messages compatible with SPADE.
Based on the FIPA ACL Message Structure Specification: http://www.fipa.org/specs/fipa00061/SC00061G.html
This module provides tools for building, validating, and parsing FIPA-ACL messages that comply with the Foundation for Intelligent Physical Agents (FIPA) standards.
- class spade.fipa_message.FIPAMessageBuilder(sender: str, receiver: str)[source]
Bases:
objectBuilder for FIPA-ACL messages for agent communication.
This class provides a fluent interface for creating messages that follow the FIPA Agent Communication Language standard.
- Attributes:
message (Message): The SPADE Message object being built metadata (Dict): Dictionary with FIPA-ACL metadata
- LANGUAGES: ClassVar[dict] = {'fipa-sl': 'FIPA Semantic Language (standard)', 'fipa-sl0': 'FIPA SL level 0', 'fipa-sl1': 'FIPA SL level 1', 'fipa-sl2': 'FIPA SL level 2', 'json': 'JavaScript Object Notation', 'string': 'Plain text string', 'xml': 'Extensible Markup Language'}
- PERFORMATIVES: ClassVar[dict] = {'accept-proposal': 'Accept a proposal', 'agree': 'Agree to perform an action', 'cancel': 'Cancel a previously agreed action', 'cfp': 'Call for proposal (request proposals)', 'confirm': 'Confirm that something is true', 'disconfirm': 'Inform that something is false', 'failure': 'Report failure to execute action', 'inform': 'Inform that something is true', 'inform-if': 'Inform whether a proposition is true', 'inform-ref': 'Inform the value of a reference', 'not-understood': 'Indicate that the message was not understood', 'propagate': 'Ask an agent to send a message to others', 'propose': 'Make a proposal', 'proxy': 'Ask an agent to act as proxy', 'query-if': 'Ask whether a proposition is true', 'query-ref': 'Ask the value of a reference', 'refuse': 'Refuse to perform an action', 'reject-proposal': 'Reject a proposal', 'request': 'Request that an action be performed', 'request-when': 'Request that an action be performed when a condition holds', 'request-whenever': 'Request that an action be performed whenever a condition holds', 'subscribe': 'Subscribe to information'}
- PROTOCOLS: ClassVar[dict] = {'fipa-brokering': 'Brokering protocol', 'fipa-contract-net': 'Contract net protocol', 'fipa-propose': 'Propose protocol', 'fipa-query': 'Query protocol', 'fipa-recruiting': 'Recruiting protocol', 'fipa-request': 'Request protocol', 'fipa-subscribe': 'Subscribe protocol'}
- build() Message[source]
Build and return the SPADE Message object.
- Returns:
Message: Message object ready to send.
- Raises:
ValueError: If performative has not been set.
- Example:
>>> msg = builder.build() >>> await agent.send(msg)
- classmethod create_inform_message(sender: str, receiver: str, content: dict, ontology: str = 'general') Message[source]
Convenience method to create ‘inform’ messages.
- Args:
sender (str): Sender JID. receiver (str): Receiver JID. content (Dict): Message content. ontology (str): Message ontology.
- Returns:
Message: FIPA-ACL ‘inform’ message.
- Example:
>>> msg = FIPAMessageBuilder.create_inform_message( ... sender="agent1@localhost", ... receiver="agent2@localhost", ... content={"data": "value"}, ... ontology="database" ... )
- classmethod create_request_message(sender: str, receiver: str, action: str, parameters: Optional[dict] = None) Message[source]
Convenience method to create ‘request’ messages.
- Args:
sender (str): Sender JID. receiver (str): Receiver JID. action (str): Action to request. parameters (Dict): Action parameters.
- Returns:
Message: FIPA-ACL ‘request’ message.
- Example:
>>> msg = FIPAMessageBuilder.create_request_message( ... sender="agent1@localhost", ... receiver="agent2@localhost", ... action="update-database", ... parameters={"table": "users"} ... )
- classmethod create_response_message(original_msg: Message, content: dict, performative: str = 'confirm') Message[source]
Create a response message to another message.
- Args:
original_msg (Message): Original message being responded to. content (Dict): Response content. performative (str): Response performative (“confirm”, “failure”, etc.).
- Returns:
Message: FIPA-ACL response message.
- Example:
>>> response = FIPAMessageBuilder.create_response_message( ... original_msg=received_msg, ... content={"status": "success"}, ... performative="confirm" ... )
- set_body(content: Union[dict, str, Any], as_json: bool = True) FIPAMessageBuilder[source]
Set the message body content.
- Args:
content: Message content. Can be dict, str, or other type. as_json (bool): If True, serializes non-string content to JSON or
treats string content as already-serialized JSON. If False, uses content as string.
- Returns:
FIPAMessageBuilder: Self for method chaining.
- Example:
>>> builder.set_body({"data": "value"}, as_json=True) >>> builder.set_body('{"data": "value"}', as_json=True) >>> builder.set_body("plain text", as_json=False)
- set_conversation_id(conversation_id: str) FIPAMessageBuilder[source]
Set a specific conversation ID.
- Args:
conversation_id (str): Unique ID for the conversation.
- Returns:
FIPAMessageBuilder: Self for method chaining.
- Note:
If not set, one is automatically generated with UUID.
- Example:
>>> builder.set_conversation_id("db-update-123")
- set_custom_metadata(key: str, value: Any) FIPAMessageBuilder[source]
Add custom metadata to the message.
- Args:
key (str): Metadata key. value: Metadata value. It will be converted to a string for storage.
- Returns:
FIPAMessageBuilder: Self for method chaining.
- Example:
>>> builder.set_custom_metadata("priority", "high")
- set_in_reply_to(reply_to: str) FIPAMessageBuilder[source]
Set which message is being replied to.
- Args:
reply_to (str): Value of the ‘reply-with’ field from the original message.
- Returns:
FIPAMessageBuilder: Self for method chaining.
- Example:
>>> builder.set_in_reply_to("msg-abc123")
- set_language(language: str) FIPAMessageBuilder[source]
Set the content language.
- Args:
- language (str): Content language. Recommended to use
“json”, “xml”, or “fipa-sl”.
- Returns:
FIPAMessageBuilder: Self for method chaining.
- Example:
>>> builder.set_language("json")
- set_ontology(ontology: str) FIPAMessageBuilder[source]
Set the message ontology.
- Args:
ontology (str): Ontology that defines the terms/concepts used.
- Returns:
FIPAMessageBuilder: Self for method chaining.
- Example:
>>> builder.set_ontology("database-update")
- set_performative(performative: str) FIPAMessageBuilder[source]
Set the speech act (performative) of the message.
- Args:
- performative (str): Type of speech act. Must be one of the
valid FIPA-ACL performatives.
- Returns:
FIPAMessageBuilder: Self for method chaining.
- Raises:
ValueError: If the performative is not valid.
- Example:
>>> builder.set_performative("inform")
- set_protocol(protocol: str) FIPAMessageBuilder[source]
Set the interaction protocol.
- Args:
protocol (str): FIPA protocol. E.g., “fipa-request”, “fipa-subscribe”.
- Returns:
FIPAMessageBuilder: Self for method chaining.
- Example:
>>> builder.set_protocol("fipa-request")
- set_reply_by(minutes: int = 5) FIPAMessageBuilder[source]
Set deadline for response.
- Args:
minutes (int): Minutes until response wait expires.
- Returns:
FIPAMessageBuilder: Self for method chaining.
- Example:
>>> builder.set_reply_by(10) # 10 minutes to respond
- class spade.fipa_message.FIPAMessageParser(message: Message)[source]
Bases:
objectParser for received FIPA-ACL messages.
Provides methods for extracting and validating FIPA metadata from incoming messages.
- get_conversation_id() str[source]
Get the conversation ID.
- Returns:
str: Conversation ID, or “unknown” if not present.
- get_custom_metadata(key: str, default: Any = None) Any[source]
Get custom metadata.
- Args:
key (str): Metadata key. default: Default value if key does not exist.
- Returns:
Any: Metadata value or default value.
- get_language() str[source]
Get the content language.
- Returns:
str: Content language, or “unknown” if not present.
- get_ontology() str[source]
Get the message ontology.
- Returns:
str: Message ontology, or “unknown” if not present.
- get_performative() str[source]
Get the message performative.
- Returns:
str: Message performative, or “unknown” if not present.
- get_protocol() str[source]
Get the interaction protocol.
- Returns:
str: FIPA protocol, or “unknown” if not present.
- get_reply_with() str[source]
Get the message ID for responses.
- Returns:
str: Value of ‘reply-with’, or empty string if not present.
- is_valid_fipa_message() bool[source]
Check if the message has the basic FIPA-ACL structure.
- Returns:
bool: True if message passes FIPA-ACL validation.
- parse_body() Any[source]
Parse the message body according to its language.
- Returns:
Any: Parsed content. If the language is “json” (or the body looks like JSON), returns the decoded JSON (typically a dict or list). If JSON parsing fails or the body is not JSON, returns the original body string unchanged.
- Note:
This method does NOT raise
json.JSONDecodeError. Instead, it gracefully returns the raw body string when JSON decoding fails, allowing callers to handle malformed content as needed.- Example:
>>> parser = FIPAMessageParser(message) >>> content = parser.parse_body() # Returns dict if JSON, str otherwise
spade.message module
- class spade.message.Message(to: Optional[Union[str, JID]] = None, sender: Optional[Union[str, JID]] = None, body: Optional[str] = None, thread: Optional[str] = None, metadata: Optional[Dict[str, str]] = None)[source]
Bases:
MessageBase
- class spade.message.MessageBase(to: Optional[Union[str, JID]] = None, sender: Optional[Union[str, JID]] = None, body: Optional[str] = None, thread: Optional[str] = None, metadata: Optional[Dict[str, str]] = None)[source]
Bases:
objectBase class for message handling in SPADE.
- property body: Optional[str]
Get body of the message Returns:
str: the body of the message
- classmethod from_node(node: Message) Type[MessageBase][source]
Creates a new spade.message.Message from a slixmpp.stanza.Message
- Args:
node (slixmpp.stanza.Message): a slixmpp Message
- Returns:
spade.message.Message: a new spade Message
- get_metadata(key: str) Optional[str][source]
Get the value of a metadata. Returns None if metadata does not exist.
- Args:
key (str): name of the metadata
- Returns:
str: the value of the metadata (or None)
- property id: int
- match(message: MessageBase) bool[source]
Returns wether a message matches with this message or not. The message can be a Message object or a Template object.
- Args:
message (spade.message.Message): the message to match to
- Returns:
bool: wether the message matches or not
- property sender: JID
Get jid of the sender
- Returns:
slixmpp.JID: jid of the sender
- set_metadata(key: str, value: str) None[source]
Add a new metadata to the message
- Args:
key (str): name of the metadata value (str): value of the metadata
- property thread: Optional[str]
Get Thread of the message
- Returns:
str: thread id
- property to: JID
Gets the jid of the receiver.
- Returns:
slixmpp.JID: jid of the receiver
spade.presence module
- class spade.presence.Contact(jid: JID, name: str, subscription: str, ask: str, groups: list)[source]
Bases:
object- get_presence(resource: Optional[str] = None) PresenceInfo[source]
- update_presence(resource: str, presence_info: PresenceInfo)[source]
- class spade.presence.PresenceInfo(presence_type: PresenceType, show: PresenceShow, status: Optional[str] = '', priority: int = 0)[source]
Bases:
object
- class spade.presence.PresenceManager(agent, approve_all: bool = False)[source]
Bases:
object- get_contact_presence(jid: Union[str, JID], resource: Optional[str] = None) PresenceInfo[source]
- get_presence() PresenceInfo[source]
- get_show() PresenceShow[source]
- on_available(peer_jid: str, presence_info: PresenceInfo, last_presence: Optional[PresenceInfo])[source]
- set_presence(presence_type: PresenceType = PresenceType.AVAILABLE, show: PresenceShow = PresenceShow.CHAT, status: Optional[str] = '', priority: int = 0)[source]
- class spade.presence.PresenceShow(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]
Bases:
Enum- AWAY = 'away'
- CHAT = 'chat'
- DND = 'dnd'
- EXTENDED_AWAY = 'xa'
- NONE = 'none'
- class spade.presence.PresenceType(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]
Bases:
Enum- AVAILABLE = 'available'
- ERROR = 'error'
- PROBE = 'probe'
- SUBSCRIBE = 'subscribe'
- SUBSCRIBED = 'subscribed'
- UNAVAILABLE = 'unavailable'
- UNSUBSCRIBE = 'unsubscribe'
- UNSUBSCRIBED = 'unsubscribed'
spade.template module
- class spade.template.ANDTemplate(expr1, expr2)[source]
Bases:
BaseTemplate
- class spade.template.NOTTemplate(expr)[source]
Bases:
BaseTemplate
- class spade.template.ORTemplate(expr1, expr2)[source]
Bases:
BaseTemplate
- class spade.template.Template(to: Optional[Union[str, JID]] = None, sender: Optional[Union[str, JID]] = None, body: Optional[str] = None, thread: Optional[str] = None, metadata: Optional[Dict[str, str]] = None)[source]
Bases:
BaseTemplate,MessageBaseTemplate for message matching
- class spade.template.XORTemplate(expr1, expr2)[source]
Bases:
BaseTemplate
spade.trace module
- class spade.trace.TraceStore(size: int)[source]
Bases:
objectStores and allows queries about events.
- all(limit: Optional[int] = None) List[Tuple[datetime, Message, Optional[str]]][source]
Returns all the events, until a limit if defined
- Args:
limit (int, optional): the max length of the events to return (Default value = None)
- Returns:
list: a list of events
- append(event: Message, category: Optional[str] = None) None[source]
Adds a new event to the trace store. The event may hava a category
- Args:
event (spade.message.Message): the event to be stored category (str, optional): a category to classify the event (Default value = None)
- filter(limit: Optional[int] = None, to: Optional[str] = None, category: Optional[str] = None) List[Tuple[datetime, Message, Optional[str]]][source]
Returns the events that match the filters
- Args:
limit (int, optional): the max length of the events to return (Default value = None) to (str, optional): only events that have been sent or received by ‘to’ (Default value = None) category (str, optional): only events belonging to the category (Default value = None)
- Returns:
list: a list of filtered events
- received(limit: Optional[int] = None) List[Tuple[datetime, Message, Optional[str]]][source]
Returns all the events that have been received (excluding sent events), until a limit if defined
- Args:
limit (int, optional): the max length of the events to return (Default value = None)
- Returns:
list: a list of received events
spade.web module
- class spade.web.WebApp(agent)[source]
Bases:
objectModule to handle agent’s web interface
- add_get(path: str, controller: Coroutine, template: str, raw: Optional[bool] = False) None[source]
Setup a route of type GET
- Args:
path (str): URL to listen to controller (coroutine): the coroutine to handle the request template (str): the template to render the response or None if it is a JSON response raw (bool): indicates if post-processing (jinja, json, etc) is needed or not
Adds a new entry to the menu.
- Args:
name (str): name of the entry url (str): url to be redirected to icon (str): icon to be displayed (Default value = “fa fa-circle”)
- add_post(path: str, controller: Coroutine, template: str, raw: Optional[bool] = False) None[source]
Setup a route of type POST
- Args:
path (str): URL to listen to controller (coroutine): the coroutine to handle the request template (str): the template to render the response or None if it is a JSON response raw (bool): indicates if post-processing (jinja, json, etc) is needed or not
- find_behaviour(behaviour_str: str) Optional[Type[CyclicBehaviour]][source]
- start(hostname: Optional[str] = None, port: Optional[int] = None, templates_path: Optional[str] = None)[source]
Starts the web interface.
- Args:
hostname (str, optional): host name to listen from. (Default value = None) port (int, optional): port to listen from. (Default value = None) templates_path (str, optional): path to look for templates. (Default value = None)
- async spade.web.start_server_in_loop(runner: AppRunner, hostname: str, port: int, agent)[source]
Listens to http requests and sends them to the webapp.
- Args:
runner (AppRunner): AppRunner to process the http requests hostname (str): host name to listen from. port (int): port to listen from. agent (spade.agent.Agent): agent that owns the web app.