Agent Oriented Prog
Agent Oriented Prog
Agent Oriented Prog
Programming
(AOP)
1
Grading
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)
4
3. 兩台Notebook 電腦上網 來做 DEMO 並檢視文件
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
最後,一起做驗收測試
6
Programming Goal
The goal of programming is to reduce cognitive load of
developers through moving up the abstraction levels.
agent
object distributed mentality
method data state
7
Three Programming Paradigms
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
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.
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
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
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.
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.
18
Uses of Mobile Agent
1) Disconnected computing, such as personal digital assistant
(PDA) that might be disconnected in short notice.
19
Why are agents important?
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 middle-
ware 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
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.*;
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;
52
Parallel Behaviour
import jade.core.*; import jade.core.behaviours.SequentialBehaviour;
import jade.core.behaviours.ParallelBehaviour; import jade.core.behaviours.OneShotBehaviour;
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;
55
Sequential Behaviour(Cont.)
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.
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, reply-
with, in-reply-to, reply-by.
For example,
– if agent i sends to agent j a message which contains:
reply-with 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:
62
Examples of the 3 ways above
1) String: age:25 name:Tzou
easy for human, but hard for parser
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.*;
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.
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.
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;
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);}
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.
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:
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-1-
JObjects except that it implements AgentAction and not
java.io.Serializable)
class MakeOperation implements AgentAction
{
private String accountId;
private int type;
private float amount;
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).
95
BankOntology
Step 3: you define the schema of the object.
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:
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 > ...
106
BankServerAgent (Cont.)
class ReceiveMessages extends CyclicBehaviour
{
public ReceiveMessages(Agent a) {
super(a);
}
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 message Buffer
msg msg ... msg msg
send()
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
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;
manager.registerLanguage(language);
> 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);
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;
> 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");
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:");
126
Agent Mobility
(reference:
http://www.iro.umontreal.ca/~vaucher/Agents/Jade/Mobility/)
127
Agent Mobility (Cont.)
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.)
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
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.)
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,
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,
143
Example
………..
Location dest = (Location)locations.get(destName);
MobileAgentDescription mad = new
MobileAgentDescription();
mad.setName (new AID(“Johnny ”, AID.ISLOCALNAME) );
mad.setDestination (dest);
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)
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
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;
//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.)
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;
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
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.)
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.
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