Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

MENOUFIA UNIVERSITY ‫جامعة المنوفية‬

FACULTY OF COMPUTERS ‫كلية الحاسبات والمعلومات‬


AND INFORMATION
ALL DEPARTMENTS ‫جامعة المنوفية‬ ‫جميع األقسام‬
ARTIFICIAL INTELLIGENCE ‫الذكاء اإلصطناعي‬

JADE Java Agent DEvelopment Framework as Part


of Artificial Intelligence Course

By

Ahmed Fawzy Gad


Faculty of Computers and Information (FCI)
Menoufia University
Egypt
ahmed.fawzy@ci.menofia.edu.eg
JADE Framework Syllabus
Week 1
 Agent-Oriented Programming (AOP).
 What is agent?
 Agent properties.
 Agents Frameworks.
 JADE (Java Agent DEvelopment framework)
o Brief History.
o Documentation.
o Architecture.
 Main Container
o Special Characteristics.
o Special Responsibilities
 CT (Container Table).
 GADT (Global Agent Descriptor Table).
 AMS (Agent Management System).
 DF (Directory Facilitator).
o Drawbacks
 System Bottleneck
 LADT (Local Agent Descriptor Table)
o Example.
 GADT Cache
o Example.
 Dynamic System
 System Single Point of Failure.
 Multiple Main Containers
 Downloading JADE
o Important JADE Files
 Preparing JADE Environment
o CLASSPATH Environment Variable
 GUI
 CMD
 classpath Option
 Running JADE for the First Time
 JADE GUI Overview
o Review about Computer Networks
 OSI Reference Model
 Transport Layer
o JADE Network Overview
 JADE Agent GUID
 JADE Agents Connections

Week 2
 Programming with JADE
 JADE Basic Services
 Preparing Java IDE (NetBeans)
o Add JADE to IDE
 Running JADE from NetBeans
o External Java Code
o Main Class Application Property
 Creating JADE Agent
o jade.core Package
 Agent Class
o Overriding setup()
 Add Agent to the JADE Environment
o Via GUI
o Via CMD
 Agent Identifiers
 Agent Termination
 Agent Behaviors
o Creating Agent Behaviors
 Behavior Abstract Class
o Adding Behaviors to Agent
o JADE Behavior Scheduling
 JADE Agent Communication
o JADE Message Passing Overview
o JADE ACL Overview
 Sending Message
 Receiving Message
o Tips on Message Receiving
 Which type of behavior to use?
 What is the order of adding agents to the JADE environment?
 Adding Two Agents via CMD
****Week 1****
Agent-Oriented Programming (AOP) Paradigm
Agent-Oriented Programming (AOP) is a programming paradigm that is based on some theoretical
concepts in artificial intelligence. AOP paradigm is different from the known paradigms like
sequential, procedural, OOP, and more.
The main concept that AOP uses is the concept of agents. AOP creates applications that are a
collection of components called software agents.
AOP has some differences from the previously used programming paradigms like Object-Oriented
Programming (OOP).
In OOP, the application were based on some components called objects. Each object has its own
data and behavior and the object was completely controlled by the programmer. The
programmer decides when an object is created, what the object can do, when the object can do
a given behavior, when to interact with other objects and how, and so on.
Agents in AOP has a degree of autonomy. They can know the when to do a given behavior and
how and when to interact with other agents without external interaction.

Note:
Programming paradigm is a way or style of programming. Some languages are adopted to work
in some paradigms.
Some of the known programming paradigms are:
 Imperative.
 Declarative.
 Structured.
 Procedural.
 Object-Oriented.
 Event-Driven.
 Logic.
One language may support multiple programming paradigms and called multi-paradigm
languages.

What is agent?
An agent or specifically a software agent is a term has its roots in AI and means a software entity
that can do intelligent actions continuously and autonomously on behalf of the user in an
environment in which other agents exist.
The goal of creating an agent is to work on behalf of the user. So as much as the user can work
the agent should be. Because the user can make decisions and do intelligent actions, the agent
should also make decisions and do intelligent actions. The user can adapt with its environment
easily even after changing it, so also the agent should adapt with its environment.
[[EXPLAIN THE MEANING OF ENVIRONMENT BY EXAMPLE]]
There are other characteristics that should be found in the agent to be efficient to work on behalf
of the user.
Software agents should have a number of properties like:
 Mobile: Agents in general should be mobile and move from its location to other locations
in its environment. Software agents can exchange data with the other nodes in its
environment or network.
 Autonomous: Agents can independently do tasks.
 Rational: Agents should know how to think and know how to achieve their tasks in the
right way.
 Reactive: Agents monitors their environment and respond to changes that occur in the
environment.
 Proactive: Agents don`t act only in responding to their environment but can be initiative.
 Social: Agents can cooperate with humans and other agents in order to achieve tasks.
Agents should know about other agents in its environment and their capabilities and how
to negotiate with them.
 Self-learning: Agents can learn from the surrounded environment to improve themselves
and adapt to the environment.

Multi-Agent System (MAS)


A multi-agent system is a system that consists of a number of agents working on behalf of the
user that can interact and cooperate with each other to complete tasks as much as people do.

Agent Frameworks
A software agent can live within its environment and can`t live outside it. The environment that
hosts the agents is called an agent framework.
Examples of agent frameworks:
 JACK.
 Agent Factory.
 Agent Builder.
 JADE.
 IMPACT.
 ZEUS.

The framework used in the course for developing software agents is JADE.

JADE

JADE Brief History


JADE stands for Java Agent DEvelopment framework is a framework for developing multi-agent
systems. JADE is one of the most popular multi-agent frameworks if not being the most popular.
JADE is completely developed using Java.
 JADE development started in 1998 by Telecom Italia LAB (TILAB).
 The first open source JADE version was released in 2000.
 In May 2003 Telecom Italia Lab and Motorola Inc. made a collaboration agreement for
better industrial involvement for JADE.

JADE Documentation
 JADE Book: Bellifemine, Fabio Luigi, Giovanni Caire, and Dominic Greenwood. Developing
multi-agent systems with JADE. Vol. 7. John Wiley & Sons, 2007.
 JADE Website:
o http://jade.tilab.com/
o http://jade.tilab.com/doc/tutorials/JADEProgramming-Tutorial-for-
beginners.pdf

JADE Architecture
JADE is used to create a runtime environment where agents can live. The JADE runtime
environment is called a Container. JADE Container is called so because it can contain multiple
agents.
The JADE Container is a Java process that provides all services for hosting and executing agents
inside the JADE Container.
JADE >> Runtime Environment >> Container >> Java Process
The following figure represents the main architectural elements in JADE and the relationship
among them.

JADE can have multiple containers as shown in the figure. For sure each container will have its
agents. The set of all active containers is called a Platform.
But there is a special JADE Container called the Main Container. The platform can have only one
Main Container which is regarded the default JADE Container. The JADE Main Container is the first
container to be launched.

JADE Main Container Special Characteristics


The JADE Main Container has some special characteristics compared to other Containers:
 It is the first container to be launched.
 It is the entry point to creating JADE agents.
 Other JADE Containers must register themselves in the JADE Main Container.
 All JADE agents must register themselves in the JADE Main Container.
 JADE Main Container has two special agents called DF and AMS.
JADE Main Container Special Responsibilities
JADE Main Container has some special responsibilities:
 Managing the Container Table (CT): The CT is the registry of the other JADE Containers.
 Managing the Global Agent Descriptor Table (GADT): The GADT is the registry for all
agents in any JADE Container holding information about agent's status and location.
 Hosting the Agent Management System (AMS): The AMS is a special JADE agent that is
responsible for providing the following services:
o White Pages service (i.e. naming service): This service assigns each agent a
globally unique name called Agent Identifier (AID).
o Agent authorization service: This service provided by AMS assigns the agents the
authorizations they need to function like creating or killing other agents.
 Hosting the Directory Facilitator (DF): The DF is a special agent that is responsible for
providing the following services:
o Yellow Pages service: it allows agents to publish description about one or more
services they provide to allow other agents to discover the use these services.

JADE Main Container Drawbacks


 System Bottleneck.
 System Single Point of Failure.

JADE Main Container System Bottleneck


Note that the white and yellow pages services are mainly used to allow cooperation among agents
helping an agent to know which agents provide a specific service and the ID of such agents.
Because these services are located into the JADE Main Container, each time an agent needs to
call a service in another agent it must query the JADE Main Container for agents having that
service.
With a large number of agents asking for services in other agents there will be a massive number
of queries sent to the JADE Main Container causing a system bottleneck.

LADT
To overcome such problem, there will be a Local Agent Descriptor Table (LADT) in each container.
So when an agent wants to find a service, it searches for such service in its Container LADT. If the
service found it will use it and if not it will query the JADE Main Container for an agent outside its
local Container providing that service.
Explanatory example:
GADT Cache
To decrease the number of JADE Main Container queries for a specific service, the containers will
also have a local GADT.
After the agent queried the Main Container for a service, the Main Container will reply by the
agents providing such service in addition to information helping to access such agent.
If the agent wants to use that service another time, it needs to call the Main Container again for
information about agents providing such a service.
To avoid requesting information requested earlier, the containers other than the Main Container
will have a local GADT cache. This cache will contain information about the services used
previously. If the agent wants to use a previously used service, it will query the local GADT. If it
want to use a new service, it will query the Main Container GADT and caches the received
information. This helps in reducing the number of calls sent to the JADE Main Container.
Explanatory example:
Dynamic System
Because the JADE systems are dynamic, it is possible for an agent to be killed and that may cause
problems in cached information in GADT. Suppose that information about Agent3 Srvc1 was
cached in Caontainer1 GADT cache and Agent3 was killed, then there is wrong information stored
in the Container1 GADT cache. To overcome that problem, updates should be sent about cached
data.

JADE Main Container Single Point of Failure


There is another problem in the JADE Main Container. The Main Container is a single-point of
failure within the system. If the JADE Main Container failed the whole system will fail.

Multiple Main Containers


It is possible to start more than one JADE Main Container but each Main Container will represent
a different platform in which normal containers will live as shown in the JADE architecture
diagram.

Downloading JADE
JADE can be downloaded from its official site http://jade.tilab.com/download/jade.
JADE distribution contains five archive files:
1. jadeBin.zip: Pre-compiled JADE Java archive (JAR) files.
2. jadeDoc.zip: JADE offline documentation.
3. jadeExamples.zip: Java source code of various examples.
4. jadeSrc.zip: Java source code.
5. jadeAll.zip: Contains all the above four archive files.

Important JADE Files


 jade/doc/index.html: Inside the jadeDoc.zip. An HTML page regarded the entry point to
access the offline JADE documentation.
 jade/lib/jade.jar: Inside jade.Bin.zip. Pre-compiled JADE Java archive (JAR).

Preparing JADE Environment

CLASSPATH Environment Variable


For running a used-defined Java class, Java must know where that class is located. One way for
locating java classes is via the CLASSPATH system environment variable. The CLASSPATH variable
tells Java the paths in which the used-defined classes are located.

Setting the CLASSPATH Environment Variable


Because all JADE classes are located into the Java archive (JAR) file, we need to make the
CLASSPATH set to the JADE JAR file path.
The default value of the CLASSPATH is '.' meaning that it is set to the current directory.
Assuming that the JADE JAR file was located into that path 'C:\jade\lib\jade.jar'.
The CLASSPATH environment variable can be set by different ways:
 GUI
 CMD

GUI
1.From the desktop, right click the My Computer icon.
2.Choose Properties from the context menu.
3.Click the Advanced tab (Advanced system settings link in Vista).
4.Click Environment Variables. In the section System Variables, find the CLASSPATH
environment variable and select it. Click Edit. If the CLASSPATH environment variable does
not exist, click New
5. In the Edit System Variable (or New System Variable) window, specify the value of the
CLASSPATH environment variable. Click OK. Close all remaining windows by clicking OK.
https://docs.oracle.com/javase/tutorial/essential/environment/paths.html

CMD
Values of the environment variables can be changed in three scopes:
 Shell/Window.
 User.
 System/Machine/Global.

You can check if the CLASSPATH variable exists or not by dumping all environment variables using
the set command. This command prints all environment variables in addition to their values.
C:> set

Difference between CMD set and setx commands


set modifies the current shell (window) environment variables and any modifications over the
environment variables will be removed as soon as the window is closed.
setx modifies the value permanently and the change take effect for future shells not the shells
already running. You need to exit the close shell and reopen it again to see the changes.
setx by default changes the environment variables for the current user. To make setx changes the
environment variables values for the system, use the /M option.
For example:
setx /M PATH 'VALUE'

To print only the value of the CLASSPATH environment variable, use the echo command:
C:> echo %CLASSPATH%
If the output was %CLASSPATH% in Windows, then that environment variable doesn`t exist.

To set the CLASSPATH environment variable:


C:> set CLASSPATH 'C:\jade\lib\jade.jar'

But there is a problem in setting the CLASSPATH environment variable by changing the CLASSPATH
environment variable value.
Assuming that you need to run Class1 and it was located in PATH1, then you need to add that
path to the CLASSPATH environment variable.
To run another class Class1 located in PATH2, you also need to add that path to the CLASSPATH
environment variable.
Now, two classes of the same name Class1 are located in different paths PATH1 and PATH2 added
into the CLASSPATH environment variable. There might be confliction about which Class1 you
mean.
To solve that problem, you need to remove the PATH1 value from the CLASSPATH environment
variable to be able to use the new version of the Class1 into the PATH2.
For example:
C:> set CLASSPATH 'PATH2'
To run the Class1 in PATH1, you need to change the path again.
C:> set CLASSPATH 'PATH1'

So you will end running one class and breaking another class.

classpath Option
Another way to specifying the CLASSPATH variable value is using the java/javac -classpath (-cp)
option.
This option assigns a temp value of the CLASSPATH environment variable. After the running of the
class stops, that value is removed from the CLASSPATH environment variable.
Example, to run the previous Java class without changing the CLASSPATH environment variable
value, use this command:
C:> java -cp 'PATH2' Class1
This command runs Class1 in PATH2 and after run the CLASSPATH environment variable stays
unchanged.
Running JADE for the First Time
Assuming JADE JAR file was located in this path 'C:\jade\lib\jade.jar', to run the JADE Main
Container via the JADE GUI use this command:
C:> java -cp 'C:\jade\lib\jade.jar' jade.Boot -gui

Where jade in jade.Boot is the package name and Boot is the class name within that package.
The -gui option has the effect of running the JADE graphical user interface.
This GUI is provided by an agent called Remote Monitoring Agent (RMA). That agent allows the
administrator to manipulate and monitor the running platform.

JADE GUI Overview

JADE creates its own network that differs slightly from the normal networks discussed earlier.

Review about Computer Networks


In the computer networks course we knew that networks are used to exchange data between
devices. The network was consisting of end-user devices connected by intermediate devices.
It is important to understand the basic network concepts like IP, subnet mask, port number,
socket, OSI, and TCP.
For creating a connection from PC1 to PC2, PC1 must know the socket that it will use for that
connection. The socket consists of IP address and a port number.

Open System Interconnection (OSI) Reference Model


There was an OSI 7-layers reference model working as a framework responsible for modelling
how data is exchanged between network nodes.

Transport Layer
There was a layer responsible for creating connections which is the transport layer number 4 in
OSI. This layer has two common protocols called UDP and TCP. To create a connection, the TCP is
used.

JADE Network Overview

JADE Agent GUID


GUID = Global Unique IDentifier
Nodes in the JADE network are not a set of devices but rather a set of agents. So JADE networks
consist of agents with each agent having its own unique address for making connections.
The agent address has the following form:
<local-name>@<platform-name>
<agent-name>@<user-name>/<IP-address>:<port-number>
Where IP-address:port-number consists the socket.
The address can be create via either machine user name or machine IP address. For example:
test@ahmed:1099
test@192.168.1.6:1099
The following figure represents the main JADE GUI with the RMA address shown in the bar:

JADE Agents Connections


Connections between agents in JADE network can be:
1. Inter-platform: Connections between agents in the same platform.
2. Intra-platform: Connections between agents in different platforms.
Monitoring JADE Environment via the RMA GUI
There are different monitoring options provided by the RMA GUI to allow the administrator to
control the JADE platforms and agents. For example, the JADE RMA GUI provides the following
options to control agents:
 Create.
 Kill.
 Suspend.
 Resume.
 Clone.
 Sending messages.

Killing Agent
We can try killing the RMA agent using the RMA GUI monitoring options. Just highlight the RMA
agent and click the Kill icon or right-click the agent and click the Kill option in the options menu.
You will note that the GUI was terminated because the agent responsible for the GUI was killed.

JADE Booting Options


There are a number of options that can be added to the normal JADE booting command like
creating a container:
C:> java jade.Boot -container -host Dell
C:> java jade.Boot -container -host 192.168.1.10
This command creates a new container on the host specified by its name or IP address.
Some arguments can be passed to an agent:
C:> java jade.Boot foo:FooAgent(1,arg2,argument3)
This passes three arguments separated by commas to the FooAgent agent.
http://jade.tilab.com/documentation/tutorials-guides/how-to-configure-your-agent/

After learning how to launch JADE, next is to learn how to program JADE applications in Java.
What was done is just importing a Java library and next is to know about the following:
 Packages in that library.
 Classes in each package.
 Methods and attributes in each class.
****Week 2****
Programming with JADE

JADE Basic Services


There are a number of basic services provided by the JADE framework including:
 Creating agents.
 Agents Tasks or Behaviors.
 Agents Cooperation: More than one agent can work together to execute tasks by
exchanging messages and using other agents services.
All of these tasks are implemented programmatically using Java. So it is required to know to link
between JADE and Java before implementing any of such tasks.

Preparing Java IDE


Previously we worked with JADE through the Windows CMD. But to be able to write Java code
that use the JADE we have to write it inside files.
Java code can be written inside a normal text file but with the .java extension. But unfortunately
the text files are not appropriate for creating professional projects with a large number of
packages with each package containing a number of classes because text files don`t organize the
project files.
So rather than writing the Java code inside text files we have to use a Java IDE. IDE stands for
Integrated Development Environment is a software suite providing all tools the developer may
need to create applications.
There are many Java IDEs that can be used like:
 NetBeans.
 JDeveloper.
 Eclipse.
 IntelliJ IDEA.

The IDE used in this course is NetBeans due to its popularity and simplicity.

Add JADE to IDE


As explained earlier, JADE is just a Java library that is to be added to the Java IDE. Follow these
steps to add a new Java library in NetBeans application:
 Create a new Java Application.
 Right-click the application and click Properties.
 Select Libraries.
 Click Add JAR/Folder.
 Navigate to the jade.jar and select it.
 Click OK.

Running JADE from Netbeans


External Java Code
After adding the JADE JAR file, next is to run the JADE GUI as done earlier using CMD.
Because the JADE monitoring GUI is created using the RMA, to create the GUI that agent must be
created.
Assuming that the package name is jadeapplication and class name is JADEApplication, the JADE
environment will be created and then the RMA get called by the following code:

1. // http://stackoverflow.com/questions/17646076/how-to-start-jade-gui-within-
another-gui
2. package jadeapplication;
3.
4. import jade.core.Runtime;
5. import jade.core.Profile;
6. import jade.core.ProfileImpl;
7. import jade.wrapper.AgentController;
8. import jade.wrapper.ContainerController;
9. import jade.wrapper.StaleProxyException;
10.
11. public class JADEApplication {
12. ContainerController myContainer;
13.
14. public static void main(String[] args) {
15. JADEApplication jade = new JADEApplication();
16. jade.test();
17. }
18.
19. public void test(){
20. //Create the JADE envioenment
21. Runtime myRuntime = Runtime.instance();
22. Profile myProfile = new ProfileImpl();
23. myContainer = myRuntime.createMainContainer(myProfile);
24. //Call the RMA GUI
25. try {
26. AgentController rma = myContainer.createNewAgent("rma", "jade.tools.
rma.rma", null);
27. rma.start();
28. }catch(StaleProxyException e){
29. e.printStackTrace();
30. }
31. }
32. }

Main Class Application Property


The work with JADE in this course can be established via both code and GUI.
Because there are many parts in this course requiring writing code like Prolog and AI Search
Techniques, we can avoid writing too much code in JADE and doing some tasks through GUI.
The first thing to do through GUI is launching the JADE enviornment.

Using CMD, there was no prior Java code to create the JADE environment and call the RMA. Also
it is not required to write a Java code to run the JADE environment and call the RMA.
These tasks can be done in a more favorable way which is to launch the JADE GUI when the
application starts. This by making the jade.Boot class the main class in the project.
Up to this point, the main class was the class called JADEApplication which is responsible for calling
the jade.Boot class.
We can make the jade.Boot as the main class and avoid creating another class that calls JADE.
To make the jade.Boot class as the main class in the project in Netbeans, follow these steps:
 Right-click the application and click Properties.
 Select Run.
 Set the Main Class to jade.Boot.
 Set the Arguments to -gui.
 Click OK.
Next time the application get run, the JADE RMA will be called directly without any additional Java
code.

Creating Agents
Creating a JADE agent is very simple because agents are created by just extending the Agent class
found in the jade.core package.

1. package jadeapplication;
2.
3. import jade.core.Agent;
4.
5. public class NewAgent extends Agent{
6.
7. }

The jade.core package and its sub-packages implement the JADE kernel. The JADE kernel is the
core of JADE much like the OS kernel do.
The jade.core package contains the fundamental classes responsible for:
 Creating agents.
 Creating containers.
 Managing agents and containers.
 Sending and receiving data among agents.

Adding Agent to the JADE Environment


But when viewing the list of active agents in the JADE RMA GUI there is no new agent added. This
is because the previous code just created the agent without adding it to the environment.

Via GUI
Using JADE RMA GUI we can add the created agent in the environment. Starting by adding that
agent to the Platform Main Container we can follow the following steps
 Select an agent platform or a container in the agents tree in which the agent will be
inserted.
 Click Actions menu then Start New Agent menu item. Similarly, click the Start New Agent
menu item.
 Insert the agent parameters in the Insert Start Parameters window. The least parameters
to insert are:
 Agent name: It is the name that appears in the GUID.
 Class name: It is the class name that creates the agent.
 Click OK.
After clicking OK, the agent will be added to the environment.

Via CMD
Using CMD we can add the agent to the JADE environment. For example:
java -cp "D:\FCI\MUFIC\Courses\2016-2017\2nd Semester\Artificial Intelligence (AI)\JADE\JADE-
all-4.4.0\JADE-bin-
4.4.0\jade\lib\jade.jar;C:\Users\Dell\Documents\NetBeansProjects\JADEApplication\build\class
es" jade.Boot -gui Test:jadeapplication.NewAgent
This command will launch the JADE environment and opens the RMA GUI then creates the agent
in the class NewAgent in the jadeapplication package and set its name to Test.
This command includes two paths:
1. JADE JAR Path: D:\FCI\MUFIC\Courses\2016-2017\2nd Semester\Artificial Intelligence
(AI)\JADE\JADE-all-4.4.0\JADE-bin-4.4.0\jade\lib\jade.jar
2. Compiled Java Classes Path:
C:\Users\Dell\Documents\NetBeansProjects\JADEApplication\build\classes

Overriding setup()
The jade.core.Agent class has a method called setup() of the following signature:

1. protected void setup(){…}

That method is responsible for making agent initializations and adding behaviors to the agents. It
is much like the object constructor.
The constructor is called immediately after the object is created. Also setup() is called after the
agent is created.

The minimum Java code that implements an agent and prints a message indicating that the agent
started is as follows:

8. package jadeapplication;
9.
10. import jade.core.Agent;
11.
12. public class NewAgent extends Agent{
13.
14. @Override
15. protected void setup(){
16. System.out.println("Hello. I am the first
complete JADE agent created in this course.");
17. }
18. }

This example just extends the jade.core.Agent class and overrides the setup() method with a
message printed when the agent is created.

Agent Identifiers
Every agent has two identifiers:
1. Local Agent Identifier (AID): It is the identifier of the agent inside the local platform. It
can be called the agent local name.
2. Global Unique Identifier (GUID): It is the agent identifier inside the network. It can be
called the agent name.
The AID class inside the jade.core package returns the agent identifiers through its getAID()
method.
The AID and GUID can be printed inside the setup() as follows:

1. System.out.println("AID : " + getAID().getLocalName());


2. System.out.println("GUID : "+ getAID().getName());

The GUID has this form:


<local-name>@<platform-name>
Notes:
The agent local name is used to find the AID:

1. AID id = new AID("Test", AID.ISLOCALNAME);

The agent name is used to find the GUID:

1. AID id = new AID("Test@192.168.1.10:1099/JADE", AID.ISGUID);

Agent Termination
After the agent finished its work it still alive. To kill the agent, the doDelete() method inside the
Agent class must be called.
After the doDelete() method get called the agent is removed from its container.
There is a method called takeDown() which get called before the agent is killed. It does a similar
job like the setup() method.

1. protected void takeDown(){…}

Code for agent termination:

1. package jadeapplication;
2.
3. import jade.core.Agent;
4. import jade.core.AID;
5. import jade.lang.acl.ACLMessage;
6.
7. public class NewAgent extends Agent{
8.
9. @Override
10. protected void setup(){
11. System.out.println("Hello. I am the first
complete JADE agent created in this course.");
12. doDelete();
13. }
14.
15. @Override
16. protected void takeDown() {
17. System.out.println("Agent will be terminated soon.");
18. }
19.
20.
21.
22. }

Agent Behaviors
Remember that an agent is meant to make behaviors on behalf of the user. Behaviors are tasks
that the agent do. So after creating the agent, next is to add behaviors to the agent.

Creating Agent Behaviors


The developer can create its own behaviors by extending the Behavior abstract class which is
inside the jade.core.behaviors package. The developer also can use some of the already
implemented behaviors in JADE.

Behavior Abstract Class


A behavior can be created by just extending the Behavior abstract class as follows.

1. package jadeapplication;
2.
3. import jade.core.behaviors.Behaviors;
4.
5. public class NewBehavior extends Behavior{
6.
7. }

Because the jade.core.behaviors.Behaviors class is an abstract class, its abstract methods must
be overridden.
The jade.core.behaviors.Behaviors class has two abstract methods:

1. public void action(){…}


2. public boolean done(){…}

The action() method is used to hold the agent behavior. The done() method is used to check
whether the behavior completed or not. It returns true if the behavior was completed and false if
not completed.

The following code implements a behavior that just prints a message and ends.

1. package jadeapplication;
2.
3. import jade.core.behaviours.Behaviour;
4.
5. public class MyBehavior extends Behaviour{
6.
7. @Override
8. public void action() {
9. System.out.println(" This is a behavior.");
10. }
11.
12. @Override
13. public boolean done() {
14. return true;
15. }
16. }

Adding Behaviors to Agent


The previous code just implements a behavior but that behavior is not yet added to any agent.
Behaviors are added to the agent using the addBehavior() method inside the jade.core.Agent
class.
Behaviors can be added to the agent either when the agent starts, inside the setup() method, or
inside other behaviors.

The following code adds the previous behavior to the previously created agent.
It just takes an object of the class implementing the behavior and assigns it to the agent using its
addBehavior() method.

1. package jadeapplication;
2.
3. import jade.core.AID;
4. import jade.core.Agent;
5.
6. public class NewAgent extends Agent{
7.
8. @Override
9. protected void setup(){
10. System.out.println("Hello. I am the first JADE agent created in this cou
rse.");
11.
12. this.addBehaviour(new MyBehavior());
13. }
14.
15. }

JADE Behavior Scheduling


JADE behaviors scheduling are cooperative or non-preemptive meaning that once the behavior
of an agent enters execution it can`t be blocked. So it must run until being completed.
So the developer must decide when an agent completes and take care of not creating behaviors
that never completes.
To see what happens, the previous behavior class will be modified to accept a message to be
printed and enters an infinite loop printing that message.

1. package jadeapplication;
2.
3. import jade.core.behaviours.Behaviour;
4.
5. public class MyBehavior extends Behaviour{
6.
7. private String behaviorMessage;
8.
9. public MyBehavior(String behaviorMessage){
10. this.behaviorMessage = behaviorMessage;
11. }
12.
13. @Override
14. public void action() {
15. for(;;){
16. System.out.println(behaviorMessage);
17. }
18. }
19.
20. @Override
21. public boolean done() {
22. return true;
23. }
24. }

Next is to add two behaviors of the previously modified class to the agent created and note how
the agent first behavior never completes and the second behavior never enters in execution.

1. package jadeapplication;
2.
3. import jade.core.Agent;
4.
5. public class NewAgent extends Agent{
6.
7. @Override
8. protected void setup(){
9. System.out.println("Hello. I am the first JADE agent created in this cou
rse.");
10.
11. this.addBehaviour(new MyBehavior("My first behavior."));
12. this.addBehaviour(new MyBehavior("My second behavior."));
13. }
14.
15. }

Because the first behavior never ends execution the second behavior never enters execution. The
programmer must take care of such situations.

Other Behaviors Quick Overview


p11-13. Caire, Giovanni. "JADE tutorial: JADE programming for beginners." Documentación de
JADE 3 (2009).

JADE Agent Communication


One feature of JADE agents is the ability to communicate with each other.

JADE Message Passing Overview


The general scenario of message passing in JADE is described in the following diagram:
Agent A1 want to send a message to agent A2. A1 formulates the message and delivers it to the
JADE runtime environment. The JADE runtime environment inserts the message to the receiver
mailbox and receiver A2 got notified.
Each agent has a message queue or mailbox in which messages from other agents can be received.
After the agent got notified, it can work with the message by different means.

JADE ACL Overview


The communication among agents in JADE is specified by a language called Agent Communication
Language (ACL). The ACL has the following fields in the message:
 Sender.
 Receiver(s).
 Message intention or performative: This filed indicated the sender`s intention from
sending the message. It can be:
o REQUEST: If the sender wants the receiver to do an action.
o INFORM: If the sender wants to just inform the receiver about a fact without
making an action.
o QUERY_IF: If the sender want to check a condition at the receiver.
o CFP, PROPOSE, ACCEPT_PROPOSAL, REJECT_PROPOSAL: If the sender and
receiver want to negotiate about something.
 Content: For REQUEST message, it is the action to be performed. For INFORM message,
it is the fact to tell the receiver about.
 Content language.
 Ontology.

The minimum fields required are:


1. Message intention.
2. Receiver.
3. Content.

Sending Message
To send a message from an agent to another in JADE, the ACLMessage class located in the
jade.lang.core package is used.
After taking an object, we have to set the required fields.
 Message intention is added as an argument to the ACLMessage class constructor or using
the setPerformative() method.
 The receiver is added using the addReceiver() method that accepts the agent ID. Either
AID or GUID.
 Content is added via the setContent() message that accepts the content as string.

For example, the following code sends an informational message to the DF special JADE agent.

1. package jadeapplication;
2.
3. import jade.core.Agent;
4. import jade.core.AID;
5. import jade.lang.acl.ACLMessage;
6.
7. public class NewAgent extends Agent{
8.
9. @Override
10. protected void setup(){
11.
12. ACLMessage acl = new ACLMessage(ACLMessage.INFORM);
13. acl.addReceiver(new AID("df", AID.ISLOCALNAME));
14. acl.setContent("Just an infromational message.");
15. this.send(acl);
16. }
17.
18. }

Receiving Message
Suppose that we have two agents with the local names agent1 and agent2 and we need to send
a message from agent1 to agent2.

Agent1 code:

1. package jadeapplication;
2.
3. import jade.core.AID;
4. import jade.core.Agent;
5. import jade.lang.acl.ACLMessage;
6.
7. public class NewAgent extends Agent{
8.
9. @Override
10. protected void setup(){
11. System.out.println("Hello. I am the **first** JADE agent created in this
course.");
12. ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
13. msg.addReceiver(new AID("agent2", AID.ISLOCALNAME));
14. msg.setContent("Just an informational message.");
15. this.send(msg);
16. }
17. }

Agent2 code:

1. package jadeapplication;
2.
3. import jade.core.Agent;
4.
5. public class NewAgent2 extends Agent{
6.
7. @Override
8. protected void setup(){
9. System.out.println("Hello. I am the **second** JADE agent created in thi
s course.");
10. this.addBehaviour(new MyBehavior());
11. }
12. }

We now knew how to send a message but how to receive a message from a user-defined agent?
To receive a message in an agent, you just need to create a behavior that waits for message.
The action() method of that behavior will contain a simple code suggested by JADE to do that
task. The code is written inside the action() method waits for messages.

Tips on Message Receiving


There are a number of questions to be answered to be able to create two agents being able to
send and receive messages.

Which type of behavior to use? One-shot Behavior, CyclicBehavior, Generic Behavior,


WalkerBehavior, or TickerBehavior.
The best answer is CyclicBehavior because the agent should check periodically for messages.
Another near type is TickerBehavior but it will delay message by the amount of time delay
specified.

Behavior code:

1. package jadeapplication;
2.
3. import jade.core.behaviours.CyclicBehaviour;
4. import jade.lang.acl.ACLMessage;
5.
6. public class MyBehavior extends CyclicBehaviour{
7.
8. @Override
9. public void action() {
10. ACLMessage msg = this.getAgent().receive();
11. if(msg != null){
12. System.out.println("\n*****New Message*****");
13. System.out.println("Message sender AID : "+ msg.getSender().getLocal
Name());
14. System.out.println("Message content : "+msg.getContent());
15. }else {
16. block();
17. }
18. }
19. }

What is the order of adding agents to the JADE environment?


Generally the receiver must be available before messages are sent. Because agent2 is the receiver
so it must be available before the sender which is agent1 sends messages.
So answer is that agent2 must be created before agent1.
Using JADE RMA GUI, if agent1 was created before agent2, so agent1 will send the message to
the JADE runtime environment and by its role will search for an agent with a local name agent2.
It won`t find such agent so the message will be discarded.

The CMD command to launch the JADE environment and add two agents is as follows:
java -cp "D:\FCI\MUFIC\Courses\2016-2017\2nd Semester\Artificial Intelligence (AI)\JADE\JADE-
all-4.4.0\JADE-bin-
4.4.0\jade\lib\jade.jar;C:\Users\Dell\Documents\NetBeansProjects\JADEApplication\build\class
es" jade.Boot -gui -agents
"agent2:jadeapplication.NewAgent2;agent1:jadeapplication.NewAgent"

Note: Using CMD the order of added agents in the command is irrelevant as JADE will launch the
agents based on their dependencies on each other. So the following command does the same task
even if agent1 is added before agent2.
java -cp "D:\FCI\MUFIC\Courses\2016-2017\2nd Semester\Artificial Intelligence (AI)\JADE\JADE-
all-4.4.0\JADE-bin-
4.4.0\jade\lib\jade.jar;C:\Users\Dell\Documents\NetBeansProjects\JADEApplication\build\class
es" jade.Boot -gui -agents
"agent1:jadeapplication.NewAgent;agent2:jadeapplication.NewAgent2"

You might also like