Agent-Based Systems. Grading l Mid-term Exam 30% l Labs 40% l Final Presentation 30%

Post on 12-Jan-2016

213 views 0 download

Transcript of Agent-Based Systems. Grading l Mid-term Exam 30% l Labs 40% l Final Presentation 30%

Agent-Based Systems

Grading

Mid-term Exam 30%

Labs 40%

Final Presentation 30%

3

OOSE/04 Notes: 2004 by SEC

Project Documents (NOT Used)

張一二李一三 .rar 內含下列文件 :

產品說明 .doc

驗收測試 .doc

架構 .xxx (UML class diagram)

Scanners.java (header, pseudo code, source code) …

4

OOSE/04 Notes: 2004 by SEC

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 並檢視文件

5

OOSE/04 Notes: 2004 by SEC

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)

6

OOSE/04 Notes: 2004 by SEC

Changes in Computing World

0. Single Machine C, Unix

1. Internet TCP/IP

2. Web HTTP, UDDI, SOAP

3. Semantic Web Agent, Ontology

Software Engineering Goal

SE goal is to reduce cognitive complexity through moving up abstraction levels.

Paradigm shifts raise the level of abstraction for developers.

We see paradigm shifts in recent SE history:

agent

object modal

function data

Three Software Engineering paradigms

1. Function paradigm

2. Object paradigm

3. Agent paradigm

Function paradigm

A software system is composed of functions, each performs a specific task. And the functions are not nested.

Typical language: C

The paradigm reduces cognitive load of developers, since structured constructs are used here to eliminate “goto” which causes huge cognitive load.

C Example of Function paradigm

main () { printf(“%d”, power(2, 3) /* 2**3 expects 8 */ ); }

int power (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); }

Object paradigm

A software system is composed of classes, each contains data structure and methods.

Object can be constructed at run-time that allocates a copy of the data structure of the class, and an object can invoke a method of its class.

Typical language: Java

This paradigm reduces communication load between customers and developers, as classes exactly model real-world entities.

Note that a method is actually a function just mentioned. That is, object paradigm extends function paradigm.

Java Example of Object paradigm

public class MathClass {

private mathLevels myMathLevel;

public MathClass ( ) { } /* constructor */

public power (int x, int n) { …}

} // MathClass

Agent paradigm

A software system is composed of agents. Agents can be created from agent classes. Each agent executes independently, and it can communicate with other agents.

An agent holds modal that presents mental model of its owner, and agent communication is driven by modal operator, such as Belief, Uncertainty.

Typical platform: JADE (Java Agent DEvelopment Framework)

This paradigm reduces communication load of customers, as agents easily model customers’ experiences, attitudes and thoughts in mental model.

Note that agent class extends Java thread class. That is, agent paradigm extends object paradigm.

JADE Example of Agent paradigm/* 計算 y=x^n */

class PowerBehaviour extends SimpleBehaviour {

private boolean finished = false; private int x ,n,y;

public PowerBehaviour (MathAgent agent, int x, int n) {

super (agent); this.x=x; this.n=n; }

public boolean done() { return finished; }

public void action() { for(y=x;--n>0;y*=x);finished=true; }

} // end of PowerBehaviour

public class MathAgent extends Agent {

protected void setup() {

PowerBehaviour power = new PowerBehaviour(this, 2, 3);

this.addBehaviour(power); }

} // end of MathAgent

Agent paradigm (Cont.)

The promises of agent paradigm are:

1) Improved flexibility:

Agents can register (join) or deregister (leave) a society (that is a software system) at any time. A 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, a software system is more reliable.

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.

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.

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]

Uses of Mobile Agent

1) Disconnected computing, such as 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]

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 ever-more powerful abstractions with which to build computer systems. [www.agentlink.org]

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.

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.

Architecture of a FIPA Agent Platform

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.

JADE Agent Platform distributed over several containers

Agent life cycle

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.

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

Starting JADE java jade.Boot (without GUI)

java jade.Boot -gui (see figure below)

Running an Agent

java jade.Boot [AgentName]:[ClassName] – AgentName: a globally unique agent name.

– ClassName: the Java class name.

For example:

java jade.Boot -gui ping1:PingAgent

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.

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:HelloWorld

Running an HelloWorld Agent Using Eclipse

Create a new project

Running an HelloWorld Agent Using Eclipse

Select Java Project and click Next

Running an HelloWorld Agent Using Eclipse

Project name is Agent then click Next

Running an HelloWorld Agent Using Eclipse

Click Finish

Running an HelloWorld Agent Using Eclipse

Click mouse right button at mouse to set Build Path

Running a HelloWorld Agent Using Eclipse

Add http.jar,

iiop.jar,

jade.jar,

jadeTools.jar and

commons-codec-1.3.jar

into Eclipse

Running an HelloWorld Agent Using Eclipse

Click mouse right button at mouse to new a class

Running an HelloWorld Agent Using Eclipse

Name is HelloWorld and Superclass is jade.core.Agent

Running an HelloWorld Agent Using Eclipse

Copy example and paste in Eclipse

Running an HelloWorld Agent Using Eclipse

Click red area and select Run…

Running an HelloWorld Agent Using Eclipse

Click mouse right button at mouse and select new

Running an HelloWorld Agent Using Eclipse

Name is HelloWorld and Main Class is jade.Boot

Select Arguments

Running an HelloWorld Agent Using Eclipse

Program arguments is –gui Hello:HelloWorld

Click Apply and Run to run agent

Running an HelloWorld Agent Using Eclipse

If run success, it will show as follow

Agent Behaviors

Simple Behaviors: – SimpleBehaviour, OneShotBehaviour, CyclicBehaviour

Composite Behaviors: – ParallelBehaviour, SerialBehaviour

SimpleBehaviourimport 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;

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

public boolean done ( ) {return finished;} }; // new SimpleBehavior

addBehaviour (decative); } //setUp

}// DecativeReentrant

java jade.Boot -container doreme1:DecativeReEntrant

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 java jade.Boot doreme2:DecativeSequential

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); }

java jade.Boot parall:ParallelBehaviourAgent

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

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 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.

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).

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

– Agent j will respond with a message containing:in-reply-to order567

54

OOSE/04 Notes: 2004 by SEC

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.

55

OOSE/04 Notes: 2004 by SEC

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()

56

OOSE/04 Notes: 2004 by SEC

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()

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.setOntology(“Weather-forecast-ontology”);

msg.setContent(“Today it’s raining”);

send(msg);

Example - Senderimport 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;

}

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") ;

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

Example - Receiver

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;}

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 addBehaviour()

} // end of protected void setup()

} // end of SimpleReceiver class

Using One Computer

Inputs the command:– java jade.Boot baz:SimpleSender bob:SimpleReceiver

Outputs the message below:

63

OOSE/04 Notes: 2004 by SEC

Using Two Computers

In this Example, the Receiver must be executed.

When the Sender is executed, it needs to add:

-container -host bob’s ip

after jade.Boot.

64

OOSE/04 Notes: 2004 by SEC

Result of Receiver (bob)

Receiver inputs the command:– java jade.Boot bob:SimpleReceiver

Receiver outputs the message below:

65

OOSE/04 Notes: 2004 by SEC

Result of Sender (baz)

Sender inputs the command:– java jade.Boot -container -host bob’s ip baz:SimpleSender

Sender outputs the message below:

Message Templates

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 FIFO.

Message Template Exampleimport 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);

} // TemplateReceiver

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;}

}

protected void setUp() {

DoSimpleReceiveBehaviour behaviour = new DoSimpleReceiveBehaviour(this);

addBehaviour(behaviour); } //setUp

} // action ???

java jade.Boot template:TemplateReceiver

69

OOSE/04 Notes: 2004 by SEC

2. Message Content with Java Objects

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

70

OOSE/04 Notes: 2004 by SEC

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.

71

OOSE/04 Notes: 2004 by SEC

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.

72

OOSE/04 Notes: 2004 by SEC

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

73

OOSE/04 Notes: 2004 by SEC

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; }

}

74

OOSE/04 Notes: 2004 by SEC

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);

75

OOSE/04 Notes: 2004 by SEC

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.

76

OOSE/04 Notes: 2004 by SEC

BankServerAgentclass 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) );

...

}

}

77

OOSE/04 Notes: 2004 by SEC

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

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.

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.

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é.

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

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.

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.

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

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.

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…

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

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";

...

}

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;

public String getAccountId() {return accountId; }

public int getType() {return type; }

……

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;

}

}

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.

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();

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

...

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

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.

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)

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

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.

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);

}

...

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

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.

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);

...

}

...

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();

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

BankServerAgent (Cont.)

class HandleOperation extends OneShotBehaviour

{

private ACLMessage request;

HandleOperation(Agent a, ACLMessage request)

{

super(a);

this.request = request;

}

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

Directory Facilitator (DF) to find other agents

In the previous examples – sent messages to other agents by using their names in the outgoing

message.

In reality – 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

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.

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.*;

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");

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");

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));

}

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

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;

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);

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);

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.

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

Building agent with integrated GUI

JADE has provided an mechanism to manage interactions between the two threads when integrating a GUI with an agent.

The mechanism is based on event passing.

1. The agent interacting with the GUI

2. The GUI interacting with the agent

The agent interacting with the GUI

When your agent program interacts with the GUI, it just calls the method within the GUI program.

The GUI interacting with the agent

JADE has provided the abstract class GuiAgent that extends the Agent class.

This class has two specific methods: – postGuiEvent()

In GUI. Use addParameter() in GuiEvent object to adds the parameters and

passes it as argument to the postGuiEvent() method.

– onGuiEvent() In agent class. Your agent use to receive and process events that are passed by the GUI

via the method postGuiEvent(). onGuiEvent() method as equivalent of actionPerformed() method. The agent program must extend the GuiAgent class

BankClientAgentGui

// The BankClientAgentGui class implements the ActionListener interface.

class BankClientAgentGui extends JFrame implements ActionListener {

...

// myAgent is a reference to the owner agent class.

private BankClientAgent myAgent;

public BankClientAgentGui(BankClientAgent a) {

myAgent = a;

...

}

BankClientAgentGui (Cont.)public void actionPerformed(ActionEvent ae) {

// Process the event according to it's source

if (ae.getSource() == ok) {

if (menu.getSelectedItem().equals( "New Account“ )) {

// Create a GUI event, take NEW_ACCOUNT as an event type

GuiEvent ge = new GuiEvent(this, NEW_ACCOUNT);

// Posts this GUI event from the GUI thread to the event queue

myAgent.postGuiEvent(ge);

} else if (menu.getSelectedItem().equals( "Deposit“ )) {

BankClientAgentGui (Cont.)

…………

Account account = accounts.get(acList.getSelectedIndex());

int type = DEPOSIT;

// Create a GUI event, take type as an event type

GuiEvent ge = new GuiEvent(this, type);

// Add account and amount as parameter to this GuiEvent.

ge.addParameter(account);

ge.addParameter(new Float(amount) );

// Posts this GUI event from the GUI thread to the event queue

myAgent.postGuiEvent(ge);

…………

} // end if

BankClientAgent (Cont.)

public class BankClientAgent extends GuiAgent {

...

// Reference to the BankClientAgentGui class

protected BankClientAgentGui myGui;

protected void setup() {

// calls the constructor of the BankClientAgentGui class

// passing this agent in parameter to it :

myGui = new BankClientAgentGui( this );

myGui.setVisible(true);

}

...

BankClientAgent (Cont.) // abstract method to handle posted GUI events

protected void onGuiEvent(GuiEvent ev) {

// calling the method getType() on the GuiEvent object

// and processes the event by calling the appropriate handler.

command = ev.getType();

if (command == NEW_ACCOUNT) {

createAccount();

} else if (command == DEPOSIT) {

// get the parameter from the GuiEvent object

Account acc = (Account)ev.getParameter(0);

float amount = ((Float)ev.getParameter(1)).floatValue();

requestOperation(acc, amount);

}else if (………)

...

}

}

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 intra-platform mobility, that is, an agent can move only within the same platform (JADE) from container to container.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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:

(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

)

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.

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.

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

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(); }………………

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.

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(); }

Example - Get available locations with AMS

//Receive response from AMS

ACLMessage resp = blockingReceive ();

ContentElement ce = getContentManager().extractContent (resp);

Result result = (Result) ce;

jade.util.leap.Iterator it = result.getItems().iterator();

while (it.hasNext()) {

Location loc = (Location)it.next();

……………..

}

} catch (Exception e) { e.printStackTrace(); }

149

OOSE/04 Notes: 2004 by SEC

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.

150

OOSE/04 Notes: 2004 by SEC

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.

151

OOSE/04 Notes: 2004 by SEC

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.

152

OOSE/04 Notes: 2004 by SEC

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)

153

OOSE/04 Notes: 2004 by SEC

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.

154

OOSE/04 Notes: 2004 by SEC

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

155

OOSE/04 Notes: 2004 by SEC

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!");

}

156

OOSE/04 Notes: 2004 by SEC

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());

}

157

OOSE/04 Notes: 2004 by SEC

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");

}

}

158

OOSE/04 Notes: 2004 by SEC

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

159

OOSE/04 Notes: 2004 by SEC

Example - SimpleRequestResponderimport 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));

}

160

OOSE/04 Notes: 2004 by SEC

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.");

161

OOSE/04 Notes: 2004 by SEC

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;

}

162

OOSE/04 Notes: 2004 by SEC

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;

}

}

163

OOSE/04 Notes: 2004 by SEC

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

164

OOSE/04 Notes: 2004 by SEC

FIPA-Contract-Net

165

OOSE/04 Notes: 2004 by SEC

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.

166

OOSE/04 Notes: 2004 by SEC

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.

167

OOSE/04 Notes: 2004 by SEC

FIPA-Propose

168

OOSE/04 Notes: 2004 by SEC

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.

169

OOSE/04 Notes: 2004 by SEC

FIPA-Subscribe

170

OOSE/04 Notes: 2004 by SEC

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.