Home
Magentix 2 - GTI-IA
Contents
1. Inputs NormName Identifier of the norm UnitName Identifier of the unit Outputs ContentNorm Exceptions ForbiddenNormException NotInUnitOrParentUnitEx ception InvalidUnitTypeException NormNotExist sException UnitNotExistsException EmptyParame tersException Description Provides information about a specific norm Inputs TargetTypeName roleName positionName or InformTarget Norms agentName TargetTypeValue Identifier of the object affected by norm or _ UnitName Identifier of the unit Outputs NormName UnitName TargetTypeName Target TypeValue gt Exceptions ForbiddenNormException AgentNotInUnitException InvalidTargetTypeException UnitNotExistsException EmptyParametersException Table 8 6 OMS Proxy Informative services API Description Requests the adoption of a specific role within a unit Inputs RoleName Identifier of the role AcquireRole UnitName Identifier of the unit Outputs RoleName acquired Exceptions PlayingRoleException ForbiddenNormException NotSupervisorOrCreatorInUnitException NotInUn itOrParentUnitException RoleNotExistsException UnitNotExistsException EmptyParametersException Description Requests to leave a role Inputs RoleName Identifier of the role LeaveRole UnitName Identifier of the unit Outputs RoleName left Exceptions NotPlaysRoleException
2. Derivation Predicates EO ro ro ro ro ro ro ro leCardin leCardin leCardin leCardin leCardin leCardin leCardin ali ality moderator ality participant ality brother ality president ality reporter ality follower leCardin ality moderator ty participant frate forum fraternity panel panel panel virtual forum rnity 4 1 2 1 1 1 1 1 H Cardin 4 0 ty supervisor forum position ty creator virtual positionCardin ty member virtual 1 2 positionCardin positionCardin ty subordinate forum 4 H positionCardin ty creator fraternity 4 H positionCardin ty member fraternity positionCardin ty creator panel positionCardin ty member panel A BNF Syntax of the Normative Language 165 Norms descriptions Forum It is not allowed registering new roles with the position creatorx isNorm noRegRole forum hasDeontic noRegRole forum f hasTarget noRegRole forum positionName creator hasAction noRegRole forum registerRole xForum Changing the parent unit of the organization is prohibitx isNorm noRegRole forum hasDeontic noJoinUnit forum f hasTarget noJoinUnit forum positionName _ hasAction noJoinUnit forum joinUnit Fraternity Only one agent can play the ro
3. term term EI informTargetNorms targetTypePred targetValuePred term term informRole term 7 term 7 term informNorm term term term EI acquireRole term term term E leaveRole term term term deonticPred deontic variable targetTypePred targetType variable targetValuePred OMSPositions constant variable OMSActionNamePred OMSActionName variable 160 A 2 Predicates Summary numericConstantPred numericConstant variable MSConstants OMSPositions OMS Accessibility OMSVisibility OMSUnitTypes MSPositionsPred OMSPositions variable MSAccessibilityPred OMSAccessibility variable MSVisibilityPred OMSVisibility variable MSUnitTypesPred OMSUnitTypes variable MSPositions creator member subordinate supervisor MSAccessibility external internal O O O O O O O O O MSVisibility public private MSUnitTypes flat team hierarchy A 2 Predicates Summary Unit Predicates isUnit UnitName hasType UnitName Type hasParent UnitName ParentName Role Predicates isRole RoleName U
4. Invalid RoleName s position is not a valid value B Exceptions 171 Exception name Description InvalidServiceURLException Service URL is not a valid OWL S docu ment InvalidTargetTypeException Target type is not valid The target types al lowed are agentList roleList and position InvalidTargetValue Target value is not valid because not exists this ID in the target type associated InvalidUnitTypeException unitType is not a valid unitType value InvalidVisibilityException visibility is not a valid visibility value MySQLException Error mysql error result NormExistsInUnitException Not allowed The norm is already registered in the unit NormNotExistsException The norm not exists in the unit NotCreatorA gentInUnitException Not allowed There are agents in unit playing roles with position different from creator NotCreatorException Not allowed The Agent AgentName does not play any role with position creator unit Name NotCreatorInParentUnitException Not allowed The Agent AgentName does not play any role with position creator inside the parent unit NotCreatorInUnitException Not allowed The Agent AgentName does not play any role with position creator inside the unit NotCreatorInUnitOrParentUnitException Not allowed The agent does not play any role with creator posi
5. gt ee 99 14 9 5 nes lt positionName e6 99 activation expression ee 99 expiration expression targetType agentName roleName positionName genAtomicCondition OMSCondition genAtomicFormula genAtomicFormula stringConstant listOfTerms variable OMSConstants action OMSAction genActionFormula 157 158 A 1 Grammar genActionFormula genActionFormula It is prepared to incorporate more actions in future versions i e SFActions 6609 listOfTerms term term term constant variable OMSConstants e expression simpleExpression not expression expression 2 expression expression expression expression simpleExpression genAtomicCondition relExpression 173 EE relExpression relTerm lt gt gt pw 99 66 lt gt gt relTerm relTerm genAtomicFormula arithExpression arithExpression arithTerm 880 tt div mod artihTerm ee 99 arithTerm numericConstant variable arithTerm arithExpression ee 99 variable 4 Z 0 Z constant numericConstant stringConstant numericConstant 0 9
6. put the service inputs values HashMap lt String String gt agentInputs new HashMap lt String String gt for String input serviceInputs 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 4l 42 43 44 45 46 47 48 130 8 4 Programming Agents that Request Services if input equalsIgnoreCase x agens np utes p ub ut 3107 else if input equalsIgnoreCase y agentInputs put input 4 AGenEE NOUS put Anput Loui agents or organizations providers ArrayList lt Provider gt providers oracle getProviders web services providers ArrayList lt String gt providersGroundingWSDL oracle getProvidersGroundingWSDL if providers isEmpty System out println this getName Requesting Addition service tasas Building the ACL message ACLMessage msg new ACLMessage msg setReceiver new AgentID providers get 0 getEntityID msg setLanguage providers get 0 getLanguage msg setPerformative providers get 0 getPerformative msg setSender getAid Building the content of the message in XML String content st buildServiceContent oracle getServiceName agentInputs ACL message content is formed by XML format with service name and inputs msg setContent content this send request msg ServiceTools
7. 40 4 8 Creating a CFactory Template 42 Magentix2 supports the set of basic interaction protocols defined by FIPA Thereby agents can communicate to each other by means of different protocols explained in this section Each implemented protocol provides the basic message exchange between two agents for a given type of conversation a request a query etc 4 1 Interaction Protocols Three interaction protocols specified by FIPA Request Query and the Contract Net have been implemented in the Magentix2 basic conversational protocol For this purpose a set of classes have been implemented and they can be found into the es upv dsic gti ia architecture package Within all of the protocols implemented agents can play both initiator and responder role These roles implement different behaviors The initiators are executed once per conversation while responders are executed cyclically so they will return to its initial state after reaching the final one The set of classes in the es upv dsic gti 28 4 Advanced conversational agents CAgents 29 ia architecture package have been designed so that programmers do not need to deal with neither message sending nor protocol status monitoring Thus programmers only have to define what should be done in each state of the protocol and prepare messages before sending The actions performed in each state are defined by handlers for initiator roles and preparers for resp
8. Any agent from any organization But it is not allowed to acquire a role with Position Creator or Position Supervisor if the agent already plays a role with Position Subordinate in the organization What agents can ac quire roles with acces sibility internal in the organization Any agent from this organization or any agent from its parent unit Any agent from this organization or any agent from its parent unit But it is not al lowed to acquire a role with Position Cre ator or Position Supervisor if the agent already plays a role with Position Subor dinate in the organization Table 8 3 Differences among the diverse organization types 8 Virtual Organizations 105 8 1 3 Service Facilitator The SF is a support mechanism used by organizations and agents to offer and discover ser vices The SF provides an environment in which the autonomous entities can register service descriptions as directory entries The SF acts as a gateway to access the THOMAS framework The SF can find services search ing for a given service profile This is done using matchmaking mechanisms over the inputs outputs and keywords of the services to search The SF also acts as a yellow pages manager and in this way it can also find which entities provide a given service Services may have some pre conditions that have to be true before the service can be executed They exchange one or more input and output messa
9. lt Back x Forward y N 2 al ma Location Magentix2 apache tomcat 7 0 4 webapps docs examples host manager manager omsservices ROOT SearchCheapHotel sfservices MA EXIST war 4 items selected 92 1 MB Figure 10 5 Location of web services files war 10 4 1 Running Bridge Agents Bridge agents are in charge of sending and receiving messages to or from foreign agents For example they allow Magentix2 agents to communicate with Jade agents BridgeAgentInOut manages messages that go from inside the platform to outside whereas BridgeAgentOutIn does the opposite Bridge agents can be running on any host they do not have to be in the same host where the QPid broker or other agents are running A Java program has to be written and executed in order to launch bridge agents The following code shows how to launch these agents import es upv dsic gti ia core AgentsConnection import es upv dsic gti ia core AgentID import es upv dsic gti ia core BridgeAgentInOut import es upv dsic gti ia core BridgeAgentOutIn public class Main public static void main String args throws Exception AgentsConnection connect private BridgeAgentInOut inOutAgent private BridgeAgentOutIn outInAgent 10 Advanced platform administration 155 inOutAgent new BridgeAgentInOut new AgentID BridgeAgentInOut outInAgent new BridgeAgentOutIn new AgentID BridgeAgentOutIn inOutAgent s
10. Argumentation example packages and classes a Main ArgCAgent java methods o o e e Argumentative agents core packages and classes Main DomainCBR java methods o o e e e Main ArgCBR java methods o e o Main CBR persistence methods o o e Methods to implement in the Argumentation Protocol TraceEvent class constructor parameters o Trace Manager error codes 2 2 ee Tracing service publication and unpublication methods Tracing service subscription and unsubscription methods Tracing services and tracing entities listing methods System related domain independent tracing services Agent s lifecycle related domain independent tracing services Agent s messaging related domain independent tracing services Tracing service publication related domain independent tracing services Event s types allowed to customize 2000000004 Action information about the mask reception 04 Agent behavior depending of its position o o How visibility and accessibility attributes affect roles Differences among the diverse organization types OMS Proxy Service Access taking into account the role position played by the requesting agent ol hed
11. domain and argumentation case bases in each CBR run e Commitment Store is a resource of the argumentation framework that stores all the information about the agents participating in the problem solving process argumentation dialogues between them positions and arguments By making queries to this resource every agent of the framework can read the information of the dialogues that it is involved in To facilitate the communication among argumentative agents and the commitment store this resource has been implemented as a Magentix2 CAgent 6 2 1 Argumentative Agents ArgCAgent Class With the class ArgCAgent java Magentix2 distribution includes an implementation of an ar gumentative agent This agent is an extension of the Magentix2 conversational agent CAgent see Section 4 Argumentative agents have two CBR modules Domain CBR and Argumen tation CBR The main functionalities of the argumentative agents are the generation selection and evaluation of positions and arguments These are specified as methods to facilitate a better 58 6 2 Argumentation API understanding of the code and to facilitate modifications and updates Table 6 4 provides an overview of the main methods used to manage positions and arguments in the ArgCAgent java class Next we explain how argumentative agents can manage positions and arguments Method Description addPosition Returns an ACLMessage with the locution ADDPOSITION and a Position
12. stringConstant a z 0 Z OMSCondition OMSUnitPred OMSRolesPred OMSNormsPred OMSRoleEnactPred OMSUnitPred isUnit term y ee hasParent term term hasType term 7 OMSUnitTypesPred y 669 6699 OMSRolesPred isRole term term y hasAccessibility term term OMSAccessibilityPred has Visibility term term OMSVisibilityPred hasPosition term term 7 OMSPositionsPred y OMSNormsPred isNorm term term y y term term OMSActionNamePred hasDeontic term term deonticPred hasAction hasTarget term term targetTypePred target ValuePred A BNF Syntax of the Normative Language 159 OMSActionName registerUnit deregisterUnit registerRole deregisterRole registerNorm deregisterNorm informMembers informRole allocateRole deallocateRole joinUnit informA gentRole informQuantity Members informUnit informUnitRoles informTargetNorms informNorm acquireRole leaveRole OMSRoleEnactPred isAgent term
13. y playsRole o term e term ee term o roleCardinality term term numericConstantPred positionCardinality OMSPositionsPred term numericConstantPred OMSAction registerUnit term 5 OMSUnitTypesPred term term term deregisterUnit term term registerRole term term OMSAccessibilityPred OMSVisibilityPred OMSPositionsPred term deregisterRole term term term registerNorm term term deonticPred target TypePred target ValuePred 7 OMSActionNamePred term deregisterNorm term term term allocateRole term term term term y deallocateRole term term term 7 term y joinUnit o term ds term term o informAgentRole term term informMembers term term 7 OMSPositionsPred term informQuantity Members term term 5 OMSPositionsPred term informUnit term term y EI informUnitRoles
14. Also an agent can be reported by other agent that the latter ACCEPTs its position Alternatively the agent can receive a FINISHDIALOGUE locution in this state and it will go to the state Send Position to start the actions to leave the dialogue when it has proposed yet a position Assert the agent that received the WHY request will ASSERT a support argument to the opponent if it can This implies going to the state Wait Attack and wait for incoming attack arguments If the agent is not able to provide a support argument to defend its position it must move back to the state Propose with the locution NOCOMMIT to withdraw its position from the dialogue and if possible propose another generated posi tion Also argumentative agents do not respond to the same WHY query from the same opponent agent twice In this case the argumentative agent will move back to the state Central and ignore the repeated WHY request Wait Attack in this state the agent that has put forward a support argument for its position waits for an ATTACK or an ACCEPT locution In the case that an ATTACK is received the agent will go to the state Defend to try to rebut the attack If the agent receives an ACCEPT it means that the opponent agent has accepted its position and the proponent agent will move back to state Central Defend in this state an agent that has received an ATTACK from an opponent agent tries to reply with another ATTACK In t
15. CFactory for FIPA Request Interaction Protocol for the initiator agent dynamically modified without affecting the IP the conversation is following or other ongoing conversations which follows that IP In figure 4 1 an example of an IP transformed into a graph associated to a CFactory is shown This IP corresponds to the FIPA Request Interaction Protocol FIPA 2002 for the initiator role In figure 4 2 a global view of a CAgent is shown In this figure the agent shown has three CFac tories two of them are participant and the third one is initiator At the same time the agent has two ongoing CProcessors that manage two conversations Conv1 and Conv2 The first one has been created by the initiator CFactory 1 the other one by the participant CFactory 1 The initiator CFactory 1 created the CProcessor managing Conv1 because the execution of the agent dictates that instead the Conv2 was created by the participant CFactory 1 because the agent received an inform message From this moment on every message with the message parameter conversation_id set to Conv1 will be automatically assigned to the CProcessor managing that conversation The same will occur with Conv2 messages If in the future the agent receives a request message the participant CFactory 2 will create a new CProcessor which will manage the new conversation Other possibility is that the agent receives an in form message with an unknown conversati
16. Data flow for the argumentation process of the helpdesk application provide a brief explanation of this example Details of the implementation can be found in the JavaDoc of the files of the package In order to show how the developed system works the data flow for the problem solving pro cess or argumentation process to solve each problem is shown in Figure 6 4 and described below arrows in the figure are labelled with the number of the data flow step that they repre sent 1 First we have some argumentation agents running in the platform and representing the technicians of the call centre The tester agent sends the problem to solve also known as ticket in the common call centre terminology to the group of agents 2 Each agent evaluates individually if it can engage in the dialogue offering a solution To do that the agent makes a query to its domain CBR to obtain potential solutions to the ticket based on previous solutions applied to similar tickets To compute such similarity agents use a weighted Euclidean algorithm that searches their domain cases case bases for previous problems that semantically match the category of the current ticket to solve Thus the algorithm retrieves all problems of the same category and of related categories and select those that syntactically match assign the same values to the attributes that match the ticket attributes and overpass a defined similarity threshold If one or more valid solu
17. ForbiddenNormException RoleNotExistsException UnitNotExistsException EmptyParametersException 120 8 2 Programming agents which use THOMAS AllocateRole Description Forces an agent to acquire a specific role Inputs RoleName Identifier of the role UnitName Identifier of the unit TargetAgentName Identifier of the agent that will ac quire the role Outputs RoleName acquired Exceptions SameAgentNameException PlayingRoleException ForbiddenNormException NotSupervisorOrCre atorInUnitException AgentNotInUnitException NotInUni tAndNotCreatorException InvalidUnitTypeException NotMemberOrCreatorInUnitException RoleNotExistsException UnitNotExistsException NotValidIdentifierException EmptyParametersExcep tion DeallocateRole Description Forces an agent to leave a specific role Inputs RoleName Identifier of the role UnitName Identifier of the unit TargetAgentName Identifier of the agent that will leave the role Outputs RoleName acquired Exceptions SameAgentNameException NotPlaysRoleException ForbiddenNormException NotSupervisorOrCreator InUnitExceptioneption AgentNotInUnitException NotInUni tAndNotCreatorException InvalidUnitTypeException NotMemberOrCreatorInUnitException RoleNotExistsException UnitNotExistsException EmptyParametersException Table 8 7 OMS Proxy Dyna
18. acid ose tad aOR ae de ope d he ae 27 4 Advanced conversational agents CAgents 28 4 1 Interaction Protocols es 28 4 2 HowtoimplementaFIPA Protocol e 29 4 2 t BIPA Request ida sob rtt a E ele A 30 4 42 PIPA Query com km dem omm roy Guy ES P3 30 4 23 FIPA Contract Net lee 31 4 3 Programming CAgents ees 32 44 Hello World CAgent es 34 4 5 Creating a CFactory and its CProcessor lle 36 4 6 Sending Errors 02 9 uc os doe Paras ee LE eee Bae a 39 4 7 Using a CFactory Template eee 40 4 8 Creating a CFactory Template o lens 42 5 BDI Agents JasonA gents 46 5 1 Programming BDI Agents 0 002 000 eee eee 46 6 Argumentative Agents 49 6 1 Argumentation Framework 0 00000 2 eee ee eee 49 6 1 1 Framework Architecture eA 50 6 1 2 Dialogue Strategies 2 ee e 54 6 2 Argumentation APL s s srs aair ae ea a R4 E o 57 6 2 1 Argumentative Agents ArgCAgent Class 57 6 2 2 Argumentation Protocol 000000008 61 6 3 Programming Argumentative Agents 2e 66 6 3 1 How to run Magentix2 Argumentative Agents 66 6 3 2 How to create your own Magentix2 Argumentative Agent 68 6 3 3 Example Call Centre Application o o 72 7 Tracing Service 75 7 1 Trace Model and Features lees 75 7 1 1 Supported Features lees 76 liza Trace Evett 2 9 ak G
19. and ask for a justification the agent moves back to the state Central Wait Assert in this state the agent that has challenged a position waits for a response from the challenged agent If it receives such a response with the locution ASSERT it tries to rebut the position of the challenged agent and moves to the state Attack Otherwise if the challenged agent cannot provide a justification for its position it must withdraw such position from the dialogue with the locution NOCOMMIT and the chal lenger moves back to the state Central Also if the agent does not receive any response before a specified timeout it will move again to the state Central Attack in this state if an agent has received a justification for a challenged position it tries to generate an attack with the locution ATTACK In this case the agent moves to the state Attack2 However if it is not able to attack the position it will accept it with the locution ACCEPT and move back to the state Central Attack2 once an agent has generated an attack for the position of a proponent agent it waits in this state for the answer of the proponent Thus if the proponent is able to counter attack and sends a locution ATTACK the agent will move back to the state At tack to try to generate a new attack to rebut the position of the proponent Otherwise the proponent must withdraw its position from the dialogue with the locution VOCOMMIT and the attacker agent mo
20. e Oracle Java Development Kit JDK 7 or later e Apache Tomcat 7 or later e MySQL server 5 0 or later 2 1 2 Installation of Magentix2 In order to install Magentix2 the corresponded zipped package has to be downloaded Once Magentix2 is downloaded you need to unzip the file Just double click the file or run the following command unzip magentix2 2 1 0 zip Inttp ww oracle com technetwork java archive 139210 html http tomcat apache org download 70 cgi http www mysql com downloads The latest installable version is in http gti ia upv es sma tools magentix2 downloads php 6 2 1 Installing Magentix2 In the unzipped directory you have now the Magentix2 agent platform ready to be configured and started Before running the Magentix2 platform you need to finish the installation by executing the setup script e In Linux and MacOS X run the following command magentix setup py e In Windows XP Windows 7 and Windows 8 double click the nagentix setup ex file Then a text interface for the installation is provided This setup process will ask you some required users and passwords to configure and deploy the components needed by Magentix2 It will also check that all the required dependencies are installed and properly configured The setup script will ask you for the following data e MySQL root password used to create the magentix user and create the database schema for the platform
21. e Tomcat user and password used to deploy the Magentix webservices to the tomcat app server Note that the tomcat user MUST have the manager script role to be able to deploy webapps To do this add the following lines to your tomcat users xml file located where your tomcat installation is or at etc tomcat where USERNAME and PASSWORD must be changed by the user and password you assign to tomcat lt role rolename manager script gt lt user username USERNAME password PASSWORD roles manager script If every dependency is correctly installed and running the setup script will finish with the message Magentix succesfully installed When installation ends you can run the Start Magentix script in order to start the services and platform agents this script must be executed as follows 2 Quick Start 7 e In Linux and MacOS X run the following command Start Magentix sh e In Windows XP Windows 7 and Windows 8 gt Start Magentix bat To check that all is correctly configured and Magentix2 has been successfully installed and running execute the example Start BasicExample sh This script run a basic example cd examples Start BasicExample sh The output of this example should be like the following one Executing I m consumer 2 1 1 2 1 5 198907549 364 iW Thread 2 SingleAgent Example SenderAgent2 Executing I m the sender Executing I m the sender n
22. new TraceManager new AgentID TM 7 Tracing Service 79 Agents communicate with the Trace Manager using the methods available in the class es upv dsic gti ia trace TraceInteract These methods internally send an ACL message to the Trace Manager This message will be processed by the Trace Manager which responds to these requests via ACL messages to requester agents When the request sent to the Trace Manager an error ACL message is sent to the requester tracing entity with an error code in order to let the tracing entity know the reason why the request was rejected These error codes are available in the class es upv dsic gti ia trace TraceError and their meaning is described in Table 7 2 Table 7 2 Trace Manager error codes TRACE ERROR Undefined trace error ENTITY NOT FOUND Tracing entity not present in the system PROVIDER NOT FOUND Provider is not offering the tracing service SERVICE NOT FOUND Tracing service not offered by any tracing entity in the system SUBSCRIPTION NOT FOUND Subscription to the tracing service not found ENTITY DUPLICATE Tracing entity already present in the system SERVICE DUPLICATE Tracing service already offered by the tracing entity SUBSCRIPTION DUPLICATE Subscription already exists BAD ENTITY Tracing enity not correct BAD SERVICE Tracing service not correct PUBLISH ERROR Impossible to publish th
23. qpid apache org download cgi The following libraries must be installed before building the source distribution of Qpid e libboostiostreams 1 35dev http www boost org 1 35 e e2fsprogs http e2fsprogs sourceforge net 1 39 e pkgconfig http pkgconfig freedesktop org wiki 0 21 e uuid 1 21 41 4 e ruby 4 2 e ruby 1 8 In Ubuntu operating systems these packages can be installed using the Synaptic package man agement tool but any other package manager might be valid As an example figure 10 1 147 148 10 1 Advanced Apache Qpid wer Gestor de paquetes Synaptic mm Pol ix Archivo Editar Paquete Configuraci n Ayuda e D B squeda r pida Q Recargar Marcar todas las actualizaciones Aplica Propiedades boost Buscar J E Paquete Versi n instalada ltima versi n Descripci Administrad n i sistem libboost1 37 dbg 1 37 0 3ubuntu3 Bibliotec Administraci n del sistema cies jibbaosti35 dbg 1 35 0 Subuntu5 Bibliotec pa del T libboost iostreams1 37 0 1 37 0 3ubuntu3 Bibliotec nma a O 3 libboost iostreams1 35 0 1 35 0 8ubuntu5 Bibliotec on libboost iostreams1 34 1 1 34 1 15ubuntu3 Bibliotec Bibliotecas multiverse O pyste 1 34 1 15ubuntu3 Boost Py MUNI L libboost iostreams dev 1 34 1 15ubuntu3 Archivos Bibliotecas i Antiguo mHE libboost iostreams1 37 dev 1 37 0 3ubuntu3 Archivos Secciones L libbo
24. super aid public void execute System out println Hi I m agent this getName and I start my execution ACIMessage msg null try msg this receiveACLMessage catch InterruptedException e e printStackTrace System out println Hi I m agent this getName and I ve received the message msg getContent This agent does not extend from BaseAgent but from SingleAgent section 3 1 2 this allows using the receiveACLMessage method This method halts the agent execution until it receives a message The method execute of the Consumer agent does nothing but wait until the agent receives a message When the agent receives a message it assigns the message to the variable msg and then it shows the message content on the console 21 22 23 24 25 26 27 28 29 30 31 32 33 34 2 Quick Start 13 Once both agents are programmed the Main java class should be programmed This class is in charge of connecting the agents to the broker and starting their execution The code of this class is shown below package agent import import import import public pub org apache log4j Logger org apache log4j xml DOMConfigurator es upv dsic gti ia core AgentID es upv dsic gti ia core AgentsConnection class Main lic static void main String args Tes x Setting the Logger DOMConfigurator configure configuration l
25. 1 Appender 1 appender name Console class org apache log4j ConsoleAppender layout class org apache log4j PatternLayout lt param name ConversionPattern value d 5p t C 2 SF L m n lt layout gt lt appender gt Figure 3 2 Appender 2 The following parameters must be specified in any connection to the broker e lt QpidHost gt the host or ip address to connect to defaults to localhost e lt QpidPort gt refers to the port to connect to defaults to 5672 e lt QpidVhost gt allows an Qpid virtual host to be specified for the connection defaults to test e lt QpdidUser gt user name to access Qpid e lt QpidPassword gt password to access Qpid e lt QpidSSL gt indicates if SSL is used during the connection its value is always false when security is not enabled There are three different ways to establish a connection to the Qpid broker using the connect method implemented in the es upv dsic gti ia core AgentsConnection class e Calling connect without parameters In this case the parameters are gathered from the Settings xml file For example gt This file is located in the configuration directory of the Magentix2 installation 20 3 1 Basic classes for building agents BaseAgent and SimpleAgent AgentsConnection connect Thus it is possible to specify the connection parameters inside the Settings xml file Note that if all the parame
26. 8 6 Programming agents which use organizational messaging 2 The Addition agent and the Product agent acquire the role operation of the Calculator organization Also the James agents acquires the role student of the School organization 3 The Addition agent registers the Addition service in the SF Also the Product agent registers the Product and Square services in the SF 4 The James agent wants to calculate the equation 5 3 4 Firstly it searches for a service to add two numbers and it finds the Addition service It makes a GetService of this service to obtain the required information to request it It also searches for a service to make the product and another one to square In these cases it finds the Product service and the Square service It makes a GetService of the two services to obtain their information 5 The James agent requests the Addition service to add 3 and 4 Then with this result requests the Product service to multiply it by 5 Finally the result of this operation is used to square it with the Square service that is provided by a web service This implies that the James agent has to execute it itself by using the Service Tools provided in the Magentix2 API The James agent has obtained the final result of the equation that it wanted to solve Then it sends a message to the Initiator agent to inform that the example has ended 6 The Initiator agent receives the message informing that the example has ende
27. DETAIL 7 originEntity OriginAgentId content SerializedMessage MESSAGE_RECEIVED A FIPA ACL message was received by DestinationAgentId tService MESSAGE RECEIVED 8 originEntity DestinationAgentId content OriginAgentId MESSAGE RECEIVED DETAIL MESSAG ER EC EIV ED is that MESSAGE R A FIPA ACL message was received by DestinationAgentId The difference with EC EIV ED D ETAIL trace events include the ACL message they refer to tService MESSAGE REC EIV ED D ETAIL 9 originEntity Destination AgentId content SerializedMessage information they provide are detailed in Table 7 9 7 Tracing Service 87 Table 7 9 Tracing service publication related domain independent tracing services PUBLISHED TRACING SERVICE A tracing service ServiceName was published by the tracing entity ESId tService PUBLISHED TRACING SERVICE 10 originEntity ESId content ServiceName UNPUBLISHED_TRACING_SERVICE A tracing service ServiceName was unpublished by the tracing entity ESId tService UNPUBLISHED_TRACING_SERVICE 11 originEntity ESId content ServiceName 7 5 Customizable Trace Support In the trace system of Magentix2 the trace events are customiza
28. FIPA ACL Message Consumer Agent CA Sender Agent SA g SAsends the message to the CA FIPA ACL Message QPID Broker Figure 3 3 Messages exchange thought QPID Broker in Magentix2 3 2 Agent Communication In Magentix2 each agent has a message queue on the Qpid broker where other agents can post messages addressed to her The Figure 3 3 illustrates how a sender agent posts a message in a queue Then a consumer agent is able to read this message 3 2 1 FIPA ACL Language Messages exchanged by Magentix2 agents have the format specified by the ACL language defined by the FIPA international standard for agent interoperability This format comprises a number of fields such as e Sender of the message e list of receivers e Performative REQUEST INFORM QUERY IF CFP PROPOSE ACCEPT PROPOSAL REJECT PROPOSAL etc e Content e Content Language http www fipa org 3 Basic Programming 23 e Content Ontology e Conversation id reply with in reply to reply by etc A message in Magentix2 is implemented as an instance of the es upv dsic gti_ia core ACLMessage class that provides get and set methods for handling all the fields of a message 3 2 2 Sending Messages To send a message to another agent the programmer must fill the fields of an ACLMessage object and then call the send method of the es upv dsic gti_ia core BaseAgent class The code below informs an agent
29. Magentix2 distribution folder Specifically the parameters that affect Qpid configuration in the Settings xml file are the following 10 Advanced platform administration 149 lt entry key host gt localhost lt entry gt lt entry key port gt 5672 lt entry gt lt entry key vhost gt test lt entry gt lt entry key user gt guest lt entry gt lt entry key pass gt guest lt entry gt lt entry key ssl gt false lt entry gt For example if the port which Qpid broker is listening to is modified from the default 5672 to 5671 this change has to be also made on the Settings xml file For those looking to adjust the Qpid broker operation there are plenty of advanced configuration options for further information please refer to http qpid apache org books 0 7 AMQP Messaging Broker CPP Book html index html Please note that if two ore more Qpid brokers have to work federated a link between all the broker s amq topic exchange has to be added 10 2 Advanced MySQL MySQL is a main component of the THOMAS framework This section explains how to prop erly configure MySQL to work in conjunction with THOMAS This section helps you to con figure MySQL properly All the information about the organizations created with the THOMAS framework and running on the Magentix2 platform is permanently stored in a MySQL database It is possible to create the database schema and the user employed by the THOMAS
30. The first type of attack that the agent will try to generate is a counter example attack with the method generateCEAttack and if it is 6 Argumentative Agents 61 not possible the agent will try to generate a distinguishing premise attack with the method generateCEAttack The counter example attack consists on an argument that includes a domain case or an argument case whose conclusion contradicts the conclusion of the attacked argument A distinguishing premise attack consists on an argument that includes a premise or a set that describes the problem and that the attacked agent did not consider to generate its position and its associated support argument or a premise that both agents have but with different data value 6 2 2 Argumentation Protocol Argumentative agents need a protocol to exchange positions and arguments and engage in the argumentation dialogue The protocol is represented by a set of locutions that the agents use to communicate with each other and a state machine that defines the behaviour of an agent in the argumentation dialogue The state machine has been implemented in the ArgCAgent java class by overwriting the states of the argumentation protocol of the API This proto col has been implemented in the Argumentation Participant java abstract class of the cAgents protocols package In each state of the protocol the different locutions that can be received and generated are taken into account to act in
31. UnitName Identifier of the unit Outputs NormName deleted Exceptions ForbiddenNormException NotSupervisorOrCreator InUnitException NotMemberOrCreatorInUnitEx ception InvalidUnitTypeException NotInUnitAnd NotCreatorException AgentNotInUnitException NormNotExistsException UnitNotExistsException EmptyParametersException Table 8 5 OMS Proxy Structural services API Description Provides a role description of a specific unit Inputs RoleName Identifier of the role InformRole UnitName Identifier of the unit Outputs Accessibility Visibility Position Exceptions ForbiddenNormException X VisibilityRoleException RoleNotExistsException UnitNotExistsExceptiont sException EmptyParametersException Description Provides unit description Inputs UnitName Identifier of the unit InformUnit Outputs lt UnitType ParentUnitName gt Exceptions ForbiddenNormException NotInUnitOrParentUnitEx ception InvalidUnitTypeException UnitNotExistsEx ception EmptyParametersException Description List the roles that have been registered inside a unit Inputs UnitName Identifier of the unit InformUnitRoles Outputs lt RoleName Accessibility Visibility Position gt 118 8 2 Programming agents which use THOMAS Exceptions ForbiddenNormException UnitNotExistsException EmptyParametersException Description L
32. Writer writer return new JsonWriter writer JsonWriter DROP ROOT MODE String result xstream2 toXML product response setContent result this send response This time the MarketAgent transforms a Java object into a JSON object As in the previous step it uses the library XStream Finally we assign the JSON object as the content of the response message Before we can test this example it is important to make sure that the example html file and the redirect php script are both in the same web server By security reasons cross commu nication between different hosts is forbidden Besides we have to specify in redirect php the address where our HTTP interface service is running We can indicate the address modifying the following line in redirect php Srequest new HTTP Request2 http localhost 8081 HTTP Request2 SSMESSHODAEOSSSI In this example the HTTP interface is running in the localhost CHAPTER 10 Advanced platform administra tion 10 1 Advanced Apache Qpid 147 10 2 Advanced MySQL e 149 10 3 Advanced Apache Tomcat 152 10 4 Advanced platform Services 153 10 1 Advanced Apache Qpid Qpid broker is a main component of Magentix2 In this section is described how it can be installed in case it was not desired to install Qpid together with Magentix2 Apache Qpid can be downloaded from http
33. a com plete support for virtual organizations and SOA like services THOMAS Methods Techniques and Tools for Open Multi Agent Systems framework has been integrated with Magentx2 with this purpose Argente et al 2011 8 1 Overview of THOMAS framework The THOMAS framework tries to communicate agents and SOA like services in a transparent but independent way Agents can offer and invoke services in a transparent way to other agents or entities as well as external entities can interact with our agents through the use of the offered services Different types of virtual organizations are supported by the THOMAS framework Each or ganization can contain others organizations Furthermore diverse roles can be assigned to 99 100 8 1 Overview of THOMAS framework each organization These roles are characterized by some attributes which restrict its behavior regarding THOMAS framework Thus agent must play those roles in order to belong to an organization In addition Magentix2 offers a new communication mechanism based on the virtual organiza tions structure Thus this organizational messaging allows mass communication among agents of an organization taking into account the type of roles agents play THOMAS framework consists of a set of modular services Agents have access to the infras tructure offered by THOMAS through a set of services provided by two main agents Service Facilitator SF This agent offers a yellow p
34. algorithms to calcu late similarity measures between cases cAgents protocols Argumentation Participant java CommitmentStore Protocol java Abstract class that defines the ar gumentation participant protocol to be followed by the CAgents Abstract class that defines the protocol that the Commitment Store follows to attend the peti tions of the agents Table 6 5 Argumentative agents core packages and classes a list of premises or a domain case without solution and a threshold of similarity The domain CBR module searches the domain case base and returns a list of similar domain cases to the given problem In addition with every request attended and every CBR cycle performed the module adds modifies or deletes one or more domain cases of the domain case base In the current version of the API if the problem that has been solved is similar enough over certain similarity threshold to a case of the domain cases case base the update algorithm updates this case with the new data acquired Otherwise a new domain case is created and added to the case base The main methods of the Domain CBR are shown in Table 6 6 for a detailed explanation of all Domain CBR methods see the DomainCBR java associated JavaDoc The Argumentation CBR can be used to look for previous argumentation experiences and use 70 6 3 Programming Argumentative Agents Method Parameters Description addCase domain case Adds
35. checked if those norms are fulfilled that is their target and activations are satisfied whereas their expiration are not In case a permitted norm is satisfied the service is provided with no restrictions and no structural norm related with unit types or role properties are considered Concretely the properties of the roles accessibility visibility position are not taking into account in the execution of the services such as informative services 2 FORBIDDEN norms It is checked if there are some forbidden norms registered which ac tion correspond with the requested service In that case it is also checked if those norms are fulfilled that is their target and activations are satisfied whereas their expiration are not If a forbidden norm is satisfied the service is not provided and a ForbiddenNormEx ception exception is thrown 3 Structural norms All predefined norms of the service are checked before provide the service If no one is satisfied the service is provided as usual 8 1 5 3 Normative Example Forum In this section an example of how to use the normative context provided by THOMAS is ex plained Concretely the Figure 8 2 shows the scenario where there are three units an organi zation named forum which type is hierarchy and its two descendent organizations fraternity which type is team and panel which type is flat Furthermore there is the virtual unit which represents the THOMAS world and acts as the
36. consequence and move to the next state Inside each state the corresponding actions are performed using the necessary calls to the different functions of the agent shown in Table 6 9 of Section 6 3 2 Also argumen tative agents can make queries to the commitment store and retrieve information about their argumentation dialogue Recall that since argumentative agents are a special type of Magen tix2 cAgents agents queue messages and send or receive them in the corresponding send and receive states see Section 4 The behaviour of the commitment store resource has been implemented by overwriting the abstract class CommitmentStore_Protocol java of the cAgents protocols package in the Commitment Store java class The set of allowed locutions of our argumentation protocol are codified as constants in the Argumentation Participant protocol of the cAgents protocols package These locutions are the following e OPENDIALOGUE with this locution an agent opens the argumentation dialogue ask ing other agents to collaborate or negotiate to solve a problem that it has been presented with e ENTERDIALOGUE with this locution an agent engages in the argumentation dialogue to solve the problem 62 Also 6 2 Argumentation API WITHDRAWDIALOGUE with this locution an agent leaves the argumentation dia logue ADDPOSITION with this locution an agent puts forward its position as its proposed solution to solve the problem under disc
37. each group of positions that promote the same value agents sort them by their suitability degree The most suitable position is selected as the one that the agent is going to propose and defend first The argumentation API of Magentix2 includes several similarity algorithms to compute the similarity degree SimD in the SimilarityAlgorithms java class Also the Metrics java class includes several metrics to compute distances between cases which are used in the similarity algorithms Table 6 2 shows these methods which belong to the argAgents package The specific algorithm that an argumentative agents uses to compute the similarity degree be tween two cases can be set in the configuration xml file of the configuration pack age shown below root domaincbr lt similarity gt normalizedEuclidean lt similarity gt normalizedEuclidean or weightedEuclidean or normalizedTversky gt domaincbr lt root gt SUPPORT ARGUMENTS MANAGEMENT A list of possible support arguments is generated with the method generateSupportArguments by using different combinations of the available support elements in the support set This list 60 6 2 Argumentation API Class Method Description Metrics java doDist This method decides about which is the data type of its attributes and return the distance between them Metrics java dist This method calculates the distance between a pair of att
38. entity in the system by invoking the method requestAllTracingServices The Trace Manager only alows for subcribing to all available services if you have been launched in monitorization mode Thus the following code would not work and the requester agent would receive a REFUSE ACL message with an AUTHORIZATION ERROR error code TraceManager tm new TraceManager new AgentID TM More code here This will NOT work x requestAllTracingServices this Launching the Trace Manager with the monitorization flag set to true like in the example will just work TraceManager tm new TraceManager new AgentID TM true x More code here This will work requestAllTracingServices this All these methods related to the subscription and unsubscription processes are described in more detail in Table 7 4 An example of tracing service subscription can be found in Section 7 6 1 in line number 20 where the agent subscribes to the NEW AGENT tracing service Line number 68 also shows an example of subscription to a tracing service called MESSAGE SENT DETAIL offered by a specific origin entity Later in that source code in lines 74 and 75 it can be observed how the agent unsubscribes from these tracing services 7 3 3 Listing The Trace Manager allows for listing tracing entities and tracing services available in the sys tem by invoking listTracingEntities and listTracin
39. events of that tracing service may be delivered to the tracing entity tService SUBSCRIBE 1 originEntity Trace Manager entity to which the tracing service request was made content tServiceName tServiceDescription length tServicedescription ESid ESid can be any UNSUBSCRIBE The tracing entity cancelled the subscription to a tracing service t ServiceName coming from the ES entity ESid which can be any if the removed subscription referred to trace events coming from any ES entity which provided it tService UNSUBSCRIBE 2 originEntity Trace Manager entity to which the tracing service request was made content tServiceName ESid ESid can be any UNAVAILABLE TS The specified tracing service ServiceName is no longer available This can be the conse cuence of the origin entity which provided the tracing service terminating its own execution or unpublishing the tracing service It also can be a consecuence of changes in the autho rization graph of the tracing service Receiving this trace event implies unsubscription from the tracing service but no UNSUBSCRIBE trace event is expected tService UNAVAILABLE TS 3 originEntity system host content tServiceNamefESid ESid can be any 7 4 4 Tracing service publication related domain independent tracing ser
40. is a value that provides an estimation of the number of steps that it took to reach an agreement posing a similar argument in the past e Explanatory Power E P is a value that represents the number of pieces of information that each argument covers It is based on the number of knowledge resources were used to generate each similar argument case retrieved The selection of these specific parameters to estimate the support factor of a position or ar gument has been determined by the nature of the elements of our argument cases Thus the persuasiveness and support degrees take into account the acceptability status stored in the argument cases the attack and risk degrees look at the attacks received by the argument that an argument case represents the efficiency degree makes use of the dialogue graphs stored in 56 6 1 Argumentation Framework the argument cases and the explanatory power computes the number of justification elements that argument cases have Therefore the support factor is computed by using the following formula SF wpp PD wsp SD wgp 1 RD 6 1 wap 1 AD wep ED wep EP i where w 0 1 5 wi 1 are weight values that allow the agent to give more or less importance to each parameter of the support factor In Magentix2 argumentative agents these weights can be set by specifying the corresponding parameters in the agent s constructor as will be show in Section 6 3 Thus an agent can u
41. main method of each Java application as follows DOMConfigurator configure configuration loggin xml Logger logger Logger getLogger Run class The file loggin xml is used to specify what level of log messages are written to the log files for each component Moreover Log4j allows logging requests to print to multiple destinations called appenders Two appenders predefined for Magentix2 are showed in 3 1 and 3 2 figures Specifically the appender 1 figure 3 1 indicates a file as the standard output The appender 2 figure 3 2 indicates the console as the standard output Please to learn more about appenders refer to http logging apache org log43 1 2 index html 3 1 4 Connecting to the Qpid Broker A connection to the Qpid broker must be established before launching any agent This connec tion will be used by agents to communicate with each other At this point it is assumed that users have a Qpid broker running properly and the agents are launched Ihttp jakarta apache org gt This file is located in the configuration directory of the Magentix2 installation 3 Basic Programming 19 appender name File class org apache log4j FileAppender lt param name File value logs Magentix2 log gt layout class org apache log4j PatternLayout gt 9 lt param name ConversionPattern value t 5p c 2 smsn gt lt layout gt lt appender gt Figure 3
42. o o 8 3 1 Service Registration e 8 3 2 Provide services ma a a Reto dd 8 4 Programming Agents that Request Services 0 a 8 4 1 Service Search Process o ee 8 4 2 Service Request Process 8 5 Running THOMAS Example lA 8 6 Programming agents which use organizational messaging 8 6 1 Registration into the organization o 8 62 Building the Message A 8 63 Completing Message 0000000000048 8 64 Sending the Message lA 8 7 Organizational Messaging Example HTTP Interface 9 1 Framework cuui ACE a EOE RE ACE NUS SW Y t 9 2 TOOL SA Looks it ode Dawes a Os hee oos ay dcbet s 92E Magentix2 8 0 pepe a od di ead TR edo 9 2 2 Redirect php sos eg mm e ote LIRE ne oe eus 9 35 Example ii ec eR Re erm A AAA Hir S GERE ae es Advanced platform administration 10 1 Advanced Apache Qpid o noaa 10 2 Advanced MySQL isaac amp sae ba OE ee SERE dS 10 3 Advanced Apache Tomcat o o e 10 4 Advanced platform Services o e e 10 4 4 Running Bridge Agents o o e e 10 4 2 Running OMS and SF Agents o o III 99 99 100 101 105 106 107 113 113 124 124 126 126 127 128 132 134 135 136 136 136 137 141 141 144 144 144 144 A BNF Syntax of the Normative Language A Grammar A 2 Predicate
43. println Hi I m agent this getName and I start my execution ACLMessage msg new ACLMessage ACLMessage INFORM msg setSender this getAid msg addReceiver new AgentID Consumer msg setContent Hi I m Sender agent and I m running on Magentix2 this send msg Following there is an explanation of all the code in the previously shown execute method line by line e The agent says hello and shows its name on the console line 14 A new ACLMessage called msg is created line 15 The performative of this message is Inform This agent Sender agent is set as the sender of the message line 16 The Consumer agent is added as a receiver of the agent line 17 The content of the message msg is specified line 18 20 21 22 23 24 25 12 2 2 Developing and executing a first agent e Finally the agent sends the message and with this ends its execution line 19 Now it is time to program the Consumer agent This agent will wait until it receives the message from the Sender agent Then it will show the content of the message on the console and it ends its execution The code of the Consumer agent is shown below package agent import es upv dsic gti_ia core ACLMessage import es upv dsic gti ia core AgentID import es upv dsic gti ia core SingleAgent public class Consumer extends SingleAgent boolean gotMsg false public Consumer AgentID aid throws Exception
44. public class Sender extends BaseAgent a gt B JRE System Library JavaSE 1 6 Y B Referenced Libraries i magentix2 2 01 jar with dependencies zip F Y configuration clientrepo E loggin xml Connect Mylyn fii policy xml Connect to your task and ALM B securityUser properties tools E Settings xml BE Outline 33 m Josh esee dB agent v import declarations es upv dsic gti ia core ACLMes es upv dsic gti ia core AgentID es upv dsic gti_ia core BaseAge e El Problems 2 gt Javadoc 8 Declaration 1error 0 warnings 0 others Description Resource Path Location Type Y O Errors 1 item Implicit super constructor BaseAgent is und Senderjava MyFirstAgent src a line7 Java Problem writable Smart Insert 13 1 Figure 2 2 Programming a first agent with Eclipse beginning of the agent execution is added The method execute is the main method of the agent and finalize is executed just before the agent ends its execution and it is destroyed 20 21 22 2 Quick Start 11 In this specific example it is only needed to implement code in the method execute The code of the agent is shown below package agent import es upv dsic gti ia core ACLMessage import es upv dsic gti ia core AgentID import es upv dsic gti ia core BaseAgent public class Sender extends BaseAgent public Sender AgentID aid throws Exception super aid public void execute System out
45. request refers originEntity AgentID of the specific agent which offers the tracing service If not specified the subscription unsubscription request is considered to refer to tracing services offered by any tracing entity in the system two methods are described in more detail in Table 7 5 In response to any of these requests a list of available tracing entities or available tracing services will be sent to the applicantAgent as an AGRE list will be included in the content field of the ACL message E ACL message The requested When a list of avalable tracing entities has been requested the content of the reply message will be structured as follows e Message content list entities lt number of t entities gt lt t entity description list gt e t entity description list List of concatenated tracing entity descrip tions each of which is structured as follows 7 Tracing Service 83 lt entity type gt lt entity identifier length gt lt entity identifier gt e entity type gt 0 1 2 meaning agent artifact or aggregation When a list of tracing services has been requested the content of the reply message will be structured as follows e Message content list services lt number of t services gt lt t service description list gt e t service description list List of concatenated tracing service descrip tions each of which is structured as follow
46. requester On the other hand if the providers of a service are registered in the SF as web services ground ings the requester of these services will have to execute the service by itself using the class ServiceTools of the package es upv dsic gti_ia organization see Section 8 4 2 8 4 Programming Agents that Request Services This section describes how an agent that requires services from other agents can search and request services in THOMAS 8 Virtual Organizations 8 4 1 Service Search Process 127 e Search of a service Agents can use the SearchService service to find required ser vices The method SearchService of the SFproxy makes a request to this service with the following parameters List of inputs of the service to search These inputs has to be specified as types of an ontology In ServiceTools class the main types integer float double string boolean are specified as constants to be easier to the developer List of outputs of the service to search These inputs has to be specified as types of an ontology as the inputs explained before List of keywords of the text description of the service to search Each String added to this list will compute to find it in the text description of the service profiles registered in the SF SearchService profile similarity ServiceProfile 1 0 ServiceProfile2 0 75 inputs outputs keywords Figure 8 7 Agent interaction
47. result of the execution will appear on the console and it should be something similar to what is shown below Hi I m agent Consumer and I start my execution Hi I m agent Sender and I start my execution Hi I m agent Consumer and I ve received the message Hi I m Sender agent and I m running on Magentix2 CHAPTER 3 Basic Programming 3 1 Basic classes for building agents BaseAgent and SimpleAgent ooo 15 3 2 Agent Communication 22 3 3 Basic conversational agents QueueAgents 26 3 1 Basic classes for building agents BaseAgent and Sim pleAgent 3 1 4 BaseAgent In order to create a basic Magentix2 agent it is necessary to define a class which extends the class es upv dsic gti ia core BaseAgent The logic of the agent should be implemented overriding three methods e init it is used to add instructions that should be executed at the beginning of the agent s execution if it is needed e execute it must contain the main logic of the agent e finalize itis used to add instructions that should be executed at the end of the agent s execution if it is needed A unique identifier with a new instance of Agent ID class must be associated to the agent 15 16 3 1 Basic classes for building agents BaseAgent and SimpleAgent when it is created SenderAgent xtends BaseAgent x SenderAgent agent new Sende
48. that gave rise to this conclusion Justification The problem description has a domain context that consists of the premises that characterise the argument In addition if we want to store an argument and use it to generate a persuasive argument in the future the features that characterise its social context must also be kept The social context of the argument case includes information about the proponent and the opponent of the argument and about their group Moreover we also store the preferences ValPref of each agent or group over the set of possible values that arguments can promote pre defined in the system Finally the dependency relation between the proponent s and the opponent s roles is also stored In our framework we consider three types of dependency relations power when an agent has to accept a request from another agent because of some pre defined domination relationship between them authorisation when an agent has signed a contract with another agent to provide it with a service and hence the contractor agent is able to impose its authority over the contracted agent and charity when an agent is willing to answer a request from another agent without being obliged to do so 54 6 1 Argumentation Framework In the solution part the conclusion of the case the value promoted and the acceptability status of the argument at the end of the dialogue are stored The acceptability status shows if the argument was deemed
49. the method Get Service of the SFProxy class Once the service specification is obtained the oracle can be asked about any field in the ser vice specification The available methods for the Oracle class can be found in the Javadoc documentation of the project obtain the the service OWL S specification String serviceOWLS sfProxy getService ServiceProfile load in the oracle the service OWL S specification and parse it Oracle oracle new Oracle serviceOWLS access to the service OWL S information through the oracle ArrayList lt String gt service inputs oracle getOwlsProfileInputs ArrayList lt Provider gt providers oracle getProviders ArrayList lt String gt providersGroundingWSDL oracle getProvidersGroundingWSDL 8 3 Programming Agents that Offer Services This section describes how an agent that offers services to the other agents inside the organiza tion can register announce and provide its services 8 3 1 Service Registration e Registering a new service An agent wants to register its own service in the SF Figure 8 5 The OWL S specification of the service must be available in a url This specifica tion has to follow the OWL S standard having the profile and process of the service It also needs to specify the provider or providers of the service in the following way 8 Virtual Organizations 125 If the provider is an agent or an organization the profile has
50. the timeout is exceeded The responder agent has the han dleAcceptProposal and handleRejectProposal methods which are called depending on whether the proposal was accepted or not and their main characteristic is that both of them receive as input parameters all the messages exchanged by both agents so far 32 4 3 Programming CAgents 4 3 Programming CAgents CAgents facilitate the use and management of conversations CAgents use CFactories and CProcessors these two components control ongoing conversation and create new ones On the one hand CFactories act as Interaction Protocols IPs and are in charge of creating new CPro cessors On the other hand CProcessors act as instances of CFactories that is conversations CFactories have a graph made up of states and arcs A graph specifies the sequence of actions that a conversation which is following that protocol has to take Each state represents a specific action and each arc represents a possible transition between two states A collection of states actions has been defined e Begin This state represent that the agent starts the conversation e Final This state represent that the agent ends the conversation e Send In this state the agent sends a message e Wait When a agent reaches this state the conversation halts until a message is assigned to the conversation Then according to the type of the arrived message an specific subsequent Receive state is executed The type of
51. to read th public void execute ACLMessage msg while finish EEVA newspaper Thread sleep 1000 jy CECR InterruptedException e e printStackTrace System out println Daddy this getName Ok I us Bisa m msg Shall we go to the park new ACLMessage ACLMessage REQUEST msg setSender this getAid msg setContent GO TO THE PARK msg setReceiver new AgentID Timmy send msg msg setReceiver new AgentID Bobby send msg while Bobby agree Timmy_agree Lie Thread sleep 1000 45 46 47 48 49 50 M 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 7 Tracing Service 91 catch InterruptedException e e printStackTrace iae dd Thread sleep 1000 catch InterruptedException e e printStackTrace System out println Daddy this getName Ok Let FSG CAI emis public void onTraceEvent TraceEvent tEvent DateFormat formatter new SimpleDateFormat HH mm ss SSS Cal r lendar calendar Calendar getInstance cal lendar setTimeInMillis tEvent getTimestamp ACLMessage msg ale tEvent getTracingService contentEquals NEW_AGENT TraceInteract requestTracingService this MESSA
52. transparent The role is visible throughout the system External any agent can acquire this role Public any agent can request information about the role Public Internal Role with restricted access although visible throughout the system Internal in order to acquire this role agents must participate in the organization in which the role was registered or in its Parent Organiza tion Public any agent can request information about the role Private External Role fully accessible but with limited visibility External any agent can acquire this role Private information about the role is only provided if requested agents participate in the organization in which the role was registered or in its Parent Organization Private Internal Maximum protection of the role The unit acts like a black box for these roles Internal agents must participate in the organization or in its parent organization to acquire the role Private agents can request information about the role if they partici pate in the organization in which the role was registered or in its Parent Organization Table 8 2 How visibility and accessibility attributes affect roles FLAT TEAM HIERARCHY Allowed role Creator Creator positions Member Supervisor Subordinate What agents can Any agent from this organization except those who only play roles with Position Creator send organizational mes
53. two input numbers doubles and returns the addition dou ble It is provided by agent that calls to a web service 8 Virtual Organizations 133 e Square This service squares an input number double and returns the result double It is provided by a web service Following we briefly explain the actions of the THOMAS example shown in the diagram of Figure 8 9 5 Request Addition Service 5 Request Product Service 3 RegisterService Addition ation calculator 2 AcquireRol 2 AcquireB operation ca 3 RegisterService Product 6 DeregisterService 4 SearchService GetService Initiator Agent 1 RegisterUnit RegisterRole 6 DeregisterUnit DeregisterRole DeallocateRole OMS SF Figure 8 9 Thomas Example diagram 1 The Initiator acquires the role participant of the default unit virtual Then it registers the organizations Calculator and School Calculator is a team unit its parent unit is virtual and the name of the default role is creator On the other hand the unit School is a flat organization its parent unit is virtual and the name of the default role is also creator Once the agent registers the units it also creates the roles needed So first the Initiator agent registers a role named operator member public and external inside the unit Calculator Secondly it registers a role named student member public and external inside the unit School 134
54. types allowed to customize LIFE_CYCLE Subscriptions to tracing services related to agents life cycle Agent creation and destruction CUSTOM Publication and subscription to tracing services defined by users MSG Subscription to the sending and receiving of ACL messages MSG_DTL Subscription to the sending and receiving of ACL messages with the content included LIST ENTITIES List all the tracing entities LIST SERVICES List all the tracing services SUBSCRIBE TO Subscription to all available tracing services ALL SERVICES Table 7 11 Action information about the mask reception WELCOME W The mask is sent because the TM has just launched Another possibility is to receive it as a response of a newAgent event UPDATE U The mask is sent because the tracing policy has changed and the TM informs all the agents with a new mask event DIE D The TM informs agents about it is going to shut down So the trace support will be not available registered at the platform The TM will use it to check if it is allowed to register new services or subscriptions The agent will check the current mask in order to generate or not events By default agents will have a mask with no events allowed When the agent TM is created it is activated the trace support and the agents receive the trace support mask with the allowed events 7 6 Example TraceDaddy This simple example shows ho
55. wRD wAD wED wEP agent start where socialEntity represents the social entity name role preference values created for this agent friendsList is an ArrayList with the social entities that represent the friends of the agent the agents that it knows depenRelsList is an ArrayList that represents the de pendency relations that the agent has with the rest of agents of the system group represents the group that the agent belongs and commitmentStoreID represents the identifier of the com mitment store resource There are also two ArrayList called iniDomainCasesFilePath and finDomainCasesFilePath with the file paths that store the initial and final domain cases case bases In addition domCBRindex establishes an index in the sense of a Hash Table index to retrieve cases from the domain cases case base and domCBRthreshold establishes a threshold over which two cases are considered as similar The iniArgCasesFilePath and finArgCases FilePath ArrayLists represent the file paths that store the initial and final argument cases case bases Finally the wPD wSD wRD wAD wED and wEP are the weights assigned to the parameters to compute the supportFactor Different combinations of these weight allow argumentative agents to follow different argumentation strategies 6 3 2 How to create your own Magentix2 Argumentative Agent Magentix2 provides the core of the argumentation protocol the Domain CBR the Argumen tation CBR and the
56. was a Query Ref 4 2 3 FIPA Contract Net The classes ContractNet implements the behaviour of the protocol of the same name whose operation is the initiator sends a proposal to several responders then evaluates their answers and finally chooses the preferred one or no one The messages exchanged are 1 CFP Call For Proposal it specifyes the action to carry out and when it is appropriate the conditions on the performance 2 Refuse when responders reject their participation 3 Not Understood when there were failings in the communication 4 Propose when a responder makes proposal to the initiator 5 Reject Proposal in the case the initiator evaluates a proposal and reject it 6 Accept Proposal when the initiator evaluates a proposal and accepts it sending this type of message to accept them 7 Failure responder send this type of message when their proposals were accepted and something wrong happened 8 Inform Done this messages is sended by responders when their proposals were ac cepted and the action was performed successfully 9 Inform Results this message is sended by responders when their proposals were ac cepted and they need to inform about the results of the operation performed The initiator ContractNetInitiator has two main methods the handlePropose method which is called each time a response is received and the handleAllResponses method which is called when all responses are received or
57. 5 Jason and the Golden Fleece of agent oriented programming Multi Agent Programming pages 3 37 Burdalo L Terrasa A Juli n V and Garc a Fornes A 2010 TRAMMAS A Tracing Model for Multiagent systems In First International Workshop on Infraestructures and Tools for Multiagent Systems pages 42 49 FIPA 2002 FIPA Request Interaction Protocol Specification FIPA Fogu s R L Alberola J M Such J M Espinosa A and Garca Fornes A 2010 To wards Dynamic Agent Interaction Support in Open Multiagent Systems In Proceedings of the 13th International Conference of the Catalan Association for Artificial Intelligence volume 220 pages 89 98 IOS Press Heras S 2011 Case Based Argumentation Framework for Agent Societies PhD thesis De partamento de Sistemas Inform ticos y Computaci n Universitat Polit cnica de Val ncia http hdl handle net 10251 12497 Rao A S 1996 Agentspeak D Bdi agents speak out in a logical computable language In Modelling Autonomous Agents in a Multi Agent World MAAMAW pages 42 55 Springer Verlag Val E D Criado N Rebollo M Argente E and Julian V 2009 Service Oriented 175 176 Bibliography Framework for Virtual Organizations In International Conference on Artificial Intelli gence ICAI volume 1 pages 108 114 CSREA Press Walton D Reed C and Macagno F 2008 Argumentation Schemes Cambridge University Press
58. ACLMessage r 7 6 Example TraceDaddy ACLMessage R AGREE response_msg response_msg response_msg EQU Equals GO TO T Sponse msg new ACLMessag EST H E PARK setSender this getAid setContent GO TO THE I ACLMessag PARK setReceiver msg getSender send response msg You no daddy if msg getPerformativeInt ACLMessag ACLMessage R REFUS E response msg new ACLMessag EQU EST response_msg setSender this getAid response_msg setContent NO ACLMessag response msg setReceiver msg getSender send response msg 7 6 3 Main application source code package TraceDaddy port port port port port plste org apache org apache l log4j Logger log4j xml DOMConfigurator es upv dsic gti ia core AgentID es upv dsic gti ia core AgentsConnection es upw dsrc gti ia trac class Run TraceManager 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 7 Tracing Service 95 Dubie SE atc vota small tan gia args Boy olderSon youngerSon Daddy dad Setting the Logger x DOMConfigurator configure configuration loggin xml Logger logger Logger getLogger Run clas
59. ActionExec gt feedback getTS getLogger info Agent getAgName is doing action getActionTerm 48 5 1 Programming BDI Agents if action getActionTerm equals doAction perform the action set the result for example always true action setResult true add the executed action to the list of action executions feedback add action The code in AgentSpeak L is written in a different file the path to the file is passed as an argument to the constructor of the JasonAgent class A sample code of an AgentSpeak L program is shown below val Sel E22 v1 X source Ag Ag self SAR ESAS dabis TEN OMA AQ goto X Y source Ag true lt println Received achieve goto X Y from Ag amm DO E ALE ec Ge i sp des t kqml received Sender askOne fullname ReplyWith true lt send Sender tell Maria dos Santos ReplyWith send the answer CHAPTER 6 Argumentative Agents 6 1 Argumentation Framework 49 6 2 Argumentation API 57 6 3 Programming Argumentative Agents 66 This chapter describes the argumentative agents API of Magentix2 This API allows agents to engage in argumentation dialogues to reach agreements about the best solution for a problem that must be solved First we introduce the theory of the argumentation framework that Magentix2 argumentative agen
60. Context As we explain in sections 8 1 1 and 8 1 2 there are some predefined norms called structural norms which control the access to OMS services Thus some OMS services are only available if agents which request them play some role inside the organization with a concrete position table 8 4 It is possible to avoid these structural norms or make them more restrictive by means of defining new norms using the registerNorm service of the OMS In this way users can add PERMITTED or FORBIDDEN norms to relax or restrict the access control to the OMS services in an organization Position OMS Services Creator Member Supervisor Subordinate RegisterUnit DeregisterUnit RegisterRole DeregisterRole RegisterNorm DeregisterNorm AquiereRole LeaveRole AllocateRole DeallocateRole JointUnit X InformAgentRole InformMembers InformQuantityMembers InformUnit InformUnitRoles InformTargetNorms InformRole InformNorm 1 The agent should also play another role with position creator in the parent unit x 1 K FX WoW oW OK OK OK 1 PX FX MK KK OK OK t A MK MM KO PA p pA M M KKK WoW oW oW KOKO XX oW MM KO PA XM oW oW oW oW WOW X X 2 The agent could acquire another role with posistio creator or position supervisor in its organization Table 8 4 OMS Proxy Service Access taking into account the role position played by the requesting agent 108 8 1 Overview of THOMAS framework 8 1 5 1 Norm Description Norm
61. Creator fraternity hasDeontic noRegRoleCreator fraternity f hasTarget noRegRoleCreator fraternity agentName _ hasAction noRegRoleCreator fraternity registerRole xFraternity Changing the parent unit of the organization is prohibit x isNorm noJoinUnit fraternity hasDeontic noJoinUnit fraternity f hasTarget noJoinUnit fraternity positionName _ hasAction noJoinUnit fraternity joinUnit Panel Only one agent can play the role moderator isNorm noAcRoleModerator panel hasDeontic noAcRoleModerator panel f hasTarget noAcRoleModerator panel agentname hasAction noAcRoleModerator panel acquiereRole xPanel The agent which plays the role moderator should play the role moderator in the forum unit isNorm controlAcRoleModerator panel hasDeontic controlAcRoleModerator panel f hasTarget controlAcRoleModerator panel agentname hasAction controlAcRoleModerator panel acquiereRole A BNF Syntax of the Normative Language 167 xPanel Only the role moderator can add norms isNorm noRegNorm panel hasDeontic noRegNorm panel f hasTarget noRegNorm panel agentname Ag hasAction noRegNorm panel registerNorm xPanel Only the role moderator can delete norms x isNorm noDeregNorm panel hasDeontic noDeregNorm panel f hasTarget noDeregNorm panel agentname Ag hasAction noDeregNorm panel d
62. Enterprise Help User Information Schema Privileges Resource Limits r E Server Information o Service Control E Startup Parameters di User Administration 10 3 Advanced Apache Tomcat thomas anywhere Schema database privileges assigned to the user Schema Assigned Privileges Available Privileges Server Comecion ls SELECT Grants the SELECT privild YJ Health E information A INSERT Grants the INSERT privile amp g Server Logs Now AA UPDATE Grants the UPDATE privil Backup mamas DELETE Grants the DELETE privil Restore Backup CREATE Grants the CREATE privil di Replication Status A DROP Grants the DROP privileg e Catalogs GRANT Grants the GRANT privile l b A REFERENCES Grants the REFERENCES User EERE A INDEX Grants the INDEX privile Cal A ALTER Grants the ALTER privilec amp debian sys maint A CREATE TMP TABLE Grants the CREATE TMP amp root LOCK TABLES Grants the LOCK TABLES A CREATE VIEW Grants the CREATE VIEW 20 SHOW VIEW Grants the SHOW VIEW CREATE ROUTINE Grants the CREATE ROU ESSEN Nr B ALEER ROLITIME Grants thes ep poum ly Processing backup file Figure 10 4 Assigning privileges to the thomas user in the User Administration option of the MySQL Administra tion tool Note grayed privileges mean they are provided through Global Privileges b New User 49 Discard Changes f A
63. GE SENT DETAIL new AgentID tEvent getContent else if tEvent getTracingService contentEquals MESSAGE SENT DETAIL msg ACLMessage fromString tEvent getContent System out Orin tli As getName O sav formatter format calendar getTime msg Geusendem testi gis o oi IS qe getPerformative msg getContent if msg getContent contentEquals GUAAAAAA TracelInteract cancelTracingServiceSubscription this MESSAGE SENT DETAIL new AgentID Timmy 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 92 7 6 Example TraceDaddy TraceInteract cancelTracingServiceSubscription this MESSAGE SENT DETAIL new AgentID Bobby finish true public void onMessage ACLMessage msg if msg getPerformativeInt ACLMessage AGREE amp amp msg getContent contentEquals GO TO THE PARK Systeme oute Prine PM D ad dy AENA sde EN ame Et MSG Agee Senders MA MS NS suc CES getPerformative msg getContent if msg getSender getLocalName contentEquals Bobby ODE Bobby_agree true if msg getSender getLocalName contentEquals Timmy BOE Timmy agree true 7 6 2 Boy class package TraceDaddy import es upv dsic gti ia core ACLMessage import
64. Ma Inform tica ogia Inteligencia Artificial Grupo de Tecnol lt U AL Ji Ji o ep GOBIERNO MINISTERIO e sE 0 a y LIE lH UNIVERSITAT AGREEMENT gg DEESFANA E INNOVACI N POLITECNICA TECHNOLOGIES DE VALENCIA Contents Acknowledgments Contributors 1 Introduction 1 1 Motivation Seg s ae ed es A AG ee Be EG EM ee da 1 2 Manual Structure ee Quick Start 2 Installing Magentix2 es ZA Requirements c som Soe RE BO a E 2 1 2 Installation of MagentixX2 ee 2 1 3 Magentix2 installation description 04 2 1 4 Uninstalling Magentix2 ee 2 2 Developing and executing a first agent lees Basic Programming 3 1 Basic classes for building agents BaseAgent and SimpleAgent 3 Base Are aia 4ae2 oot Aper Lo a Boba d 3 1 2 SimpleAge nt cocido ee ke Rue x XS ONSE 3 1 3 Initialization Tasks eee 3 1 4 Connecting to the Qpid Broker o 3 1 5 Running Agents e 3 1 6 Agent life Cycles tac e e Be aye ta ree 3 1 7 Running Examples ee 3 2 AgentCommunication lese 321 FIPA ACL Language 4r 3 2 2 Sending Messages es 3 2 3 Receiving Messages een 3 2 4 External Communication lees 3 3 Basic conversational agents QueueAgents lens IX XI 3 3 1 Running QueueAgents 2 0 00 00000048 26 3 3 2 Examples
65. NormException NotCreatorInUni tOrParentUnitException VirtualUnitException Unit NotExistsException EmptyParametersException Description Updates the parent unit Inputs UnitName Identifier of the unit JoinUnit ParentUnitName Identifier of the new parent unit Outputs UnitName joined to ParentUnitName Exception SameUnitException VirtualParentException For biddenNormException NotCreatorInParentUnitEx ception NotCreatorInUnitException AgentIDnt NotInUnitException ParentUnitNotExistsException UnitNotExistsException EmptyParametersException Description Creates a new norm within a specific organization that can be associated to a role position or agent RegisterNorm Inputs UnitName Identifier of the unit NormContent The norm described in THOMAS lan guage see appendix A Outputs NormName registered 8 Virtual Organizations 117 Exceptions RoleNotExistsException InvalidPositionException InvalidUnitTypeException ForbiddenNormException NotSupervisorOrCreatorInUnitException NotMem berOrCreatorInUnitException InvalidUnitTypeEx ception NotInUnitAndNotCreatorException Agent NotInUnitException NormExistsInUnitException UnitNotExistsException EmptyParametersException Description Removes a specific norm from a unit Inputs NormName Identifier of the norm DeregisterNorm
66. O DV wc EEG OT C Tes E V a desea V no wine xeusalersi t 7 p 315109 The HTTP interface does not send the ACL Message directly to the target agent instead it creates a dummy agent that will send the ACLMessage This functionality allows the HTTP interface to manage multiple and concurrent HTTP POST requests The name of a dummy agent is InterfaceAgentX where X will be a number As an example the receiver conversa tion id sender and content fields of the ACLMessage that the target agent would recive after the HTTP interface would receive the previous JSON object would be the following ACLMessage receiver Mik ACLMessage conversation_id convl ACLMessage sender InterfaceAgentl ACLMessage content agent name V Mike conversation_id Gua nal eo nis mts EE ESTO C Ar QUT Co BR TTC GNIS CIN C Ug Shs Olin The target agent can respond to the HTTP request sending an ACLMessage to the Inter faceAgent that sent the ACLMessage with the HTTP request The content of the ACLMessage sent to the InterfaceAgent will be used as the message body of the reply to the HTTP request Continuing with the previous example the ACLMessage that the agent Mike would send to the InterfaceAgent1 could be ACLMessage receiver InterfaceAgentl ACLMessage conversation_id convl ACLMessage sender Mik ACLMessage content name Banana id 123 price usos jh As you may note the content of this
67. SameDomainAnd premises solution Returns the argument cases with the SocialContextAccepted socialContext same domain and social context that have been accepted in the past Table 6 7 Main ArgCBR java methods Method Description doCache Stores the current domain cases case base in a specified file path doCacheInc Stores the current domain cases case base in a specified file path but keeping the contents of that file loadCaseBase Loads a case base stored in a specified file path Table 6 8 Main CBR persistence methods the Magentix2 CAgent implementing the argumentative functions of the agent Inside the execution method the myArgumentation class extends the argumentation protocol of Magentix2 Concretely the argumentation API of Magentix2 includes two special proto cols that allow agents to argue the Argumentation Participant protocol and the CommitmentStore Protocol Both are abstract classes of the cAgents protocols package that argumentative agents and the commitment store extend respectively These classes provide a template for the behaviour of the argumentative agents and the commitment store Each one implements a new CFactory see CAgent JavaDoc for more information with the graph that specifies the sequence of states and transitions among them that agents can pass through during the argumentation dialogue Therefore to create a new argumentative agent it is necessary to implement
68. The platform starts a conversation with each agent that has 20 21 22 23 24 25 26 27 28 29 30 31 4 Advanced conversational agents CAgents 35 j Py JJ 2 A pg been just created by sending it a welcome message This sending creates the first CProcessor of the agent In order to manage this message the user must implement the execution method defined by the class CAgent this method will be executed by the first CProcessor It is also in this method where all other actions and behaviours of the agent has to be implemented protected void execution CProcessor myProcessor ACLMessage welcomeMessage System out println myProcessor getMyAgent getName the welcome message is welcomeMessage getContent i System out println myProcessor getMyAgent getName inevitably I have to say hello world ShutdownAgent method initialize the process which will finalize the active conversations of the agent When this process ends ene pita tfe OTT sends a finalize message to the agent myProcessor ShutdownAgent In order to manage the finalization message the user has to implement the finalize method defined by the CAgent class protected void finalize CProcessor myProcessor ACLMessage finalizeMessage System out println myProcessor getMyAgent getName the finalize message is finali
69. This is received by the Product and Display agents The Display agent prints this message to standard output 7 The agents that play the Operator role only Product agent receive the numbers five 140 8 7 Organizational Messaging Example and three to calculate their calculations 5 x 3 15 and communicate the results as an organizational messages These are received by the Summation agent 8 The Summation agent sends the sum of all results received 15 15 as an organiza tional message This is received by the Display agent which prints this value to standard output 9 To finalize this example the scenary is disassembled The Creator agent deregisters all the roles belonging to Calculator organization and deregisters the organization Si multaneously the Noisy agent deallocates and deregisters all the roles belonging to the External organization and deregisters the organization All agents finalize their execu tions To run the example the user has to enter in the Magentix2 examples bin folder where it has been installed Then the user has to execute the Start OrganizationalExample sh script with administrator privileges cd Magentix2 examples bin sudo sh Start OrganizationalExample sh CHAPTER 9 HTTP Interface 9 1 Framework oooooooooooooo 141 92 Tool i34 SR A ae 144 9 3 Example E VR e ern 144 In order to allow interaction between a Magentix2 agent and t
70. To do it the user has to use the source code from the Magentix2 src directory and create a project to modify the code The Magentix2 library must be included in the project The steps to perform this task are explained in Section 2 2 In this case the code to modify is located in the Argumentation Example pack age The main class to execute tests is TestArgCAgent java In this class the user can modify the initial data given to the agents the number of agents to execute the number of problems to solve and the weights of the argumentative agents to perform different argumentation strate gies The behaviour of the argumentative agents can be changed modifying the default actions of the methods in the ArgCAgent java class see Table 6 4 Furthermore in the argumentation example provided we assume the existence of a fester agent that is in charge of requesting a group of ArgCAgents to solve a problem This agent implemented in the Magentix2 argu mentation API with the class TesterArgCAgent extends a Magentix2 SingleAgent Also it is in charge of gathering information at the end of the protocol and convey the final solution proposed A standard argumentative agent can be created and executed by using these commands 6 Argumentative Agents 67 Package Classes Description AgentsCreation java This class has different methods to create groups of agents and Argumentation Example some of their parameters ArgCAgent java This class impleme
71. a new domain case to domain case base Otherwise if the same domain case exists in the case base adds the relevant data to the existing domain case getPremisesSimilarity premisesl premises2 Obtains the similarity between two HashMap of premises using the simi larity algorithm specified in the config uration of this class retrieve premises threshold Retrieves the most similar domain cases to the given premises with a sim ilarity degree greater or equal than a given threshold Table 6 6 Main DomainCBR java methods this knowledge to select the best positions and arguments to propose Thus argument cases store information related to the domain and the social context where previous arguments and their associated positions were used The information about the domain consists of a set of fea tures premises to compare cases and information about the social context where the proposed solution was applied e g the agents that participated in the dialogue to solve the problem their roles or their value preferences The latter information can determine if certain positions and arguments are more persuasive than others for a particular social context and hence agents can select the best ones to propose in the current situation As for the domain cases case base if the argument cases created during the problem solving process are similar enough to previ ous argument cases stored in the argument cases case base th
72. acceptable unacceptable or undecided in view of the other arguments that were put forward in the agreement process Therefore an argument is deemed acceptable if it remains undefeated at the end of the argumentation dialogue unacceptable if it was defeated during the dialogue and undecided if its acceptability status cannot be determined with the current information about the dialogue In addition the conclusion part includes information about the possible attacks that the argument received during the process These attacks could represent the justification for an argument to be deemed unacceptable or else reinforce the persuasive power of an argument that despite being attacked was finally accepted Finally the justification part of an argument case stores the information about the knowledge resources that were used to generate the argument represented by the argument case the set of domain cases and argument cases In addition the justification of each argument case has a dialogue graph or several associated which represents the sequence of arguments that form the dialogue where the argument was proposed In this way the complete conversation is stored as a directed graph that links argument cases that represent the arguments of the dialogue This graph can be used later to improve the efficiency in an argumentation dialogue in view of a similar dialogue that was held in the past 6 1 2 Dialogue Strategies In each step of an argument
73. age service and also a service descriptor in charge of providing a green page service Organization Manager Service OMS It is mainly responsible of the management of the organizations and their entities Thus it allows the creation and the management of any organization and the roles the agents play 8 1 1 Roles in THOMAS Roles in THOMAS are defined with a RoleName that acts as an identifier Furthermore each role is always associated with a particular organizational unit Also each role has the following attributes lt Position Accessibility Visibility gt e Position The possible values that this field can take are Member Supervisor subordi nate or Creator This value must be assigned to roles when they are created Not all the values are allowed to any type of organization see section 8 1 2 Anytime an agent registers an organization it is automatically assigned a new role with a creator position to him This position gives permission to register and dereg ister organizations and roles In addition it is possible to assign a creator role using the services offered by the THOMAS API see section 8 2 1 In Table 8 1 a summary of the role behavior taking into account its position is shown e Accessibility This attribute allows controlling who can acquire roles Specifically the permitted values are 8 Virtual Organizations 101 External roles can be acquired by agents who do not play any ro
74. agentix2 argAgents knowledgeResources package Domain Cases 6 Argumentative Agents 51 String String String String Float Boolean Description String Value Promoted String Figure 6 1 Example Structure of a Domain Case The structure of domain cases that an argumentation system that implements our framework depends on the application domain As example Figure 6 1 shows the structure of a possi ble domain case Here an argumentative agent must solve a problem characterised by three premises of different data types P1 P2 and P3 In this example the argumentative agent ArgAgent has found the domain case DC1 that matches de description of the problem to solve has all or some of the premises of the problem with the same data values for this premises also including an extra feature P4 Note that here we assume that domain cases also store the value promoted by the solution that they represent see on the arguments structure below for a more detailed explanation This is a design decision that can be replaced by any other assumption Domain cases are implemented in Magentix2 by using the DomainCase java class of the argAgents knowledgeResources package Arguments Arguments in Magentix2 are implemented as java classes concretely in the Argument java class of the Magentix2 argAgents knowledgeResources package In our proposal argu ments that agents interchange have the following struct
75. applicantAgent String serviceName unpublishTracingService AgentID tms aid BaseAgent applicantAgent String serviceName tms aid Agent ID of the Trace Manager which will process the request If not specified the request is directed to the default Trace Manager TM applicantAgent Agent which is publishing the tracing service serviceName String identifying the tracing service which is being published or un published description Human readable description of the tracing service which is being pub lished An example of tracing service publication can be publishTracingService this TracingService 1 An example of tracing service where the running agent this publishes a tracing service called TracingService_1 which is described as An example of tracing service Once the running agent is done sharing these trace events it can unpublish the tracing service by invoking the corresponding method referring to the already published tracing service unpublishTracingService this TracingService 1 7 3 2 Tracing service subscription Before receiving any trace event agents have to request the corresponding tracing service by invoking requestTracingService This subscription can be cancelled later by invoking 7 Tracing Service 81 cancelTracingServiceSubscription It is also possible to subscribe to all available tracing services offered by any tracing
76. ases of its domain cases case base which features match the given problem with a similarity degree greater than a given threshold If the agent has been able to retrieve similar domain cases and use their solu tions to propose a solution for the current problem the agent will engage in the dialogue with the locution ENTERDIALOGUE and will go to the state Propose The agent only engages in the dialogue if it has solutions to propose Otherwise the agent can refuse to engage in the dialogue with the locution WITHDRAWDIALOGUE 4 Propose when the agent is in this state it has retrieved a list of similar domain cases to the current problem to propose a solution position to defend If there are several solu tions to propose it will select the most suitable and go to the state Central Otherwise 64 6 2 Argumentation API the agent will leave the dialogue with the locution WITHDRAWDIALOGUE Central this is a central state since the agent can try to attack other positions or defend its position from the attacks of other agents First the agent checks if there is any WHY request from other agent This locution is used to ask an argumentative agent to justify its position In that case the agent will go to the state Assert to try to generate a support argument for its position If the agent has not received any WHY request before a specified timeout it will go to the state Query Positions to challenge the positions of other agents
77. assert the argument To make this selection Magentix2 argumentative agents can use different tactics From our point of view a tactic consist on assigning more or less weight to the elements of an argument support factor used to select positions and arguments The support factor estimates how suitable a current position or argument is in view of the suitability of similar arguments to support or attack similar positions or arguments put forward in previous argumentation di alogues which are stored in the agent s case base of argument cases In this way the agent can select the most suitable position or argument to propose next The support factor is computed by a linear combination of several parameters e Persuasiveness Degree PD is a value that represents the expected persuasive power of an argument by checking how persuasive an argument case with the same problem description and conclusion was in the past e Support Degree SD is a value that provides an estimation of the probability that the conclusion of the current argument was acceptable at the end of the dialogue e Risk Degree RD is a value that estimates the risk for an argument to be attacked in view of the attacks received for an argument s with the same problem description and conclusion in the past e Attack degree AD is a value that provides an estimation of the number of attacks received by a similar argument s in the past e Efficiency degree E D
78. ation process a Magentix2 argumentative agent can choose a spe cific locution to put forward and a content for it The mechanism that agents follow to make such decisions is known as dialogue strategy In our case based argumentation framework agents select the best locution to bring up depending on the dialogue protocol that they are following and the content of this locution depending on the knowledge that they have in their knowledge resources and the tactic that they follow to argue A Magentix2 argumentative agent will not initially accept any position from a peer This agent will challenge positions of other peers when they are different from its position even if they appear in its list of potential positions to propose Also it will try to generate an answer for any attack that it receives but opposite to open minded agents argumentative agents do not accept the position of the peer that generated the attack if the last wins the debate If an argumentative agent cannot generate positions it will not participate in the dialogue Finally agents will accept arguments from other agents that have a power or authorisation dependency relation over them 6 Argumentative Agents 55 Depending on its dialogue protocol the agent will choose the next locution to put forward on the dialogue game Then among the potential arguments that the agent may generate it has to select one to propose This implies to select the content of the locution to
79. ble Platform administrators can define the appropiate trace level of the platform Thus platform applications only use the necessary trace support to avoid the application overload Some platform applications may not be interested in any events and in fact trace support is not needed However other domains might need a full trace support Allowed Action A LIFE CUSTOM MSG DTL LIST LIST SUBS ALL 9 91 ENTITIES SERVICES SERVICES 1 0 0 T 0 0 0 al 0 0 Figure 7 1 Trace Support Mask In the trace support it is defined a mask which allows administrators to determinate the types of events supported at the platform by means of a bit position for each type of event Figure 7 1 The meaning of each bit position is are detailed in Tables 7 10 and 7 11 This definition should be incorporated to the settings xml of the platform Thus it could be possible to run the platform without trace support even without an agent TM Notice that the events related with the agents life cycle will be always generated but the mask informs regarding if it is possible for agents to subscribe to these life cycle events or not Moreover it would be possible to start the platform without trace support and then run it launching the agent TM and informing the existing agents about the new event mask This mask is going to be used both by the TM which read it from the settings and the agents 88 7 6 Example TraceDaddy Table 7 10 Event s
80. can play the role president QnoAcRolePresident f agentName acquireRole president fraternity _ roleCardinality president fraternity 1 _ Only the role president can add new norms noRegNorm f lt positionName member gt registerNorm _ fraternity _ _ _ _ Only the role president can delete norms noDelNorm f lt positionName member gt deregisterNorm fraternity _ _ _ _ Only the president can add new roles 112 8 1 Overview of THOMAS framework noRegRole f lt positionName member gt registerRole fraternity _ r r Only the president can delete roles noDeRegRole f positionName member deregisterRole fraternity _ _ It is not allowed registering new roles with the position creator QnoRegRoleCreator f agentName registerRole fraternity _ _ creator Changing the parent unit of the organization is prohibit noJoinUnit f positionName joinUnit fraternity _ _ e Unit panel Only one agent can play the role moderator QnoAcRoleModerator f lt agentName acquireRole moderator panel _ roleCardinality moderator panel 1 _ The agent which plays the role moderator should play the role moderator in the forum unit controlAcRoleModerator f lt agentName _ gt acquireRole moderator panel Ag not playsRole Ag moderator forum Only the
81. d It deal locates all the roles and deregisters all services roles and units To run the example the user has to enter in the Magentix2 examples folder where it has been installed Then the user has to execute the Start ThomasExample sh script with administrator privileges cd Magentix2 examples bin sudo sh Start ThomasExample sh 8 6 Programming agents which use organizational messag ing This section describes how an agent that wants to send a message to an organization can build fill the fields of an ACLMessage and send the organizational message The example shown in 8 Virtual Organizations 135 Figure 8 10 is used to illustrate this section It is formed by the Sender Agent that acquires role member in the unit team and two Receivers Agents with the role member in the unit team The unit virtual is parent of the unit team buildOrganizationalMessage team Request OMS Figure 8 10 Organizational messaging Example diagram 8 6 1 Registration into the organization AcquireRole member team OMSproxy Figure 8 11 Agent interaction protocol to acquire role Agent e Registration in the unit Agents need to be registered into the organizations by means of acquiring some available role before using organizational messaging For example in figure 8 10 an organization called team is shown In this organization the role member 136 8 6 Programming agents which use organizational me
82. d in the dialogue If it can not it does a WITHDRAWDIALOGUE doQueryPositions creates a message to send to the Commitment Store with locution GETALLPOSITIONS to obtain all the positions of the dialogue doSendPosition sends an ACLMessage with the position defended by the agent doSolution actions to perform when the final solution to the current problem to solve arrives in an ACLMessage doWhy choose a position to send a WHY message if it can Table 6 9 Methods to implement in the Argumentation Protocol 6 3 8 Example Call Centre Application To date the system is implemented in the domain of a customer support application where several operators represented by software agents argue to provide the best solution for an in cidence also known as ticket received Thus we use this example domain to show how ArgCAgents can be executed Int the current version of the software the example is imple mented in the Argumentation Example package which includes the java files for creating agents AgentsCreation java the template code of the argumentative agent ArgCAgent java a file to create case bases with data about example domain cases and argument cases CreatePartitions java a test file for executing the example TestArgCAgent java and a file with a template of the tester agent TesterArgCAgent java In this section we 6 Argumentative Agents 73 Operators amp Experts Commitment Store Figure 6 4
83. dAgentName not exists AgentNotInUnitException Not allowed The Agent AgentName is not inside the unit unitName AlreadyRegisteredException All information is already registered in service profile service profile DBConnectionException Cannot connect to DataBase DeletingTableException Deleting value a table tableName Empty ParametersException Invalid Empty parameters ExchangeBindException Exchange bind error e ExchangeUnbindException Exchange unbind error e ForbiddenNormException A norm forbidden the service execution IDUnitTypeNotFoundException Error idunitType idunitType not found in database InsertingTableException Inserting new value at table tableName InvalidAccesibilityException accessibility is not a valid accesibility value InvalidDataTypeException Invalid input or output data type InvalidDeonticException Deontic parameter is not valid The deontic pa rameters allowed are f o and p InvalidExpressionException The input parameters to build a norm are not valid InvalidIDException ID parameter is not valid InvalidOMSActionException The action executed is not a valid OMS action InvalidParametersException The input parameter is not valid InvalidPositionException position is not a valid position value for this Unit type InvalidRolePositionException
84. ddReceiver receiver Sending the message send msg 3 3 Basic conversational agents QueueAgents 3 3 4 Running QueueAgents First it is needed to define a protocol Secondly we have to create a new instance of this protocol and add it to the agent tasks method addTask In the initiator role it is necessary to create and fill in the appropriate message for the desired protocol For example for the protocol request ACLMessage msg new ACLMessage ACLMessage REQUEST msg setReceiver new AgentID HospitalAgent msg setProtocol InteractionProtocol FIPA_REQUEST MSG asceContentCraccidente tom Wt EIS OEC EMITTE msg setSender this getAid this addTask new FIPARequestInitiator this msg For the responder it is needed to create a template with the desired protocol MessageTemplate template new MessageTemplate InteractionProtocol FIPA REQUEST this addTask new FIPARequestResponder this template When a task is added a new thread is created for the agent Therefore it is necessary to be careful which the main thread of the agent is not finished For instance a monitor can be used to wait for the completion of the roles 3 Basic Programming 27 import es upv dsic gti_ia architecture Monitor private Monitor monitor new Monitor protected void execute this addTask new FIPARequestInitiator this msg monitor wai
85. der to create a JasonAgent it is necessary to specify its AgentID the file with the AgentSpeak L program that the interpreter will execute and the agent architecture the agent will use in this case a standard MagentixAgArch Finally you need to start the execution of the agent using the start method To stop an agent just use the Shutdown method It is possible to modify the agent architecture in the following example the MagentixAgArch default architecture will not be used instead a new one is created which extends from Magen tixAgArch public class SimpleArchitecture extends MagentixAgArch this method just adds some perception to the agent Override public List lt Literal gt perceive List lt Literal gt 1 new ArrayList lt Literal gt l add Literal parseLiteral x 10 return 1 This new architecture called SimpleArchitecture just adds a perception to the agent overriding the method perceive of the MagentixAgArch class As said before usually the architecture is modified in order to add new actions to the agent this could be done just overriding the method act ActionExec action List ActionExec feedback ofthe archi tecture This method receives an action as an argument and a list of action executions called feedback In the code below it is shown how to manage a new external action of the agent called doAction Override public void act ActionExec action List lt
86. do Sergio Palanca C mara Javier Palomares Chust Alberto Adri n P rez Pedro Rebollo Pedruelo Miguel Rodrigo Solaz Mario Ruiz Jos Vicente Soler Bayona Jos Terrasa Barrena Andr s Valero Cubas Soledad XI CHAPTER 1 Introduction 11 Motivation 0 cc cee cw eee hm n 1 12 MamualStructure cee eee 2 1 1 Motivation Magentix2 is an agent platform for open Multiagent Systems Its main objective is to bring agent technology to real domains business industry logistics e commerce health care etc Magentix2 platform is proposed as a continuation of the first Magentix platform The final goal is to extend the functionalities of Magentix providing new services and tools to allow the secure and optimized management of open Multiagent Systems Nowadays Magentix2 provides support at three levels e Organization level technologies and techniques related to agent societies e Interaction level technologies and techniques related to communications between agents e Agent level technologies and techniques related to individual agents such as reasoning and learning Thus Magentix2 platform uses technologies with the necessary capacity to cope with the dy namism of the system topology and with flexible interactions which are both natural conse quences of the distributed and autonomous nature of its components In this sense the platform has been extended in order to
87. e informRole RoleName UnitName AgentName informNorm NormName UnitName AgentName acquireRole RoleName UnitName AgentName leaveRole RoleName UnitName AgentName A 2 1 Operators not not q addition amp and em subtraction ada or see multiplication Different cien power d Equal STe division Ma Less div X integer division lt Less or equal mod modular division es Greater gt Greater or equal 162 A 3 Predicates of the forum example A 3 Predicates of the forum example Units descriptions isUnit virtual hasType virtual flat hasParent virtual virtual isUnit forum hasType forum hierarchy hasParent forum virtual isUnit fraternity hasType fraternity team hasParent fraternity forum isUnit panel hasType panel flat hasParent panel forum Roles descriptions isRole participant virtual hasAccessibility participant virtual external hasVisibility participant virtual public hasPosition participant virtual creator isRole moderator forum hasAccessibility moderator forum internal hasVisibility moderator forum private hasPosition moderator forum supervisor isRole participant forum hasAccessibility participant forum internal hasVisibility participant forum public A BNF Syntax of the Normative Language 163 hasPosition participant forum subordina
88. e attributes are position creator accessibility internal visibility private e Reporter It should be played by agents which add news to the panel They are not allowed to add norms roles in the unit Its role attributes are position member accessi bility external visibility private 8 Virtual Organizations 111 e Follower It should be played by agents which read news from the panel They are not allowed to add norms roles in the unit Its role attributes are position member accessibility external visibility public Regarding the forum unit creating new roles with position creator is not allowed Respecting the fraternity unit creating new roles with position creator is prohibited Concerning the panel organization it is prohibited that agents know which roles are played by other agents Also changing the parent unit of the organizations is prohibited Following some of the norms needed to obey the specification of the forum scenario are de scribed using the THOMAS syntax see appendix A section A 3 in order to know for the pred icates the OMS uses for reasoning e Unit forum It is not allowed registering new roles with the position creator noRegRole f lt positionName supervisor gt registerRole _ forum _ _ creator _ _ _ Changing the parent unit of the organization is prohibit noJoinUnit f lt positionName _ gt joinUnit forum iu ys e Unit fraternity Only one agent
89. e tracing service UNPUBLISH ERROR Impossible to unpublish the tracing service SUBSCRIPTION ERROR Impossible to subscribe to the tracing service UNSUBSCRIPTION ERROR Impossible to unsubscribe from the tracing service AUTHORIZATION ERROR Unauthorized to do so Some of the methods available in es upv dsic gti ia trace TraceInteract assume that a default trace manager called TM is running while others allow specifying the Trace Manager to which requests are to be directed Actions related to tracing services can be classified in three main groups which are explained in more detail in the following sections Publication Unpublication of tracing services Sec tion 7 3 1 subscription unsubscription to from tracing services Section 7 3 2 and listing of tracing entities or services Section 7 3 3 80 7 3 Tracing Services 7 3 1 Tracing service publication In order to publish and unpublish tracing services agents have to use respectively the meth ods publishTracingService and unpublishTracingService These methods are de scribed in more detail in Table 7 3 Table 7 3 Tracing service publication and unpublication methods publishTracingService BaseAgent applicantAgent String serviceName String description publishTracingService AgentID tms_aid BaseAgent applicantAgent String serviceName String description unpublishTracingService BaseAgent
90. e update algorithm updates those cases with the new data acquired Otherwise new argument cases are created and added to the case base The main methods of the Argumentation CBR are shown in Table 6 7 for a detailed explanation of all Argumentation CBR methods see the ArgCBR java associated JavaDoc The contents of the case bases of the Domain CBR and the Argumentation CBR can be stored as java serialised objects In this way we provide a quick and simple data persistence mecha nism Thus both DomainCBR java and ArgCBR java classes include different methods to load and save information about cases from to data files see Table 6 8 The main functionalities of the argumentative agents generation selection and evaluation of positions and arguments are specified as methods to facilitate a better understanding of the code and to facilitate modifications and updates The main method of the argumenta tive agents is the execution method This method overwrites the execution method of 6 Argumentative Agents 71 Method Parameters Description addCase argument case Adds a new argument case to the case base Two cases are considered equal if they have the same domain context social context conclusion and status of acceptability getDegrees argumentProblem Return a list with the degrees at solution allPosi tack efficiency explanatory power tions index persuasiveness support and risk of an argument case get
91. eExistsInUnitException UnitNotExistsException NotValidIdentifierException EmptyParametersException DeregisterRole Description Removes a specific role from a unit Inputs RoleName Identifier of the role UnitName Identifier of the unit Outputs RoleName deleted Exceptions ForbiddenNormException NotSupervisorOrCreator InUnitException NotMemberOrCreatorInUnitEx ception InvalidUnitTypeException NotInUnitAnd NotCreatorException AgentNotInUnitException RoleInUseException RoleContainsNormsException RoleNotExistsException UnitNotExistsException EmptyParametersException RegisterUnit Description Creates a new unit within a specific organization Inputs UnitName Identifier of the new unit 116 8 2 Programming agents which use THOMAS Type flat teamor hierarchy ParentUnitName Identifier of the parent unit Creator The name of the new creator role Outputs UnitName created Exceptions ParentUnitNotExistsException ForbiddenNormExcep tion NotCreatorInParentUnitException UnitExistsEx ception NotValidIdentifierException EmptyParame tersException Description Removes a unit from an organization Inputs UnitName Identifier of the unit DeregisterUnit Outputs UnitName deleted Exceptions NotCreatorAgentInUnitException SubunitsInUnitEx ception Forbidden
92. eMethod public String run CProcessor myProcessor ACLMessage messageToSend messageToSend setContent Would you like to come with me to Phere Memarcns E messageToSend setReceiver new AgentID Sally messageToSend setSender myProcessor getMyAgent getAid return WAIT PROPOSE setMethod new PROPOSE Method talk cProcessorTemplate registerStat ROPOSE E P talk cProcessorTemplate addTransition BEGIN PROPOSI talk cProcessorTemplate registerState new WaitState WAIT 1000 E addTransition PROPOSE WAIT talk cProcessorTemplat ReceiveState RECEIVE new ReceiveState RECEIVE class RECEIVE Method implements ReceiveStateMethod public String run CProcessor myProcessor ACLMessage messageReceived return FINAL RECEIVE setAcceptFilter null null gt accept any message RECEIVE setMethod new RECEIVE Method RECEIVE talk cProcessorTemplate registerStat talk cProcessorTemplate addTransition WAIT RECEIVE 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 4 Advanced conversational agents CAgents 39 FinalState FINAL new FinalState FINAL class FINAL Method implemen
93. ease refer to the folder examples httpinterface of your Magentix2 distribution The example is composed by two parts e example html This web page contains a form The user specifies a type of product and a maximum prize The user will get a product that satisfies her specifications http en wikipedia org wiki Universally unique identifier 9 HTTP Interface 145 e MarketAgent This agent receives the request from the web page example html and re turns an appropriate product The example html webpage uses several javascript libraries in order to send the HTTP POST request asynchronously These libraries are included in the head section of the html code The html file also uses our javascript library Magentix2 js When the user submits the form the javascript function transformData is called function transformData var pp f1 serializeArray var data createJSONOb ject MarketAgent pp requestAppData data This function takes every input of the form and constructs an associative array with them Then it calls to the function createJSONObject of the Magentix2 js library The parameters are MarketA gent the name of our agent and the array with the content of the form The resulting JSON object will be something like this agent_name MarketAgent conversation_id 5ala2c78 91b2 465c SS ASS adis COME entes te Cs RESI CC A o EUA Finally the transformData calls the function req
94. eator and Manager All agents begin its execution in the scenario 2 The Creator and Noisy agents try to build an organizational message but their requests are rejected The Creator agent can not send an organizational message because it only plays the Creator role with creator position within Calculator organization In the same way the Noisy agent can not send an organizational message because it doesn t belong to Calculator organization 8 Virtual Organizations 139 DeallocateRole DeregisterRole 1 RegisterUnit 9 Deregister External DeallocateRol RegisterRoles DeregisterRoles OMS Figure 8 12 Organizational Message Example diagram 3 The Summation agent sends Formula 6 3 as an organizational message This is received by the Product Addition and Display agents The Display agent prints this message to standard output 4 The agents that play the Operator role Addition and Product agents receive the numbers six and three to calculate their calculations 6 3 9 and 6 x 3 18 respectively and communicate the results as an organizational messages These are received by the Summation agent The Addition agent leaves the Operator role 5 The Summation agent sends the sum of all results received 9 18 27 as an organiza tional message This is received by the Display agent which prints this value to standard output 6 The Summation agent sends Formula 5 3 as an organizational message
95. ee a eb ed ee en OMS Proxy Structural services API o ooo OMS Proxy Informative services API o ooo OMS Proxy Dynamic services API 0 oo o OMS Proxy Organizational messaging service API SESPrOXY ABT 2 6 Seti war bat ia ee Sa hk of Gr BA EAR Gr kA B 1 Trace Exceptions and associated messages B 2 THOMAS Exceptions and associated messages VIII Acknowledgments Financial support from the Ministerio de Ciencia e Innovaci n of the Spanish Government under TIN2008 04446 project and under Consolider Ingenio CSD2007 00022 grant is kindly acknowledged IX Contributors Sorted alphabetically Alemany Bordera Jos Argente Villaplana Estefania Bellver Faus Joan Botti Navarro Vicente J B rdalo Rapa Luis Antonio Carrascosa Casamayor Carlos Criado Pacheco Natalia De la Fuente Anuarbe Miguel angel Del Val Noguera Elena Espacia Garcia Sergio Espinosa Minguet Agustin Fernandez David Garcia Fornes Ana Garcia Marques Maria Emilia Garcia Pardo Gim nez de los Galanes Juan Angel Giret Boggino Adriana Her ndez L pez Luis Heras Barber Stella Mar a Jordan Prunera Jaume Magi Jorge Cano Javier Juli n Inglada Vicente L pez Fogu s Ricard Mejias Rodr guez Jos Manuel Miguel Alberola Juan Miguel Such Jos Mulet Mengual Luis Navarro Ll cer Mart Pajares Ferran
96. en the requester agent has to execute the service by itself To perform this task the class ServiceTools of the package es upv dsic gti ia organization provides the method executeWebService to facilitate the execution of web services to the developers This method receives as parameters the url of the service WSDL document to execute it and the inputs of the service The inputs can be specified in two ways in a HashMap giving the name of the input and its value or with an XML string in the following form 1 inputs 2 lt inputX gt valueX lt inputX gt 3 lt inputY gt valueY lt inputY gt 4 lt inputs gt In the following example the requester agent tries to make a request of the found service to the agent or organization providers if there are providers list lines 28 51 If there are not agent or organization providers providers list is empty then it tries to obtain the Web Services groundings WSDL documents that provide the service providersGrounding WSDL list lines 52 60 In this case the requester agent has to execute the service by itself using the ServiceTools class provided by THOMAS Requesting the execution of the Addition service get the first service found because it is the most suitable String serviceOWLS sfProxy getService foundServices get 0 get 0 r Oracle oracle new Oracle serviceOWLS get service inputs ArrayList lt String gt servicelnputs oracle getOwlsProfileInputs
97. entation scheme consists of a set of premises and a conclusion that is presumed to follow from them Also each argumentation scheme has associated a set of critical questions that represent potential attacks to the conclusion supported by the scheme A case base with domain cases that represent previous problems and their solutions Agents can use this knowledge resource to generate their positions in a dialogue and arguments to support them The position of an agent represents the solution that this agent proposes Also the acquisition of new domain cases increases the knowledge of agents about the domain under discussion A case base with argument cases that store previous argumentation experiences and their fi nal outcome Argument cases have three main objectives they can be used by agents 1 to generate new arguments 2 to select the best position to put forward in view of past argumentation experiences and 3 to store the new argumentation knowledge gained in each agreement process improving the agents argumentation skills Argumentation Schemes The concrete set of argumentation schemes used also depends on the application domain of our argumentation framework The Magentix2 argumentation API only provides a ba sic template for them with the common components of Walton s like argumentation schemes Walton et al 2008 A user that wants to use this knowledge resource must overwrite the ArgumentationScheme java class of the M
98. er java at that moment As it can be seen in the figure the code of the agent has an error because it lacks a constructor So a basic constructor which calls the constructor of the base class is created A Magentix2 agent has three main methods init execute and finalize They are executed in the cited order In the method init the code that has to be executed at the 10 2 2 Developing and executing a first agent Cv B i Gy 8 oe or Package Explorer 3 SER SM Y i MyFirstAgent a gt Y Bsre ent All gt Activate gt B JRE System Library JavaSE 1 6 amp Uncategorized Y wi Referenced Libraries 3 magentix2 2 01 jar with dependencies zip F Y configuration gt clientrepo fii loggin xml fi policy xml B securityUser properties l Settings xml connect Mylyn Connect to your task and ALM tools BE Outline 51 n An outline is not available El Problems 2 Javadoc 8 Declaration 7B items Description Resource Path Location Type n agent MyFirstAgent src Figure 2 1 Project and package creation ri 6 6 X a Ov Q E Gy OG 4 PIB a m fv ji er 5 Pava Hf Package Explorer t Bi sn D Main java BB Task List 3 TB Y i MyFirstAgent package agent Or ie gt vigore import es upv dsic gti ia core ACLMessage alc ELE Y di agent import es upv dsic gti ia core AgentID ud gt Bl Consumer java import es upv dsic gti ia core BaseAgent Uncategorized gt D Mainjava c
99. eregisterNorm Panel No one can add roles x isNorm noRegRole panel hasDeontic noRegRole panel f hasTarget noRegRole panel positionName hasAction noRegRole panel registerRole isNorm noDeRegNormRegRole panel hasDeontic noDeRegNormRegRole panel f hasTarget noDeRegNormRegRole panel roleName moderator hasAction noDeRegNormRegRole panel registerNorm xPanel No one can delete roles x isNorm noDeRegRole panel hasDeontic noDeRegRole panel f hasTarget noDeRegRole panel positionName _ hasAction noDeRegRole panel deregisterRole isNorm noDeRegNormDeregRole panel hasDeontic noDeRegNormDeregRole panel f hasTarget noDeRegNormDeregRole panel roleName moderator hasAction noDeRegNormDeregRole panel registerNorm Panel Knowing which roles are played by other agents is prohibit x 168 A 3 Predicates of the forum example isNorm noSupInfAgRole panel hasDeontic noSupInfAgRole panel f hasTarget noSupInfAgRole panel agentName Ag hasAction noSupInfAgRole panel informAgentRole isNorm noDeRegNormNoSupInfAgRole panel hasDeontic noDeRegNormNoSupInfAgRole panel f hasTarget noDeRegNormNoSupInfAgRole panel roleName moderator hasAction noDeRegNormNoSupInfAgRole panel registerNorm xPanel Changing the parent unit of the organization is prohibit x isNorm noJoinUnit Panel hasDe
100. ersion Thus any agent in the system can request trace events from any other agent without needing any direct or indirect authorization 7 Tracing Service 77 7 2 Trace Event Trace events are represented in the platform as instances of the class es upv dsic gti_ia core TraceEvent public class TraceEvent implements Serializable private String tService private long timestamp private TracingEntity originEntity private String content The different attributes of this class indentify the tracing service to which the trace event be longs the tracing entity which originated the trace event and the time at which it was produced expressed as the amount of milliseconds from 1 Jan 1970 at 00 00 00 Epoch This informa tion can be complemented when needed with extra data stored in the content attribute Trace event instances are created by invoking the constructor of the class Details of the param eters are explained in Table 7 1 As it can be seen the timestamp attribute of the trace event is not stablished by any parameter of the constructor This is because the timestamp of each trace event is internally set to the time at which the constructor of the class was invoked Table 7 1 TraceEvent class constructor parameters TraceEvent String tService AgentID originAid String content tService String identifying the tracing service to which the trace event is associ ated t
101. ervice is provided by agents or and organizations If there is one or more groundings it means that the service is provided by a web service The Register Service returns a response describing if the service has been entirely registered or the number of providers and groundings added to an already registered service profile In all cases 1t returns a description of what is registered or not and an OWL S specification of the registered services or all data of the already registered service An agent can register 1ts own implementation of an existing profile or create a new service from the scratch In all cases the OWL S specification must have the profile and the process and the Register Service will detect if the profile is already registered In this case the providers agents organizations or groundings web services of the new specification will be added to the registered service in the SF database 124 8 3 Programming Agents that Offer Services 8 2 1 4 Oracle extracting information from OWL S The Oracle is a class that allows developers to parse the profile of a semantic service spec ified in OWL S in order to extract the required information such as service inputs outputs providers list of roles or organizational units Oracle needs just the OWL S string containing the service specification to analyze it as a parameter in the constructor of the class see the example This specification can be obtained with
102. es 17 21 Afterwards a CFactory from the template is created line 29 During the creation it is required to specify the name of the new CFactory the request message the agent owner of the CFactory and the time in milliseconds that the agent will wait for the inform or failure message Once the CFactory template is defined it is possible to create a new instance from it 20 21 22 23 24 25 26 27 28 29 30 31 32 33 4 Advanced conversational agents CAgents 41 Finally the just created CFactory is added to the agent line 30 and in the last line of the code a synchronous conversation from this CFactory is started In this example the agent is going to act as the initiator in the REQUEST protocol defined by FIPA In order to do so she has to extend the class FIPA_REQUEST_Initiator implementing the method that receives results of the request dolnform class myFIPA REQUEST extends FIPA REQUEST Initiator protected void doInform CProcessor myProcessor ACLMessage msg I System out println myProcessor getMyAgent getName msg getSender name informs me msg getContent We create the message that will be sent in the doRequest method of the conversation msg new ACLMessage ACLMessage REQUEST msg setReceiver new AgentID Sally msg setContent May you give me yo
103. es upv dsic gti ia core AgentID import es upv dsic gti ia core BaseAgent public class Boy extends BaseAgent private int age private boolean finish false AgentID dad 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 7 Tracing Service 93 public Boy AgentID aid int age AgentID dad throws Exception super aid this age age this dad dad SASS O UA rl A A SS EN aMSN A selgatisio getName and I m this age years old public void execute ACLMessage msg int counter 5 while finish if this age lt 5 msg new ACLMessage ACLMessage REQUEST msg setSender this getAid Set Cero tate 528 OE msg setContent Give me your toy else msg setContent GUAAAAAA cotos ay msg setReceiver new AgentID qpid Timmy localhost SUSO send msg AE Thread sleep 1000 catch InterruptedException e e printStackTrace public void onMessage ACLMessage msg if msg getSender getLocalName contentEquals dad getLocalName Daddy 48 49 50 51 52 53 54 29 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 94 if msg getPerformativeInt uf elsel msg gertCcontent content finish true
104. ese trace events 7 1 1 Supported Features The present version of Magentix2 does not support all of the tracing features considered in the model However those which are not yet supported will be incorporated in future versions of the platform e Tracing Entities Although the model considers not only agents but also non agent entities or aggrega tions event tracing facilities incorporated to the present version of Magentix2 platform only consider agents Artifacts and aggregations will be included in future versions of the platform Publication and Subscription Publication and unpublication of trace events is completely supported in the present ver sion of the platform so tracing entities can dynamically at run time publish the event types which they can throw and unpublish them when they do not want to share that information anymore In the same way tracing entities can dynamically subscribe to trace events in which they are interested and unsubscribe from them whenever they do not want to receive these trace events anymore However although the model lets tracing entities filtering trace events according to many parameters the present version of Magentix2 only allows agents to filter trace events according to the event type and the agent which threw the event Authorization Security issues addressed by the model have also been postponed for future versions of the platform and they are not considered in this v
105. framework in MySQL by means of the the execution of the script magentix setup py This script is located in the main directory of the Magentix2 installation folder The commands needed to execute this script are the following from the Magentix2 root directory python magentix setup py However it is also possible to create the THOMAS database infrastructure step by step without using the cited script In this case it is necessary to load into MySQL the complete structure of the database from the db schema sgl and grants sql files These files are located into the directory bin sql In order to load these files the MySQL Administrator tool should be opened and then the Restore Backup option must be selected choosing the db schema sql backup file to be restored An example of this procedure can be shown in the figure 10 2 150 10 2 Advanced MySQL File Edit View Tools MySQL Enterprise Help Ef server Information o Service Control XI Startup Parameters 88 User Administration amp Server Connections Catalogs Backup File to Restore 4 thomas home joabelfa workspace j THOMASMAGENTIX2 thoma Change Path Replication not enabled Figure 10 2 Restoring the db schema sql backup file in the Restore Backup option of the MySQL Administrator The next required step is to add a new user to the THOMAS schema in the User Administration option of the MySQL Administrator tool see Figure 10 3 The required fie
106. gServices respectively These 82 7 3 Tracing Services Table 7 4 Tracing service subscription and unsubscription methods requestTracingService BaseAgent requesterAgent String serviceName AgentID originEntity requestTracingService AgentID tms_aid BaseAgent requesterAgent String serviceName AgentID originEntity requestTracingService 1 serviceName BaseAgent requesterAgent String requestTracingService AgentID tms_aid BaseAgent requesterAgent String serviceName requestAllTracingServices BaseAgent requesterAgent requestAllTracingServices AgentID tms aid BaseAgent requesterAgent cancelTracingServiceSubscription BaseAgent requesterAgent String serviceName AgentID originEntity cancelTracingServiceSubscription AgentID tms aid requesterAgent BaseAgent String serviceName AgentID originEntity cancelTracingServiceSubscription BaseAgent requesterAgent String serviceName cancelTracingServiceSubscription AgentID tms aid BaseAgent requesterAgent String serviceName tms aid Agent ID of the Trace Manager which will process the request If not specified the request is directed to the default Trace Manager TM requesterAgent Agent which is subscribing unsubscribing to the tracing service serviceName String identifying the tracing service to which the
107. ges A successful service execution has some effects on its environment This parameters are called IOPE in put output preconditions effects Moreover there could be additional parameters which are independent of the service functionality non functional parameters such as quality of service deadlines and security protocols among others A service represents an interaction between two entities which are modelled as communica tions among independent processes In our case the Multi agent Technology provides us with FIPA communication protocols Taking into account that we are dealing with semantic services another important data is the ontology used in the service When the service description is accessed any entity has all the needed information available to interact with the service Services registered and discovered by SF in THOMAS are demanded or offered by some agent or organization Figure 8 1 Demanded services are services which are wished by autonomous entities but no agent or organization provides them Offered services are provided and regis tered in the THOMAS environment by agents or organizations The final execution of this services will be finally made by a web service an internal behavior of an agent or an agent internal call to a web service The set of services provided by the SF to manage the services of the platform meta services are classified in 3 categories these services are described in more deta
108. he SFProxy 122 Agent interaction protocol to register a service o a 125 Agent interaction protocol to register new providers 126 Agent interaction protocol to search Service o a 127 Agent interaction protocol to request a service o a 131 Thomas Example diagram ee 133 Organizational messaging Example diagram ss 135 Agent interaction protocol to acquire role a 135 Organizational Message Example diagram o o 139 HTTP Interface framewok o ee 142 10 1 10 2 10 3 10 4 10 5 Installing libboost iostreams 1 35 dev library with Synaptic tool 148 Restoring the db schema sql backup file in the Restore Backup option of the MySQL Administrator a 6 E aa e ees 150 Adding the necessary user information into the THOMAS schema in the User Administrator option of the MySQL Administrator tool 151 Assigning privileges to the thomas user in the User Administration option of the MySQL Administration tool 22e 152 Location of web services files war ln 154 VI List of Tables 6 1 6 2 6 3 6 4 6 5 6 6 6 7 6 8 6 9 7 1 7 2 7 3 7 4 7 5 7 6 17 7 8 7 9 7 10 7 11 8 1 8 2 8 3 8 4 8 5 8 6 8 7 8 8 8 9 ArgCAgent java methods to manage positions and arguments Methods to compute the distance and similarity between cases
109. he outside world an HTTP interface service has been developed The service is automatically started when the StartMa gentix sh script is executed so no special action is required A common use for the HTTP Interface service is a webpage that allows its users to monitor and interact with the agents run ning in Magentix2 The examples in this section show how to interact with Magentix2 agents using a web page and using Javascript and PHP However the use of the HTTP interface is not exclusive for web pages and can be used in other scenarios 9 1 Framework The functionality of the HTTP Interface service is quite simple It listens to the port 8081 and expects to get an HTTP POST request The HTTP interface extracts the target agent from the HTTP POST body message and sends that body message as the content of an ACLMessage to the target agent The information that the HTTP POST request contains must be a well formed JSON object Besides the JSON object has to obbey to the following guideline Inttp en wikipedia org wiki JSON 141 142 9 1 Framework Web Server HTTP Post JSON HTTP Post JSON HTTP Response Web Application HTTPInterface Magentix 2 Figure 9 1 HTTP Interface framewok The JSON object must contain a field called agent_name The content of this field is the name of the target agent that will receive the content of the HTTP request The object must contain a field called conversat
110. hese events are later processed in the event handler in line number 67 More details on these tracing services and on how to understand the information provided by these trace events are available in Table 7 7 7 4 3 Messaging related domain independent tracing services These domain independent tracing services provide information related to message based agent communication These tracing services are also requestable and thus it is also necessary to sub scribe to them before receiving any trace event they may provide An example of use of these tracing services can be observed in Section 7 6 1 in line number 68 where the daddy agent requests a tracing service called MESSAGE SENT DETAIL in order to inspect every message that his boy agents Bobby or Timmy send More details on these tracing services and on how to understand the information provided by these trace events are available in Table 7 8 7 Tracing Service 85 Table 7 6 System related domain independent tracing services TRACE ERROR Generic non determined error in the tracing process tService TRACE ERROR 0 originEntity system host content Human readable error description SUBSCRIBE The tracing entity requested a tracing service with name tServiceName to an ES entity ESid which can be any to express interest in trace events of that tracing service coming from any of ES entities From that time trace
111. his case the proponent agent will move back to the state Wait Attack to wait for the response of the opponent agent However if the proponent agent is not able to counter attack it must move back to the state Propose with the locution VOCOMMIT to withdraw its position from the dialogue and if possible propose another generated position Query Positions in this state the agent that has decided to challenge the positions of other agents requests the commitment store the list of current positions proposed in the dialogue with the locution GETALLPOSITIONS 6 Argumentative Agents 65 10 11 12 13 14 15 Get Positions the agent that has requested the commitment store for active positions in the dialogue moves to this state to wait for an answer Here the agent can receive the list of positions with the same locution GETALLPOSITIONS Alternatively the agent can receive a FINISHDIALOGUE locution in this state and it will go to the state Send Position to start the actions to leave the dialogue when it has proposed yet a position Also if the agent does not receive any response before a specified timeout it will move back again to the state Central Why in this state the agent that has received a list of potential positions to challenge makes a random choice to challenge one of them with the locution WHY from these positions that are different to its own Otherwise if there are no positions to challenge
112. ication Status Additional Information L Catalogs Full Name The user s full name User Accounts ote v XS p Description Additional description of the user debian sys maint Email The user s email address 3 root Contact Information Optional messager information amp thomas tel fax ICQ etc 20 Icon Icon assigned to the user Change b New User S Discard Changes Apply Changes Processing backup file Figure 10 3 Adding the necessary user information into the THOMAS schema in the User Administrator option of the MySQL Administrator tool scription of the services In order to specify the required parameters for Jena the Settings xml file located in the configuration directory will be configured The parameters that affect Jena configuration in the Settings xml file are the following Properties jena gt entry key dbType gt MySOL lt entry gt entry key dbURL gt jdbc mysql localhost thomas lt entry gt entry key dbDriver gt com mysql jdbc Driver lt entry gt Check if the direction where agents OMS and SF are running is different host from where the MySQL is configured with the data base schema employed by the THOMAS framework If the OMS and SF are running in the same host the configuration by default is correctly Finally all available privileges for THOMAS tables must be assigned to the thomas user Figure 10 4 152 File Edit View Tools MySQL
113. ies can be more or less suitable depending on the other agents that participate in the dialogue the tactics that they follow and their available knowledge resources 6 Argumentative Agents 57 6 2 Argumentation API In this section we define the different modules that implement the argumentation API of the Magentix2 platform and their functionality For a tutorial on how to use these modules for programming argumentative agents see Section 6 3 e Domain CBR module consists of a CBR module with domain dependent data previ ous problem solving experiences stored in the form of domain cases This CBR has to be initialised with data of the application domain e Argumentation CBR module consists of a CBR module with argumentation data pre vious arguments stored in the form of argument cases Once an agent has a list of po tential solutions for a current problem it has to select the best position to put forward among them Also the agent can generate arguments to support its position and attack another agent s arguments and positions Then this module is used to look for previ ous argumentation experiences and use this knowledge to select the best positions and arguments to propose e Argumentative agent is an agent with a Domain CBR and an Argumentation CBR able to engage in an argumentation dialogue to solve a problem This agent learns about the domain problem and the argumentation dialogue adding and updating cases into the
114. il at Table 8 9 e Registration they allow adding and removing services from the SF directory e Affordability they allow managing the association between providers and their ser vices 106 8 1 Overview of THOMAS framework Type Offered by Implementation E r EC Agent Behaviour Offered Figure 8 1 Handled Services demanded and implementations of offered services supported e Discovery services in charge of searching and composing services as an answer to user requirements 8 1 4 Organization Manager Service This component is in charge of organizations life cycle management including specification and administration of their structural components roles organizative and units and their ex ecution components participant agents and the roles they play and active units in each mo ment The OMS provides agents with a set of services for organization life cycle management Val et al 2009 classified in e Structural services which modify the structural organization specification i e roles organizational units and norms see Table 8 5 e Informative services that give information of the current state of the organization see Table 8 6 e Dynamic services that allow managing role enactment and dynamic entry exit of agents see Table 8 7 8 Virtual Organizations 107 These services are published in the SF and also available thought the OMSproxy class see section 8 2 8 1 5 Normative
115. imestamp Time at which the trace event was generated The time is expresed in milliseconds from 1 Jan 1970 at 00 00 00 Epoch originAid Agent ID of the agent which originated the trace event Internally the constructor converts originAidtoa TracingEntity content Any extra data which could be necessary to complement or understand the meaning of the trace event This attribute can be empty Once created trace events can be sent by means of the public method sendTraceEvent TraceEvent tEvent included in the class es upv dsic gti ia core BaseAgent This method does not create the instance of the trace event and thus it is necessary to invoke the TraceEvent constructor before sending it For instance if an agent wants to create a trace event for a service called SIMPLE SERVICE it could be made in this way 1 78 7 3 Tracing Services Creation of the trace event x TraceEvent tEvent new TraceEvent SIMPLE SERVICE this getAid This is a simple trace event provided by a simple tracing SeTmsite cti Sending the event x send tEvent The class es upv dsic gti ia core BaseAgent includes a trace event handler method similar to the ACL message handler onTraceEvent TraceEvent tEvent This method executes automatically each time a trace event is received by the agent however it is empty This means tha
116. in this case 1000ms It is possible to define a wait state that will wait an unlimited amount of time until a message is received if the timeout is set to 0 A transition from PROPOSE state to this wait state is added After a wait state it is mandatory to define one or more receive states In this example it is only defined one receive state A receive state needs a method to execute and a message filter This filter specifies which messages can be managed by this receive state In this example the filter is set to null therefore this receive state accepts any message The code defining the receive state named RECEIVE starts at line 34 Finally it is defined the final state of the protocol at line 46 Every protocol has to finish in a final state Final states methods can use the responseMessage variable passed as argument as a mean to return a value of the conversation Once the method that will be executed by this state is defined the transitions from other states to this one are added and the state registered in the CProcessor There is only one thing left to finish the CAgent it is necessary to add the CFactory to the set of CFactories of the agent It is possible to add a CFactory as an initiator one or as a pariticipant one depending on the role the agents will play on the conversations generated by the CFactory In this case the CFactory is added as an initiator one Once the CFactory has been added it can create new CProces
117. ing a CFactory and its CProcessor template can be a laborious task In order to facilitate this a set of CFactories templates are provided in Magentix2 At the moment the templates are e FIPA Request e FIPA Contract net e FIPA Recruiting All of this templates are available in both versions initiator and participant The source code of the examples shown in this sections are accessible at the folder examples s rc requestFactory A CFactory template is a java class that has already defined the states and the transitions of the CProcessor template A template can be modified in order to adapt it to any specification Some templates have abstract methods that are necessary to implement by the users Others methods offer a default behaviour that can be modified if needed As an example it is shown how to adapt the FIPA Request Initiator template provided in Magentix2 to a scenario where one agent Harry asks another agent Sally for her phone number In this case it is necessary to create a new class that extends the template FIPA REQUEST Ini tiator lines 6 12 This class has an abstract method that is mandatory to implement the doInform method lines 7 11 This method is executed when the initiator receives the results of what it requested All the other methods for the other states have a default behaviour that can be modified in this example it is not necessary to do so The message that contains the request is created lin
118. ing all the messages sent by Magentix2 agents in which the recipient are agents running on another platform that uses http as communication protocol Then the BridgeAgentInOut encapsulates the entire message and sends it via http BridgeAgentOutIn the implementation of this agent can be found in the es upv dsic gti ia core BridgeAgentOutIn class The BridgeAgentOutIn routes messages from external agents received via http to Magentix2 agents Therefore BridgeAgentOutIn decodes the http message received and creates an ACLMessage mes sage After that BridgeAgentOutIn sends the new created message to the recipient s mailbox Notice that the BridgeAgentInOut and the BridgeAgentOutIn agents must be launched and in stantiated to allow external communication This is made together with the rest of platform services and platforms agents by means of the Start Magentix sh command explained in sec tion 2 1 3 Thus the BridgeAgentInOut and the BridgeAgentOutIn agents would be launched at localhost and the agent BridgeAgentOutIn will be listening in the 8081 port For other configurations please refer to section 10 4 1 Inside Magentix2 external agents are identified to send messages to them by means of an http address that must be used when creating the corresponding AgentID For instance the fol lowing example shows the code which could be added into the execute method of a Magentix2 agent to send a Request message to another age
119. ion These tracing services are included in the class es upv dsic gti ia coreTracingService 84 7 4 Domain Independent Tracing Services 7 4 4 System domain independent tracing services System domain independent tracing services provide information which may be necessary for any tracing entity in order to understand the sequence of trace events which it has received These tracing services are not requestable and thus trace events are received by tracing entities as they excute without having previously subscribed to them For instance if a tracing service were not available anymore all those agents which had previously requested it would receive an UNAVAILABLE TS trace event so that these agents know that the service is not being offered anymore Details on system domain independent tracing services and on the information which their events provide are detailed in Table 7 6 7 4 2 Agents lifecycle domain independent tracing services These domain independent tracing services provide tracing information related to agents en tering or leaving the system These tracing services are requestable and thus it is necessary to subscribe to them before receiving any trace event they may provide An example of use of these tracing services can be observed in Section 7 6 1 in line number 20 The daddy agent requests the tracing service NEW AGENT in order to receive a trace event each time a new agent enters the system T
120. ion as we can see in this code example 126 8 4 Programming Agents that Request Services 2 ArrayList lt String gt resultRegister sfProxy registerService http localhost 8080 testSFservices testSFservices owl owls Addition owl e Registering new providers When a service is already registered it is possible to add new providers agents organizations or web services The RegisterService of the SF detects automatically if the profile of the given OWL S specification is already regis tered in the SF and just adds the new providers to the SF database The given OWL S specification must have the same profile so the SF recognize that is the same service and it associates the new providers to the registered service see Figure 8 6 RegisterService http url service2 owl 0 groundings and 2 providers registered to service profile Agent http url service2 owls ServiceProfile Figure 8 6 Agent interaction protocol to register new providers 8 3 2 Provide services In THOMAS there are different ways of providing a service as represented in Figure 8 1 On the one hand in the cases that the providers are registered in the SF as agents or organizations the requests to that services will be sent to the corresponding agent or organization as specified in the OWL S registered in the SF The agents or organizations can execute their service as an internal behaviour or as a web service but this is not visible to the
121. ion_id The content of this field should be a unique identifier This identifier will be used in the messages sent between the HTTP interface service and the target agent The object must also contain a field called content The content of this field is the information that the target agent will manage When the HTTP Interface gets the HTTP POST request it reads the JSON object included in the message body of the HTTP POST request The HTTP Interface extracts from the JSON ob ject the field agent_name The content of this field specifies the target agent The content of the field conversation_id of the JSON object will be used as the conversation_id of the ACLMessage that will be sent to the target message Finally the entire JSON is used as the content of the ACLMessage Please note that the entire JSON is used as content therefore the target agent has to be capable to deal with the fields agent name and conversation id Magentix2 includes the XStream library which is able to manage JSON objects in java For more information about XStream and JSON please go to http xstream codehaus org json tutorial html For better understanding an example of a valid JSON obect is given below In this example a web page allows users to ask for supermarket products to an agent The user has to specify the type of the product and the maximum price she is willing to pay 9 HTTP Interface 143 ina Gentian ame ce MC INE ON VS Sasso mech MEX GI
122. ist the roles and units in which an agent is in a specific InformAgentRole ae Inputs RequestedAgentName Identifier of the agent re quested Outputs lt RoleName UnitName gt Exceptions AgentNotExistsException ForbiddenNormException EmptyParametersException Description Indicates entities that are members of a specific unit Optionally it is possible to specify a role and position of this unit so then only members playing this role or InformMembers position are detailed Inputs UnitName Identifier of the unit RoleName Identifier of the role Position member supervisor or subordinate Outputs AgentName RoleName gt Exceptions RoleNotExistsException InvalidRolePositionExcep tion ForbiddenNormException AgentNotExistsEx ception UnitNotExistsException EmptyParameter sException Description Provides the number of current members of a specific unit Optionally if a role and position is indicated then InformQuantity only the quantity of members playing this roles or posi Members tion is detailed Inputs UnitName Identifier of the unit RoleName Identifier of the role Position member supervisor or subordinate Outputs Integer Exceptions RoleNotExistsException InvalidRolePositionExcep tion ForbiddenNormException AgentNotExistsEx ception UnitNotExistsException EmptyParameter sException Description Provides the content of the norm InformNorm 8 Virtual Organizations 119
123. its execution BOYS Bobby and Timmy Bobby which is only 5 sends each second an ACL request message to Timmy which is 7 to request him his toy Give me your toy After 5 denials Bobby starts requesting it by crying sending an ACL message with a loud GUAAAAAA Both Boy agents reply NO to any request which does not come from their father and only AGREE when their dad requests them to GO TO THE PARK When dad requests them via an ACL message to go to the park both sons agree and end their execution 7 6 1 Daddy class package TraceDaddy import java text DateFormat import java text SimpleDateFormat import java util Calendar 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 4l 42 43 44 90 im im im im im postees postes pommes port es po ues private boolean private boolean private boolean UTD JUI VS upv upv upv blic class Daddy onc ale abel ojal Aber Seat aiaks Sieal abere Choa listo 7 6 Example TraceDaddy core ACLMessage ECOLCPAGSM ETD core BaseAgent core TraceEvent trace ira ce mbei c extends BaseAgent finish false Bobby_agree false Timmy_agree false public Daddy AgentID aid throws Exception super aid raceInteract requestTracingService this NEW AGENT System out println Daddy this getName I want
124. its own IPs The begin state of the CProcessor template is defined by default It starts creating a new IP modifying this predefined begin state In line 8 this begin state is got from the template In the lines below a new method for this state is cre ated This method will be executed when the conversation reaches this begin state Therefore this method will be executed when the conversation starts Every method in a conversation state has to return the name of the state the CProcessor will travel to In this examples the begin state always travels to the state called PROPOSE In line 16 the method just defined is associated to the begin state Starting at line 18 a new send state is defined called PROPOSE Once the state is created it is necessary to define a method for this state A method for a send state has to return the name of the next state and also has to assign a value to the variable messageToSend which is passed to the method as an argument As can be seen the message is going to be sent to agent Sally and the objective of the message is to propose Sally to go to the cinema Once the state PROPOSE has been created registered and all the transitions to it have been 4 Advanced conversational agents CAgents 37 added In line 31 a new wait state called WAIT is created This type of states does not need a method to execute During its creation it is necessary to define the name of the state and the timeout
125. knowledge resources see Table 6 5 needed to crete your own argumenta tive agent and not directly using the default argumentative agent provided in the Argumenta tion Example The main tasks to perform to create an argumentative agent are e To use the Domain CBR to store and retrieve domain knowledge e To use the Argumentation CBR to store and retrieve argumentation knowledge e To implement the argumentation protocol methods and thus specify how to perform the actions of the argumentative agent in the states of the designed argumentation protocol The Domain CBR can be used to generate and select positions to defend in the argumentation dialogue To make a query to the domain CBR the user has to provide a problem codified as 6 Argumentative Agents 69 Package Classes Description argAgents argCBR ArgCBR java CommitmentStore java Configuration java domCBR DomainCBR java knowledgeResources Metrics java SimilarityAlgorithms java This CBR stores argument cases that represent past argumenta tion experiences and their final outcome Agent that stores all the informa tion about the argumentation di alogues Configuration parameters This CBR stores domain knowl edge of previously solved prob lems Package that contains the classes needed to manage the data of the CBRs and arguments Used by the CBRs to measure the similarity between case at tributes based on their distance Contains
126. lds must be fulfilled with the following information User thomas Password thomas You can automate this step by loading the grants sql file The ServerName databaseName userName and password entries must be also configured in the Settings xml file located in the configuration directory The parameters that affect MySQL configuration in the Settings xml file are the following lt Properties msg gt entry key serverName gt localhost lt entry gt entry key databaseName gt thomas lt entry gt entry key userName gt thomas lt entry gt entry key password gt thomas lt entry gt On the other hand the THOMAS framework uses Apache Jena for manage the semantic de 10 Advanced platform administration 151 File Edit View Tools MySQL Enterprise Help 3 Server Information User Information Schema Privileges Resource Limits E Service Control 7 8 new_user DH Startup Parameters Login and additional information on the user oM di a 9 Login Information ES Server Connections EE thomas The user will have to enter this MySQL ij Health y P o J username to connect to the MySQL server Gg Server Logs NOWIPOSSNORE pe Type in a new password if you want A L U to set a new value Sa Backup NC E se i Restore Backup Confirm Password Type the new password again to confirm g Repl
127. le in the organiza tion Internal in this case it is necessary participate into the organization that is the requested agent should play some role in the organization e Visibility By means of this attribute it is possible to control what information about roles is provided Concretely the allowed values for this attribute are Public information services always provide the requested information Private the requested information is provided only if the requested agent belongs to the same organization where the role is registered The relationship between accessibility and visibility attributes can be seen in the table 8 2 8 1 2 Units in THOMAS THOMAS framework gives support for three types of organizations or units Flat Team and Hierarchy Each type of organization is governed by different structural norms In the Table 8 3 a comparative of these types of units is shown Furthermore there is an organization created by default named Virtual This is a flat unit which represents the THOMAS world and it is the starting point to enter in the system A role named Participant is always available in the Virtual organization This role has the following attributes RoleName Participant Position Creator Visibility Public Accessibility External gt Position Unit Types Behavior Allowed Creator All types Send organizational messages is not allowed Register Deregister uni
128. le presidentx isNorm noAcRolePresident fraternity hasDeontic noAcRolePresident fraternity f hasTarget noAcRolePresident fraternity agentName _ hasAction noAcRolePresident fraternity acquireRole xFraternity Only the role president can add new norms isNorm noRegNorm fraternity hasDeontic noRegNorm fraternity f hasTarget noRegNorm fraternity positionName member hasAction noRegNorm fraternity registerNorm xFraternity Only the role president can delete normsx isNorm noDeregNorm fraternity hasDeontic noDeregNorm fraternity f hasTarget noDeregNorm fraternity positionName member hasAction noDeregNorm fraternity deregisterNorm xFraternity Only the role president can add rolesx isNorm noRegRole fraternity 166 A 3 Predicates of the forum example hasDeontic noRegRole fraternity f hasTarget noRegRole fraternity positionName member hasAction noRegRole fraternity registerRole xFraternity Only the role president can delete rolesx isNorm noDeRegRole fraternity hasDeontic noDeRegRole fraternity f hasTarget noDeRegRole fraternity positionName member hasAction noDeRegRole fraternity deregisterRole Fraternity It is not allowed registering new roles with the position creatorx isNorm noRegRole
129. message is a JSON object but it does not follow the guideline explained previously This is not a problem the reply content is free and may contain any type of data 144 9 2 Tools 9 2 Tools Magentix2 provides two tools to facilitate the communication between Magentix2 agents and a webpage Magentix2 js and Redirect php This tools can be obtained from the examples folder of the Magentix2 distribution 9 2 1 Magentix2 js Magentix2 js is a Javascript library that facilitates the creation of JSON objects that are ac cepted by the HTTP interface The two main functions of the library are createJSONOb ject agent name conversation id content and createJSONObDject agent name content The first one returns a JSON object with the conversation id field set to the value passed as parame ter The second one returns a JSON object with a new conversation_id this id is a UUID The parameter content has to be an associative array of elements that will be used as the content of the resulting JSON object 9 2 2 Redirect php This php can redirect an HTTP POST request to any address You can use it to redirect HTTP POST requests to your HTTP interface This php requires the Pear HTTP Request2 library you can get this library from http pear php net package HTTP Request2 redirected 9 3 Example In this section only a brief explanation of how to interact with a Magentix2 agent from a webpage is shown For the complete example pl
130. mic services API BuildOrganiza tionalMessage Description Builds a new organizational message Inputs UnitName Identifier of the unit Outputs Message built and ready to send 8 Virtual Organizations 121 Exceptions UnitNotExistsException NotPlaysAnyRoleException InvalidUnitTypeException AgentNotInUnitException OnlyPlaysCreatorException Table 8 8 OMS Proxy Organizational messaging service API 8 2 1 2 SFProxy We can find the SFProxy inside the package es upv dsic gti ia organization To use its functionality a new instance of the SFProxy class must be created to access the methods contained in the SF In the constructor the agent who executes the service has to be specified There are two options In the first one the url where SF services are deployed is taken from the settings xml configuration file see section 10 Notice that this is the recommended option private SFProxy sfProxy new SFProxy this On the contrary in the second option the url where SF services are deployed war should be specified in the constructor if the user does not want to use the default url from the settings xml configuration file private SFProxy sfProxy new SFProxy this url SFProxy provides a developer with a set of methods to manage available services as Table 8 9 shows Description Registers a service or part of it Inputs ServiceURL RegisterSer
131. ml configuration file private OMSProxy omsProxy new OMSProxy this url Notice that only Queue and Conversational Agents can make use of these proxy classes because the capacity of follow a conversation is required 8 Virtual Organizations 115 OMSProxy provides a developer with a set of methods to manage available services This services are classified into three different types structural dynamic and informative Tables 8 5 8 6 8 7 and 8 8 show respectively these sub types These methods return a string if are successfully provided If not they through a THOMAS exception see appendix B for further details Some OMS services are only available if agents which request them play a role inside the organization with a determined position Table 8 4 summarizes the available access to the services taking into account the position of the role RegisterRole Description Creates a new role within a unit Inputs RoleName Identifier of the new role UnitName Identifier of the organizational unit Accessibility internal or external Visibility public or private Position member supervisor or subordinate Outputs RoleName created Exceptions InvalidPositionException ForbiddenNormException NotSupervisorOrCreatorInUnitException NotMem berOrCreatorInUnitException InvalidUnitTypeEx ception NotInUnitAndNotCreatorException Agent NotInUnitException Rol
132. nfiguration directory will be configured The parameters that affect THOMAS configuration in the Settings xml file are the following lt l Properties thomas entry key OMSServiceDescriptionLocation gt http localhost 8080 omsservices services lt entry gt entry key SFServiceDescriptionLocation gt http localhost 8080 sfservices services lt entry gt Check if the direction where agents OMS and SF are running is different host from where the services OMS and SF are deployed or if the port is different If the OMS and SF are running in the same host that web services are deployed the configuration by default is correctly In the same way in order to run any developed web service from Tomcat it is necessary to copy the packaged library serviceName war to the subdirectory webapss of the Tomcat installation directory Once all the necessary services have been properly copied to the webapss directory Tomcat can be started running the startup sh file on the bin subdirectory of the Tomcat installation directory 10 4 Advanced platform services This section explains how to launch platform agents without using the standard methods shown previously on this manual This can be useful when some default parameters have been changed or if the platform runs in a distributed way 154 10 4 Advanced platform services webapps File Browser File Edit View Go Bookmarks Tabs Help
133. ni zation As this agent register each unit it also plays the role Creator of them At the end of the example it deallocates all roles and deregister all units roles and services Addition This agent acquires the role Operation of the Calculator organization It also registers and provides the service Addition Product This agent acquires the role Operation of the Calculator organization It also registers the services Product and Square It only provides the service Product e James It represents an student which needs computing some operations and demand the other their services This agent acquires the role Student of the School organizations It looks for the different services it needs Addition Product and Square to calculate a simple mathematical operation Then either ask the service providers in carrying out such services or run them directly if no provider Services in the THOMAS example are deployed in the webapps folder of the Apache Tomcat in Magentix2 installation folder The OWL S specifications are located in webapps testSFservices testSFservices owl owls The WSDL documents can be found in webapps testSFservices WEB INF services service_name META INF Service name wsdl The following services are used in the THOMAS example e Product This service multiplies two input numbers doubles and returns the product double It is provided by an agent behavior e Addition This service adds
134. nitName hasAccessibility RoleName UnitName Accessibility hasVisibility RoleName UnitName Visibility hasPosition RoleName UnitName Posision e Norm Predicates isNorm NormName UnitName hasDeontic NormName UnitName Deontic hasTarget NormName UnitName TargetType TargetValue hasAction NormName UnitName OMSActionName e Role Enactment Predicates isAgent AgentName playsRole AgentName RoleName UnitName A BNF Syntax of the Normative Language 161 Derived Predicates roleCardinality RoleName UnitName Cardinality positionCardinality Position Value UnitName Cardinality Predicates of Services registerUnit UnitName UnitType ParentUnitName A gentName CreatorName deregisterUnit UnitName AgentName registerRole RoleName UnitName Accessibility Visibility Position AgentName deregisterRole RoleName UnitName AgentName registerNorm NormName UnitName Deontic TargetType Target Value OMS ActionName AgentName deregisterNorm NormName UnitName AgentName allocateRole RoleName UnitName TargetAgentName AgentName deallocateRole RoleName UnitName TargetAgentName A gentName joinUnit UnitName ParentName AgentName informA gentRole RequestedA gentName AgentName informMembers UnitName RoleName PositionValue AgentName informQuantityMembers UnitName RoleName PositionValue AgentName informUnit UnitName AgentName informUnitRoles UnitName AgentName informTargetNorms TargetType TargetName UnitName AgentNam
135. nt problem and adds it in the domain cases case base Also stores all the generated argumentation data in the argument cases case base Finally makes a cache of the domain CBR and the argumentation CBR Table 6 1 ArgCAgent java methods to manage positions and arguments POSITION MANAGEMENT A position is a solution that defends an agent as the correct one to apply to solve the problem at hand The position generation is made in two steps First the agent retrieves from its Domain CBR the most similar domain cases to the current problem to solve by using the retrieve method of the DomainCBR java class With them the agent is able to propose its position 6 Argumentative Agents 59 in view of the solutions applied to similar problems in the past Then the agent evaluates the suitability of each position by using its Argumentation CBR to compute the support factor pa rameters by using the method get Degrees of the ArgCBR java class Then each position is assigned a suitability degree by using the formula Suitability Wsimp SimD wsp SF 6 2 where w 0 1 5 gt w 1 are weight values that allow the agent to give more or less importance to the similarity degree with the domain cases used to generate its position or the support factor these weights can be set in the agent s constructor Agents sort their potential positions from most to less suitable depending on their value preference order and for
136. nt running into a JADE platform 20 21 22 23 24 3 Basic Programming AgentID rec zx JADE defau iver new AgentID lt parameters receiver nam Host in wh AgentName hostname 1099 JAD ich the JADE agent is running receiver host hostname domain JADE defau receiver por Default pr receiver pro Building New Requ keep OT GNE OT AG en a UT SUPE otocol POCA AE a ACLMessage x ACLMessag st messag ES 25 msg new ACLMessage ACLMessage R The JADE EQUEST agent is added as a receiver of t iver receiver msg setRec The Magentix2 agent sends the message send msg ne message In a similar way the following example shows how an external JADE agent sends a message to a Magentix2 agent from the JADE platform JADE source code AgentID rec iver new AgentID agentname hotsname of the Magentix2 platform in which the agent d SEIS DEDISTI GI receiver setName consumer hostname Host in which the BridgeAgentOutIn agent is been executed and the port in which i t is listened receiver addAddresses http host domain 8081 26 3 3 Basic conversational agents QueueAgents Creation of a Request Messag ACLMessage msg new ACLMessage ACLMessage REQUEST Addition of the receiver of the message msg a
137. nts the argu mentative agent as a CAgent It can engage in an argumentation dialogue to solve a problem CreatePartitions java This class creates different partitions of domain cases and argument cases to make tests TestArgCAgent java This class launches a test with argumentative agents including the commitment store and a tester agent that acts as initiator of the dialogue TesterArgCAgent java This class represents a tester agent in charge of sending the test domain case to solve to a group of agents and acts as the initiator of the dialogue TestArgumentation datafiles partitionsInc Folder with the data files to per form tests Table 6 3 Argumentation example packages and classes Method Parameters Description generateAttack Argument incomingArgument op Defends and attacks other ponentID agents positions generatePositions problem Evaluates if it can propose a po sition generateSupportArguments myPosition opponentID Defends its position updateCBs solution Stores generated data in the dia logue Table 6 4 Main ArgCAgent java methods ArgCAgent agent new ArgCAgent new AgentID qpid agentName localhost 8080 SocialEntity friendsList depenRelsList group commitmentStoreID iniDomainCasesFilePath finDomainCasesFilePath domCBRindex domCBRthreshold iniArgCasesFilePath finArgCasesFilePath 68 6 3 Programming Argumentative Agents wPD wSD
138. ocessor myProcessor ACLMessage messageReceived doReceive myProcessor messageReceived return FINAL protected void doFinal CProcessor myProcessor ACLMessage messageToSend messageToSend myProcessor getLastSentMessage class FINAL Method implements FinalStateMethod public void run CProcessor myProcessor ACLMessage messageToSend doFinal myProcessor messageToSend Once all the states are defined the next step is to create a method that returns a new CFactory In this method new states are created and the methods defined before are assigned to them The transitions between the states are also defined in this method Depending on the IP some parameters will be needed In this case it is only necessary to specify the name of the CFactory the maximum number of simultaneous conversations the agent who owns the CFactory and the timeout for the wait state The code of this method is shown below 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 availableConversations CFactory theFactory new CFactory name availableConversations Processor template setup CProcessor processor BEGIN State BeginState BEGIN BeginState PROPOSE State SendState PROPOSE a PROPOSE setMethod new PROPOSE public CFactory newFactory String name processor registerState PROPOSE
139. od doe Neues esc cubo k E Ius db eR E TI 4 3 Tracing Servicess vL a hal ysl teed oye b eg a ae sea 78 7 3 1 Tracing service publication 20 2 2 000 80 7 3 2 Tracing service subscription lees 80 TN uec Pues Diary Sgr Fes p hte amp UR RO ee 81 7 4 Domain Independent Tracing Services o 83 7 4 1 System domain independent tracing services 84 7 4 2 Agent s lifecycle domain independent tracing services 84 7 4 3 Messaging related domain independent tracing services 84 7 4 4 Tracing service publication related domain independent tracing services 85 7 5 Customizable Trace Support o e 87 10 7 6 Example TraceDaddy e 7 6 1 Daddy Class si sanc dos ten OA ed a a ena e 1 6 2 BOY ClASS ie toe dite fe hd eee BN ee ed Oe te Pecan 7 6 3 Main application source code o a FOA Results 302 3 e e el eek a Red Rue BO oe AAA Virtual Organizations 8 1 Overview of THOMAS framework e e 8 1 Rolesin THOMAS e 8 1 2 Unitsin THOMAS e 8 1 3 Service Facilitator o ee eee 8 1 4 Organization Manager Service o o e 8 1 5 Normative Context 0000000002 eee 8 2 Programming agents which use THOMAS e 8 2 1 Magentix2 API for THOMAS es 8 3 Programming Agents that Offer Services o
140. oggin xml Logger logger Logger getLogger Main class ia Connecting to Opid Broker AgentsConnection connect localhost 5672 test guest guest false try Yee Instantiating a sender agent x Sender senderAgent new Sender new AgentID Sender Vx Instantiating a consumer agent Consumer consumerAgent new Consumer new AgentID Consumer TENG Vx 35 36 37 38 39 40 41 42 43 44 45 14 2 2 Developing and executing a first agent Execute the agents Es consumerAgent start senderAgent start catch Exception e l or e e mee ons a or E getMessage In lines 14 and 15 the logger mechanism is set up Its basic functionality is to show messages at some points of the code This messages have a priority level associated these levels go from info to error It is needed to specify the configuration file for the debugger and the class to debug Main class in this example In line 20 the connection to the broker for all the agents launched in this class is set up In this particuar case it is specified that the QPid broker is running in the same host that the agents The other parameters are the values for a default configuration of the broker From lines 27 to 38 the agents are created specifying an agent id for each one and then they are started If Eclipse is used the example can be run using the run button The
141. on file for the Magentix2 logger where is specified how log messages are dis played Magentix2 uses log4j as debugger for more information about this software please refer to http logging apache org log4j 1 2 manual html There is a valid configuration folder for any Magentix2 project in the Magentix2 installation folder In this example project this configuration folder will be used Thus it is only nec essary to copy the folder configuration in the root folder of the project in this case workspace MyFirstAgent Then it is necessary to create a new package named agent in the project In figure 2 1 itis shown how Eclipse looks like after taking these actions The example shown here consists in two agents Sender and Consumer The agent Sender sends a message to agent Consumer who writes the content of the received message on the console In order to set this example it is required to create three Java classes Sender java Consumer java and Main java Sender java and Consumer java will contain the code of the agents Besides Main java will create the connexion to the broker for the agents and start them Now how to program the Sender java class is shown This class has to extend BaseAgent class section 3 1 1 Therefore it is necessary to import some classes from magentix2 2 1 0 jar with dependencies zip Once the library is included Eclipse suggests you to import the necessary classes that library Figure 2 2 shows Send
142. on_id In that case the participant CFactory 1 will create a new CProcessor and two conversations which follows the same IP This conversations will be managed simultaneously the previous Conv2 and the new conversation For more information about CAgents please refer to Fogu s et al 2010 34 4 4 Hello World CA gent Agent e Participant Factory DU l j Infprm A Participant Factory 2 Initiator Factory 1 Request lt lt _ _ gt Figure 4 2 Global view of a CAgent In the next sections some examples of CAgents are explained All the code of these examples are available in the examples directory of Magentix2 platform 4 4 Hello World CAgent The code shown in this section corresponds to the code located in examples src myFirstCA gent HelloWorldAgent java In the code below the method execution is where the user has to implement the main code of the agent In this hello world agent the main behaviour of the agent is just to say hello world The only way to terminate a cAgent is to call the Shut down method from the agent instance or the ShutdownAgent method from a CProcessor instance of the CAgent The method finalize is executed when the agent is just about to finish its execution thus this is where the user can introduce ending actions for the agent class HelloWorldAgentClass extends CAgent public HelloWorldAgentClass AgentID aid throws Exception super aid
143. onder roles e Handlers A handler is a method which is executed when a specific protocol state is reached for agents playing initiator roles Each protocol has a handler per each state it can reach Although there are default handlers which do nothing defined for each protocol agent programmers can overload each handler with the functionality they require in each protocol state 1 protected void handleAgree ACIMessage agree 2 logger info Good news 3 e Preparers Preparers are similar to handlers but are executed when the agent plays the responder role in the protocol Messages must be filled carefully because leaving a field empty can interrupt the entire protocol Therefore we encourage the use of the method createReply included in ACLMessage messages This method produces a new answer to the original message with the required fields covered so only required ones need to be modified 1 protected ACLMessage prepareResultNotification ACLMessage inmsg 2 ACLMessage outmsg 3 4 ACLMessage msg inmsg createReply 5 return msg 6 4 2 How to implement a FIPA Protocol Following some explanations of how the FIPA Protocols proportionated by Magentix2 have been implemented are proportioned in order to illustrate how new protocols could be imple mented 30 4 2 How to implement a FIPA Protocol 4 2 1 FIPA Request This protocol allows agents to request other agents to perform an action and i
144. onditions to fulfil a norm Until a service is provided the OMS agent checks if some norm is satisfied in which case that norm is applied Users should add predicates related with data known in the THOMAS world such as role details played roles organization structure agent names etc see A for further explanation The ee 99 Activation could be empty in that case the norm is always fulfilled e Expiration is a well formed formula expressed by means of first order predicates which indicates when a norm expires So if the expiration of a norm is satisfied the norm is not applied although the activation is fulfilled Users should add predicates related with data known in the THOMAS world such as role details played roles organization structure agent names etc see A for further explanation The Expiration could be empty gt in that case the norm never expires 8 Virtual Organizations 109 8 1 5 2 Norm Checking The OMS agent is the responsible of verifying if some norm applies before provide a service Thus users can add forbidden or permitted norms to restrict or relax the predefined rules for accessing to services respectively In particular the order in which the restrictions and norms are checked before provide a service of the OMS is as follows 1 PERMITTED norms It is checked if there are some permitted norms registered which ac tion correspond with the requested service In that case it is also
145. ontic noJoinUnit Panel f hasTarget noJoinUnit Panel positionName _ hasAction noJoinUnit Panel joinUnit APPENDIX B Exceptions B 1 Trace Exceptions ooo 169 B THOMAS Exceptions 66 169 B 1 Trace Exceptions The methods of the TraceInteract class can throw Trace exceptions These exceptions extends from the java lang Exception The exception classes can be found in the package es upv dsic gti ia trace exception The following table shows the name indicates the kind of problem of the exception class and its associated message Exception name Description TraceServiceNotAllowedException Have been tried to execute an operation forbid den by the trace mask TraceSystemUnreachableException Trace Manager is unreachable Table B 1 Trace Exceptions and associated messages B 2 THOMAS Exceptions The methods of the OMSProxy and SFProxy class can throw THOMAS exceptions These ex ceptions inherit from THOMASException class which extends from the java lang Exception 169 170 B 2 THOMAS Exceptions The exception classes can be found in the package es upv dsic gti ia organization exception The following table shows the name indicates the kind of problem of the exception class and its associated message Exception name Description AgentNotExistsException Not found The agent Requeste
146. ose unique purpose is sending console messages to inform about mes sages sent by agents with Manager role within Calculator organization e Summation Agent who plays the Manager role with member position within Calcu lator organization It requests to each of its subordinates to do the operation for which they are prepared Then it adds up all the responses and sends a message reporting the result e Product Agent who plays the Operator role with member position within Calculator organization It only provides the Product operation and informs of the result e Addition Agent who plays the Operator role with member position within Calculator organization It only provides the Addition operation and informs of the result e Noisy Agent who plays two roles The first the Creator role with creator position within External organization as a result to create this organization The second the Manager role with member position within External organization It tries to send a Organizational Message to the Calculator organization requesting a calculation using two numbers Following we briefly explain the actions of the Organizational Message example shown in the diagram of Figure 8 12 1 Scenario creation is the first task to begin the example The Creator agent creates the Calculator organization and their roles Creator Manager and Operator Simultane ously the Noisy agent creates the External organization and their roles Cr
147. ositions but that other agents did not considered If different attacks can be generated agents select the best attack to rebut the position of another agent by making a query to their argument cases case base extending the characterisation of each case with the current social context In this way agents can gain knowledge about how each potential attack worked to rebut the position of an agent in a past argumentation experience with a similar social context When an agent is able to rebut an attack the opponent agent makes a vote for its position Otherwise the agent must withdraw its position and propose an alternative position if possible The dialogue finishes when no new positions or arguments are generated after a specific time The fester agent is in charge of making queries to the commitment store agent to determine if the dialogue must finish Then this agent retrieves the active positions of the participating agents If all agents agree the solution associated to the agreed position is selected Otherwise the most frequent position wins In case of draw the most voted position in selected If even in this case the draw persists a random choice is made Finally the tester agent communicates the final solution the outcome of the agreement process to the participating agents CHAPTER 7 Tracing Service 7 4 Trace Model and Features 75 72 Trace Event sant ah e ia als 77 7 3 Tracing Ser
148. ost python1 34 1 1 34 1 15ubuntu3 Bibliotec EM ana a am Mec E saae E Estado 2 Archivos de desarrollo de la biblioteca Boost lostreams Origen 28 Obtener captura de pantalla 1 Filtros personalizados Parte de la colecci n de bibliotecas Boost de C Resultados de b squeda I On Ne ne mm I mmm mmm mmm mmm m m om m mm oo LL 101 paquetes listados 1185 instalados 0 rotos 0 para instalar actualizar 0 para desinstalar Figure 10 1 Installing libboost iostreams 1 35 dev library with Synaptic tool shows how to install the libboost iostreams 1 35 dev library Once all the required libraries have been installed Qpid broker can be downloaded from http qpid apache org download cgi To install Qpid the following steps must be performed e Uncompressing the donwloaded Opid file e configure prefix opt qpid gt Using the prefix option when con figuring the location where the Qpid binaries are installed can be specified in this ex ample case opt qpid e make install After a successful installation Qpid can be launched executing the following command inside the folder where Qpid was installed in this example case opt qpid qpidd Some values Qpid broker set by default are used by some components of Magentix2 therefore if any of them is changed it is possible that the Settings xml file has to be also modified This file can be found in the configuration directory of
149. ovider to ask and its parameters In the obtained OWL S specification with GetService is specified the providers of the service and their parameters To make a request of the service the provider has to be an agent or organization In case that the providers are web services with a grounding in the specification the service has to be executed by the requester agent Using the Oracle class provided in the package es upv dsic gti_ia organization the OWL S specification is parsed to obtain the information of the service including its inputs and its providers There are two different ways to request a service depending on the type of the providers If the providers are agents or organizations their parameters entity ID entity type language and performative to make the request are obtained from the OWL S specification using the Oracle class Then the requester agent should properly build the message to make the request and wait for the response of the provider to obtain the result In ServiceTools class it is possible to find the method build ServiceContent which returns an XML description receiving as parameters the 8 Virtual Organizations 129 inputs and the name of the requested service This description is understood by all THOMAS services and the services of the provided examples If the providers are web services the URL of the WSDL documents are obtained from the OWL S specification using the Oracle class Th
150. p tion ServicesNotFoundException MySQLExcep tion Table 8 9 SF Proxy API M1 Call M2 Request Y SFproxy M3 Agree M5 Result M4 Inform Figure 8 4 Interaction between user agent and SF agent through the SFProxy 8 Virtual Organizations 123 8 2 1 3 Basic Service Management Services are composed by a profile which is a semantic description of the service useful for customers to locate appropriate service and a process which details how to interact with the service Different agents can provide different processes different implementations to the same service profile general description When an agent needs to register a new service in the organization the RegisterServic method of the SFProxy class is invoked The following code shows how to register it in the organization ArrayList lt String gt resultRegister sfProxy registerService http localhost 8080 testSFservices testSFservices owl owls Addition Omar The Register Service tries to register the service that is specified as parameter The parameter is the original URL of the OWL S specification of the service The contents of the OWL S specification of a service must have the profile that describes the service and the process that describes its implementation If one or more providers agents or organization are specified in the profile contactInformation of the service 1t means that the s
151. pply Changes 10 3 Advanced Apache Tomcat Apache Tomcat is a main component of Magentix2 because it allows to access to standard Java web services If Apache Tomcat was installed during the Magentix2 Desktop version installation it will not be necessary to follow the steps shown here On the other hand this section helps to configure it properly THOMAS platform is based on services chapter 8 so SF and OMS service implementations have to be available as standard web services Moreover Magentix2 offers another service named MMS section which is responsible of controlling the user access to the platform This service must be also available as an standard web service Any other user service such as the application examples need also to be available as standard web services As mentioned above Magentix2 uses Apache Tomcat to allow it Apache Tomcat can be downloaded from http tomcat apache org The installa tion instructions can be found at http tomcat apache org tomcat 7 0 doc setup html 10 Advanced platform administration 153 Once Tomcat is installed packaged libraries of THOMAS services omsservices war sfser vices war have to be copied from the webapps directory of the Magentix2 installation to the subdirectory webapss of the Tomcat installation directory Then the path where web services are deployed is required In order to specify these pa rameters the Settings xml file located in the co
152. processor addTransition BEGIN WAIT State WaitState WAIT processor registerState WAIT processor addTransition PROPOSE RECEIVE State ReceiveState RECEIVE filter new MessageFilter RECEIVE setAcceptFilter filter processor registerState RECEIVE 4 8 Creating a CFactory Template CAgent myAgent myAgent BEGIN setMethod new BEGIN Method PROPOS int long timeout null theFactory cProcessorTemplate processor getState BEGIN new SendState PROPOSE ethod new WaitState WAIT E timeout WAIT new ReceiveState RECEIVE RECEIVE setMethod new RECEIVE Method accept any message E processor addTransition WAITE R EC EIV EDE FinalState FINAL FINAL setMethod new FINAL Method processor registerState FINAL A processor addTransition RECEIVE return theFactory new FinalState FINAL FINAL 38 4 Advanced conversational agents CAgents 45 y How to use a CFactory template is shown in the previous section 4 7 For this specific template the instructions are the same 2 CHAPTER 5 BDI Agents JasonAgents 5 1 Programming BDI Agents 46 Jason Bordini et al 2005 is an interpreter for an extended ver
153. protocol to search service The following example shows how to search for a service The desired service should have the word addition in its description two double inputs an one double output Array Array Array searc searc Scarce hInputs add ServiceT hInputs add ServiceT oo ool ls Ontol List String searchKeywords new ArrayList Stri ogical ls Ontol ogical searchKeywords add addition TypesConstan TypesConstan hOutputs add ServiceTools OntologicalTypesConsta List lt String gt searchInputs new ArrayList lt String gt List lt String gt searchOutputs new ArrayList lt String gt ng gt ts DOUBL ts DOUBL hes DOUBT 128 8 4 Programming Agents that Request Services 20 21 22 23 24 25 ArrayList lt ArrayList lt String gt gt foundServices do Waiting for services EA a Thread sleep 2 1000 catch InterruptedException e e printStackTrace foundServices sfProxy searchService searchInputs searchOutputs searchKeywords while foundServices isEmpty 8 4 2 Service Request Process e Request a service After the agent has found the desired service it has to get the main information of this service to make a request So the agent has to use the GetService to obtain the required data to specify the inputs of the service and to know the pr
154. r any external agent that implement FIPA commu 114 8 2 Programming agents which use THOMAS nication and the services they provide Services requests through FIPA request protocol were received by this type of agents In order to ease the interaction among user agents and OMS and SF agents two classes are provided OMSProxy and SFProxy They work as a proxy for OMS and SF respectively encapsulating and hiding the details of the underlying communication protocol Thus the de veloper can interact with OMS and SF using simple function calls 8 2 1 1 OMSProxy M1 Call M2 Request T OMSproxy M3 Agree E M5 Result OMS M4 Inform Figure 8 3 Interaction between user agent and OMS agent through the OMSProxy The OMSProxy can be found in the package es upv dsic gti ia organization To use its functionality a new instance of the OMSProxy class must be created to access the methods contained in the OMS In the constructor the agent who executes the service has to be specified There are two options In the first one the url where OMS services are deployed is taken from the settings xml configuration file please see section 10 Notice that this is the recommended option private OMSProxy omsProxy new OMSProxy this On the contrary in the second option the url where OMS services are deployed war should be specified in the constructor if the user does not want to use the default url from the settings x
155. rAgent new AgentID qpid emisor8localhost 8080 In order to start the agent s execution is only needed to call the start method which causes the execution of the agent s logic flow AA execute asta ZO O Thus the methods init execute and finalize should not be called directly Fur thermore notice that agents should finalize in an ordered way If its execution is interrupted or aborted they do not disconnect from the Qpid broker and this could provoke errors later The following code shows how to implement a new BaseAgent class named SenderAgent This agent only shows its name by the screen import es upv dsic gti ia core ACLMessage import es upv dsic gti ia core AgentID import es upv dsic gti ia core BaseAgent public class SenderAgent extends BaseAgent public SenderAgent AgentID aid throws Exception super aid public void execute System out println Executing I m getName Furthermore the following source code creates and runs an agent of the class SenderAgent which extends BaseAgent 3 Basic Programming 17 Connecting to Qpid Broker AgentsConnection connect Instantiating a sender agent SenderAgent myAgent new SenderAgent new AgentID qoid emisor localhost 8080 Execute the agent myAgent start 3 1 2 SimpleAgent In order to create a simple Magentix2 agent it is required to define a cla
156. ributes Sililarity Algorithms java normalizedEuclideanSimilarity Returns a list of the candidate domain cases with a similarity degree to the given domain cases The similarity is calculated using normalized Euclidean distance among the premises Sililarity Algorithms java weightedEuclideanSimilarity Returns a list of the candidate domain cases with a similarity degree to the given domain cases The similarity is calculated using weighted Euclidean distance among the premises Sililarity Algorithms java normalizedTverskySimilarity Returns a list of the candidate domain cases with a similarity degree to the given domain cases The similarity is calculated using normalized Tversky distance among the premises Table 6 2 Methods to compute the distance and similarity between cases is ordered by using the suitability degree explained before and the argument that has the higher degree is proposed first as support argument to justify the agent s position ATTACK ARGUMENTS MANAGEMENT To generate an attack argument the premises that the argument to attack has and the social context between the agents that are arguing are taken into account With this information ar gumentative agents extract the argument cases that match with the current position and have a similar social context Then if the dependency relation allows to attack the other agent the agent generates the attack argument
157. role moderator can add norms QnoRegNorm f lt agentName Ag gt registerNorm panel _ Ag not playsRole Ag moderator plana Only the role moderator can delete norms noDeregNorm f lt agentName Ag gt deregisterNorm _ panel Ag not playsRole Ag moderator plana 8 Virtual Organizations 113 No one can add roles noRegRole f lt positionName _ gt registerRole panel _ r _ _ Lra noDeRegNormRegRole f lt roleName moderator gt deregisterNorm NormX panel _ hasAction NormX panel registerRole _ No one can delete roles noDeRegRole f lt positionName _ gt deregisterRole panel _ _ _ noDeRegNormDeregRole f lt roleName moderator gt deregisterNorm NormX panel _ hasAction NormX panel deregisterRole Knowing which roles are played by other agents is prohibit noSupInfAgRole f lt agentName Ag gt informAgentRole Ag _ aip eds QnoDeRegNormnoSupInfAgRole f lt roleName moderator gt deregisterNorm NormX panel hasAction NormX panel informAgentRole _ Changing the parent unit of the organization is prohibit noJoinUnit f lt positionName _ gt jexmunit ipstnel 3 6 8 2 Programming agents which use THOMAS 8 2 1 Magentix2 API for THOMAS SF and OMS have been defined as two types of intermediary agents in order to address the translation between Magentix2 agents o
158. s xx Connecting to Qpid Broker AgentsConnection connect iia Instantiating the Trace Manager TraceManager tm new TraceManager new AgentID TM tm setTraceMask new TraceMask 1001000100 System out pti AGC ENEETARTAING I AAN Vik Instantiating Dad x dad new Daddy new AgentID qpid MrSmith localhost SUSO Instantiating sons x olderSon new Boy new AgentID qpid Timmy localhost 28080 7 dad getAid youngerSon new Boy new AgentID qpid Bobby localhost SUSO 9 adad gerardo Execute the agents x 48 49 50 51 52 53 54 55 96 7 6 Example TraceDaddy dad start olderSon start youngerSon start catch Exception e ilf Cyr TS CETT O TR GUESS TUS getMessage 7 Tracing Service 7 6 4 Results IENEI JE IET N 55 Daddy MrSmith I want to read the newspaper Timmy I m Timmy and I m 7 years old Bobby I m Bobby and I m 5 years old rSmith 16 11 06 077 qpid Timmy localhost 8080 said REFUSE NO rSmith 16 11 07 072 qpid Bobby localhost 8080 said REQUEST Give me your toy ES 165115075077 5 corc 1 une Localinosic 9080 said REFUSE NO rSmith 16 11 08 075 qpid Bobby localhost 8080 said REQUEST Give me your toy rSmith 16 11 08 080 qpid Timmy localhost 8080 said REFUSE NO rSmith 16 11 09 077 qpid Bobby localhost 8080
159. s lt service name length gt lt service name gt lt service description length gt lt service description gt Table 7 5 Tracing services and tracing entities listing methods listTracingEntities BaseAgent requesterAgent listTracingEntities AgentID tms aid BaseAgent requesterAgent listTracingServices BaseAgent requesterAgent listTracingServices AgentID tms aid BaseAgent requesterAgent tms aid Agent ID of the Trace Manager which will process the request If not specified the request is directed to the default Trace Manager TM requesterAgent Agent which is requesting the list of available tracing entities and ser vices 7 4 Domain Independent Tracing Services The platform offers a set of domain independent tracing services Some of them can be re quested by agents in order to receive the corresponding trace events while others are not re questable and the corresponding trace events are received even without having requested them previously this can be seen as a default subscription to the tracing service The rest of the section will describe them as well as how to interpret their correspoding trace events accord ing to the TraceEvent class and its attributes previously described in Section 7 2 Domain independent tracing services can be classified in four main groups System agent s lifecycle messaging and tracing service publicat
160. s Summary A 2 1 Operators A 3 Predicates of the forum example o B Exceptions B 1 Trace Exceptions B 2 THOMAS Exceptions Bibliography IV 157 157 160 161 162 169 169 169 175 List of Figures 2 1 2 2 3 1 32 3 3 4 1 4 2 4 3 6 1 6 2 6 3 6 4 7 1 8 1 8 2 8 3 8 4 8 5 8 6 8 7 8 8 8 9 8 10 8 11 8 12 9 1 Project and package creation ens 10 Programming a first agent with Eclipse llle 10 Appender F aast r afa aa a Aa a a a a AA en aye Ne a AaB ty a cays 19 Appender 2 24 kt 4th ee endo RARE eg eee eed Ba ee RE 19 Messages exchange thought QPID Broker in Magentix2 22 CFactory for FIPA Request Interaction Protocol for the initiator agent 33 Global view of a CAgent ee ee 34 myFirstCProcessorFactories example o o o 36 Example Structure of aDomain Case o a 51 Structure of an Argument Case e e 53 ArgumentationProtocol o oo e 63 Data flow for the argumentation process of the helpdesk application 73 Trace Support Mask dd chad er tenu Bat Bee vl od eed 87 Handled Services demanded and implementations of offered services supported 106 Organizational view of the form example organizations roles and agents 110 Interaction between user agent and OMS agent through the OMSProxy 114 Interaction between user agent and SF agent through t
161. s are registered into an organizational unit with a unique name inside that organization They should be written following the syntax of the THOMAS normative language see appendix A for a detailed explanation which is based on AgentSpeak language Concretely the appear ance of a norm is as follows AnormName Deontic Target Action Activation Expiration where e Deontic f o p where f is used for forbidden norms which restrict the access to services o is used for obligation norms and p is used for permitted norms which relax the access to services Although a norm can be registered with a deontic value of obligation the OMS only manage forbidden or permitted norms e Target lt type id gt where type agentName roleName position Name whereas id is the associated value for example the position value creator or the anony mous variable _ when any value is accepted The field target allows users to deter mine which agents will be affected by a norm For example taking into account an sce nario in which a norm was registered in a unit with the target lt agent Name consumer gt this norm only affects the agent which name is consumer e Action is the name of the service THOMAS only manage norms which action corre spond with an OMS service see appendix A to build Action field correctly e Activation is a well formed formula expressed by means of first order predicates which indicates the c
162. s can be launched by calling to their start method Examples agentl start agent2 start 3 1 6 Agent life cycle The agent life cycle for a BaseAgent is composed of the following steps init execute gt finalize gt terminate These methods are defined in the es upv dsic gti_ia core BaseAgent class The init and finalize methods are automatically executed before and after the execute method The programmer can override them in order to include initialization or termination tasks The terminate method MUST NOT be overriden since it terminates the qpid conections with the broker Otherwise the agent will not finalize correctly All the user code designated to stop the agent must be placed in the finalize method 3 1 7 Running Examples In the examples folder of the Magentix2 package there are some basic examples of Magentix agents e BaseAgent Example this is an example of sender consumer agents The sender agent sends an ACL Message to the consumer agent When the ACLMessage arrives to the consumer agents a message is shown e SingleAgent Example this is an example of sender consumer agents The sender agent sends an ACL Message to the consumer agent When the ACLMessage arrives to the consumer agents a message is shown The consumer is in blocked state waiting the message 22 3 2 Agent Communication SA prepares the message to the CA CA gets the message from EN its message queue
163. s of the tracing service provide by Magentix2 Chapter 8 explains in detail the support for virtual organizations provided by the Magentix2 platform In this way this chapter gives details about how the THOMAS Methods Tech niques and Tools for Open Multi Agent Systems framework has been integrated with Ma gentx2 and how Magentix2 agents can use it Chapter 9 is about describes the HTTP service supplied by Magentix2 in order to facilitate the interaction between Magentix2 agents and the outside world In order to customize the Magentix2 platform installation or distribute it in diverse hosts the chapter 10 should be consulted Concretely this chapter is about administration and configu ration aspects related with the different components of the platform Apache Qpid the imple 1 Introduction 3 mentation of AMQP Advanced Message Queuing Protocol used for agent communication MySQL the database server used to maintain persistent information about the virtual organi zations manage by the platform Apache Tomcat which allows agents to access to and provide standard Java web services and advanced Magentix2 platform services such as the services which allows the communications with external agents or with the THOMAS framework CHAPTER 2 Quick Start 2 1 Installing Magentix2 5 2 2 Developing and executing a first agent 9 2 1 Installing Magentix2 2 1 1 Requirements
164. s that match the problem to solve and other extra premises that do not appear in the description of this problem but that have been also considered to draw the conclusion of the argument and optionally any knowl edge resource used by the proponent to generate the argument domain cases argument cases and argumentation schemes This type of argument is called a support argument On the other hand if the argument attacks the argument of an opponent the support set can also include any of the allowed attack elements of our framework These are distinguishing premises counter examples or critical questions This other type of argument is called an attack argument Definition 6 1 1 Distinguishing Premise A distinguishing premise is a premise that does not appear in the description of the problem to solve and has different values for two cases or a premise that appears in the problem description and does not appear in one of the cases Definition 6 1 2 Counter Example A counter example for a case is a previous case i e a domain case or an argument case that was deemed acceptable where the problem description of the counter example matches the current problem to solve and also subsumes the problem description of the case but proposing a different solution Definition 6 1 3 Critical Question A critical question is a question associated to an argu mentation scheme that represents a potential way in which the conclusion drawn from the
165. sages What agents can re Any agent from this organization except who Supervisors receive all messages Subordi ceive organizational what only play roles with Position Creator nates only receive messages sent by Super messages visors Creators do not receive messages What agents can regis ter deregister organiza tions Any agent from this organization which plays roles with Position Creator What agents can join an organization to an other Any agent from this organization which plays both a role with Position Creator and a role with Position Creator in the new Parent organization What agents can regis ter deregister roles Any agent from this organization Creator What agents can allo cate deallocate roles Agents from other organizations Any agent from this organization Agents from this organization with Position Creator or Position Supervisor What agents can re quest public informa tion Any agent from any organization What agents can re quest private infor mation Any agent from this organization What agents can re quest information about organizations Any agent from any organization What agents can re quest information about attributes of the roles Any agent from this organization or any agent from its parent unit What agents can ac quire roles with acces sibility external Any agent from any organization
166. said REQUEST Give me your toy rSmith 16 11 09 083 qpid Timmy localhost 8080 said REFUSE NO rSmith 16 11 10 080 qpid Bobby localhost 8080 said REQUEST Give me your toy rSmith 16 11 10 094 gqpid Timmy localhost 8080 said REFUSE NO rSmith 16 11 11 082 qpid Bobby localhost 8080 said EST GUAAAAAA rSmith 16 11 11 087 gqpid Timmy localhost 8080 said REFUSI NO Daddy MrSmith Daddy MrSmith Daddy MrSmith Daddy MrSmith r1 O C Lr Ok I give up Shall we go to the park Timmy says AGREE GO TO THE PARK Bobby says AGREE GO TO THE PARK JE Ok Let s go children CHAPTER 8 Virtual Organizations 8 1 Overview of THOMAS framework 99 8 2 Programming agents which use THOMAS 113 8 3 Programming Agents that Offer Services 124 8 4 Programming Agents that Request Services 126 8 5 Running THOMAS Example 132 8 6 Programming agents which use organizational messaging ooooooooo morro ee eee 134 8 7 Organizational Messaging Example 137 As it has been pointed out in the introduction Magentix2 platform not only has as aims to pro vide a guaranteed communication mechanism to the programmer but also to provide
167. saje received in consumer agent by receiveACLMessage Hello I m the sender HearderValue 2 1 3 Magentix2 installation description Once Magentix2 has been installed the following folders are created e magentix root directory includes the executable files and folders required to launch and start the platform and services The main ones are the following which allows users to start and stop the Magentix2 platform Start Magentix sh and Start Magentix bat it launches the Qpid server and the plat form agents OMS SF TM and bridge agents Stop Magentix sh and Stop Magentix bat it stops Qpid and the platform agents OMS SF TM and bridge agents The commands needed to execute this script are 8 2 1 Installing Magentix2 Stop Magentix sh LICENSE txt includes the license under Magentix2 is distributed Magentix2 is licensed under the GNU LESSER GENERAL PUBLIC LICENSES RELEASE NOTES includes the changelog of the last releases of the platform magentix setup py and magentix setup exe configure magentix to be launched at first time configuration sub directory includes the Settings xml and loggin xml configuration files necessary to launch Magentix2 user agents docs includes the API in html format and the Magentix2 User manual in pdf format lib includes Magentix2 library an all additional libraries required by Magentix2 How to import this library in projects is
168. scheme can be attacked Therefore if the opponent asks a critical question the argument that supports this argumentation scheme remains temporally rebutted until the question is conve niently answered Argument Cases 6 Argumentative Agents 53 ARGUMENT CASE SOLUTION Argument Type JUSTIFICATION PROBLEM Conclusion Value Acceptability Status SOCIAL CONTEXT DOMAIN CONTEXT Dependency Relation Premises RECEIVED ATTACKS CASE Dd MMMM AAA a A PROPONENT OPONENT ID ID CRITICAL COUNTER ARGUMENTATION Role Role QUESTIONS EXAMPLES SCHEMES ValPref ValPref AAA AAA DISTINGUISHING po PREMISES Role ValPref Figure 6 2 Structure of an Argument Case Argument cases are the main structure that we use to computationally represent argumenta tion knowledge in Magentix2 concretely in the ArgumentCase java class of the Magen tix2 argAgents knowledgeResources package Their structure is generic and domain independent Figure 6 2 shows the generic structure of an argument case Argument cases have the three possible types of components that usual cases of CBR systems have the description of the state of the world when the case was stored Problem the solution of the case Conclusion and the explanation of the process
169. se the following dialogue tactics depending on the weight that it assigns to the elements of the support factor when it selects the best argument to bring up in each step of the argumentation dialogue e Persuasive Tactic the agent selects such arguments which similar argument cases were more persuasive in the past assigns more weight to the persuasiveness degree e Maximise Support Tactic the agent selects such arguments that have higher probability of being accepted at the end of the dialogue assigns more weight to the support degree e Minimise Risk Strategy the agent selects such arguments that have a lower probability of being attacked assigns more weight to the risk degree e Minimise Attack Tactic the agent selects such arguments that have received a lower number of attacks in the past assigns more weight to the attack degree e Maximise Efficiency Tactic the agent selects such arguments that lead to shorter argu mentation dialogues assigns more weight to the efficiency degree e Explanatory Tactic the agent selects such arguments that cover a bigger number of cases or argumentation schemes That is such arguments that are similar to argument cases that have more justification elements assigns more weight to the explanatory power As pointed out before the dialogue strategy that an agent follows determines the locution and content that it puts forward in each step of the dialogue Thus different strateg
170. seException Not allowed The role is played by some agents RoleNotExistsException roleName does not exist in unit unitName SameA gentNameException Invalid The TargetAgentName is the same than AgentName SameUnitException Invalid The Parent Unit is the same than Unit ServiceProfileNotFoundException Service profile not found in Jena DataBase ServiceURINotFoundException Service URI not found in Jena DataBase ServicesNotFoundException Services not found SubunitsInUnitException Not allowed There are subunits in unit Unit Name UnitExistsException Invalid Unit UnitName exists UnitNotExistsException Unit unitName does not exist VirtualParentException Not allowed The Parent Unit can not be changed VirtualUnitException Not allowed this is the virtual unit B Exceptions 173 Exception name Description VisibilityRoleException Not allowed The visibility of the role is pri vate and agent AgentName does not play any role in the unit unitName Table B 2 THOMAS Exceptions and associated messages Bibliography Argente E Botti V Carrascosa C Giret A Julian V and Rebollo M 2011 An Ab stract Architecture for Virtual Organizations The THOMAS approach Knowledge and Information Systems 29 2 379 403 Bordini R H bner J and Vieira R 200
171. showed in section 2 2 examples includes some examples of Magentix2 agents implementation src includes Magentix2 sources webapps includes all services required by THOMAS and Magentix2 It also includes a user web service example bin includes some executables needed by Magentix2 to run 2 1 4 Uninstalling Magentix2 Magentix2 is very simple to remove from one system The steps to uninstall are 1 Stop Magentix2 platform Stop Magentix sh 2 Delete Magentix2 installation directory Shttp www gnu org copyleft lesser html 2 Quick Start 9 2 2 Developing and executing a first agent This section explains step by step how to program a Magentix2 agent The images shown here correspond to the Eclipse IDE but everything should be similar in any other IDE Magentix2 li brary works with jdk1 7 which is available at http www oracle com technetwork java javase downloads index html The first step is to start Eclipse and create a new project MyFirstAgent The java library magentix2 2 1 0 jar with dependencies zip which can be found in the 1ib directory has to be included in the project as a referenced library Magentix2 platform and the agents running on it need a configuration folder with two files Settings xml and loggin xml Settings xml configures all the parameters related to the platform func tionality like MySQL parameters or how agents connect to the QPid broker Loggin xml is the configurati
172. sion of AgentSpeak L Rao 1996 and implements the operational semantics of that language It has been developed by Jomi F H bner and Rafael H Bordini Jason has been integrated in Magentix2 platform therefore we can program agents in AgentSpeak and run them on Magentix2 platform For examples and demos of how to program in AgentSpeak L please refer to the webpage of the Jason project http jason sourceforge net Jason Jason html 5 1 Programming BDI Agents Magentix2 integrates Jason providing two classes JasonAgent and MagentixAgArch Ma gentixAgArch manages the AgentSpeak L interpreter the reasoning cycle of the agent and how the agent acts and perceives to from the environment The JasonAgent class acts as a link between the AgentSpeak L interpreter and the platform Both classes can be modified and adapted to the desired needs but usually only MagentixAgArch would need to be modified in order to add external actions to the agent external actions are actions which affect the agent environment The code of how to create and execute a basic JasonAgent is shown below MagentixAgArch arch new MagentixAgArch JasonAgent agent new JasonAgent new AgentID bob src test 46 5 BDI Agents JasonAgents 47 java jasonTest 1 demo asl arch agent start In the code shown above first an instance of MagentixAgArch class called arch is created then a JasonAgent called agent is created in or
173. sors In line 63 the agent starts a synchronous conversation this is the execution of the agent will halt until the conversation ends The method startSyncConver sation is used in order to start a synchronous conversation This method requires the name of the initiator CFactory which will create a new conversation as a parameter The result of the conversation is stored in the variable response In the last line of the code the result of the conversation is shown on the console filter new MessageFilter performative PROPOSE CFactory talk new CFactory TALK filter 1 this A CProcessor always starts in the predefined state BEGIN We have to associate this state with a method that will be executed at the beginning of the conversation BeginState BEGIN BeginState talk cProcessorTemplate getState BEGIN class BEGIN Method implements BeginStateMethod 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 38 4 5 Creating a CFactory and its CProcessor public String run CProcessor myProcessor ACLMessage msg In this example there is nothing more to do than continue to the next state which will send the messag return PROPOSE EJ y BEGIN setMethod new BEGIN Method SendState PROPOSE new SendState PROPOSE class PROPOSE Method implements SendStat
174. ss which extends the class es upv dsic gti ia core SingleAgent Itisaextended class from BaseAgent The SingleAgent defines a new message reception method receiveACLMessage that performs blocking reception It receives a new message in blocked mode Then when the agent retrieves the message it is removed form the head of the agent s message queue Thus how to program a SingleAgent is the same as set the BaseAgent but now you have a reception method The following code shows how to implement a new singleAgent with the receiveACLMes sage method public void execute xx This agent has no definite work Wait infinitely the arrival of new messages x SENA d xx x receiveACLMessage is a blocking function its waiting a new ACLMessage ACLMessage msg receiveACLMessage System out println Mensaje received in this getName 18 3 1 Basic classes for building agents BaseAgent and SimpleAgent agent by receiveACLMessage msg getContent 0 catch Exception e logger error e getMessage DEDISTIS 3 1 3 Initialization Tasks Magentix2 platform uses log4j as a logging facility It was developed by the Apache s Jakarta Project Its speed and flexibility allows log statements to remain in shipped code while giving the user the ability to enable logging at runtime without modifying any of the application binaries Log4j can be initialized inside the
175. ssaging is available Thus the Sender Agent should play the role member before sending an organizational message to the Receiver Agents A and B If it does not play the required role it should acquire it by means of the AcquireRole service figure 8 11 omsProxy acquireRole member team 8 6 2 Building the Message e Build an organizational message Once the agent is inside the unit with an specific role it has to use the buildOrganizationalMessage to obtain the required organizational message specifying the identifier of the organization ACLMessage msg omsProxy buildOrganizationalMessage team 8 6 3 Completing Message e Add ACL message fields After the message is built it can add the fields of an ACLMes sage such as content performative or language msg setContent 6 3 msg setPerformative ACLMessage REQUEST msg setLanguage ACL 8 6 4 Sending the Message e Send an organizational message When a message is formed the message can be sent using the send method send msg or it reached a state of type send in CFactories class REQUEST_Method implements SendStateMethod 8 Virtual Organizations 137 4 public String run CProcessor myProcessor ACLMessage messageToSend 7 OMSProxy omsProxy new OMSProxy myProcessor 8 ACLMessage msg 9 String state WAIT 0 Le od 1 msg omsProxy buildOrgani
176. st new ServiceTools 49 50 Sr 52 53 54 55 56 57 58 59 60 61 62 8 Virtual Organizations 131 HashMap lt String String outputs new HashMap lt String String 20 st extractServiceContent requestResult outputs result Equation outputs get Result else if providersGroundingWSDL isEmpty System Add Tout pri V sp electro SEN ame EE Cut alate ition Service 3 4 HashMap lt String Object gt resultExecution st exe Double result cuteWebService providersGroundingWSDL get 0 agentInputs resultDouble Double resultExecution get Result Equation resultDouble toString else no providers for this service System pro Requester Agent Service Request Touti print Ihiau Y ASS SEN an AN O vidersi oUm cet ee Adait rOn Servicen Ss eo A GetService serviceProfile OWL S specification lt b Provider Agent Service Result Figure 8 8 Agent interaction protocol to request a service 132 8 5 Running THOMAS Example 8 5 Running THOMAS Example The examples folder of the Magentix2 packages contains a basic THOMAS example In this example there are four agents Initiator This agent build the organizational framework needed First it registers the Calculator and School organizations Then it registers the roles needed in each orga
177. starting point to enter in the system as mentioned before see section 8 1 2 In the forum unit there are the following roles e Moderator It acts as supervisor and moderator of the forum Its role attributes are position supervisor accessibility internal visibility private e Participant It participates in the forum Its role attributes are position subordinate accessibility internal visibility public 110 8 1 Overview of THOMAS framework DOC irt A liigen m plas Ai supervisor Balti sa dodi re A blesidend member creator N Aabderater gt creator Figure 8 2 Organizational view of the form example organizations roles and agents The fraternity unit has two roles e President It acts as a president of the fraternity and it is in charge of adding delet ing norms and roles Only one agent can play this role Its role attributes are posi tion creator accessibility internal visibility private e Brother It represents a member of the fraternity in fact all the participants of the fraternity should play this role Its role attributes are position member accessibil ity external visibility public The panel unit has three different roles e Moderator It should be played by an unique agent which also plays the role moderator in the forum unit It is in charge of adding new norms to the unit It can not add new roles Its rol
178. support flexible interaction protocols and conversations indirect 2 1 2 Manual Structure communication and interactions among agent organizations Moreover other important aspects cover by the Magentix2 project are the security issues 1 2 Manual Structure In the following chapters how Magentix2 platform must be installed configured and used for programming agents is explained Specifically chapter 2 clarifies how Magentix2 can be fully installed in only one host in a quickly and easy way Furthermore it is also explained how to develop and to execute simple Magentix2 agents Chapter 3 is about programming aspects in Magentix2 Specifically it is possible to consult the basic classes of agents that the platform provides and the main issues related with agent communication The advanced conversational agents class is explained in chapter 4 These agents enable the participation on simultaneous conversations based on interaction protocols In chapter 5 how to program BDI agents in Magentix2 is explained Thus Magentix2 provides the classes jasonAgent and MagentixAgArch which enables programming agents in AgentS peak and run them in the Magentix2 platform The argumentation API provided by Magentix2 is shown in chapter 6 This API allows agents to engage in argumentation dialogues to reach agreements about the best solution to a problem Chapter 7 explains how agents can share information in an indirect way by mean
179. t is identified in the protocol parameter of the message with the FIPA request value The messages exchanged are 1 Request which contents the request 2 Agree or Refuse when the agent accepts the request or rejects it respectively 3 Failure when the previous message was an Agree and an error happened during the process 4 Inform done when the previous message was an Agree and the process ends success fully 5 Inform result when the previous message was an Agree the process ends successfully and there is also a result The protocol early terminates if e The initiator send to the responder a message explicitly CANCEL instead of the next initiator e The responder responds negatively to REFUSE NOT UNDERSTOOD or FAIL URE performative 4 2 2 FIPA Query This protocol allows agents to request other agents to query whether a particular proposition is true or false query if and to query for some identified objects query ref Depending on the type of request the messages can be 1 Query If or Query Ref it contents the request 2 Agree when the agent accepts the request 3 Refuse in the case the agent rejects the request 4 Failure in the case an error occurred during the process 4 Advanced conversational agents CAgents 31 5 Inform T F when the previous message was an Agree and the first message was a Query If 6 Inform Result when the previous message was an Agree and the first message
180. t the developer has to write the source code to process trace events The source code in Section 7 6 1 lines 59 to 79 shows an example of trace event handler In this case the received trace event is processed attending to its tracing service 7 3 Tracing Services Agents which are interested in sharing their trace events offer them as tracing services Agents publish their available tracing services and other agents can request those tracing services in which they are interested As a consequence only those trace events which have been requested by an agent in the system are traced and agents only receive those trace events which they have previously requested In this way trace event traffic is reduced and agents do not have to process trace events which they are not interested in In order to register available tracing entities and services as well as to manage subscriptions to tracing services the platform must have a Trace Manager running In Magentix2 the Trace Manager is a single agent the TraceManager class inherits from BaseAgent which must be running in a host of the platform The trace manager can be launched in any host where Magentix2 is running by invoking the corresponding constructor method TraceManager AgentID tmAid An example of how to launch the Trace Manager can be found in the source code of the example in Section 7 6 3 in line number 29 of the main application source code TraceManager tm
181. tart outInAgent start In the code shown above when the bridge agents are created lines 11 12 they receive a new AgentID as argument This new AgentID gets only one argument the name of the agent Platform agents like bridge agents must always have a well known name For bridge agents the names must be BridgeAgentInOut and BridgeAgentOutIn respectively In line 8 the connection of the agents to the platform is set using the method Agent sCconnection connect The parameters for this connection are specified in the configuration file Settings xml The method Agent sConnection connect should not be called if the platform secu rity is enabled Once the agents have been created with the desired parameters both are started lines 13 amp 14 This Java program has to be manually executed when starting Magentix2 platform 10 4 2 Running OMS and SF Agents OMS and SF agents provide all the services of Thomas framework These agents can be run ning on any host they don t have to be in the same host where the QPid broker or other agents are running A Java program has to be written and executed in order to launch OMS and SF agents The following code shows how to launch these agents import es upv dsic gti ia architecture Monitor import es upv dsic gti ia core AgentID import es upv dsic gti ia core AgentsConnection import es upv dsic gti ia organization OMS import es upv dsic gti ia organiza
182. tates when these incoming messages with their associated locution are received Therefore the transitions between states depend on the locutions that the agent can use in each step of the dialogue The states of the argumentation dialogue are described as follows 1 Begin this is the start state of the argumentation protocol 6 Argumentative Agents 63 no commit why open dialogue ie finish_dialogue a accept already E dialogue 4 open dialogue quier dialog P4 pun a s Begin open Propose Central c V withdraw dialogue P E Z i t accept 7 withdraw_dialogue J WN Cow oe P a N Es d NR N finish dialogue y y T y query positions y finish dialogue VA K lt Send et finish_dialogue position positions JP setallpositions timeout timeout A send_position Y Solution en rn 7 bu Y NUT i A pem Se ena timeout wes md no commit N N x d N Attack2 rene Sail N Figure 6 3 Argumentation Protocol 2 Open when the agent is initialised it remains in this state waiting for an OPENDIA LOGUE locution The agent will move back to this state when the dialogue has finished The OPENDIALOGUE locution inform the agent that a new dialogue to solve a problem has started Also when an agent received the D E locution in this state it must shutdown its execution 3 Enter in this state the agent will retrieve such c
183. te isRole brother fraternity hasAccessibility brother fraternity external hasVisibility brother fraternity public hasPosition brother fraternity member isRole president fraternity hasAccessibility president fraternity internal hasVisibility president fraternity private hasPosition president fraternity creator isRole reporter panel hasAccessibility reporter panel external hasVisibility reporter panel private hasPosition reporter panel member isRole follower panel hasAccessibility follower panel external hasVisibility follower panel public hasPosition follower panel member isRole moderator panel hasAccessibility moderator panel internal hasVisibility moderator panel private hasPosition moderator panel creator Agent Descriptions isAgent vb isAgent bigBrother isAgent ea isAgent sv playsRole vb participant virtual 164 A 3 Predicates of the forum example playsRole bigBrother participant virtual playsRole ea participant virtual playsRole sv participant virtual playsRole vb participant forum playsRole bigBrother moderator forum playsRole bigBrother moderator panel playsRole ea president fraternity playsRole sv brother fraternity playsRole ea participant forum playsRole ea follower panel playsRole sv reporter panel
184. ters are not specified in the Settings xml file it is not feasible to use the connect method without parameters An example of the Settings xml file could be lt l Propert ieS puo lowelkewe gt entry key host gt localhost lt entry gt entry key port gt 5672 lt entry gt entry key vhost gt test lt entry gt entry key user gt guest lt entry gt entry key pass gt guest lt entry gt entry key ssl gt false lt entry gt e Specifying all the parameters when calling connect Example AgentsConnection connect localhost 5672 test guest guest false e Specifying only the lt qpidhost gt parameter leaving the rest as default parameters In the current example case the default values will be 5672 test respectively Example 5 75 5 guest guest false AgentsConnection connect host domain 3 1 5 Running Agents Once agents are implemented they can be instantiated and launched Please note that the platform do not allow different agents with the same name In order to instantiate an agent an agent ID must be also created as follows e AgentID String Identifier where Identifier is the agent name Examples of creating a new instantiation 3 Basic Programming 21 SenderAgent agentl new SenderAgent new AgentID sender ConsumerAgent agent2 new ConsumerAgent new AgentID consumer Once instantiated agent
185. the abstract meth ods of the Argumentation Participant protocol The decisions and the actions to perform in each state of the argumentation protocol are codified in these methods The main methods to implement are shown in Table 6 9 Due to the complexity of defining a new argu mentative agent the user should consider to use the ArgCAgent java class of the example as a base to implement the behaviour of a new argumentative agent 72 6 3 Programming Argumentative Agents Method Description doAccept actions to perform and send an ACLMessage accepting the other agent s position or argument doAssert try to assert a support argument to respond to the WHY received previously doAttack actions to perform to generate an attack argument against an attack or assert received doDie actions to perform when the message with locution DIE is received doEnterDialogue evaluates if the agent can enter in the dialogue offering a solution doFinishDialogue actions to be executed when the dialogue has to finish doGetPositions get the positions of the agents in the dialogue sent by the Commitment Store as an object doMyPositionAccepted actions to perform when the position of the agent has been accepted doNoCommit creates an ACLMessage to send with the locution NOCOMMIT doOpenDialogue takes the domain case to solve and the dialogue ID from the received ACLMessage given doPropose proposes a position to defen
186. the message is defined by its header e Receive This state must be preceded by a Wait state In this state the agent receives a message Each Receive state manages messages with a specific set of headers CFactories can be initiator or participant the use of each type depends on the role the agent will play in the conversations On the one hand initiator CFactories start conversations when directed by agent s logic i e they do not depend on external stimuli in order to start a new conversation On the other hand participant CFactories start a CProcessor when they receive a message with the appropriate message parameters These parameters are specified using a message filter associated to the participant CFactory The transition between two states occurs when the agent receives or sends a message related to that specific conversation CProcessors are in charge of making these transitions as well as executing the actions of each state of the conversation When a CProcessor is created it has a copy of the graph specified in the CFactory that created the CProcessor During the conversation the CProcessor will execute the actions of the state the conversation is currently at and it will change the state of the conversation as new messages are sent and received As each CProcessor has its own graph an ongoing conversation can be 4 Advanced conversational agents CAgents 33 Receive Failure Receive Inform done Figure 4 1
187. ting oe oe 3 3 2 Examples In the examples folder of the Magentix2 packages there are some basic interaction protocols examples e Request this example follows the FIPA Request protocol In this example two agents are created One agent plays the responding role by simulating a hospital which listens emergency calls The other agent simulates an accident witness When the witness see an accident sends a help message to the hospital The hospital checks if the accident is placed in the action area and if it could attend it e ContractNet this is an example where the FIPA ContractNet protocol is followed In this example two types of agents are created One type of agents plays the responding role dealers The other type a single agent plays the initiator role buyer The buyer sends a purchase request to each dealer agent Each dealer agent answers the bid accord ing her preferences and waits for the buyer decision The buyer chooses one offer and informs the specific dealer and also sends a reject message to the rest of the dealers CHAPTER 4 Advanced conversational agents CAgents 4 1 Interaction ProtocolS 28 4 0 How to implement a FIPA Protocol 29 4 3 Programming CAgents 32 44 Hello World CAgent e 34 4 5 Creating a CFactory and its CProcessor 36 4 6 SendingErrors eee 39 4 7 Using a CFactory Template
188. tion SF import es upv dsic gti ia core AgentID public class Main public static void main String args throws Exception AgentsConnection connect 156 10 4 Advanced platform services OMS agentOMS OMS getOMS SF agentSF SF getSF agentOMS start agentSF start In the code shown above the agents OMS and SF are created lines 11 12 The creation of these agents does not require any parameter In line 10 the connection of the agents to the platform is set using the method Agent sConnec tion connect The parameters for this connection are specified in the configuration file Settings xml The method Agent sConnection connect should not be called if the platform security is enabled Once the agents have been created with the desired parameters both are started lines 13 amp 14 This Java program has to be manually executed when starting Magentix2 platform APPENDIX A BNF Syntax of the Normative Language ALL Grammari 2 0 ed ae a eee 157 A 2 Predicates Summary eee 160 A 3 Predicates of the forum example 162 A 1 Grammar ee 6699 norm id deontic target action activation expiration id stringConstant 6699 deontic o TEL se p 66 99 target lt agentName roleName ineconstant gt OMSPositions
189. tion in the unit or the parent unit NotInUnitAndNotCreatorException Not allowed The Agent AgentName is not inside the unit unitName and does not play any role with position creator NotInUnitOrParentUnitException Not allowed Agent AgentName is not in side the unit or parent unit NotMemberOrCreatorInUnitException Not allowed The Agent AgentName does not play any role with position member or cre ator in unit unitName 172 B 2 THOMAS Exceptions Exception name Description NotPlaysAnyRoleException The agent does not play any role NotPlaysRoleException Not allowed The agent AgentName does not play the role RoleName NotSupervisorOrCreatorInUnitException Not allowed The Agent AgentName does not play any role with position supervisor or creator in unit UnitName NotValidIdentifierException Identifier not allowed It uses any reserved word or invalid character OnlyPlaysCreatorException Not allowed The agent is only playing the role creator ParentUnitNotExistsException Parent unit parentUnitName does not exist PlayingRoleException Not allowed The agent AgentName is al ready playing the role RoleContainsNormsException Not allowed The role contains associated norms RoleExistsInUnitException Not allowed Role RoleName is already registered in the unit RoleInU
190. tions can be generated from the selected domain cases the agent will be able 74 6 3 Programming Argumentative Agents to defend a position in the dialogue We consider a valid solution any domain case from the domain CBR with one or more solutions and with a similarity degree greater than the given threshold Moreover the agent makes a query to its argumentation CBR for each possible position to defend With these queries the suitability degree of the positions is obtained This degree represents if a position will be easy to defend based on past similar argumentation experiences Then all possible positions to defend are ordered from less to more suitability degree When the agents have a position to defend a proposed solution these positions are stored by the commitment store such that other agents can check the positions of all dialogue participants Every agent tries to attack the positions that are different from its position The argumentation process consists on a series of steps by which agents try to defend its positions by generating counter examples and distinguishing premises for the positions and arguments of other agents A counter example for a case is generated by retrieving from the domain case base another case that matches the features of the former but has a different conclusion Similarly distinguishing premises are computed by selecting such premises that the agent has taken into account to generate its p
191. to be specified as a provider in the OWL S specification The provider is defined following the provider owl ontology located in the webapps folder of the Apache Tomcat in Ma gentix2 installation folder concretely in webapps ontologies The parameters of the provider are entity id entity type agent or organization communication lan guage performative to use in the petition An example of this structure is shown below 1 2 lt profile contactInformation gt 3 lt provider Provider rdf ID AdditionAgent gt 4 lt provider entityID rdf datatype xsd string AdditionAgent lt provider entityID gt 5 lt provider entityType rdf datatype xsd string gt Agent lt provider entityType gt 6 lt provider language rdf datatype xsd string FIPA ACL lt provider language gt 7 lt provider performative rdf datatype xsd string REQUEST lt provider performative gt 8 lt provider Provider gt 9 lt profile contactInformation gt If the provider is a web service the corresponding grounding has to be specified as standard specification of the OWL S services including its WSDL document URL to execute the service RegisterService http url service owl Service Registered http url service owl ServiceProfile Agent Figure 8 5 Agent interaction protocol to register a service Thus the agent can make a call to register a service specifying the url of the service OWL S specificat
192. to send to the Commitment Store createMessage Creates and returns an ACLMessage with the message arguments Messages are managed by the main execution method of cAgent s and are sent and received in the corresponding send and receive states see Section 4 generateAttack Argument Returns an attack Argument against the given argument of the given agent identifier generateCEAttack Returns a counter example attack Argument against the agent of the given agent identifier and its given premises generateDPAttack Returns a distinguishing premises attack Argument against the agent of the given agent identifier and its given premises generatePositions Returns an ArrayList of Position with all generated positions to solve the specified problem ordered from more to less suitability degree to the problem generateSupportArguments Returns an ArrayList ofsupport Argument for the given Position against the given agent identifier getDifferentPositions Returns an ArrayList of positions that are different from the defended position and also are not asked yet getDistinguishingPremises Returns an ArrayList with distinguishing premises between the HashMaps given as arguments getUsefulPremises Returns a HashMap of the useful premises of the agent of the current problem to solve the premises of the Position that are specified in the problem characterisation updateCBs Adds the final solution to the curre
193. ts FinalStateMethod public void run CProcessor myProcessor ACLMessage responseMessage messageToSend copyFromAsTemplate myProcessor getLastReceivedMessage myProcessor ShutdownAgent FINAL setMethod new FINAL Method talk cProcessorTemplate registerState FINAL talk cProcessorTemplate addTransition RECEIVE FINAL talk cProcessorTemplate addTransition PROPOSE FINAL The template processor is ready We add the factory in this case as a participant one this addFactoryAsInitiator talk Finally Harry starts the conversation ACLMessage response this startSyncConversation TALK System out println this getAid name Sally tell me response getPerformative response getContent 4 6 Sending Errors It is possible that a CAgent is unable to send a message due an error in the transport layer In this case the conversation will automatically jump to the SENDING_ERRORS state which is predefined to shutdown the agent However the agent programmer can override this state for their conversations to perform any other action and manage transport layer errors class SENDING_ERRORS_Method implements SendingErrorsStateMethod Override public String run CProcessor myProcessor ACLMessage errorMessage 40 4 7 Using a CFactory Template return SHUTDOWN 4 7 Using a CFactory Template Defin
194. ts and roles Allocate Deallocate roles to other agents Change the hierarchical relations between organizations Acquire other roles Request information about the roles played by other agents Request information about organizations and its elements Member Flat Team Send organizational messages These messages will be received for all organization members Register deregister roles Allocate deallocate roles to other agents Acquire another role Request information about the roles played by other agents Request information about organizations and its elements Supervisor Hierarchy Send organizational messages These messages will be received for all organization members Register Deregister units and roles Allocate Deallocate roles to other agents Change the hierarchical relations between organizations Acquire other roles Request information about the roles played by other agents Request information about organizations and its elements Subordinate Hierarchy Send organizational messages These messages will be received for all supervisor agents of the organization Acquire other roles Request information about the roles played by other agents Request information about organizations and its elements Table 8 1 Agent behavior depending of its position Visibility Accessibility Behavior Public External Role fully accessible and
195. ts implement Then the implementation details of the API are shown Finally a guide to run argumentative agents and an example of a call centre application are provided 6 1 Argumentation Framework Argumentative agents implement a case based argumentation framework to generate argu ments to select the best argument to put forward taking into account their social context and to evaluate arguments in view of other arguments proposed in the dialogue Also they can use different dialogue strategies to exchange information and engage in the argumentation process In this section we briefly introduce the framework and the dialogue strategies that Magentix2 argumentative agents use For a more detailed explanation we refer the reader to Heras 2011 49 50 6 1 Argumentation Framework 6 1 4 Framework Architecture Magentix2 argumentative agents can use a computational case based argumentation frame work to manage argumentation processes This section outlines the main components of this framework We have three types of knowledge resources that the agents can use to generate select and evaluate arguments by using our framework These resources are implemented in Magentix2 as java clases see 6 2 A database of argumentation schemes with a set of schemes with the structure proposed in Walton et al 2008 which represent stereotyped patterns of common reasoning in the application domain where the framework is implemented An argum
196. ublic static String BEGIN BEGIN public static String PROPOSE PROPOSE public static String WAIT WAIT public static String RECEIVE RECEIVE public static String RECEIVE FINAL protected void doBegin CProcessor myProcessor ACLMessage msg Sys temvout print lin rd sits ehe DEJN Stace class BEGIN_Method implements BeginStateMethod public String run CProcessor myProcessor ACLMessage msg doBegin myProcessor msg return PROPOSE F Ea y We want the user to implement his her method here protected abstract void doPropose CProcessor myProcessor ACLMessage messageToSend class PROPOSE Method implements SendStateMethod 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 4 Advanced conversational agents CAgents public String run CProcessor myProcessor ACLMessage messageToSend doPropose myProcessor messageToSend Je Mas 1 as ee anall ance kasme DRY elo acoso Te ae E C 43 then we can set the return type of the doRequest method to String and use it as a return value for this method return WAIT We want the user to implement his her method here protected abstract void doReceive CProcessor myProcessor ACLMessage msg class RECEIVE Method implements ReceiveStateMethod public String run CPr
197. uestAppData with the JSON object as parame ter function requestAppData data mposta redirect php datae functeson result talent Data Loaded JSON parse result json This function calls the jquery function post with the following parameters Redirect php is the php script that will redirect our HTTP POST to our HTTP interface Data is the JSON object previously shown The next parameter is the function that will be executed when we receive the reply to our request in this case we will show the result The last parameter is the type of the data For more information about jquery and the method jquery post please refer to http jquery com MarketA gent is a very simple agent it receives a query from our webpage and sends a product 146 9 3 Example encapsulated in a JSON object In the following code the MarketAgent receives the JSON containing the query and transforms it into a Java object ACLMessage msg receiveACLMessage XStream xstream new XStream new JettisonMappedXmlDriver xstream alias jsonObject JSONMessage class JSONMessage query JSONMessage xstream fromXML msg getContent Once the JSON object is a Java object it is possible to work easily with it The MarketAgent does some calculations with the input data and prepares the response XStream xstream2 new XStream new JsonHierarchicalStreamDriver GOverride public HierarchicalStreamWriter createWriter
198. ur phone number msg setProtocol fipa request msg setSender getAid The agent creates the CFactory that creates processors that initiate REQUEST protocol conversations In this example the CFactory gets the name TALK we don t add any additional message acceptance criterion other than the required by the REQUEST protocol CFactory talk new myFIPA REQUEST newFactory TALK msg 1 this 5000 this addFactoryAsInitiator talk finally the new conversation starts Because it is synchronous the current interaction halts until the new conversation ends 34 21 22 23 42 4 8 Creating a CFactory Template this startSyncConversation TALK CFactory templates are useful for reusing code It is possible to create templates of other IP or modify the existing ones in order to adapt them 4 8 Creating a CFactory Template This section explains how to implement a new CFactory template In the following example we are going to implement a template for the CFactory shown in section 4 5 First the states are defined it is in this moment when it is possible to define default methods and choose which methods are abstract and therefore mandatory to implement for the user The definition of the states is shown below public abstract class MyTemplate We can define a set of static values for referencig sates p
199. ure public Argument long id Conclusion conclusion int timesUsedConclusion String promotedValue SupportSet supportSet DependencyRelation proponentDepenRelation where conclusion is the conclusion of the argument timesUsedConclusion stores the number of times that this conclusion has been used promot edValue is the value that the agent wants to promote with this argument support Set is a set of elements that justify the argument and proponentDepenRelation is the dependency relation power authori sation or charity established between the proponent of the argument and the opponent that the 52 6 1 Argumentation Framework argument is addressed Thus in our case based argumentation framework arguments promote values These values can be personal goods e g efficiency accuracy etc or also social goods inherited from the agents dependency relations Preferences over values can determine the reasons that lead an agent to propose a specific argument or to accept or refuse an argument from another agent The support set is a knowledge resource of the Magentix2 argAgents knowledgeResources package represented by the SupportSet java class and can consist of different elements depending on the argument purpose On one hand if the argument justifies a potential solution for a problem the support set is the set of features premises that represent the context of the domain where the argument has been put forward those premise
200. ussion in the argumentation dialogue WHY with this locution an agent challenges the position or the argument of another agent asking it for a support argument NOCOMMIT with this locution an agent withdraws its position as a solution for the problem under discussion in the argumentation dialogue ASSERT with this locution an agent sends to another agent an argument that supports its position ACCEPT with this locution an agent accepts the argument or the position of another agent ATTACK with this locution an agent challenges the argument of another agent there are other allowed locutions to manage the life cycle of argumentative agents and get information from the commitment store FINISHDIALOGUE is a locution to inform an agent that it must perform the necessary actions if any before withdrawing from the dialogue DIE is a locution to inform an agent that it must shutdown its execution GETALLPOSITIONS is a locution to request the commitment store the list of available positions at a certain step of the dialogue The commitment store uses the same locution to answer this request Figure 6 3 shows the state machine that defines the behaviour of an agent that follows the Magentix2 Argumentation Participant protocol In the figure dotted states repre sent wait states where the argumentative agent waits for messages from other agents or the commitment store Also dotted lines represent transitions between s
201. ves back to the state Central Send Position an agent reaches this state when it has received a locution FINISHDI ALOGUE to start the actions to leave the dialogue when it has proposed yet a position Here the agent sends its current position to update the commitment store information and avoid possible inconsistencies After that the agent moves to the state Solution to wait for the final solution applied to solve the problem 66 6 3 Programming Argumentative Agents 16 Solution when the dialogue has finished the final solution to apply is reporter to all dialogue participants When agents receive this information they update their case bases with the data learnt from the dialogue and move back to the state Open 17 Die this is the final state of the argumentation protocol Agents move to this state when they receive the locution DIE and shutdown their execution 6 3 Programming Argumentative Agents 6 3 1 How to run Magentix2 Argumentative Agents Magentix2 provides a default implementation of an argumentative agent that can be run from the Magentix2 examples bin directory Thus the user can execute the Start Argumentation Example sh script that launches the default argumentation example cd Magentix2 examples bin sh Start ArgumentationExample sh If the user wants to use a different configuration of the parameters of the example it is nec essary to modify the source code of the example see Table 6 3
202. vice S Outputs Service registered ServiceURL 8 Exceptions DBConnectionException AlreadyRegisteredEx n Bb ception InvalidServiceURLException ServicePro z fileNotFoundException InvalidDataTypeException MySQLException Description Deregisters a complete service gt Inputs ServiceProfile DeregisterService Outputs Service ServiceProfile Deregistered 122 8 2 Programming agents which use THOMAS Exceptions ServiceURINotFoundException ServicePro fileNotFoundException DBConnectionException MySQLException Description Removes a provider agent organization or web ser 5 vice of a service T RemoveProvider Inputs ProviderName that can be a ServiceProfile e lt ProviderName or GroundingID Outputs Provider or grounding ProviderName removed Exceptions ServiceProfileNotFoundException DBConnec tionException Description Gets the OWL S description of the service Inputs ServiceProfile GetService Outputs OWL S specification of the service e Exceptions ServiceProfileNotFoundException DBConnec A 3 tionException MySQLException Description Searches a service Inputs Inputs of the service to search Outputs of the service to search SearchService Keywords of the service to search Outputs lt ServiceProfile Weigth gt Exceptions DBConnectionException InvalidDataTypeExce
203. vices ooooooooooo o 78 7 4 Domain Independent Tracing Services 83 7 5 Customizable Trace Support 87 7 6 Example TraceDaddy 88 This chapter describes the Tracing Service Support available in Magentix2 This Tracing Ser vice Support allows agents in a Multiagent System MAS share information in an indirect way by means of trace events Before describing the API provided by Magentix2 to share tracing information the following sections will present TRAMMAS the trace model which was followed to incorporate event tracing facilities to Magentix2 T 1 Trace Model and Features The trace event model incorporated to Magentix is described in detail in Burdalo et al 2010 This section will comment briefly the main characteristics of the model and those of its features which have been incorporated to the platform The trace model described in Burdalo et al 2010 offers any entity in the system active or passive the possibility to share information in the form of trace events with other entities in the system From the point of view of the trace model entities in the system are seen as tracing 75 76 7 1 Trace Model and Features entities this is entities which are able to generate and or receive trace events Trace events are offered by tracing entities as different tracing services which can be requested by interested tracing entities when they want to receive th
204. vices These domain independent tracing services provide information related to tracing services be ing published by tracing entities in the system For instance a generic agent may need to be noticed when a specific tracing service is being offered or when another agent is not shar ing certain tracing information anymore These domain independent tracing services and the 86 7 4 Domain Independent Tracing Services Table 7 7 Agent s lifecycle related domain independent tracing services NEW_AGENT A new agent Agent Id executing in a host host was registered in the system tService NEW_AGENT 4 originEntity system host content AgentId AGENT DESTROYED An agent Agent Id executing in a host host was destroyed tService AGENT DESTROYED 5 originEntity system host content AgentId Table 7 8 Agent s messaging related domain independent tracing services MESSAGE SENT A FIPA ACL message was sent from OriginAgentIdtoDestinationAgentId tService MESSAGE SENT 6 originEntity OriginAgentId content DestinationAgent ld MESSAGE SENT DETAIL A FIPA ACL message was sent from OriginAgentld The difference with MESSAGE SENT is that MESSAGE SENT DETATIT trace events include the ACL message they refer to tService MESSAGE SENT
205. w to use domain independent tracing services to follow other agents activities and to make decisions according to that activity In this case a Daddy agent listens to his sons Boy agents while they are playing and when one of them starts crying he proposes them to take them to the park When both children agree daddy and his sons leave the building and the application finishes As the agents use only the trace events related with the agents life cycle and message detail the optimal trace level is defined with the mask value 1001000100 see Figure 7 1 lexcept life cycle that will be always generated 7 Tracing Service 89 e Initialization DADDY Requests to the NEW_AGENT tracing service in order to know when children ar rive Prints on screen that he intends to read the newspaper BOYS Bobby and Timmy Print on screen their name and age e Execution DADDY Each time a NEW_AGENT event is received Daddy requests the tracing service MESSAGE SENT DETAIL in order to listen to what that agent says Each time a MESSAGE_SENT_DETAIL trace event is received Daddy prints its content on screen and checks if the content of the message is equal to GUAAAAAA If so Daddy cancels the subscription to MESSAGE_SENT_DETAIL tracing ser vices and sends ACL request messages to both children to propose the go to the park When both childre have replied with an AGREE message Daddy agent prints it on screen and ends
206. whose identifier is receiver with the text Hello I m sender Building a ACLMessage ACLMessage msg new ACLMessage ACLMessage REQUEST msg setReceiver receiver msg setSender this getAid msg setLanguage ACL msg setContent Hello I m getName Sending a ACLMessage send msg 3 2 3 Receiving Messages Whenever a message is posted in the message queue of an agent this agent is notified by the onMessage ACLMessage msg method This method allows agents to receive any message automatically Note that agents can also keep all received messages in an internal list or queue for reading them later Agent programmers must overwrite the onMessage method when implementing a new agent in order to process received messages For instance public void onMessage ACLMessage msg 24 3 2 Agent Communication When a message arrives it is shown in the screen logger info Mensaje received in this getName agent by onMessage msg getContent 3 2 4 External Communication An external agent is any agent not running over Magentix2 platform but communicating to any of the agents running on Magentix2 In this sense Magentix2 implements the FIPA HTTP message transport protocol by means of two special Magentix2 agents e BridgeAgentInOut this agent is implemented in the es upv dsic gti_ia core BridgeAgentInOut class This agent is in charge of receiv
207. zationalMessage team 2 messageToSend copyFromAsTemplate msg 3 4 messageToSend setPerformative ACLMessage REQUEST 5 messageToSend setLanguage ACL 6 messageToSend setContent 6 3 7 8 catch THOMASException e 9 e printStackTrace 20 state FINAL 21 22 return Staten 23 24 8 7 Organizational Messaging Example The examples folder of the Magentix2 packages contains an Organizational Message example This example shows an scenario with THOMAS organizations and CAgents that make use of organizational messaging This case consists of the following two units e Calculator Team type organization where its agents send Organizational Messages to calculate the sum of the transaction carried out by its agents e External Flat type organization whose unique purpose is that one of its agents tries to send a Organizational Message to Calculator organization The agents involved in this case and its features are described below 138 8 7 Organizational Messaging Example e Creator Agent who plays the Creator role with creator position within Calculator or ganization whose purpose will be to create the entire organizational structure organiza tion and roles In addition it tries to send an Organizational Message to the Calculator organization requesting some calculation using two numbers e Display Agent who plays the Manager role with member position within Calculator organization wh
208. zeMessage getContent O 36 4 5 Creating a CFactory and its CProcessor 4 5 Creating a CFactory and its CProcessor The code shown in this section corresponds to the code located in examples src myFirstCPro cessorFactories Harry java The CFactory shown here corresponds to the one shown in figure 4 3 Send Purpose Wait Receive Final 6 6 REIP Figure 4 3 myFirstCProcessorFactories example In order to create a CProcessor first it is necessary to define the states and the transitions that compose the graph associated to the CProcessor This can be done in the execution method of the agent Every conversation starts with a begin state called BEGIN In the first line of the code below a new CFactory is created The parameters passed to the constructor are the CFac tory s name a message filter that will determine which messages will make this CFactory to start a new CProcessor acting as a conversation how many CProcessors this CFactory can man age simultaneously and finally a reference to the agent which owns the CFactory Specifically this CFactory called TALK will create the CProcessor when the agent receives messages with propose performative and it can only manage one CProcessor at a time When a CFactory is created it has already a CProcessor template predefined by default This template is from new instances of CProcessor will be created This default CProcessor template has to be mod ified by the user in order to create
Download Pdf Manuals
Related Search
Related Contents
Rotel RA970BX User's Manual User`s Manual for the M5-1003 DVI/USB/RS-232 and Audio ダウンロード Copyright © All rights reserved.
Failed to retrieve file