WYKŁAD 6 JADE - Java Agent DEvelopment Framework http://jade.tilab.com/index.html JADE jest systemem oprogramowania ułatwiającym tworzenie systemów agentowych i wieloagentowych. Składa się z trzech części:! systemu czasu wykonania (runtime environment) środowiska w którym żyją programy agentów (jade.boot)! biblioteki klas, które są wykorzystywane do oprogramowania podstawowych funkcji życiowych agenta! zestawu narzędzi (programów) umożliwiających monitorowanie i administrowanie wszystkimi elementami infrastruktury JADE. Organizacja infrastruktury JADE: container - działająca instancja środowiska - systemu czasu wykonania platform - zbiór aktywnych instancji (uruchomionych na jednym komputerze lub na kilku komputerach połączonych siecią). Każda platforma zawiera przynajmniej jeden container, pierwszy z uruchomionych nazywa się main container. main container posiada zawsze dwóch specjalnych agentów: AMS - Agent Management System realizujący usługi nazywania-identyfikacji i zarządzania agentami, DF - Directory Facilitator realizujący usługi YellowPages 1
Instalacja:! system JADE i oprogramowanie agentów jest napisane w języku Java, do poprawnego działania konieczne jest wcześniejsze zainstalowanie JDK, przynajmniej w wersji 1.4 ( http://java.sun.com/j2se )! pliki instalacyjne systemu JADE można uzyskać ze strony internetowej TILAB: http://jade.tilab.com/index.html należy je rozpakować i skopiować do katalogu JADE (np. x:\jade ) jadebin.zip skompilowane-gotowe do użycia pliki systemu JADE w postaci zbioru archiwów JAR x:\jade\lib\jade.jar \jadetools.jar \Base64.jar \http.jar \iiop.jar Ścieżkę x:\jade należy dodać do CLASSPATH. Uruchomienie środowiska: java\jade.boot gui jadedoc.zip dokumentacja systemu, opis bibliotek, wraz z instrukcjami administrowania i programowania, w postaci HTML oraz plików PDF x:\jade\doc\api\ \examples\ \html\ \tools\ \tutorials\ jadesrc.zip kody źródłowe całego systemu JADE (free software, GNU License) jadeexamples.zip kody źródłowe demo oraz przykładów opisywanych w dokumentacji 2
Implementacja prostego agenta HalloWorld W systemie JADE agenci tworzeni są poprzez dziedziczenie własności podstawowej klasy jade.core.agent i przedefiniowanie podstawowych jej metod: protected void setup( ) This protected method is an empty placeholder for application specific startup code. protected void takedown( ) This protected method is an empty placeholder for application specific cleanup code. import jade.core.agent; public class HalloWorldAgent extends Agent protected void setup() System.out.println( Hallo World! my name is + getaid().getname()); uruchomienie kodu: java jade.boot Pierwszy:HalloWorldAgent Wybrane metody klasy jade.core.agent: void addbehaviour( Behaviour b ) This method adds a new behaviour to the agent. protected void afterclone() Actions to perform after cloning. protected void aftermove() Actions to perform after moving. protected void beforeclone() This empty placeholder method shall be overridden by user defined agents to execute some actions before copying an agent to another agent container. 3
protected void beforemove() This empty placeholder shall be overridden by user defined agents to execute some actions before the original agent instance on the source container is stopped ACLMessage blockingreceive( ) Receives an ACL message from the agent message queue. ACLMessage blockingreceive(long millis) Receives an ACL message from the agent message queue, waiting at most a specified amount of time. ACLMessage blockingreceive(messagetemplate pattern) Receives an ACL message matching a given message template. void doactivate() Make a state transition from suspended to active or waiting (whichever state the agent was in when dosuspend() was called) within Agent Platform Life Cycle. void doclone(location destination, java.lang.string newname) Make this agent be cloned on another location. void dodelete( ) Make a state transition from active, suspended or waiting to deleted state within Agent Platform Life Cycle, thereby destroying the agent. void domove(location destination) Make this agent move to a remote location. void dosuspend() Make a state transition from active or waiting to suspended within Agent Platform Life Cycle; the original agent state is saved and will be restored by a doactivate() call. void dowait() Make a state transition from active to waiting within Agent Platform Life Cycle. void dowait(long millis) Make a state transition from active to waiting within Agent Platform Life Cycle. void dowake() Make a state transition from waiting to active within Agent Platform Life Cycle. AID getaid() Method to query the private Agent ID. AID getams() Get the Agent ID for the platform AMS. getarguments( ) protected java. lang.object[] Get the array of arguments passed to this agent. AgentContainer getcontainercontroller() Return a controller for the container this agent lives in. ContentManager getcontentmanager() Retrieves the agent's content manager 4
int getcurqueuesize() This method retrieves the current lenght of the message queue of this agent. AID getdefaultdf() Get the Agent ID for the platform default DF. java.lang.string getlocalname( ) Method to query the agent local name. java.lang.string getname( ) Method to query the agent complete name (GUID). Location here( ) Method to retrieve the location this agent is currently at. void postmessage(aclmessage msg) Put a received message into the agent message queue. void putback(aclmessage msg) Puts a received ACL message back into the message queue. ACLMessage receive( ) Receives an ACL message from the agent message queue. receive( MessageTemplate pattern ) ACLMessage receive Receives an ACL message matching a given template. void removebehaviour( Behaviour b ) This method removes a given behaviour from the agent. void restore(java.io.inputstream s) This method reads a previously saved agent, replacing the current state of this agent with the one previously saved. void send( ACLMessage msg ) Send an ACL message to another agent. protected void setup() This protected method is an empty placeholder for application specific startup code. protected void takedown() This protected method is an empty placeholder for application specific cleanup code. void write(java.io.outputstream s) Write this agent to an output stream; this method can be used to record a snapshot of the agent state on a file or to send it through a network connection 5
Każdy z agentów ma swoją globalnie unikalną nazwę: <local-name>@<platform-name> Nazwa local-name nadawana jest w poleceniu uruchomienia agenta: java jade.boot... Tomek:HalloWorldAgent Janek:HalloWorldAgent Domyślna nazwa platformy <platform-name> ma postać: <main-host>:<main-port>/ JADE Inicjalizacja i kończenie życia agenta: Uruchamiając program agenta można mu z linii poleceń przekazać parametry inicjalizacyjne: java jade. Boot... Nazwa:myPackage.MyAgent( arg1 arg2 ) Zawartość tych parametrów może być odczytana za pomocą funkcji getarguments(): protected void setup() System.out.println( Hallo World! my name is + getaid().getname()); Object[] args = getarguments(); if (args!= null) System.out.println( My arguments are: ); for (int i = 0; i < args.length; i++) System.out.println( - + args[i] ); 6
Zakończenie życia agenta następuje po wywołaniu przez jego kod metody dodelete( ) lub w wyniku działań podjętych przez AMS. W ramach kończenia życia agenta automatycznie wywoływana jest metoda takedown( ), która powinna uporządkować (posprzątać) zasoby środowiska wykorzystywane przez agenta (na podobnej zasadzie jak destruktor). protected void setup( ) System.out.println( My name is + getaid().getname()); Object[] args = getarguments(); if (args!= null) System. out. println( My arguments are: ); for (int i = 0; i < args. length; i++) System.out.println( - + args[ i] ); dodelete( ); protected void takedown( ) System.out.println( Bye... ); Diagram cyklu życia agenta: 7
Działanie agenta poprzez wykonywanie zachowań (behaviour): Działanie agenta zazwyczaj realizowane jest poprzez równoległe wykonywanie wielu zachowań. Nowe zachowania są kreowane poprzez dziedziczenie po podstawowej klasie jade.core.behaviours.behaviour lub po jednej ze specjalizowanych klas: OneShotBehaviour CyclicBehaviour SequentialBehaviour ParallelBehaviour FSMBehaviour WakerBehaviour TickerBehaviour Hierarchia klas pakietu jade.core.behaviours: 8
Agent tworzy/uruchamia nowe zachowania poprzez wywołanie metody addbehaviour(... ) której parametrem jest nazwa klasy implementującej to zachowanie (zdefiniowanej na podstawie jade.core.behaviours) Każda klasa nowego zachowania musi implementować dwie metody: public void action() Implements what the behaviour actually does public boolean done() Informs, whether the behaviour is finished. Shemat działania głównego wątku agenta: 9
Przykłady: public class MyThreeStepBehaviour extends Behaviour private int step = 0; public void action( ) switch (step) ; case 0: // perform operation X step++; break; case 1: // perform operation Y step++; break; case 2: // perform operation Z step++; break; //switch(...) public boolean done( ) return step == 3; public class MyAgent extends Agent protected void setup( ) addbehaviour( new TickerBehaviour(this, 1000) protected void ontick( ) // perform operation Y System.out.println("\nMineła kolejna sekunda"); ); 10
Przykłady cd. import java.io.*; import jade.core.*; import jade.core.behaviours.*; import jade.lang.acl.*; public class AgentSender extends Agent protected void setup() addbehaviour(new SimpleBehaviour(this) private boolean finished = false; public void action() try System.out.println("\nEnter responder agent name: "); BufferedReader buff = new BufferedReader(new InputStreamReader(System.in)); String responder = buff.readline(); ACLMessage msg = new ACLMessage(ACLMessage.INFORM); msg.addreceiver(new AID(responder)); msg.setcontent("firstinform"); send(msg); System.out.println("\nFirst INFORM sent"); dowait(5000); msg.setlanguage("plaintext"); msg.setcontent("secondinform"); send(msg); System.out.println("\nSecond INFORM sent"); dowait(5000); // same that second msg.setcontent("\nthirdinform"); send(msg); System.out.println("\nThird INFORM sent"); dowait(1000); msg.setontology("receivetest"); msg.setcontent("fourthinform"); send(msg); System.out.println("\nFourth INFORM sent"); finished = true; myagent.dodelete(); catch (IOException ioe) ioe.printstacktrace(); public boolean done() return finished; ); // addbehaviour(...) 11 dodanie i definicja zachowania