JADE Tutorial

文章推薦指數: 80 %
投票人數:10人

Administering the JADE agent platform. 4. Identifying the building blocks for an agent programming. 5. Your first agent program. 6. Programming behaviours. BuildingMulti-AgentSystemswithJADE   Overview Gettingstarted AdministeringtheJADEagentplatform Identifyingthebuildingblocksforanagentprogramming Yourfirstagentprogram Understandingandprogrammingbehaviours Definingontologies BuildingagentwithintegratedGUI Exploringmobility WhataboutintelligencewithJADE? DeveloppingrealapplicationsystemswithJADE Resourcesandlinks   1.Overview   2.Gettingstarted   3.AdministeringtheJADE agentplatform   4.Identifyingthebuilding blocksforanagentprogramming   5.Yourfirstagentprogram   6.Programmingbehaviours   7.Definingontologies BeyondthecommunicativeactswhichJADEprovidessupportto incompliancewithFIPAspecifications,foragentstobeabletocommunicate inawaythatmakessensforthem,theymustsharethesamelanguage,vocabulary andprotocols.Inmostofthecases,youwillnotneedtodefineanewlanguage foryourapplicationsincethesupportprovidedbyJADEwiththeimplementation ofthethecodecclassfortheFIPA-SLnlanguagesiscompleteandflexibleenough torespondtoyourneeds. However,besidethesupportprovidedbytheframework,you mustdefineyourownvocabularyandsemanticforthecontentofthecommunication betweenyouragents.Thisrequiresultimatelythedefinitionofanontology, i.e,theterminologyandthesemanticofobjectsinvolvedinyouragentsspace ofcommunication.Infact,JADEprovidesthreewaystoimplementcommunication betweenagents.Thefirstandbasicwayconsistsofusingstringtorepresent thecontentofmessages,asdiscussedpreviouslywhendesigningYour firstprogram.Thisisconvenientwhenthecontentofmessagesisatomic data,butnotinthecaseofabstractconceptsthatneedtobeexpressedas meta-data.Insuchcases,usingstringrepresentationwillrequiretoparse thecontentofmessages,whichoperationcanbecumbersomeandsourceoferrors. ThesecondwayisbasedontheuseofJavaobjectsasthecontentofmessages. SomeJADEdevelopperswillfindthiswayeasierandconvenientinparticular whendealingwithapplicationwhereagentsevolveinalocalandhomogenous networkenvironmentandwheretheyarebuiltgenerallyintothesamelanguage. Whereasthethirdwayinvolvesthedefinitionofanontology,whichcanbeviewed asaninterfacethatenablesagentscommunicatinginaspecificlanguageto becompliantwithFIPAAgentCommunicationLanguagespecifications,forthe purposeofinteroperabilitywithotheragentsystems. InourBankexamplethatfollows,weshowinafirststephow itispossibletoimplementcommunicationbetweenagentsusingJavaobjects forthecontentofmessages.Inasecondstep,weshowthroughthesameexample howJavaobjectscanbeconvertedfordesigninganontologywiththesupport forontologyprovidedbyJADE. 7.0Thebankexample Inthisexample,twoagentsimplementaserviceofsavings account.One,implementedbytheBankServerAgent class,actsasaserverandtheother,implementedbytheBankClientAgent classactsasclient.ThetwoclassesimplementtheBankVocabulary interfacethatcontainsthelistoftermsthatconstitutethespecificlanguage oftheagents.Thebankdirectoryconsistsof3subdirectoriesthatcontain thecodessourceforthe3versionsoftheexample.Thefirstversionofthe exampleshowshowtoimplementcommunicationbetweenagentsusingJavaobjects. Thesecondversionshowshowtoimplementthecommunicationbetweenagents usinganontology.Andthethirdversionshowshowtointegrateagraphical userinterfacetoanagent. Theconversationbetweenthetwoagentsfollowsaverysimple protocol.Tocreateanaccountortomakeanoperation,theclientagentsends aREQUESTmessagetotheserveragent.TheserveragentrespondswithanINFORM afterprocessingtherequestorwithanNOT_UNDERSTOODifitcannotdecode thecontentofthemessage.Toqueryinformationaboutaspecificaccount, theclientagentsendsaQUERYtotheserveragentwhichrespondswithan INFORMafterprocessingthequeryorwithaNOT_UNDERSTOODifitcannotdecode thecontentofthemessage. 7.1UsingJavaobjectsascontentofmessages InthesamefileastheBankServerAgent class,aredefinedasexternalclasses,asetofjavaobjectsthatrepresent thesemanticsofconceptsinvolvedinouragentscommunicationspace.These objectsare: Account:definingtheconceptofabanksavingsaccount Operation:definingtheconceptofabankoperation MakeOperation:definingtheactionofmakinganoperation suchasdepositorwithdrawal OperationList:definingtheconceptofthelistoflast operations CreateAccount:definingtheactionofcreatinganaccount Information:definingtheconceptofqueryinginformation aboutanaccountsuchasthebalanceandthelist oflastoperations Problem:definingtheresultofanactionthatfails Whendesigningtheclassesofyourjavaobjects,makesure toimplementthejava.io.Serializableinterface,otherwhise theserializationofthecontentofthemessagesbeforetheirsendingwill fail.Tosetthecontentofamessageusingjavaobjects,youjustcallon themessageobject,themethodsetContentObject(...)ofthe ACLMessageclassthatthrowsajava.io.IOException,towhich youpassinargumentyourjavaobject.Let'stakealookofhowthisisdone byexaminingtheexampleofourclientagentrequestingtheserveragentto makeanoperation. TheMakeOperationclassgoes: class MakeOperationimplementsBankVocabulary,java.io.Serializable{ privateString accountId; privateinttype; privatefloatamount; publicStringgetAccountId() { returnaccountId; } publicintgetType() { returntype; } publicfloatgetAmount() { returnamount; } publicvoidsetAccountId(String accountId){ this.accountId=accountId; } publicvoidsetType(int type){ this.type=type; } publicvoidsetAmount(float amount){ this.amount=amount; } } First,wecreateaninstanceoftheMakeOperation objectandsetit'snecessaryattributes,asillustratedbythefollowing fragmentofcodepickedfromtherequestOperation()andsendMessage(...) methodsintheBankClientAgent class: voidrequestOperation() { ... MakeOperationmo=newOperation(); mo.setAccountId(acc.getId()); mo.setType(command); mo.setAmount(amount); sendMessage(ACLMessage.REQUEST,mo); } voidsendMessage(intperformative,Objectcontent){ ACLMessagemsg=newACLMessage(performative); try{ msg.setContentObject((java.io.Serializable)content); msg.addReceiver(server); send(msg); ... } catch(Exceptionex){ex.printStackTrace();} } Ontheotherside,theserverreceivesanddecodethecontent ofthemessageasimplementedintheinnerclassesReceiveMessages andHandleOperationoftheBankServerAgent class: classReceiveMessages extendsCyclicBehaviour{ publicReceiveMessages(Agent a){ super(a); } publicvoidaction(){ ACLMessagemsg=receive(); if(msg==null){block();return;} try{ Objectcontent=msg.getContentObject(); switch(msg.getPerformative()){ case(ACLMessage.REQUEST): if(actioninstanceofCreateAccount) addBehaviour(newHandleCreateAccount(myAgent,msg)); elseif(contentinstanceofMakeOperation) addBehaviour(newHandleOperation(myAgent,msg)); ... } } classHandleOperation extendsOneShotBehaviour{ ACLMessage request; publicHandleOperation(Agenta,ACLMessagerequest){ super(a); this.request=request } publicvoidaction(){ try{ Operationop=(Operation)request.getContentObject(); ACLMessagereply=request.createReply(); //Processtheoperation Objectresult=processOperation(op); ... } catch(Exceptionex){ex.printStackTrace();} } } } 7.2Defininganontologyforthecontentofmessages Anapplication-specificontologydescribestheelementsthat canbeusedascontentofagentmessages.Anontologyiscomposedoftwoparts, avocabularythatdescribetheterminologyofconceptsusedbyagentsintheir spaceofcommunication,andthenomenclatureoftherelationshipsbetween theseconcepts,andthatdescribetheirsemanticandstructure.Youimplement anontologyforyourapplicationbyextendingtheclassOntology predefinedinJADEandaddingasetofelementschemasdescribingthestructure ofconcepts,actions,andpredicatesthatareallowedtocomposethecontent ofyourmessages.Youmayalsoextenddirectlythebasicontologyclasses BasicOntologyandACLOntology.Butifyou choosetoextendtheOntologyclass,youindirectlyextendsthese basicclassessincetheyarealsoextendedbytheOntologyclass. Intheversion2ofthebankexample,wedefinedtheBankOntology classthatourtwoagentsusetocommunicateinplaceofthejavaobjects thatwediscussedpreviously.Wedonot"throwaway"ourjavaobjects thatremaininfactvalid,butinsteadofusingthemdirectlyinthecontent ofmessages,wejustwrappthemintospecificstermsandconceptsdefined withintheBankOntologyclass.Todo that,wejustmodifiedslightlyourjavaclassesbymakingthemimplement theappropriateinterfacesprovidedbyJADE.Infact,whendefininganontology youwillgenerallydealwiththethreeinterfacesConcept, AgentActionandPredicate.Thecorresponding classestobeusedinyourontologyclassarerespectivelytheConceptSchema, AgentActionSchemaandPredicateSchema. Examiningthehierarchyoftheseclasses,weseethatthe AgentActionSchemaclassinheritsfromtheConceptSchema classwhichinturnisasubclassoftheTermSchemaclass.While thePredicateSchemaclassinheritsfromtheContentElementSchema class. java.lang.Object | +--jade.content.schema.ObjectSchema | +--jade.content.schema.ObjectSchemaImpl | +--jade.content.schema.TermSchema | +--jade.content.schema.ConceptSchema | +--jade.content.schema.AgentActionSchema java.lang.Object | +--jade.content.schema.ObjectSchema | +--jade.content.schema.ObjectSchemaImpl | +--jade.content.schema.ContentElementSchema | +--jade.content.schema.PredicateSchema Animportantpointtoknowiswhentouseoneoranother oftheseontologyobjects.Tobrieflyexplainthat,let'sexaminethesethree examples: AgentArequestsagentBtoperformaspecifictask.Accordingto FIPA,thecontentofthemessagethatAsendstoBmustbean"action", i.e.,atuplewhichslotsaretheidentifierofagentthat isrequestedtoperformtheaction(hereagentB)andadescriptor respresentingthetasktobeperformed(heretherequestedtask).In JADE,thetaskwillbedefinedbyajavaobjectimplementingtheAgentAction interfaceandtheactionwillbeaninstanceoftheclassAction towhichyoupassinargumentstheAIDofagentBandtheobjectdescribing thetasktobeperformed. AgentAasksagentBifagivenpropositionistrue.Accordingto FIPA,thecontentofthemessagemustbetheobjectrepresentingthe propositiontocheck.InJADEapropositioncanbedefinedbyajava objectimplementingtheinterfacePredicate. Nowlet'stakeanexampleclosertoourbankexample:supposethe clientagentrequeststheserveragenttoperformanactionconsisting ofmakingadepositonagivenaccount.Todothis,wedefinedtheclass MakeOperationdescribingtheactiontobeperformed.Since itisanactiontheMakeOperationclassimplementstheAgentAction interface.Ontheserverside,onceithasprocessedtheinformation, itrepliesbysendingbacktogetherwiththerequestedactionwrapped inaResultobject,anAccountobjectrepresenting theresultofprocessingtheoperation.AstheAccountobject isnotanagentactionneitheraproposition,wesimplydefineditas aconceptbyimplementingtheinterfaceConcept. Besidesthesethreeinterfacesthatallowyoutodefinetheabstractsobjects ofyourapplicationontology,JADEalsoprovidessupportfordefiningatomic elementsthatconstitutegenerallytheslotsoftheabstractconcepts,such asString,Integer,Floatandsoon.Thesupport fortheseatomictypesofobjectsisprovidedthroughtheclassPrimitiveSchema andhandledbytheBasicOntologyclass. Applyingtheseprinciples,thejavaobjectspreviouslydefined intheversion1ofthebankexamplearemodifiedasfollows: theAccountclass nowimplementstheConceptinterface theOperation classimplementstheConceptinterface theMakeOperation classimplementstheAgentActioninterface theCreateAccount classimplementstheAgentActioninterface theInformation classimplementsthePredicateinterface theProblem classimplementstheConceptinterface Comparativeleywiththeversion1,onlyoneclassdisappeared. ThisistheOperationListclasswhichisofnousenowsincethe Resultclass(whichisprovidedbyJADE)thatweusetoholdthe resultofactionsthataresperformedbytheserveragentcontainsalready aListobjectattribute. Nowlet'sseestepbystephowtoputtogetherallthese piecesofpuzzletodefineanapplication-specificontologybyexaminingthe exampleofmakinganoperation. Step1:youdefinethevocabularyofyour agentscommunicationspace.IntheBankVocabulary interface,wehavethefollowinglinesofcodethatdefinetheterminology involvedintheconceptofmakinganoperation: public interfaceBankVocabulary{ ... publicstatic finalStringMAKE_OPERATION="MakeOperation"; publicstaticfinalStringMAKE_OPERATION_TYPE="type"; publicstaticfinalStringMAKE_OPERATION_AMOUNT="amount"; publicstaticfinalStringMAKE_OPERATION_ACCOUNTID="accountId"; ... } Step2:youdefinethejavaclassthatspecifiesthestructure andsemanticoftheobjectMakeOperation. publicclass MakeOperationimplementsAgentAction{ privateinttype; privatefloatamount; privateStringaccountId; publicintgetType() { returntype; } publicfloatgetAmount() { returnamount; } publicStringgetAccountId() { returnaccountId; } publicvoidsetType(int type){ this.type=type; } publicvoidsetAmount(float amount){ this.amount=amount; } publicvoidsetAccountId(String accountId){ this.accountId=accountId; } }//EndMakeOperation Ajavaclassdefininganontologyobjectmustnecessarily includethesetandgetmethodsthatallowtoaccesstheattributesofthe classthatmustbedeclaredprivate.Takecarewhenchoosingtheattributes namesofyourobjectandtheircorrespondinggetandset methods.Infact,youcannotchooseanynameyoulikeatthisstepbecause theymustimperativelymatch(caseinsensitive)thenamesthatyougaveto theseattributeswhendefiningthevocabulary.forexampleinthevocabulary, wedecidedthatthenamefortheelementMAKE_OPERATION_TYPEis"type". Sointhejavaclass,thenameoftheattributemustbetypeand thecorrespondinggetandsetmethodsmustbegetType() andsetType().Thisisanimportantpointtobeawareaboutbecause duringtheoperationoffillingthecontentofthemessage,thecontentmanager firstreadstheattributetypethatitassociateswiththeclassMakeOperation. ItthensearchesintheontologyundertheMakeOperationschema, fortheelementidentifiedinthevocabularybythename"type". Ifitcannotfindsuchanelementitthrowsanexception. Step3:youdefinetheschemaoftheobject. IntheBankOntology classwefindtheselinesofcodethatspecifiytheschemaoftheconcept MakeOperation: public classBankOntologyextendsOntologyimplementsBankVocabulary{ //---------->The nameidentifyingthisontology publicstaticfinalStringONTOLOGY_NAME="Bank-Ontology"; //---------->The singletoninstanceofthisontology privatestaticOntologyinstance=newBankOntology(); //---------->Method toaccessthesingletonontologyobject publicstaticOntologygetInstance(){returninstance;} //Privateconstructor privateBankOntology(){ super(ONTOLOGY_NAME, BasicOntology.getInstance()); try{ //-------AddConcepts ... //-------AddAgentActions ... //MakeOperation add(as=newAgentActionSchema(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(OntologyExceptionoe){ oe.printStackTrace(); } } }//BankOntology Notethattheconstructorofyourontologyclassmustbe definedwithprivateaccessandincludethestaticpublicmethodgetInstance() thatyouragentprogramcallstogetareferencetothesingletoninstance ofyourontologyclass. IntheclassAgentActionSchema,youhaveasetof add(...)methods,someofwhichareinheritedfromtheConceptSchema classthatitextends.Thesemethodsallowyoutoaddtotheschemaofthe objectthatyouaredefiningtheelementsthatwillbeusedbythecontent managerasslotswhenfillingthecontentofmessages.Inourexample,we usedtheadd()methodthattakesthreearguments,thenameofthe slottobeadded,theschemaofthisslotandtheoptionality.Theoptionlaity cantaketwovalues:MANDATORYindicatingthattheslotcannothaveanull value,orOPTIONALindicatingthatitcanhaveanullvalue.Theconsequence isthatifyouspecifyMANDATORY,thenthiselementmustbeimperativelyprovided whensettingthevaluesofcorrespondingattributesinthejavaclass.On theotherhandifyouspecifyOPTIONAL,youareallowedtonotprovideavalue forthisslot. Step4:youarenowreadytousetheontology forthecontentofyouragentsmessages.Tosetthecontentofamessageusing anontology,youmustfirstregisterwiththeagent'scontentmanager,the ontologyandthelanguagethatwillbeusedforassemblingandparsing(or codinganddecoding)thecontentofmessages.Inourexampleweusethecodec languagewhichisimplementedinJADEthroughtheclassSLCodec andtheontologyisnaturallyourBankOntology:IntheBankClientAgent classinthedirectoryBank-2-Onto,youfindtheselinesofcode thatillustratehowtoregisterthelanguageandontology: publicclassBankClientAgent extendsAgentimplementsBankVocabulary{ ... privateCodeccodec=newSLCodec(); privateOntologyontology=BankOntology.getInstance(); protectedvoidsetup() { //Registerlanguage andontology getContentManager().registerLanguage(codec); getContentManager().registerOntology(ontology); ... } ... }//classBankClientAgent Tousetheontoloywhencomposingyourmessage,youfirst settheattributesofyourjavaobject.Thenyouspecifywithinthemessage instance,thelanguageandontologythatitcompliesto.youthenobtaina referencetotheContentManagerobjectbycallingthemethod getContentManager()oftheAgentclass.Finally youcallthefillContent(...)methodoftheContentManager objecttowhichyoupassinargumentsthemessageandthecontentthatit willbefilledwith.Thisisdonethroughthefollowinglinesofcode: publicclassBankClientAgent extendsAgentimplementsBankVocabulary{ ... voidrequestOperation() { .... MakeOperationmo=newMakeOperation(); mo.setType(command); mo.setAmount(amount); mo.setAccountId(acc.getId()); sendMessage(ACLMessage.REQUEST,mo); } ... voidsendMessage(int performative,AgentActionaction){ ... ACLMessagemsg=newACLMessage(performative); msg.setLanguage(codec.getName()); msg.setOntology(ontology.getName()); try{ getContentManager().fillContent(msg,newAction(server,action)); msg.addReceiver(server); send(msg); ... } catch(Exceptionex){ex.printStackTrace();} } }//EndBankClientAgent Attheserverside,youfollowthesamestepstoreceive andextractthecontentofthemessage.Theserveragentmustalsoregister itscontentmanagerwiththesamelanguageandontology.Then,obtaininga referencetothecontentmanagerobjectitcallsitsmethodextractContent(...) towhichitpassesinargumentthemessagetobeextracted.Itthencasts theextractedcontentwiththejavaclassthatitwasexpecting.Onceithas thejavaobject,itcanfinallyretrievethecontentoftheslotsbycalling thegetmethodsprovidedinthejavaclassoftheobject.Thisis illustratedthroughthefollowinglinesofcodeintheBankServerAgent class: publicclassBankServerAgent extendsAgentimplementsBankVocabulary{ ... privateCodeccodec=newSLCodec(); privateOntologyontology=BankOntology.getInstance(); ... protectedvoidsetup() { //Registerlanguage andontology getContentManager().registerLanguage(codec); getContentManager().registerOntology(ontology); ... } ... classReceiveMessages extendsCyclicBehaviour{ publicReceiveMessages(Agent a){ super(a); } publicvoidaction() { ACLMessagemsg=receive(); if(msg==null){block();return;} try{ ContentElementcontent=getContentManager().extractContent(msg); Conceptaction=((Action)content).getAction(); switch(msg.getPerformative()) { case(ACLMessage.REQUEST): ... if(actioninstanceof CreateAccount) addBehaviour(newHandleCreateAccount(myAgent,msg)); elseif(actioninstanceofMakeOperation) addBehaviour(newHandleOperation(myAgent,msg)); ... break; ... } catch(Exceptionex){ex.printStackTrace();} } }//EndReceiveMessages ... classHandleOperation extendsOneShotBehaviour{ privateACLMessage request; HandleOperation(Agent a,ACLMessagerequest){ super(a); this.request=request; } publicvoidaction() { try{ ContentElementcontent=getContentManager().extractContent(request); MakeOperationmo=(MakeOperation)((Action)content).getAction(); //Processtheoperation Objectobj=processOperation(mo); //Sendthereply ... } } catch(Exceptionex){ex.printStackTrace();} } }//EndHandleOperation ... }//EndBankServerAgent   8.Buildingagentwithintegrated GUI   9.Exploringmobility   10.Whataboutintelligence withJADE?   11.Developpingrealapplication systemswithJADE   12.Resourcesandlinks  



請為這篇文章評分?