Jade V

82
JADE JADE Java Agent Development Java Agent Development Framework Framework Jelena Jovanovic Email: [email protected]

description

 

Transcript of Jade V

Page 1: Jade V

JADEJADEJava Agent Development Java Agent Development

FrameworkFramework

Jelena Jovanovic

Email: [email protected]

Page 2: Jade V

204/07/23

JADE basicsJADE basics Software framework (middleware) for development

of multi-agent systems Based on FIPA standards for intelligent agents

FIPA – Foundation for Intelligent Physical Agents FIPA – Foundation for Intelligent Physical Agents (http://www.fipa.org)(http://www.fipa.org)

Fully coded in Java

Page 3: Jade V

304/07/23

JADE basicsJADE basics JADE consists of:

A runtime environment for agents Compliant with the FIPA standard for agent platforms

A library of Java classes that provide: ready-made pieces of functionality and abstract interfaces for custom, application dependent tasks.

A suite of graphical tools Facilitate administration and monitoring of running agents

Page 4: Jade V

404/07/23

JADE basicsJADE basics CONTAINERa running instance of the

JADE runtime environment

PLATFORMa set of active

containers

The main container of the platform; all other containers register with it as

soon as they start.

Page 5: Jade V

504/07/23

The FIPA compliant agent platformThe FIPA compliant agent platform

The agent platform can be split on several hosts. Each host acts as a containercontainer of agents

provides a complete run time environment for agent execution allows several agents to execute concurrently

each agent as a single Java Thread.

The first container started is the mainmain container maintains a central registry of all the other containers

=> agents can discover and interact with each other across the whole platform.

Page 6: Jade V

604/07/23

The FIPA compliant agent platformThe FIPA compliant agent platform Agent Management System (AMS)

The principle authority in the platform Keeps track of all other agents in the platform Only one AMS will exist in a single platform The AMS maintains a directory of agents’ identifiers

(AIDs) and agents’ states. Each agent must register with the AMS in order to get a valid

(i.e. unique) AID.

Page 7: Jade V

704/07/23

The FIPA compliant agent platformThe FIPA compliant agent platform Directory Facilitator (DF)

the agent that provides the default ‘yellow page’ service in the platform.

it publishes services of other registered agents from the platform, thus facilitating agents cooperation.

Message Transport System also called Agent Communication Channel (ACC), software component controlling all exchange of

messages within the platform, including messages to/from remote platforms.

Page 8: Jade V

804/07/23

Creating an agent in JADECreating an agent in JADE …is as simple as extending the jade.core.Agent class

- a common base class for user defined agents; jade.core.Agent class encompasses:

a basic set of methods that can be called to implement the custom behaviour of an agent (e.g. send/receive messages, use standard interaction protocols,…).

Each functionality/service provided by an agent should be implemented as one or more behavioursbehaviours that are executed concurrently.

Page 9: Jade V

904/07/23

Agent identifier - AIDAgent identifier - AID Each agent has a unique ID – AID AID is an instance of the jade.core.AID class An AID object includes:

a globally unique name of an agent in the form: <nickname>@<platform-name>

a number of addresses these are the addresses of the platform the agent lives in only used when an agent needs to communicate with another

agent living on a different platform.

Page 10: Jade V

1004/07/23

HelloWorldAgentHelloWorldAgent

import jade.core.Agent;

public class HelloWorldAgent extends Agent { protected void setup() {

System.out.println(“Hello World!”); System.out.println(“My name is ” + getAID().getName() );

}}

Page 11: Jade V

1104/07/23

Running an agentRunning an agent Agents can not be executed directly; they must execute

within a larger program which provides the necessary services – JADE runtime environment.

To run your agent you have to: compile it:

javac –classpath <JADE-jars> HelloWorldAgent.java

start it from JADE runtime environment:java –classpath <JADE-jars> jade.Boot fred:HelloWorldAgent

Page 12: Jade V

1204/07/23

Running an agentRunning an agent Alternatively, you can set up CLASSPATH variable:

;.;c:\jade\lib\jade.jar;c:\jade\lib\jadeTools.jar;…

and then run the example with:java jade.Boot fred:HelloWorldAgent

or create a batch file (e.g., helloworld.bat):java -classpath <jade-jars> jade.Boot

fred:HelloWorldAgent

inside jade directory and run it

Page 13: Jade V

1304/07/23

Running an agentRunning an agent The best alternative is to use EJIP – Eclipse

JADE Integration Plugin http://www.mars-team.com/ejip/ simply run your agents from your development

environment requirements:

JDK 1.4.2 (at least) Eclipse 3.2

Page 14: Jade V

1404/07/23

HelloWorldAgentHelloWorldAgent Note that our agent is still running! If we want to stop it we have to tell it

explicitly by executing its doDelete() method.

Let’s learn more about an agent’s lifecycle

Page 15: Jade V

1504/07/23

Agent life cycleAgent life cycle a JADE agent can be in one of several states, according to

Agent Platform Life Cycle specification provided by FIPA

Page 16: Jade V

1604/07/23

Agent life cycleAgent life cycle InitiatedInitiated - an Agent object is built, but hasn't registered

itself yet with the AMS, has neither a name, nor an address and cannot communicate with other agents.

ActiveActive – the Agent object is registered with the AMS, has a regular name and an address and can access all the various JADE features. an agent is allowed to execute its behaviours (i.e. its tasks)

only in this state. SuspendedSuspended – the Agent object is currently stopped; no

agent behaviour is being executed. WaitingWaiting – the Agent object is blocked, waiting for

something; it is ‘sleeping’ and will wake up when a condition is met (typically when a message arrives).

Page 17: Jade V

1704/07/23

Agent life cycleAgent life cycle UnknownUnknown – the Agent is definitely dead; it is no more

registered with the AMS. TransitTransit – a mobile agent enters this state while it is

migrating to the new location. The system continues to buffer messages that will then be sent to its new location.

The Agent class contains: constants for representing agent’s possible states (e.g. AP_ACTIVE, AP_WAITING)

public methods to perform transitions between the various states (e.g. doWait(), doSuspend()).

Page 18: Jade V

1804/07/23

Starting an agentStarting an agent

Includes the following steps: 1. The agent constructor is executed, 2. the agent is given an identifier (instance of

jade.core.AID class) 3. it is registered with the AMS, 4. it is put in the AP_ACTIVE state, and finally5. the setup() method is executed.

The programmer has to implement the setup() method in order to initialize the agent.

Page 19: Jade V

1904/07/23

Starting an agentStarting an agent The most important (also obligatory) thing to do

when initializing an agent (i.e. in its setup() method) is to add tasks (so called behaviours) to the queue of tasks to be executed The setup() method should add at least one task to the

agent.

After initialization, JADE automatically executes the first task from the agent’s queue of ready tasks agents tasks (forming a queue of ready tasks) are

executed according to the round-robin non-preemptive strategy - this will be discussed later in more details.

Page 20: Jade V

2004/07/23

The notion of behaviourThe notion of behaviour Agents operate independently and execute in parallel with

other agents.

The obvious way to implement this is to assign a java Thread to each agent - and this is how it is done in Jade.

However, there is a need for further parallelism within each agent because an agent may be involved in different tasks.

Possible solution: to use additional Threads to handle each concurrent agent activity;

Page 21: Jade V

2104/07/23

The notion of behaviourThe notion of behaviour

To support efficiently parallel activities within an agent, Jade has introduced a concept called BehaviourBehaviour

A behaviour is basically an Event Handler – it describes how an agent reacts to an event. an event is a relevant change of state

e.g. a reception of a message or a Timer interrupt (after the specified time has elapsed).

Page 22: Jade V

2204/07/23

Implementing a behaviourImplementing a behaviour

A behaviour is implemented as an object of a class that extends jade.core.behaviours.Behaviour.

Each class extending Behaviour must implement: the action() method – defines the operations to be

performed when the behaviour is in execution the done() method – specifies whether or not a

behaviour has completed, through the boolean value it returns

Page 23: Jade V

2304/07/23

Implementing a behaviourImplementing a behaviour

To implement an agent-specific task one should: define one or more Behaviour subclasses, add the behaviour objects to the agent’s task list

using addBehaviour(Behaviour)method

Page 24: Jade V

2404/07/23

The agent execution modelThe agent execution model

Page 25: Jade V

2504/07/23

A more realistic HelloWorld AgentA more realistic HelloWorld Agent

We have just learned that: Agent actions are normally specified through Behaviour

classes, i.e. in the action() method of these behaviours. The setup method only serves to create instances of these

behaviours and link them to the Agent object.

A more typical implementation of the HelloWorldAgent would be:

Page 26: Jade V

2604/07/23

A more realistic HelloWorld AgentA more realistic HelloWorld Agentimport jade.core.Agent; import jade.core.behaviours.*;

public class HelloWorldAgent1 extends Agent { protected void setup() {

addBehaviour( new B1( this ) ); } } class B1 extends SimpleBehaviour { public B1(Agent a) { super(a); } public void action() {

System.out.println( "Hello World! My name is " +

myAgent.getAID().getName() ); finished = true;

} private boolean finished = false; public boolean done() { return finished; } }

Page 27: Jade V

2704/07/23

A more realistic HelloWorld AgentA more realistic HelloWorld Agent The example shows some new things:

myAgent: a local variable of all Behaviour objects which stores the agent reference passed as a parameter when the behaviour was created.

SimpleBehaviour - the most flexible JADE's predefined behaviour.

Behaviour class can be specified as an internal class to the Agent; an anonymous class a separate class in the same or a separate file.

In all cases, it is usual to pass a reference to the owner agent (this) when creating a Behaviour.

Page 28: Jade V

2804/07/23

A more realistic HelloWorld AgentA more realistic HelloWorld Agent The example shows some new things:

even if the behaviour finishes the program does NOT terminate because:

the agent still exists, the JADE environment which we started stays

around to interact with other agents which could be started later in the network.

Page 29: Jade V

2904/07/23

Back to behavioursBack to behaviours A Behaviour can be added whenever it is needed,

and not only within Agent.setup() method. JADE uses a schedulerscheduler to activate behaviours

implemented by the Agent class and hidden to the programmer,

carries out a round-robin non-preemptive scheduling policy among all behaviours available in the ready queue

executes each behaviour until it releases control

Page 30: Jade V

3004/07/23

BehavioursBehaviours Because of the non-preemptive multitasking

model, programmers must avoid using: endless loops and long operations within the action() method of a

behaviour.

Remember! when the action() method of one behaviour is running,

no other behaviour can execute until the running one is finished.

Page 31: Jade V

3104/07/23

BehavioursBehaviours Every single Behaviour is allowed to block its

computation using the block method. Warning: block(milisec) does not block execution

of the behaviour; it just delaysdelays its nextnext execution. All blocked behaviours are rescheduled as soon as:

a new message arrives the programmer must take care of blocking again a behaviour

if it was not interested in the arrived message. the agent is restarted.

Page 32: Jade V

3204/07/23

BehavioursBehaviours The framework provides ready to use complex

behaviours that contain sub-behaviours and execute them according to some policy. These are provided as subclasess of the Behaviour class For example, the SequentialBehaviour class executes its

sub-behaviours one after the other.

UML Model of the Behaviour class hierarchy:

Page 33: Jade V

3304/07/23

Page 34: Jade V

3404/07/23

Primitive BehavioursPrimitive Behaviours CyclicBehaviour:

stays active as long as its agent is alive and is called repeatedly after every event.

Quite useful to handle message reception. jade.core.behaviours.CyclicBehaviour class

OneShotBehaviour: executes ONCE and dies; Not really that useful since the one shot may be

triggered at the wrong time; jade.core.behaviours.OneShotBehaviour class

Page 35: Jade V

3504/07/23

Primitive BehavioursPrimitive Behaviours WakerBehaviour:

executes the user code after a given timeout expires The user code is given in the handleElapsedTimeout() method The timeout is set in the constructor

TickerBehaviour: cyclic behaviour which executes the user-defined piece of code

repetitively waiting a given time period after each execution. The user code is given in the onTick() method The time period is specified in the constructor

ReceiverBehaviour: triggers when a given type of message is received (or a timeout

expires).

Page 36: Jade V

3604/07/23

Composite BehavioursComposite Behaviours ParallelBehaviour:

controls a set of child behaviours that execute in parallel. the important thing is the termination condition: we can specify

that the group terminates when: ALL children are done, N children are done or ANY child is done.

behaviours added directly to an Agent operate in parallel by default.

SequentialBehaviour: executes its child behaviours one after the other and terminates

when the last child has ended.

Page 37: Jade V

3704/07/23

Agent communicationAgent communication A fundamental characteristic of multi-agent systems is that

individual agents communicate and interact. According to the FIPA specification, agents communicate

via asynchronous messages. Each agent has a sort of mailbox (the agent message

queue) where the JADE runtime posts messages sent by other agents. Whenever a message is added to the message queue the receiving

agent is notified as gmail notifies you when a new email arrives.

If and when the agent actually picks up the message from the message queue to process, it is completely up to the programmer

as it is up to you whether you will read a received email

Page 38: Jade V

3804/07/23

Agent communicationAgent communication

Page 39: Jade V

3904/07/23

Agent communicationAgent communication The Agent class provides a set of methods for

inter-agent communication. Method calls are completely transparent to

where the agent resides the platform takes care of selecting the appropriate

address and transport mechanism.

Page 40: Jade V

4004/07/23

Agent communicationAgent communication To understand each other, it is crucial that agents agree

on the format and the semantics of the messages they exchange.

In JADE, messages adhere strictly to the ACL (Agent Communication Language) FIPA standard.

A message is an instance of the jade.acl.ACLMessage class

Example: The simplest message

ACLMessage msg = new ACLMessage( ACLMessage.INFORM );msg.setContent("I sell seashells at $10/kg" );

Page 41: Jade V

4104/07/23

Agent communicationAgent communication An ACL message contains:

The sender of the message (initialized automatically) The list of receivers The communicative intention (“performative”) indicating

what the sender intends Uses the restricted vocabulary of the FIPA defined set of

message types The content – the actual information included in the

message The content language – the syntax used to express the

content The ontology i.e. the vocabulary of the symbols used in

the content and their meaning

Page 42: Jade V

4204/07/23

Agent communicationAgent communication An ACL message contains – cont.:

ConversationID - used to link messages in same conversation

InReplyTo - sender uses to help distinguish answers ReplyWith - another field to help distinguish answers ReplyBy - used to set a time limit on an answer

All these properties can be accessed via the set/get<Property>() methods of the ACLMessage class.

Page 43: Jade V

4304/07/23

Agent communicationAgent communication FIPA defined performatives:

INFORM whereby one agent gives another some useful information – the most common

QUERY to ask a question, QUERY_IF if the sender wants to know whether or not a

given condition holds REQUEST to ask the other to do something CFP to call for proposals PROPOSE to start bargaining. Performatives for answers include:

AGREE REFUSE.

Page 44: Jade V

4404/07/23

Agent communicationAgent communication An agent willing to send a message should:

create a new ACLMessage object, fill its attributes with appropriate values, call the agent’s send()method…String receiver = …ACLMessage msg = new ACLMessage(ACLMessage.INFORM);msg.addReceiver(new AID(receiver));msg.setContent("FirstInform");send(msg);…

An alternative: adding an instance of the SenderBehaviour to the agent’s queue of tasks.

Page 45: Jade V

4504/07/23

Inter-agent communicationInter-agent communication The platform puts all the messages received by an agent

into the agent’s private queue (mailbox). The message queue can be accessed in:

a blocking way (using blockingReceive() method) - causes the suspensionحرمان of all the agent’s behaviours;

a non-blocking way (using receive() method) - returns immediately null if the requested message is not present in the queue.

The blocking access can have a timeout parameter representing the maximum number of milliseconds that the agent’s activity should remain blocked waiting for the requested message.

Page 46: Jade V

4604/07/23

Agent communicationAgent communication An agent willing to receive a message should call:

Agent.blockingReceive()ACLMessage msg = blockingReceive();

or Agent.receive()

… ACLMessage msg = receive();

if (msg!=null)System.out.println( " - “ + myAgent.getLocalName() + " <- " + msg.getContent() );elseblock(); …

An alternative: adding an instance of the ReceiverBehaviour to the agent queue of tasks.

Page 47: Jade V

4704/07/23

Agent communicationAgent communication

public class Receiver extends Agent {protected void setup() {

addBehaviour(new CyclicBehaviour(this) {public void action() {

ACLMessage msg = receive();if (msg!=null) System.out.println( " - " + myAgent.getLocalName() + " <- " + msg.getContent() );

block(); }});

}}

Example: a simple receiver agent

Page 48: Jade V

4804/07/23

Agent communicationAgent communication Note the use of block() without a timeout

This puts the behaviour on hold until the next message is received

When a message arrives all behaviours are activated and their action methods called one after the other.

It doesn’t matter whether other behaviours were waiting for messages or the passage of time ( with block(dt) )

If you don't call block(), your behaviour will stay active and cause a LOOP.

Page 49: Jade V

4904/07/23

Agent communicationAgent communication Answering a message:

To simplify answering, Jade provides a method createReply() which creates a reply message with all necessary attributes set correctly.…ACLMessage msg = receive();if (msg!=null) {…ACLMessage reply = msg.createReply();reply.setPerformative( ACLMessage.INFORM );reply.setContent(“Hi!Nice hearing from you!" );reply.send();}block();…

Note: in this example, there isn't much advantage of using createReply, the real benefits become obvious in applications when other attributes like conversationID or ontology have to correspond to the original message.

Page 50: Jade V

5004/07/23

Agent communicationAgent communication Often it is useful to filter messages and set up distinct

behaviours to handle messages from various agents or various kinds of messages.

To enable this, Jade provides Message Templates and a receive method which takes a template as a parameter and only returns messages matching that template.

The MessageTemplate class provides static methods to create filters for each attribute of the ACLMessage: MatchPerformative(performative)

ACLMessage.INFORM, ACLMessage.REQUEST, … MatchSender( AID ) MatchConversationID( String ) … An additional set of methods allow elementary patterns to be

combined with AND, OR and NOT operators.

Page 51: Jade V

5104/07/23

Agent communicationAgent communication Message Templates example:

MessageTemplate m1 =MessageTemplate.MatchPerformative(ACLMessage.INFORM);

MessageTemplate m2 =MessageTemplate.MatchLanguage("PlainText");

MessageTemplate m3 =MessageTemplate.MatchSender( new AID( "a", AID.ISLOCALNAME));

MessageTemplate m1andm2 = MessageTemplate.and(m1,m2);MessageTemplate notm3 = MessageTemplate.not(m3);MessageTemplate m1andm2_and_notm3 =MessageTemplate.and(m1andm2, notm3);

Page 52: Jade V

5204/07/23

Agent communicationAgent communication Tip:

when your agent should have parallel negotiations with several other agents, you should:

create a unique string (the ConversationID) to uniquely identify messages that your agent exchanges with each one of his collaborative agents.

Then you set-up a behaviour for each negotiation which only responds to messages with that particular ConversationID.

You use a Message Template to filter messages from the agent’s messages queue

Page 53: Jade V

5304/07/23

Agent communicationAgent communication

Finding agents to talk toDifferent ways to get an agent ID:

using the agent's local name (e.g. the one specified on the command line when starting a container),

using JADE's GUI interface, from a directory entry in the DF, from the AMS

keeps AIDs of all active agents

Page 54: Jade V

5404/07/23

Agent communicationAgent communication Finding an agent using its local name

Suppose that an agent container with two agents was started:

jade.Boot fred:BuyerAgent store:SellerAgent

Part of the BuyerAgent implementation:…ACLMessage msg = new ACLMessage(ACLMessage.INFORM);msg.setContent( "bla...bla...bla" );msg.addReceiver( new AID( "store", AID.ISLOCALNAME)new AID( "store", AID.ISLOCALNAME) );send(msg);…

Page 55: Jade V

5504/07/23

Agent communicationAgent communication Finding agents by searching the AMS:

import jade.domain.AMSService;import jade.domain.FIPAAgentManagement.*;...AMSAgentDescription [] agents = null;try {SearchConstraints c = new SearchConstraints();c.setMaxResults ( new Long(-1) ); //-1 means ALL

agents = AMSService.search( this, new AMSAgentDescription (), c );

}catch (Exception e) { ... }

To extract the AID from a descriptor we have to use something like agents[i].getName()

the searching

agent

A description of the agent(s) we are looking for

Page 56: Jade V

5604/07/23

Agent communicationAgent communication Example: saying hello to all other agents

AID myID = getAID();ACLMessage msg = new ACLMessage(ACLMessage.INFORM);msg.setContent( “Hello!" );for (int i=0; i<agents.length; i++) {

AID agentID = agents[i].getName();If ( !agentID.equals( myID ) )

msg.addReceiver( agents[i].getName() );}send(msg);… All currently running agents found by using the

code snippet from the previous slide

Page 57: Jade V

5704/07/23

Directory Facilitator (DF)Directory Facilitator (DF) DF is often compared to the "Yellow Pages"

phone book: Agents wishing to advertise their services register

with the DF. Visiting agents can then search the DF looking for

other agents which provide the services they desire. More formally: DF is a centralized registry of

entries which associate service descriptions to agent IDs.

Page 58: Jade V

5804/07/23

Directory Facilitator (DF)Directory Facilitator (DF) DFAgentDescription (DFD) class

used both for adding an entry and searching for services. A DF entry i.e. an instance of DFD class should contain:

The agent’s IDThe agent’s ID, A set of ontologies, protocols and languages supported by the

agent, A set of services the agent provides, i.e. descriptions of those

services

A service description (ServiceDescription) includes: the service typethe service type, the service namethe service name, the languages and ontologies required to exploit that service, a number of service specific properties.

Page 59: Jade V

5904/07/23

DFAgentDescription ClassDFAgentDescription ClassDFAgentDescriptionDFAgentDescription Name: AID // Name: AID // RequiredRequired for registration for registration ProtocolsProtocols: set of Strings : set of Strings OntologiesOntologies: set of Strings : set of Strings LanguagesLanguages: set of Strings : set of Strings ServicesServices: set of { : set of { { Name: String // { Name: String // RequiredRequired for each service specified for each service specified Type: String // Type: String // RequiredRequired ... ... Owner: String Owner: String ProtocolsProtocols: set of Strings : set of Strings OntologiesOntologies: set of Strings : set of Strings LanguagesLanguages: set of Strings : set of Strings PropertiesProperties: set of { : set of { Name: String Name: String Value: StringValue: String }} }}

Page 60: Jade V

6004/07/23

Registering with DFRegistering with DFimport jade.domain.DFService;import jade.domain.FIPAAgentManagement.*;import jade.domain.FIPAException;....DFAgentDescription dfd = new DFAgentDescription();dfd.setName( getAID() );ServiceDescription sd = new ServiceDescription();sd.setType( "buyer" );sd.setName( “online trade” );dfd.addServices(sd);try {

DFService.register(this, dfd );DFService.register(this, dfd );}catch (FIPAException fe) { fe.printStackTrace(); }

Page 61: Jade V

6104/07/23

DeregisteringDeregistering When an agent terminates, it is good practice to delete its entry

from the DF, since the system does not remove it automatically. They are automatically removed only from the AMS

Each agent is allowed only ONE entry in the DF. An attempt to register an agent already present in the DF throws an

Exception. Deregistration is usually done in takeDown() method which is

called automatically when the agent dies.

protected void takeDown(){try { DFService.deregister(this); }catch (FIPAException e) {}

}

Page 62: Jade V

6204/07/23

Searching the DFSearching the DF Purpose: Finding an agent with the specified

properties. To find an agent using the DF:

create a DFD (with no AID) where the relevant fields are initialized to the properties you require.

extract the ID of the suitable agents from the results set The search returns an array of DFDs (with AIDs) whose

attributes match your description.

Page 63: Jade V

6304/07/23

Searching the DFSearching the DF

Example: searching for agents of the type ‘buyer’

DFAgentDescription dfd = new DFAgentDescription();ServiceDescription sd = new ServiceDescription();sd.setType( "buyer" );dfd.addServices(sd);DFAgentDescription[] result = DFAgentDescription[] result =

DFService.search(this,dfd);DFService.search(this,dfd);System.out.println(“Buyer agets:”);for (int i = 0; i < result.length; ++i) { System.out.println(" " + result[i].getName() );}

Page 64: Jade V

6404/07/23

Searching the DFSearching the DF By default, the search returns an array which is either empty

or contains a single DFD. To get entries for all agents with specified properties, a third

parameter of the searchConstraints type must be added:

To get any available agent, just use a bare DFD with no service specification

…SearchConstraints all = new SearchConstraints();all.setMaxResults(new Long(-1));DFAgentDescription[] result =

DFService.search(this, dfd, all);

Page 65: Jade V

6504/07/23

DF Subscription ServicesDF Subscription Services It is possible for an agent to ask the DF to send it a

message whenever an agent of a given type registers.

DFAgentDescription dfd = new DFAgentDescription();ServiceDescription sd = new ServiceDescription();sd.setType(....);dfd.addServices(sd);SearchConstraints sc = new SearchConstraints();sc.setMaxResults(new Long(1));send(DFService.createSubscriptionMessage(this, getDefaultDF(),dfd, sc));

The DF will then send an INFORM message to the subscribed agent whenever an agent matching the supplied description registers.

Page 66: Jade V

6604/07/23

Mobile AgentsMobile Agents Agent mobility is the ability of an agent program

to migrate or to make a copy (clone) of itself across one or multiple network hosts.

The current version of JADE supports only intra-platform mobility, i.e. an agent can move only within the same platform from one container to the others.

The Agent class contains a set of methods dedicated for managing agent mobility.

Page 67: Jade V

6704/07/23

Mobile AgentsMobile Agents A typical behaviour pattern for a JADE mobile

agent will be to ask the AMS for locations and then decide if, where and when to migrate.

To move an agent, one just need to call the method doMove(Location) whose parameter is the new destination of the agent.

To get a Location object, one must query this information with the AMS, by sending it a REQUEST with either WhereIsAgentAction or QueryPlatformLocationsAction

Page 68: Jade V

6804/07/23

Finding destinationFinding destination

WhereIsAgentAction aimed for obtaining location of the agent whose identifier

(AID) is passed as a parameter. QueryPlatformLocationsAction

aimed for obtaining all available locations within the given platform (takes no parameters).

Action action = new Action();Action action = new Action();action.setActor(a.getAMS());action.setActor(a.getAMS());action.setAction(new QueryPlatformLocationsAction());action.setAction(new QueryPlatformLocationsAction());sendRequest(action);sendRequest(action);

Page 69: Jade V

6904/07/23

Finding destinationFinding destination Receiving response from the AMS

Suspend all activities until Suspend all activities until the message arrivesthe message arrives

Page 70: Jade V

7004/07/23

Moving an agentMoving an agent To make an agent move to a certain location

another agent has to: create a new MoveAction object

and fill its argument with a suitable MobileAgentDescription object,

create a request ACL messagerequest ACL message and set the MoveAction object as its content

call the Agent.getContentManager().fillContent(…) method that turns the MoveAction object into a String and writes it into the content slot of the request.

send the message to the agent that is supposed to move

Page 71: Jade V

7104/07/23

Moving an agentMoving an agent

A utility method containing a call to the Agent.getContentManager().fillContent(…)

Page 72: Jade V

7204/07/23

Moving an agentMoving an agent When the other agent receives this message it:

extracts the information about the destination to move to calls its method doMove(Location) to start the moving

process.ACLMessage msg = receive(…);if (msg.getPerformative() == ACLMessage.REQUEST) {

ContentElement content = getContentManager().extractContent(msg);Concept concept = ((Action)content).getAction();

MoveAction ma = (MoveAction)concept;Location loc = ma.getMobileAgentDescription().getDestination();if (loc != null) doMove(loc);

}

Page 73: Jade V

7304/07/23

Moving an agentMoving an agent To be able to use these objects, the SLCodec

language and the MobilityOntology must be registered with the agents content manager. This is simple as inserting the following two lines of

code in the agent’s setup() method

getContentManager().registerLanguage(new SLCodec()); getContentManager().registerOntology(MobilityOntology.

getInstance());

Page 74: Jade V

7404/07/23

Cloning an agentCloning an agent Cloning an agent is very similar to moving an agent:

instead of using a MoveAction object as content of the REQUEST to the interested agent, a CloneAction object should be used.Location dest = …AgentID aid = …MobileAgentDescription mad = new

MobileAgentDescription(); mad.setName(aid); mad.setDestination(dest); String newName = "Clone-" + agentName; CloneAction ca = new CloneAction();ca.setNewName(newName);ca.setMobileAgentDescription(mad); sendRequest(new Action(aid, ca));

Page 75: Jade V

7504/07/23

Cloning an agentCloning an agent when the agent receives the message it just calls its method

doClone(Location, String) which takes as parameters: the location where the cloned agent will start and its new name which must be different from the original agent's name.

ACLMessage msg = receive(…); if (msg.getPerformative() == ACLMessage.REQUEST) {

ContentElement content = getContentManager().extractContent(msg);Concept concept = ((Action)content).getAction();

CloneAction ca = (CloneAction)concept;String newName = ca.getNewName();Location loc = ca.getMobileAgentDescription().getDestination();if (loc != null)

doClone(loc, newName);}

Page 76: Jade V

7604/07/23

Agents with GUIAgents with GUI To build an agent with integrated GUI, one should extend

the JADE’s GuiAgent class. This class has two specific methods: postGuiEvent() and

onGuiEvent(), aimed for handling interactions between an agent and its GUI: GUI informs the agent about the user actions by posting events

through the postGuiEvent() method. onGuiEvent() method contains code for receiving and processing

events posted by the GUI (via postGuiEvent() method).

Page 77: Jade V

7704/07/23

Agents with GUIAgents with GUI

The onGuiEvent() method may be viewed as the equivalent of the actionPerformed() method in Java Swing.

To post an event to the agent, the GUI simply creates a jade.gui.GuiEvent object and passes it as an argument to the postGuiEvent()method.

A GuiEvent object has: two mandatory attributes:

the source of the event and an integer identifying the type of event

an optional list of parameters that can be added to the event object.

Page 78: Jade V

7804/07/23

Agents with GUIAgents with GUI

public class ControllerAgent extends GuiAgent {…protected ControllerAgentGui myGui; …protected void onGuiEvent(GuiEvent ev)protected void onGuiEvent(GuiEvent ev) {

command = ev.getType()ev.getType(); if (command == NEW_AGENT) { … }if (command == MOVE_AGENT) {

String agentName = (String)ev.getParameter(0)ev.getParameter(0);String destName = (String)ev.getParameter(1)ev.getParameter(1); …

} }…}

Page 79: Jade V

7904/07/23

JADE’s suite of graphical toolsJADE’s suite of graphical tools IntrospectorAgent

A tool useful for monitoring a running agent: the life cycle of the agent, ACL messages it exchanges with other agents and the agent’s behaviours in execution.

Dummy Agent a monitoring and debugging tool, use it for:

composing and sending ACL messages to other agents, viewing the list of all the ACL messages sent or received,

completed with timestamp information.

Page 80: Jade V

8004/07/23

JADE’s suite of graphical toolsJADE’s suite of graphical tools

Sniffer An agent that can intercept ACL messages while they

are in flight, and display them graphically notation similar to UML sequence diagrams

Useful for observing how collaborating agents exchange ACL messages.

Page 81: Jade V

8104/07/23

Jade Resources at WWWJade Resources at WWW Jade Official Web Site:

http://jade.cselt.it Jade Primer:

http://www.iro.umontreal.ca/~vaucher/Agents/Jade/JadePrimer.html

FIPAhttp://www.fipa.org

Page 82: Jade V

JADEJADEJava Agent Development Java Agent Development

FrameworkFramework

Jelena Jovanovic

Email: [email protected]