Transcript Agent

Agent-Oriented
Programming
(AOP)
1
Grading

Mid-term Exam
30%

Labs
40%

Final Presentation
30%
2
Project Documents (NOT Used)
張一二李一三.rar 內含下列文件:
產品說明.doc
驗收測試.doc
架構.xxx (UML class diagram)
Scanners.java (header, pseudo code, source code) …
3
Project Grading
1. 20% 題目
展現 agent 特色
1. FIPA CA& IP,
2. 一般網路程式不易做或做來繁雜的功能
新穎 實用 小型 (最好是一個功能)
2. 80% 品質
20% dependability (acceptance test cases)
20% usability (GUI)
20% reuse (headers of classes and public methods)
20% maintainability (pseudo code readability)
3. 兩台Notebook 電腦上網 來做 DEMO 並檢視文件
4
Project Development Process

先一起寫中文 產品說明驗收測試
再一起舉行 CRC 會議 訂出架構
Classes 分工後 各自寫 method (unit) headers
各自寫 unit test cases 及 test code
各自寫 pseudo code 並用test case TRACE TO DEBUG
各自依照 pseudo code 補上 source code
各自用JUnit 做 unit testing
最後,一起做驗收測試

注意: 各文件要反覆修改 (iterative development)







5
Changes in Computing World

0. Single Machine
C, Unix

1. Internet
TCP/IP

2. Web
HTTP, UDDI, SOAP

3. Semantic Web
Agent, Ontology
6
Programming Goal

The goal of programming is to reduce cognitive load of
developers through moving up the abstraction levels.

Paradigm shifts raise the abstraction level for developers.

We saw the paradigm shifts in recent history:
agent
object distributed mentality
method data state
7
Three Programming Paradigms
1. Structured Programming (SP)
2. Object-Oriented Programming (OOP)
3. Agent-Oriented Programming (AOP)
8
Structured Programming (SP)

In SP, a software system is composed of structured methods
developed in 3 structured constructs, namely:
1) sequence,
2) selection, and
3) iteration.

Typical language: C

This paradigm reduces cognitive load of developers, since the
structured constructs used eliminate “goto” which causes
huge cognitive load (jumping around when reading code).
9
C Example of Structured Programming
main () { printf(“%d”, getPower(2, 3) /* 2**3 expects 8 */ ); }
int getPower (int x, int n) /* raise x to n-th power; n>0 */
{ int i, p; p=1;
for (i=1; i<=n; ++i) p = p*x;
return (p);
} // end of getPower()
10
Object-Oriented Programming (OOP)

In OOP, a software system is composed of classes, each contains data state
and methods.
An object can be constructed at run-time that allocates a copy of the data
of a class, and an object can invoke any method of its class to update the
state of the data.

Typical language: Java

This paradigm reduces cognitive load of developers, as objects exactly
model real-world entities - although passively!

Note that a method here is the same as that in structured paradigm. Thus,
OOP extends SP by further encapsulating the data state.

11
Java Example of OOP
public class MathClass {
private int y; // other data here
public MathClass () {}
public void getPower (int x , int n ) {
for (y=x; n>0; n--) y *= x; System.out.println (y);
} // end of getPower()
}// end of class MathClass
public static void main (String[] args) {
Object anObject = new MathClass();
anObject.getPower (2, 3);
} // end of main()
12
Agent-Oriented Programming (AOP)

In AOP, a software system is composed of agents. Agents can be
constructed from agent classes, similar to that of objects. Each agent
executes independently, and it can communicate with other agents.

An agent holds mental state (belief-desire-intention, BDI) by which
decentralized control can be hidden (encapsulated).

Typical platform: JADE (Java Agent DEvelopment Framework)
BDI4JADE


This paradigm reduces cognitive load of developers, as agents proactively
model entities’ attitudes and thoughts.

Note that agent class extends Java thread class. Thus, AOP extends OOP.
13
JADE Example of AOP
/* Get y as x raised to the power of n */
class GetPowerBehaviour extends OneShotBehaviour {
private int x ,n ,y;
public GetPowerBehaviour (int x, int n) {this.x=x; this.n=n; }
public void action() { for (y=x; n>0; n--) y *= x; System.out.println (y); }
} // end of class GetPowerBehaviour
public class MyAgents extends Agent {
protected void setup() {
{ /* BDI mechanism can be put here */
GetPowerBehaviour getPower = new GetPowerBehaviour (2,3);
this.addBehaviour (getPower);
} // end of setup()
} // end of class MyAgents
14
AOP advantages
The promises of AOP are:

1) Improved flexibility:
Agents can register (join) or deregister (leave) an agent
society at any time. This kind of software system is thus very
dynamic and flexible.

2) Improved reliability:
Middle agent of an agent society can check agents’ history
and monitor agents’ performance to expel low quality agents.
Thus, this kind of software system is rather reliable.
15
Module communication in 3 paradigms

Function paradigm:
– A module is a function. Function call is the module communication
scheme.

Object paradigm:
– A software module is a class. A run-time module is an object. Message
sending is the module communication scheme.

Agent paradigm:
– A module is an agent. A modal-driven interaction is the module
communication scheme.
16
What is an agent?

A good question, and one that receives an inordinate amount
of time from within the agent community itself.

Rather as was the case in the early days of object-oriented
development, there is no one universally accepted definition
of an agent, but instead a lot of people working in closely
related areas, using similar ideas.

Put crudely, an agent is an autonomous software system: a
system that can decide for itself what it needs to do.
17
What is an agent? [cont.]

Given this basic definition, two main "religions" appear to
have emerged with respect to agents: the intelligent agents
community, and the mobile agents community.

Intelligent agents are essentially agents that can do reasoning
or planning.

Mobile agents are agents that can transmit themselves across a
computer network (e.g., the internet) and recommence
execution on a remote site. [www.agentlink.org]
18
Uses of Mobile Agent
1) Disconnected computing, such as personal digital assistant
(PDA) that might be disconnected in short notice.
2) Mobile agent can be sent to large data source and process
the data locally.
3) Dynamic deployment of software. If you need to
reconfigure hundreds of PDAs with a new version of
software, use mobile agent to do it.
[D. Kotz, p. 83, IEEE Concurrency, Sep. 1999]
19
Why are agents important?

Agents are important for several reasons:
1) they are seen as a natural metaphor for conceptualising and
building a wide range of complex computer systems (the
world contains many passive objects), but it also contains very
many active components as well);
2) they cut across a wide range of different technology and
application areas, including telecoms, human-computer
interfaces, distributed systems, and so on;
3) they are seen as a natural development in the search for evermore powerful abstractions with which to build computer
systems. [www.agentlink.org]
20
JADE Introduction

JADE agent platform
– fully implemented in Java language (version 1.4 or higher).
– simplifies the implementation of multi-agent systems through a middleware that complies with the FIPA (Foundation of Intelligent and
Physical Agent) specifications.
– supports debugging and deployment through a set of development
tools.
21
JADE Introduction (Cont.)

The agent platform can be distributed across machines and
operating systems, and the configuration can be controlled
remotely via GUI (graphical user interface).

The configuration can be changed at run-time by moving
agents from one machine to another (mobility), as and when
required.
22
Architecture of a FIPA Agent Platform
23

Agent Management System (AMS)
– is the agent who exerts supervisory control over access to and use of the Agent
Platform. Only one AMS will exist in a single platform.
– provides white-page and life-cycle service, maintaining a directory of agent
identifiers (AID) and agent state.
– Each agent must register with an AMS in order to get a valid AID.

Directory Facilitator (DF)
– is the agent who provides the default yellow page service in the platform.

The Message Transport System (MTS)
– also called Agent Communication Channel (ACC)
– is the software component controlling all the exchange of messages within the
platform, including messages to/from remote platforms.
24
JADE Agent Platform distributed over
several containers
25
Agent life cycle
26
Agent life cycle (Cont.)






INITIATED
– the 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.
ACTIVE
– the Agent object is registered with the AMS, has a regular name and address and can
access all the various JADE features.
SUSPENDED
– the Agent object is currently stopped. Its internal thread is suspended and no agent
behaviour is being executed.
WAITING
– the Agent object is blocked, waiting for something. Its internal thread is sleeping on a
Java monitor and will wake up when some condition is met (typically when a message
arrives).
DELETED
– the Agent is definitely dead. The internal thread has terminated its execution and the
Agent is no more registered with the AMS.
TRANSIT
– 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.
27
Installing/Setting up JADE

Download from http://jade.tilab.com

Unzip the JADE binary package

Add jadeTools.jar,
http.jar,
jade.jar,
iiop.jar and
commons-codec\commons-codec-1.3.jar
in “lib” directory to CLASSPATH

Add dot at end of CLASSPATH
28
Starting JADE

java jade.Boot (without GUI)

java jade.Boot -gui (see figure below)
29
Running an Agent

java jade.Boot [AgentName]:[ClassName]
– AgentName: a globally unique agent name.
– ClassName: the Java class name.

For example:
java jade.Boot ping1:PingAgent
30
Running an HelloWorld Agent

Create a simplest JADE agent is
– defining a class extending the jade.core.Agent class and
– implementing the setup() method as shown in the code below.
package hello; //Need this to get agent in GUI mode
import jade.core.*;
public class HelloWorld extends Agent{
public void setup(){
System.out.println("Agent Started: Hello World!");
System.out.println("-----About Me:-----");
System.out.println("My local name is:"+getLocalName());
System.out.println("My globally unique name is:"+getName() );
}}
 java jade.Boot -gui Hello:hello.HelloWorld
31
Running an HelloWorld Agent Using Eclipse

Create a new project
32
Running an HelloWorld Agent Using Eclipse

Select Java Project and click Next
33
Running an HelloWorld Agent Using Eclipse

Project name is Agent then click Next
34
Running an HelloWorld Agent Using Eclipse

Click Finish
35
Running an HelloWorld Agent Using Eclipse

Click mouse right button at mouse to set Build Path
36
Running a HelloWorld Agent Using Eclipse

Add jade.jar, and
commons-codec-1.3.jar

into Eclipse
37
Running an HelloWorld Agent Using Eclipse

Click mouse right button at mouse to new a class
38
Running an HelloWorld Agent Using Eclipse

Name is HelloWorld and Superclass is jade.core.Agent
39
Running an HelloWorld Agent Using Eclipse

Copy example and paste in Eclipse
40
Running an HelloWorld Agent Using Eclipse

Click red area and select Run…
41
Running an HelloWorld Agent Using Eclipse

Click mouse right button at mouse and select new
42
Running an HelloWorld Agent Using Eclipse

Name is HelloWorld and Main Class is jade.Boot

Select Arguments
43
Running an HelloWorld Agent Using Eclipse

Program arguments is –gui Hello:HelloWorld

Click Apply and Run to run agent
44
Running an HelloWorld Agent Using Eclipse

If run success, it will show as follow
45
Agent Behaviors

A behaviour represents a task that an agent can carry out
and is implemented as an object of a class that extends
jade.core.behaviours.Behaviour.
•
Simple Behaviors:
An atomic behaviour. This abstract class models behaviours that are made by a
single, monolithic task and cannot be interrupted.
•
Composite Behaviors:
An abstract superclass for behaviours composed by many parts. This class holds
inside a number of children behaviours. When a Composite Behaviour receives it
execution quantum from the agent scheduler, it executes one of its children
according to some policy. This class must be extended to provide the actual
scheduling policy to apply when running children behaviours.
46
Agent Behaviors
– jade.core.behaviours.Behaviour (implements jade.util.leap.Serializable)

jade.core.behaviours.SimpleBehaviour
– jade.core.behaviours.CyclicBehaviour
– jade.core.behaviours.OneShotBehaviour
– jade.core.behaviours.TickerBehaviour
– jade.core.behaviours.WakerBehaviour

jade.core.behaviours.CompositeBehaviour
– jade.core.behaviours.ParallelBehaviour
– jade.core.behaviours.SerialBehaviour

jade.core.behaviours.FSMBehaviour

jade.core.behaviours.SequentialBehaviour
(Reference: http://jade.tilab.com/doc/api/index.html)
47
SimpleBehaviour
CyclicBehaviour
Atomic behaviour that must be executed forever. This abstract class can be extended
by application programmers to create behaviours that keep executing continuously (e.g.
simple reactive behaviours).
OneShotBehaviour
Atomic behaviour that executes just once. This abstract class can be extended by
application programmers to create behaviours for operations that need to be done just
one time.
TickerBehaviour
This abstract class implements a Behaviour that periodically executes a user-defined
piece of code. The user is expected to extend this class re-defining the
method onTick() and including the piece of code that must be periodically executed
into it.
WakerBehaviour
This abstract class implements a OneShot task that must be executed only one just after
a given timeout is elapsed.
48
SimpleBehaviour
import jade.core.*; import jade.core.behaviours.SimpleBehaviour;
public class DecativeReentrant extends Agent{
public void setup( ){
SimpleBehaviour decative = new SimpleBehaviour(this){
boolean finished = false; int state = 0;
@Override
public void action(){
switch(state){
case 0: System.out.println("Do");
break;
case 1: System.out.println("Re");
break;
case 2: System.out.println("Me");
finished = true; break; } state++;
} // action
@Override
public boolean done ( ) {return finished;}
}; // new SimpleBehavior
this.addBehaviour (decative); } //setup
}// DecativeReentrant

Execution: java jade.Boot –gui doreme1:DecativeReentrant

Output: Do
Re
Me
49
SimpleBehaviour(Refactor)
package AgentBasedSys;
import jade.core.*; import jade.core.behaviours.SimpleBehaviour;
public class DecativeReentrant_Refactor extends Agent{
public void setup(){
DoReMeBehaviour decative = new DoReMeBehaviour(this);//new behaviour
this.addBehaviour(decative);
//add behaviour
}//setup
private class DoReMeBehaviour extends SimpleBehaviour{
boolean finished = false; int state = 0;
public DoReMeBehaviour(Agent a) { super(a); }//constructor
@Override
public void action() {
Execution: java jade.Boot
-gui
doreme2:DecativeReentrant_Refactor
Output: Do
Re
Me
switch(state){
case 0:System.out.println("Do");
break;
case 1:System.out.println("Re");
break;
case 2:System.out.println("Me"); finished = true; break; } state++;
}//action
@Override
public boolean done() { return finished; }//done
}//private DeReMeBehavior class
}//class DecativeReentrant_Refactor
50
SimpleBehaviour(Infinite)
package AgentBasedSys;
import jade.core.*; import jade.core.behaviours.SimpleBehaviour;
public class InfiniteDecativeReentrant extends Agent{
public void setup( ){
SimpleBehaviour decative = new SimpleBehaviour(){
boolean finished = false;
public void action(){
System.out.println("Do");
System.out.println("Re");
System.out.println("Me");
} // action
public boolean done ( ) { return finished; }
};// new SimpleBehavior
this.addBehaviour (decative); } //setup
}//InfiniteDecativeReentrant

Execution: java jade.Boot –gui doreme3:DecativeReentrant

Output: Do
Re
Me
Do
Re
Me
‧
‧
51
Composite Behaviour
 ParallelBehaviour
Composite behaviour with concurrent children scheduling. It is
a CompositeBehaviour that executes its children behaviours concurrently, and it
terminates when a particular condition on its sub-behaviours is met i.e. when all children
are done, N children are done or any child is done.
 SerialBehaviour
Base class for all composite behaviour whose children run serially, i.e. the composite
behaviour is blocked if and only if its current child is blocked.
• FSMBehaviour
Composite behaviour with Finite State Machine based children scheduling. It is
a CompositeBehaviour that executes its children behaviours according to a FSM
defined by the user. More specifically each child represents a state in the FSM. The
class provides methods to register states (sub-behaviours) and transitions that defines
how sub-behaviours will be scheduled.
• SequentialBehaviour
Composite behaviour with sequential children scheduling. It is a
CompositeBehaviour that executes its children behaviours in sequential order, and
terminates when its last child has ended
52
Parallel Behaviour
import jade.core.*; import jade.core.behaviours.SequentialBehaviour;
import jade.core.behaviours.ParallelBehaviour; import jade.core.behaviours.OneShotBehaviour;
public class ParallelBehaviourAgent extends Agent{
public void setup(){
SequentialBehaviour s1 = new SequentialBehaviour(this);
s1.addSubBehaviour(new OneShotBehaviour(this){public void action(){System.out.println("1) This
");}});
s1.addSubBehaviour(new OneShotBehaviour(this){public void action(){System.out.println("1)
first");}});
SequentialBehaviour s2 = new SequentialBehaviour(this);
s2.addSubBehaviour(new OneShotBehaviour(this){public void action(){System.out.println("2) That
");}});
s2.addSubBehaviour(new OneShotBehaviour(this){public void action(){System.out.println("2)
second");}});
ParallelBehaviour p = new ParallelBehaviour(this,ParallelBehaviour.WHEN_ALL);
p.addSubBehaviour(s1); p.addSubBehaviour(s2); addBehaviour(p); }}
53
Parallel Behaviour (Cont.)


Execution: java –gui jade.Boot parall:ParallelBehaviourAgent
Output: 1) This
2) That
1) first
2) second
54
Sequential Behaviour
import jade.core.*;
import jade.core.behaviours.SequentialBehaviour;
import jade.core.behaviours.OneShotBehaviour;
public class DecativeSequential extends Agent{
public void setup(){
SequentialBehaviour s = new SequentialBehaviour(this);
s.addSubBehaviour(new OneShotBehaviour(this){
public void action(){ System.out.println("Do");}});
s.addSubBehaviour(new OneShotBehaviour(this){
public void action(){System.out.println("Re");}});
s.addSubBehaviour(new OneShotBehaviour(this){
public void action(){System.out.println("Me");}});
addBehaviour(s); }}// DecativeSequential
55
Sequential Behaviour(Cont.)

Execution: java –gui jade.Boot doreme:DecativeSequential

Output: Do
Re
Me
56
Agent Communication
Language (ACL)

JADE is implemented as an object of the ACLMessage class
that provides get and set methods for handling all fields of a
message.

Message format comprises a number of fields:

Sender
– The sender of the message

Receiver (s)
– The list of receivers
57
ACL (Cont.)

Performative
– The communicative intention (also called “performative”) indicating
what the sender intends to achieve by sending the message.
– The performative can be

REQUEST, if the sender wants the receiver to perform an action.

INFORM, if the sender wants the receiver to be aware of a fact.

QUERY_IF, if the sender wants to know whether or not a given
condition holds.

CFP (call for proposal), PROPOSE, ACCEPT_PROPOSAL,
REJECT_PROPOSAL, if the sender and receiver are engaged in a
negotiation, and more.
58
ACL (Cont.)

Content
– The actual information included in the message (i.e. the action to be
performed in a REQUEST message, the fact that the sender wants to
disclose in an INFORM message …).

Ontology
– The vocabulary of the symbols used in the content and their meaning
(both the sender and the receiver must ascribe the same meaning to
symbols for the communication to be effective).
59
ACL (Cont.)

conversation-id, reply-with, in-reply-to, reply-by
– Some fields used to control several concurrent conversations and to
specify timeouts for receiving a reply such as conversation-id, replywith, in-reply-to, reply-by.

For example,
– if agent i sends to agent j a message which contains:
reply-with order567
– Agent j will respond with a message containing:
in-reply-to order567
60
Message Content

JADE provides 3 ways to implement communication
between agents:
1. Using strings as the message content.
–
Only for content of messages is atomic data, but
Not for abstract concepts, objects or structured data.
–
In such cases, the string needs to be parsed to access its various parts.
–
2. Using serialized Java objects as the message content.
–
–
Only for a local application where all agents are implemented in Java.
One inconvenience is that these messages are not readable by humans.
3. Defining the ontology objects as extension of predefined classes, so
that JADE can encode and decode messages in a standard FIPA
format.
–
This allows JADE agents to interoperate with other agent systems.
61
Message Content (cont.)

The 3 types of message content use different methods to set and get
content, as shown below:
Content type
Get content
Set content
Strings
getContent()
setContent()
Java Objects
getContentObject()
setContentObject()
Ontology Objects
extractContent()
fillContent()
62
Examples of the 3 ways above
1) String: age:25 name:Tzou
easy for human, but hard for parser
2) Java object: use getAge( ), getName( ) in Java class
“Person” to access the bit string
3) Ontology object: use extractContent ( ) in JADE to get
“ContentElement”, then casted to “Person”
(extended form JADE), then getAge()
63
1. Message Content with String

Send a message to another agent
– fill the fields of an ACLMessage object
– and then call the send() method of the Agent class.

The code below informs an agent whose nickname is Peter that “Today
it’s raining.”
ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
msg.addReceiver(new AID(“Peter”, AID.ISLOCALNAME));
msg.setLanguage(“English”);
msg.setContent(“Today it’s raining”);
send(msg);
64
Example - Sender
package stringMessageContent;
import java.io.InterruptedIOException;
import java.io.IOException;
import jade.core.*;
import jade.core.behaviours.*;
import jade.lang.acl.*;
public class SimpleSender extends Agent {
protected void setup() {
addBehaviour(new SimpleBehaviour(this) {
private boolean finished = false;
public boolean done(){
return finished;
}
65
Example – Sender (Cont.)
public void action() {
System.out.println(getLocalName() +": about to inform bob hello");
// we sleep here to give bob a chance to start.
doWait(5000);
// set performative
ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
msg.setSender(getAID());
AID id = new AID();
id.setLocalName("Bob"); // this is for one computer; if two computers, needs change
msg.addReceiver(id);
msg.setContent("Hello_BOB");
send(msg);
System.out.println(getLocalName() +": Send hello to bob");
finished = true;
doWait(5000);
doDelete();}
}); // end of addBehaviour()
} // end of protected void setup()
} // end of SimpleSender class
66
Example - Receiver
package stringMessageContent;
import jade.core.*;
import jade.core.behaviours.*;
import jade.lang.acl.ACLMessage;
public class SimpleReceiver extends Agent {
protected void setup() {
addBehaviour(new SimpleBehaviour(this) {
private boolean finished = false;
public boolean done(){return finished;}
67
Example – Receiver (Cont.)
public void action() {
ACLMessage msg = receive();
if (msg!= null){
System.out.println(getLocalName() + ": received the following message : ");
System.out.println(msg.toString());
finished = true;
myAgent.doDelete(); }
else{
System.out.println(getLocalName() + ":No message received, Blocking the
behavior till one is"); block();}} // end of action
}); // end of addBehaviour()
} // end of protected void setup()
} // end of SimpleReceiver class
68
Using One Computer

Inputs the command:
– java jade.Boot -gui bob:stringMessageContent.SimpleReceiver;
baz:stringMessageContent.SimpleSender

Outputs the message below:
69
Using Two Computers


In this Example, the Receiver must be executed.
When the Sender is executed, it needs to add the receiver’s IP as
below:
Replace
id.setLocalName("Bob");
by
id.setName("[email protected]:1099/JADE");
id.addAddresses("http://x.x.x.x:7778/acc");
where “x.x.x.x” is the receiver’s IP
70
Result of Sender (baz)

Sender inputs the command (notice receiver IP is needed):
– java jade.Boot –gui baz:stringMessageContent.SimpleSender

Sender outputs the message below:
71
Result of Receiver (bob)

Receiver inputs the command:
– java jade.Boot -gui bob:stringMessageContent.SimpleReceiver

Receiver outputs the message below:
72
2. Message Content with Java Object

There is a bank example that will show how to use java object
for message content.
– setContentObject() : Using this operation to put java object in content
– getContentObject(): Using this operation to get java object from content
(reference :
http://www.iro.umontreal.ca/~vaucher/Agents/Jade/Bank/Bank-1-jObjects/)
73
The bank example with java objects

This example creates two agents which implement the client
and server roles for a bank with savings accounts.

The BankServerAgent class, acts as a server and the
BankClientAgent class acts as client.

The two classes use a common interface,
– BankVocabulary,

that defines the constants which represent the terms that constitute the
specific language of the agents.
74
The bank example Scenario

To create an account or to make an operation, the client
agent sends a



REQUEST message to the server agent.
The server agent responds with an

INFORM after processing the request or with an

NOT_UNDERSTOOD if it cannot decode the content of the message.
To query information about a specific account, the client
agent sends a

QUERY_REF to the server agent which responds with an
–
INFORM after processing the query or with a
–
NOT_UNDERSTOOD if it cannot decode the content of the message.
75
Messages with Java Objects

Classes used in the Bank application:
– Account:

concept of a bank savings account
– Operation:

concept of a bank operation
– MakeOperation:

action of making an operation such as deposit or withdrawal
– OperationList:

concept of the list of last operations
– CreateAccount:

action of creating an account
– Information:

concept of querying information about an account such as the balance and the list
of last operations
– Problem:

result of an action that fails
76
MakeOperation
class MakeOperation implements java.io.Serializable
{
// declaring the class attributes private
private String accountId;
private int type;
private float amount;
// adding public accessor (set/get) methods.
public String getAccountId() { return accountId; }
public int getType() { return type; }
public float getAmount() { return amount; }
public void setAccountId(String accountId) { this.accountId = accountId;}
public void setType(int type) { this.type = type; }
public void setAmount(float amount) { this.amount = amount; }
}
77
BankClientAgent (fragment)
//Client “REQUEST”s the server to carry out a given operation.
MakeOperation mo = new MakeOperation();
mo.setAccountId(acc.getId());
mo.setType(command); mo.setAmount(amount);
ACLMessage msg = new ACLMessage(ACLMessage.REQUEST );
msg.addReceiver(server);
try {msg.setContentObject( mo );}
catch (Exception ex) { ex.printStackTrace(); }
send(msg);
78
BankServerAgent

On the other side,
– server receives and decodes the content of the message as implemented
in the inner classes:
ReceiveMessages and
HandleOperation
of the BankServerAgent class.
79
BankServerAgent
class ReceiveMessages extends CyclicBehaviour
{
public ReceiveMessages (Agent a) {super(a);}
public void action() {
ACLMessage msg = receive();
if (msg == null) { block(); return; }
try {
Object content = msg.getContentObject();
Concept action = ((Action) content).getAction();
switch (msg.getPerformative()) {
case (ACLMessage.REQUEST):
if (action instanceof CreateAccount)
addBehaviour( new HandleCreateAccount(myAgent, msg) );
else if (action instanceof MakeOperation)
addBehaviour( new HandleOperation(myAgent, msg) );
...
}
}
80
BankServerAgent (Cont.)
class HandleOperation extends OneShotBehaviour
{
ACLMessage request;
public HandleOperation (Agent a, ACLMessage request) {
super(a); this.request = request }
public void action() {
try {
Operation op = (Operation) request.getContentObject();
ACLMessage reply = request.createReply();
// Process the operation
Object result = processOperation(op);
...
}
catch (Exception ex) { ex.printStackTrace(); }
} // action
} // class HandleOperation
81
3. Message Content with Ontology Object

In the previous examples, we put plain text (string) or Java objects
in the message content.

FIPA-compliant agents exchange messages with well-defined
structured content language, described by an Ontology.

Ontology allows agents to exchange relatively high-level concepts
without the risk of misunderstanding.

JADE support for
– defining and using content languages based on defined ontology, and
– automatic translation between messages represented in a given content
language and Java objects.
(reference:
http://www.iro.umontreal.ca/~vaucher/Agents/Jade/Bank/Bank-2-Onto/)
82

There is a distinction between the 1)content language, and 2) the
ontology used in messages:
1) The content language describes how a message is encoded. JADE
supports:
– The FIPA-SL family of languages:

A human-readable text representation for messages which
resembles LISP or scheme.
– LEAP encoding:

A lightweight binary encoding designed especially for embedded
applications like palm-tops.
– The Java Codec:

A message encoding designed for efficient exchange between
agents on the same platform.
83
2) The ontology describes the structure and some semantics
of the message content.


JADE doesn’t support OWL or DAML+OIL directly.
In JADE, ontology are encoded as Java classes, either
written by hand or generated automatically using
tools like Protégé.
84
The bank example with ontology



This example creates two agents which implement the client
and server roles for a bank with savings accounts.
The BankServerAgent class, acts as a server and the
BankClientAgent class acts as client.
The two classes use a common interface,
– BankVocabulary,


that defines the constants which represent the terms that constitute the
specific language of the agents.
Operation
– fillContent(): Using this operation to put ontology in content
– extractContent(): Using this operation to get ontology from content
85
The bank example Scenario

To create an account or to make an operation, the client
agent sends a



REQUEST message to the server agent.
The server agent responds with an

INFORM after processing the request or with an

NOT_UNDERSTOOD if it cannot decode the content of the message.
To query information about a specific account, the client
agent sends a

QUERY_REF to the server agent which responds with an
–
INFORM after processing the query or with a
–
NOT_UNDERSTOOD if it cannot decode the content of the message.
86
Defining an application-specific ontology

An application-specific ontology describes the elements that
can be used as content of agent messages.

An ontology is composed of two parts:
1) concepts used by agents in their space of communication.
2) relationships between these concepts, and that describe
their semantics and structure.
87
Defining an application-specific ontology
(Cont.)

You implement an ontology for your application by
– Extending the class Ontology predefined in JADE and
– Adding a set of element schemas describing the structure of

concepts,

actions

predicates
88
BankOntology

We define an BankOntology class that our two agents use to
communicate.

You will deal with the three interfaces:
– Concept

domain knowledge of the communication
– AgentAction

identifier of agent that is requested to perform the action

descriptor representing the task to be performed
– Predicate


proposition representing condition to check.
Corresponding classes are
– ConceptSchema, AgentActionSchema and PredicateSchema.
89

Besides these three interfaces, JADE provides
– PrimitiveSchema (handled by the BasicOntology class) support for
defining atomic elements that constitute of concepts, such as

String,

Integer,

Float…
90

Applying these principles, the Java objects previously defined
in Bank-1-JObjects are modified as follows:
– the Account class now implements the Concept interface
– the Operation class implements the Concept interface
– the MakeOperation class implements the AgentAction interface
– the CreateAccount class implements the AgentAction interface
– the Information class implements the AgentAction interface
– the Problem class implements the Concept interface
91
Four steps in Ontology

Step 1: you define the vocabulary of your agents
communication space in the BankVocabulary interface.
public interface BankVocabulary {
...
//define the terminology for concept of making an operation
public static final String MAKE_OPERATION = "MakeOperation";
public static final String MAKE_OPERATION_TYPE = "type";
public static final String MAKE_OPERATION_AMOUNT = "amount";
public static final String MAKE_OPERATION_ACCOUNTID = "accountId";
...
}
92
MakeOperation
Step 2: you define the Java class that specifies the structure and semantic
of the object MakeOperation. (almost the same as we used in Bank-1JObjects except that it implements AgentAction and not
java.io.Serializable)
class MakeOperation implements AgentAction
{
private String accountId;
private int type;
private float amount;

public String getAccountId() {return accountId; }
public int getType()
{return type; }
……
93
MakeOperation (Cont.)
public float getAmount() {
return amount;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public void setType(int type) {
this.type = type;
}
public void setAmount(float amount) {
this.amount = amount;
}
}
94
In the BankOntology class we find these lines of code
that specify the schema of
the concept MakeOperation (next pages).

Note that the constructor of your ontology class must be
defined with private access and include the static public
method getInstance() that your agent program calls to get a
reference to the singleton instance of your ontology class.
95
BankOntology

Step 3: you define the schema of the object.
public class BankOntology extends Ontology implements BankVocabulary {
// The name identifying this ontology
public static final String ONTOLOGY_NAME = "Bank-Ontology";
// The singleton instance of this ontology
private static Ontology instance = new BankOntology();
96
BankOntology (Cont.)
// Method to access the singleton ontology object
public static Ontology getInstance() { return instance; }
// Private constructor
private BankOntology() {
super(ONTOLOGY_NAME, BasicOntology.getInstance());
try {
// Add Concepts
...
// Add AgentActions
...
97
BankOntology (Cont.)
// Specify the schema of the concept MakeOperation
add ( as = new AgentActionSchema (MAKE_OPERATION), MakeOperation.class);
as.add(MAKE_OPERATION_TYPE,
(PrimitiveSchema) getSchema(BasicOntology.INTEGER),
ObjectSchema.MANDATORY);
as.add(MAKE_OPERATION_AMOUNT,
(PrimitiveSchema)getSchema(BasicOntology.FLOAT),
ObjectSchema.MANDATORY);
as.add(MAKE_OPERATION_ACCOUNTID,
(PrimitiveSchema)getSchema(BasicOntology.STRING),
ObjectSchema.MANDATORY);
...}
catch (OntologyException oe) {oe.printStackTrace();}
}
} // BankOntology
98
BankOntology (Cont.)

add() methods allow you to
– add to the schema of the object that you are defining

add() method that takes three arguments,
– the name of the slot to be added,
– the schema of this slot and
– the optionality.

The optionality can take two values:
– MANDATORY

indicating that the slot cannot have a null value, or
– OPTIONAL

indicating that it can have a null value.
99
BankClientAgent

Step 4: At the server side, we set the content of a message
using an ontology, you must first register with the agent's
content manager
– 1) ontology

The ontology is our BankOntology
– 2) language (that will be used for coding and decoding the content of
messages)

The codec language is “SLCodec” (provided by JADE)
100
BankClientAgent
// In the BankClientAgent class in the directory Bank-2-Onto, you find these lines of code that
// illustrate how to register the language and ontology:
public class BankClientAgent extends Agent implements BankVocabulary {
...
private Codec
codec
= new SLCodec();
private Ontology ontology = BankOntology.getInstance();
protected void setup() {
// Register language and ontology
getContentManager().registerLanguage(codec);
getContentManager().registerOntology(ontology);
...
}
...
} //class BankClientAgent
101
BankClientAgent

To use the ontology when composing your message, you
1. set the attributes of your Java object
2. specify within the message instance, the language and ontology that it
complies to.
3. obtain a reference to the ContentManager object by calling the
method getContentManager() of the Agent class.
4. call the fillContent(...) method of the ContentManager object to
which you pass in arguments the message and the content that it will
be filled with.
102
BankClientAgent
public class BankClientAgent extends Agent implements BankVocabulary {
...
void requestOperation() {
....
//1. set the attributes of your Java object
MakeOperation mo = new MakeOperation();
mo.setType(command);
mo.setAmount(amount);
mo.setAccountId(acc.getId());
sendMessage(ACLMessage.REQUEST, mo);
}
...
103
void sendMessage(int performative, AgentAction action) {
...
ACLMessage msg = new ACLMessage(performative);
//2. specify language and ontology.
msg.setLanguage(codec.getName());
msg.setOntology(ontology.getName());
try {
//3. obtain ContentManager reference by calling getContentManager()
//4. pass message and content by calling fillContent()
getContentManager().fillContent(msg, new Action(server, action));
msg.addReceiver(server);
send(msg);
...
}catch (Exception ex) {
ex.printStackTrace();
}
}
} // End BankClientAgent
104
BankServerAgent

At the server side, you follow the same steps to receive and
extract the content of the message.
1. The server agent must also register its content manager with the same
language and ontology.
2. Obtaining a reference to the content manager object it calls its method
extractContent(...) to which it passes in argument the message to be
extracted.
3. It then casts the extracted content with the Java class that it was
expecting. Once it has the Java object, it can finally retrieve the
content of the slots by calling the get methods provided in the Java
class of the object.
105
BankServerAgent
public class BankServerAgent extends Agent implements BankVocabulary
{
...
private Codec codec = new SLCodec();
private Ontology ontology = BankOntology.getInstance();
...
protected void setup() {
//1. Register language and ontology
getContentManager().registerLanguage(codec);
getContentManager().registerOntology(ontology);
...
}
...
106
BankServerAgent (Cont.)
class ReceiveMessages extends CyclicBehaviour
{
public ReceiveMessages(Agent a) {
super(a);
}
public void action() {
ACLMessage msg = receive();
if (msg == null) { block(); return; }
try {
//2. Obtaining a reference to the content manager object
ContentElement content = getContentManager().extractContent(msg);
//3. casts the extracted content with the Java class
Concept action = ((Action)content).getAction();
107
BankServerAgent (Cont.)
switch (msg.getPerformative())
{
case (ACLMessage.REQUEST):
...
if (action instanceof CreateAccount)
addBehaviour(new HandleCreateAccount(myAgent, msg));
else if (action instanceof MakeOperation)
addBehaviour(new HandleOperation(myAgent, msg));
...
break;
...
}catch(Exception ex) {
ex.printStackTrace();
}
}
} // End ReceiveMessages
108
BankServerAgent (Cont.)
class HandleOperation extends OneShotBehaviour
{
private ACLMessage request;
HandleOperation(Agent a, ACLMessage request)
{
super(a);
this.request = request;
}
109
BankServerAgent (Cont.)
public void action() {
try {
//2. Obtaining a reference to the content manager object
ContentElement content = getContentManager().extractContent(request);
//3. casts the extracted content with the Java class
MakeOperation mo = (MakeOperation)((Action)content).getAction();
//Process the operation
Object obj = processOperation(mo);
//Send the reply
...
} catch(Exception ex) {
ex.printStackTrace();
}
}
} // End HandleOperation
...
}// End BankServerAgent
110
Message Templates
receive()
Agent A
msg
message Buffer
msg
msg
...
msg
send()
Agent B
msg
message Buffer
msg
...
msg
msg
receive()
111
Message Templates (Cont.)

The “MessageTemplate” class allows to build patterns to
match ACL messages against.

Elementary patterns can be combined with AND, OR and
NOT operators, in order to build more complex matching
rules.

In such a way, the queue of incoming ACL messages can be
accessed via pattern-matching rather than first-in-first-out
(FIFO).
112
Message Template Example
import jade.lang.acl.MessageTemplate;
import ….
public class TemplateReceiver extends Agent {
class DoSimpleReceiveBehaviour extends SimpleBehaviour {
private boolean finished = false;
private MessageTemplate message_template= null;
public DoSimpleReceiveBehaviour(Agent agent){
super(agent);
MessageTemplate match_inform =
MessageTemplate.MatchPerformative(ACLMessage.INFORM);
MessageTemplate match_sender =
MessageTemplate.MatchSender(new AID().setLocalName("baz"));
message_template =
MessageTemplate.and(match_inform, match_sender);
} // Constructor of DoSimpleReceiveBehaviour
113
Message Template Example (Cont.)
public void action() {
ACLMessage msg = receive (message_template);
if (msg!= null)
{System.out.println(getLocalName() + ": received the following message : ");
System.out.println(msg.toString()); finished = true; myAgent.doDelete(); }
else
{
System.out.println(getLocalName() + ":No message received, Blocking the
behaviour till one is");
block(); }// else } // action
public boolean done() {return finished;}
}// class DoSimpleReceiveBehaviour
protected void setup()
{
DoSimpleReceiveBehaviour behaviour = new DoSimpleReceiveBehaviour(this);
addBehaviour(behaviour); } //setup
}// class TemplateReceiver
java jade.Boot template:TemplateReceiver
114
Directory Facilitator (DF)
to find other agents

In the previous examples,
– agents sent messages to other agents by using their names in the
outgoing message.

In reality, however,
– agent won't know the name of the agent it wants to talk to start with.
– In order to find agents on a platform we use the directory facilitator
(DF) agent which maintains a directory providing the following
information:

maintain a list of services which can be provided, the agents who can
provide them what languages, interaction protocols and ontologies the
services require.

maintain information about the languages, protocols and ontologies
supported directly by agents
115

In order for an agent providing services to be listed in the DF
directory it must
– register itself
– register the services it provides.

Other agents may then search the DF based on the
– agent properties

its name or the languages it speaks
– properties of the services provided

services have unique names and types as part of the service description.
116
Example - DFOracle
// The oracle is extended to register its self with the DF in its setup() method. And de-register itself when it is
// terinated in the takeDown() method:
import jade.core.*;
import jade.core.behaviours.*;
import jade.lang.acl.*;
import jade.domain.FIPANames.InteractionProtocol;
//import the DF Classes.
import jade.domain.FIPAAgentManagement.*;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.proto.SimpleAchieveREResponder;
import jade.content.*;
import jade.content.onto.*;
import jade.content.onto.basic.*;
import jade.content.lang.*;
import jade.content.lang.sl.*;
import java.util.Random;
import owen.agent.tutorials.contentlanguages.ontology.*;
117
Example – DFOracle (Cont.)
public class DFOracle extends Agent {
long seed;
Ontology ontology;
Codec language;
protected long getSeed(){return seed;}
protected void setup() {
ContentManager manager = getContentManager();
language = new SLCodec();
manager.registerLanguage(language);
ontology = SimpleoracleOntology.getInstance();
manager.registerOntology(ontology);
seed = System.currentTimeMillis();
System.out.println(getLocalName()+ ": Has started, waiting for information queries");
118
Example – DFOracle (Cont.)
//register with the DF
DFAgentDescription description = new DFAgentDescription();
description.addLanguages(language.getName());
description.addOntologies(ontology.getName());
description.addProtocols(InteractionProtocol.FIPA_REQUEST);
description.setName(getAID());
// the service description describes a particular service we
// provide.
ServiceDescription servicedesc = new ServiceDescription();
//the name of the service provided (we just re-use our agent name)
servicedesc.setName(getLocalName());
//The service type should be a unique string associated with
//the service.
servicedesc.setType("AdSE-COURSE-Simple-Agent-Trading-Oracle");
119
Example – DFOracle (Cont.)
//the service has a list of supported languages, ontologies
//and protocols for this service.
servicedesc.addLanguages(language.getName());
servicedesc.addOntologies(ontology.getName());
servicedesc.addProtocols(InteractionProtocol.FIPA_REQUEST);
description.addServices(servicedesc);
//register synchronously registers us with the DF, we may
//prefer to do this asynchronously using a behavior.
try{
DFService.register(this,description);
}catch(FIPAException e){
System.err.println(getLocalName() + ": error registering with DF, exiting:" + e);
doDelete();
return;
}
// we are now registered.
addBehaviour(new SupplyRequestResponder(this));
}
120
Example – DFOracle (Cont.)
//this callback is called when our agent is about to exit
//gracefully (i.e. when asked to by the platform.)
protected void takeDown(){
//it is a very good idea to unregister from the DF when your
//agents exit, bad things will happen otherwise.
try{
DFService.deregister(this);
}catch(FIPAException e ){
System.err.println(getLocalName() + ":Error while deregistering agent:" +e);
}
}
static class IDontUnderstand extends Exception {
IDontUnderstand(String msg){
super(msg);
}
};
// …
// java jade.Boot oracle:DFOracle
121
Example - DFRequester
// The following requester provides the search for find agents providing the services of the oracle:
import jade.core.*;
import jade.core.behaviours.*;
import jade.lang.acl.*;
import jade.domain.FIPANames.InteractionProtocol;
//the DF utility classes among others.
import jade.domain.FIPAAgentManagement.*;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.proto.SimpleAchieveREInitiator;
import jade.content.*;
import jade.content.onto.*;
import jade.content.onto.basic.*;
import jade.content.lang.*;
import jade.content.lang.sl.*;
import jade.util.leap.List;
import java.util.Random;
import java.util.Iterator;
122
Example – DFRequester (Cont.)
public class DFRequester extends Agent {
Ontology ontology;
Codec language;
protected void setup() {
ContentManager manager = getContentManager();
doWait(2000);
language = new SLCodec();
manager.registerLanguage(language);
ontology = SimpleoracleOntology.getInstance();
manager.registerOntology(ontology);
123
Example – DFRequester (Cont.)
//we construct the search query in the same way as we would do
//if we were registering, except we only enter properties
//that we want to match.
DFAgentDescription searchdesc= new DFAgentDescription();
ServiceDescription servicedesc = new ServiceDescription();
//we want to find all agents that match this service type
servicedesc.setType("AdSE-COURSE-Simple-Agent-Trading-Oracle");
//there is little point in trying to find agents who don't
//speak the same language as us.
servicedesc.addOntologies(ontology.getName());
servicedesc.addLanguages(language.getName());
servicedesc.addProtocols(InteractionProtocol.FIPA_REQUEST);
124
Example – DFRequester (Cont.)
searchdesc.addServices(servicedesc);
DFAgentDescription results[];
try{
results= DFService.search(this,searchdesc);
}catch(FIPAException e){
System.err.println(getLocalName()
+ ": could not search the DF, exiting:" + e);
doDelete();
return;
}
//DF search ends here.
125
Example – DFRequester (Cont.)
if(null==results || results.length ==0 ){
System.err.println(getLocalName() + ": No Oracle Agents found, exiting");
doDelete();
return;
}else{
System.out.println(getLocalName() + ": Found "
+ results.length + " agent(s) who matched my query:");
for(int i= 0 ;i < results.length; i ++){
System.out.println(getLocalName() +":\t " +
results[i].getName().getLocalName());
}
}
// …
// java jade.Boot requester:DFRequester
126
Agent Mobility

Agent mobility is the ability for an agent program to
migrate or to make a copy (clone) itself across one or
multiple network hosts.

The current version of JADE supports only intraplatform mobility, that is, an agent can move only
within the same platform (JADE) from container to
container.
(reference:
http://www.iro.umontreal.ca/~vaucher/Agents/Jade/Mobility/)
127
Agent Mobility (Cont.)

The JADE Agent class provides a suitable
JADE API (to be discussed shortly) that
enables an agent to access the AMS agent via
FIPA ACL.

Mobile agents need to be location awared in
order to decide when and where to move.

Therefore, JADE provides a proprietary
ontology, named jade-mobility-ontology,
holding the necessary concepts and actions.
128


There are two ways to move (or clone) an
agent:
1) the agent calls doMove() (or doClone() )
to move (or clone) itself.

2) the agent call AMS to move (or clone) it.
129
JADE API for agent mobility

doMove (Location destination)
– allow agent to migrate elsewhere.


takes jade.core.Location as parameter, which
represents the destination for the migrating agent.
doClone (Location destination,String newName)
– to spawn a remote copy of itself under a different name.

takes jade.core.Location as parameter, which
represents the destination for the cloning agent.

a String containing the name of the new agent.
130
JADE API for agent mobility (Cont.)

Agents are not allowed to create their own
locations.

Instead, they must ask the AMS for the list of
the available locations and choose one from
the list.

Agents can also request the AMS to tell where
(at which location) another agent lives.
131
JADE API for agent mobility (Cont.)

beforeMove()
– is called at the starting location when the move operation
has successfully completed.
– so that the moved agent instance on the destination
container is about to be activated and the original agent
instance is about to be stopped.

afterMove()
– is called at the destination location as soon as the agent
has arrived and its identity is in place.
132
JADE Mobility Ontology

The jade-mobility-ontology ontology contains all
the concepts and actions needed to support agent
mobility.

JADE provides the class:
jade.domain.mobility.MobilityOntology,
working as a Singleton and giving access
to a single, shared instance of the JADE mobility
ontology
through the getInstance() method.
133
JADE Mobility Ontology (Cont.)

The ontology contains five concepts and two actions
(in package jade.domain.mobility):

Five concepts:
1) mobile-agent-description
• describes a mobile agent going somewhere.
• It is represented by the MobileAgentDescription class.
2) mobile-agent-profile
• describes the computing environment needed by the mobile
agent.
• It is represented by the MobileAgentProfile class.
134
JADE Mobility Ontology (Cont.)
3) mobile-agent-system
•
describes the runtime system used by the mobile agent.
•
It is represented by the MobileAgentSystem class.
4) mobile-agent-language
•
describes the programming language used by the mobile agent.
•
It is represented by the MobileAgentLanguage class.
5) mobile-agent-os
•
describes the operating system needed by the mobile agent.
•
It is represented by the MobileAgentOS class.
135
JADE Mobility Ontology (Cont.)

Two actions:
1) move-agent
• the action of moving an agent from a location to
another.
• It is represented by the MoveAction class.
2) clone-agent
• the action performing a copy of an agent, possibly
running on another location.
• It is represented by the CloneAction class.
136
JADE Mobility Ontology (Cont.)

To be able to use these objects,
you must declare the SLCodec language
and the MobilityOntology ontology and
register them with the agents content manager.
137
Accessing the AMS for agent mobility

The JADE AMS support the agent mobility,
and it is capable of performing the two actions
present in the:
jade-mobility-ontology.

Every mobility related action can be requested
to the AMS through a FIPA-request protocol,
with:
–jade-mobility-ontology as ontology value
–FIPA-SL0 as language value.
138
Accessing the AMS for agent mobility (Cont.)

The move-agent action takes
a mobile-agent-description
as its parameter.

This action moves the agent
identified by the “name and address” slot
of the mobile-agent-description
to the location present in the destination slot.
139

For example,
if an agent wants to move the agent Johnny
to the location called Front-End,
it must send to the AMS
the following ACL request message:
140
(REQUEST
:sender (agent-identifier :name RMA@Zadig:1099/JADE)
:receiver (set (agent-identifier :name ams@Zadig:1099/JADE))
:content (
(action (agent-identifier :name ams@Zadig:1099/JADE)
(move-agent (mobile-agent-description
:name (agent-identifier :name Johnny@Zadig:1099/JADE)
:destination (location
:name Main-Container
:protocol JADE-IPMT
:address Zadig:1099/JADE.Main-Container )
)
)
)
)
:reply-with Req976983289310
:language FIPA-SL0
:ontology jade-mobility-ontology
:protocol fipa-request
:conversation-id Req976983289310
)
141

Using JADE ontology support, an agent can easily add
mobility to its capabilities, without having to compose ACL
messages by hand:

1) the agent has to 1) create a MoveAction object,
2) fill its argument with
a suitable MobileAgentDescription object,
3) filled in turn with the name and address of the agent to
move and with the Location object for the destination.

2) a single call to the
Agent.getContentManager().fillContent(..,..) method can turn
the MoveAction Java object into a String and write it into the
content slot of a suitable request ACL message.
142

The clone-agent action works
in the same way,
but has an additional String argument
to hold the name of the new agent
resulting from the cloning process.
143
Example
………..
Location dest = (Location)locations.get(destName);
MobileAgentDescription mad = new
MobileAgentDescription();
mad.setName (new AID(“Johnny ”, AID.ISLOCALNAME) );
mad.setDestination (dest);
MoveAction ma = new MoveAction();
ma.setMobileAgentDescription (mad);
Action action = new Action(aid, ma); //aid is my agent identifier
144
Example (Cont.)
ACLMessage request = new
ACLMessage(ACLMessage.REQUEST);
request.setLanguage(new SLCodec().getName());
request.setOntology(MobilityOntology.getInstance().getName())
;
try {
getContentManager().fillContent(request, action);
request.addReceiver(action.getActor());
send (request);
} catch (Exception ex) { ex.printStackTrace(); }
………………
145

To move an agent, you just need to call the method
doMove(Location) within your agent program passing in
parameter to it the new destination of the agent which must be
a Location object.

You cannot create by yourself a Location object.

To get a Location object, you must query this information
with the AMS, by sending it a REQUEST with below as
content message:
– WhereIsAgentAction

allows you to obtain with the location of a given agent.
– QueryPlatformLocationsAction

allows you to query AMS to obtain all available
locations within a given platform.
146
Example - Get available locations with AMS
// Register language and ontology
getContentManager().registerLanguage(new SLCodec());
getContentManager().registerOntology(MobilityOntology.getInstance());
try {
………………….
// Get available locations with AMS
Action action = new Action(getAMS(), new QueryPlatformLocationsAction() ) );
ACLMessage request = new ACLMessage(ACLMessage.REQUEST);
request.setLanguage(new SLCodec().getName());
request.setOntology(MobilityOntology.getInstance().getName());
try {
getContentManager().fillContent(request, action);
request.addReceiver(action.getActor());
send(request);
}
catch (Exception ex) { ex.printStackTrace(); }
147
Example - Get available locations with AMS
//Receive response from AMS
ACLMessage resp = blockingReceive ();
ContentElement ec = getContentManager().extractContent (resp);
Result result = (Result) ec;
jade.util.leap.Iterator it = result.getItems().iterator();
while (it.hasNext()) {
Location loc = (Location)it.next();
……………..
}
}
catch (Exception e) { e.printStackTrace(); }
148
Interaction Protocols

JADE provides behavior classes for conversations of FIPA
(Foundation for Intelligent Physical Agents) interaction
protocols.

FIPA is an international organization, defined some standard
interaction protocols, for example:
– Request-Inform

A requested B to do some task, B can accept or reject. If B agreed, then B
will finish the task and inform A that the task has been finished.
149
Interaction Protocols (Cont.)
– Query

A wants to know something, B maybe accept or reject and then B informs
A of B’s response.
– Contract-Net

This interaction protocol allows the Initiator to send a Call for Proposal to
a set of responders, evaluate their proposals and then accept the preferred
one (or even reject all of them).
– Propose

This interaction protocol allows the Initiator to send a propose message to
the Participant indicating that it will perform some action if the Participant
agrees.
150
An Example –
FIPA Request Interaction Protocol

We use request as an example:
1. The initiator requests that
something should be done.
2. The participant either refuses, or
agrees to do it.
3. If the participant agreed to do the
thing, then they should try and do
it and
1.
report "failure" if it failed,
2.
"inform-done" if it was completed
and no results were given, or
3.
"inform-result" if there were results
to report.
151

JADE has classes for implementing the behaviors required for
this protocol.

Simple case: (for protocols involving only 2 agents)
– SimpleAchieveREInitiator (Initiator)
– SimpleAchieveREResponder (participant)

Complicated case: (for engaging multiple agents using the
same protocol.)
– AchieveREInitiator (Initiator)
– AchieveREResponder (Participant)
152
Note

We create a class which
– extends from SimpleAcheiveReInitiator behaviour and
– overides several methods:


handleAgree(..)

handleRefuse(..)

handleInform(..)

handleNotUnderstood(..) // other agent didn't understand the request

handleOutOfSequence(...) // illegal reply according to the protocol
The behavior will generate callbacks to these methods when
corresponding messages arrive.
153
Note (Cont.)

The only two things that the initiator has to do to indicate it
is starting a request protocol with the participant are:
1. Set message with a REQUEST performative.
2. Set protocol of the message with InteractionProtocol.FIPA_REQUEST
property
154
Example - SimpleRequestInitiator
import java.io.InterruptedIOException;
import java.io.IOException;
import jade.core.*;
import jade.core.behaviours.*;
import jade.lang.acl.*;
import jade.domain.FIPANames.InteractionProtocol;
import jade.proto.SimpleAchieveREInitiator;
import java.util.Vector;
import java.util.Enumeration;
public class SimpleRequestInitiator extends Agent {
// extends SimpleAchieveREInitiator and overriding handleXXX()
static class MarriageProposer extends SimpleAchieveREInitiator {
protected MarriageProposer (Agent agent, ACLMessage msg) {super (agent,msg); }
//This method is called every time an agree message is received, which is not out-of-sequence according
// to the protocol rules.
protected void handleAgree(ACLMessage msg) {
System.out.println(myAgent.getLocalName() + ": OOH! " +
msg.getSender().getLocalName() +
" has agreed to marry me, I'm so excited!");
}
155
Example - SimpleRequestInitiator (Cont.)
// This method is called every time a refuse message is received, which is
// not out-of-sequence according to the protocol rules.
protected void handleRefuse(ACLMessage msg) {
System.out.println(myAgent.getLocalName() + ": Oh no! " +
msg.getSender().getLocalName() +
" has rejected my proposal, I feel sad.");
}
// This method is called every time a inform message is received, which is not
// out-of-sequence according to the protocol rules.
protected void handleInform(ACLMessage msg) {
System.out.println(myAgent.getLocalName() + ":" +
msg.getSender().getLocalName() +
" has informed me of the status of my request." +
" They said : " + msg.getContent());
}
156
Example - SimpleRequestInitiator (Cont.)
// This method is called every time a not-understood message is received, which is not
// out-of-sequence according to the protocol rules.
protected void handleNotUnderstood(ACLMessage msg){
System.out.println(myAgent.getLocalName() + ":"
+ msg.getSender().getLocalName() +
" has indicated that they didn't understand.");
}
// This method is called every time a message is received, which is out-of-sequence
// according to the protocol rules.
protected void handleOutOfSequence(ACLMessage msg) {
System.out.println(myAgent.getLocalName() + ":"
+ msg.getSender().getLocalName() +
"has send me a message which I wasn't" +
" expecting in this conversation");
}
}
157
Example - SimpleRequestInitiator (Cont.)
protected void setup() {
System.out.println(getLocalName() +": about to propose marriage to bob ");
// wait for bob to be started.
doWait(5000);
ACLMessage msg = new ACLMessage(ACLMessage.REQUEST);
AID to = new AID();
to.setLocalName("bob");
msg.setSender(getAID());
msg.addReceiver(to);
msg.setContent("Marry Me!");
msg.setProtocol(InteractionProtocol.FIPA_REQUEST);
addBehaviour(new MarriageProposer(this,msg));
}
} // java jade.Boot baz:SimpleRequestInitiator
158
Example - SimpleRequestResponder
import java.io.InterruptedIOException;
import java.io.IOException;
import jade.core.*;
import jade.core.behaviours.*;
import jade.lang.acl.*;
import jade.domain.FIPANames.InteractionProtocol;
import jade.proto.SimpleAchieveREResponder;
import java.util.Vector;
import java.util.Enumeration;
public class SimpleRequestResponder extends Agent {
static class MarriageResponder extends SimpleAchieveREResponder{
public MarriageResponder(Agent agent){
// this only receives messages which are appropriate for the FIPA-REQUEST protocol
super(agent,
createMessageTemplate(InteractionProtocol.FIPA_REQUEST));
}
159
Example - SimpleRequestResponder (Cont.)
// This method is called when the initiator's message is received that matches the
// message template passed in the constructor.
protected ACLMessage prepareResponse(ACLMessage msg) {
ACLMessage response = msg.createReply();
// we only understand "Marry Me!" messages. it is necesary
// to reply with not-undestood if this was the case.
if(msg.getContent()!=null && msg.getContent().equals("Marry Me!")){
System.out.println(myAgent.getLocalName() + ":" +
msg.getSender().getLocalName() + " has asked me to marry him!");
AID sender = msg.getSender();
if(sender.getLocalName().equals("baz")){
//I, bob, only have eyes for baz
response.setPerformative(ACLMessage.AGREE);
System.out.println(myAgent.getLocalName() + ":I'm going to agree.");
160
Example - SimpleRequestResponder (Cont.)
}else{
// I am not easy I won't marry just anybody
response.setPerformative(ACLMessage.REFUSE);
System.out.println(myAgent.getLocalName() +
":I'm going to turn him down.");
}
}else{
response.setPerformative(ACLMessage.NOT_UNDERSTOOD);
System.out.println(myAgent.getLocalName() +
":I didn't understand what " +
msg.getSender().getLocalName() +
" just said to me.");
}
return response;
}
161
Example - SimpleRequestResponder (Cont.)
// This method is called after the response has been sent and only when one of the
// following two cases arise: the response was an agree message OR no response
// message was sent.
// Parameters:
// request - the received message
// response - the previously sent response message
protected ACLMessage prepareResultNotification(ACLMessage request ,
ACLMessage response ) {
//this callback happens if we sent a positive reply to
//the original request (i.e. an AGREE) if we have agreed
//to be married, we have to inform the other agent that
//what they have asked is now complete (or if it failed)
ACLMessage msg = request.createReply();
msg.setPerformative(ACLMessage.INFORM);
msg.setContent("I Do!");
return msg;
}
}
162
Example - SimpleRequestResponder (Cont.)
protected void setup() {
System.out.println(getLocalName() +
": I wonder if anybody wants to marry me?");
addBehaviour(new MarriageResponder(this));
}
} // java jade.Boot bob:SimpleRequestResponder
163
FIPA-Contract-Net
164
FIPA-Contract-Net (Cont.)

The initiator solicits proposals from other agents by sending a
CFP message that specifies the action to be performed.

The responders can then
– reply by sending a PROPOSE message including the preconditions that
they set out for the action, for instance the price or the time.
– send a REFUSE message to refuse the proposal.
– a NOT-UNDERSTOOD to communicate communication problems.

The initiator can then evaluate all the received proposals and
make its choice of which agent proposals will be accepted and
which will be rejected.
165
FIPA-Contract-Net (Cont.)

Once the responders whose proposal has been accepted (i.e.
those that have received a ACCEPT-PROPOSAL message)
have completed their task, they can,
– respond with an INFORM of the result of the action (eventually just
that the action has been done)
– or with a FAILURE if anything went wrong.
166
FIPA-Propose
167
FIPA-Propose (Cont.)

This interaction protocol allows the Initiator to send a propose message to
the Participant indicating that it will perform some action if the Participant
agrees.

The Participant responds by either accepting or rejecting the proposal,
communicating this with the accept-proposal or reject proposal
communicative act, accordingly.

Completion of this IP
with an accept-proposal act
would typically be followed by
1)the performance by the Initiator of the proposed action
and then
2) the return of a status response.
168
FIPA-Subscribe
169
FIPA-Subscribe (Cont.)

This interaction protocol allows the Initiator to send a subscribe message
to the Participant indicating its desired subscription.

The Participant processes the subscribe message and responds to the query
request by either accepting or rejecting the subscription.

If the Participant refuses the request it communicates a refuse,
alternatively if the Participant agree it can communicate an optional agree.

If the Participant agrees to a subscription, it communicates all content
matching the subscriptions condition using an inform-result, i.e. an inform
communicative act with a result predicate as content.

The Participant continues to send inform-results until either the Initiator
cancels, communicated by sending a cancel message, or the Participant
experiences a failure, communicated with a failure message.
170