Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
A comprehensive collection of Agent Skills for context engineering, multi-agent architectures, and production agent systems.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
skills/bdi-mental-states/references/framework-integration.md
1# BDI Framework Integration Patterns23Integration patterns for connecting BDI ontology with executable agent frameworks.45## SEMAS Rule Translation67Map BDI ontology constructs to SEMAS production rules.89### Ontology-to-Rule Mapping1011| BDI Construct | SEMAS Element | Example |12|---------------|---------------|---------|13| Belief | HEAD fact | `belief(agent_a, store_open)` |14| Supporting beliefs | CONDITIONALS | `[CONDITIONALS: time(weekday)]` |15| Desire generation | TAIL action | `generate_desire(agent, goal)` |16| Intention commitment | TAIL action | `commit_intention(agent, goal)` |17| Plan specification | TAIL action | `create_plan(agent, plan_id)` |1819### Rule Templates2021**Belief triggers desire formation:**22```prolog23[HEAD: belief(Agent, Fact)] /24[CONDITIONALS: context_condition(Agent, Context)] »25[TAIL: generate_desire(Agent, DesiredState)].26```2728**Desire triggers intention commitment:**29```prolog30[HEAD: desire(Agent, Goal)] /31[CONDITIONALS: belief(Agent, SupportingFact1),32belief(Agent, SupportingFact2)] »33[TAIL: commit_intention(Agent, Goal)].34```3536**Intention triggers planning:**37```prolog38[HEAD: intention(Agent, Goal)] /39[CONDITIONALS: goal(GoalSpec)] »40[TAIL: create_plan(Agent, PlanId)].41```4243**Plan triggers execution:**44```prolog45[HEAD: plan(Agent, PlanId)] /46[CONDITIONALS: ready_to_execute(Agent)] »47[TAIL: execute_plan(Agent, PlanId)].48```4950### Complete SEMAS Example5152```prolog53% ============================================================54% GROCERY SHOPPING SCENARIO55% ============================================================5657% Phase 1: Belief formation from world state58[HEAD: perceive(agent_a, store_open)] /59[CONDITIONALS: time(weekday_afternoon)] »60[TAIL: add_belief(agent_a, store_open)].6162% Phase 2: Desire generation from belief63[HEAD: belief(agent_a, store_open)] /64[CONDITIONALS: belief(agent_a, needs_groceries)] »65[TAIL: generate_desire(agent_a, buy_groceries)].6667% Phase 3: Intention commitment from desire68[HEAD: desire(agent_a, buy_groceries)] /69[CONDITIONALS: belief(agent_a, has_shopping_list),70belief(agent_a, store_open),71belief(agent_a, has_transportation)] »72[TAIL: commit_intention(agent_a, buy_groceries)].7374% Phase 4: Plan creation from intention75[HEAD: intention(agent_a, buy_groceries)] /76[CONDITIONALS: goal(complete_shopping)] »77[TAIL: create_plan(agent_a, shopping_plan)].7879% Phase 5: Plan execution80[HEAD: plan(agent_a, shopping_plan)] /81[CONDITIONALS: preconditions_met(shopping_plan)] »82[TAIL: execute_task(agent_a, drive_to_store),83execute_task(agent_a, select_items),84execute_task(agent_a, checkout),85execute_task(agent_a, return_home)].8687% Phase 6: World state update88[HEAD: task_complete(agent_a, checkout)] /89[CONDITIONALS: items_purchased(agent_a)] »90[TAIL: update_world_state(has_groceries),91remove_desire(agent_a, buy_groceries),92remove_intention(agent_a, buy_groceries)].93```9495### Python Translation Layer9697```python98from rdflib import Graph, Namespace, RDF99100BDI = Namespace("https://w3id.org/fossr/ontology/bdi/")101102def ontology_to_semas_rules(bdi_graph: Graph) -> list[str]:103"""104Translate BDI ontology instances to SEMAS production rules.105"""106rules = []107108# Extract belief-desire-intention chains109for intention in bdi_graph.subjects(RDF.type, BDI.Intention):110# Get supporting beliefs111supporting_beliefs = list(bdi_graph.objects(intention, BDI.isSupportedBy))112113# Get fulfilled desire114fulfilled_desires = list(bdi_graph.objects(intention, BDI.fulfils))115116# Get specified plan117specified_plans = list(bdi_graph.objects(intention, BDI.specifies))118119if fulfilled_desires and supporting_beliefs:120desire = fulfilled_desires[0]121beliefs_str = ", ".join([format_belief(b, bdi_graph) for b in supporting_beliefs])122123rule = (124f"[HEAD: {format_desire(desire, bdi_graph)}] / "125f"[CONDITIONALS: {beliefs_str}] » "126f"[TAIL: commit_intention({format_intention(intention, bdi_graph)})]"127)128rules.append(rule)129130if specified_plans:131plan = specified_plans[0]132rule = (133f"[HEAD: {format_intention(intention, bdi_graph)}] / "134f"[CONDITIONALS: ready_to_plan] » "135f"[TAIL: create_plan({format_plan(plan, bdi_graph)})]"136)137rules.append(rule)138139return rules140141def format_belief(belief_uri, graph):142label = graph.value(belief_uri, RDFS.label)143return f"belief({label or belief_uri.split('/')[-1]})"144145def format_desire(desire_uri, graph):146label = graph.value(desire_uri, RDFS.label)147return f"desire({label or desire_uri.split('/')[-1]})"148149def format_intention(intention_uri, graph):150label = graph.value(intention_uri, RDFS.label)151return f"intention({label or intention_uri.split('/')[-1]})"152153def format_plan(plan_uri, graph):154label = graph.value(plan_uri, RDFS.label)155return f"plan({label or plan_uri.split('/')[-1]})"156```157158## Logic Augmented Generation (LAG)159160Augment LLM outputs with BDI ontological constraints.161162### LAG Pipeline Architecture163164```165┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐166│ User Query │────▶│ Ontology │────▶│ Augmented │167│ │ │ Injection │ │ Prompt │168└─────────────────┘ └─────────────────┘ └─────────────────┘169│170▼171┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐172│ Validated │◀────│ Ontology │◀────│ LLM Response │173│ RDF Triples │ │ Validation │ │ (Triples) │174└─────────────────┘ └─────────────────┘ └─────────────────┘175```176177### LAG Implementation178179```python180from rdflib import Graph, Namespace181from rdflib.plugins.parsers.notation3 import BadSyntax182183BDI = Namespace("https://w3id.org/fossr/ontology/bdi/")184185class BDILogicAugmentedGenerator:186def __init__(self, ontology_path: str, llm_client):187self.ontology = Graph()188self.ontology.parse(ontology_path, format='turtle')189self.llm = llm_client190191def generate_mental_states(self, context: str) -> Graph:192"""193Generate BDI mental states from context using LAG.194"""195# Phase 1: Inject ontology into prompt196ontology_turtle = self.ontology.serialize(format='turtle')197augmented_prompt = self._build_augmented_prompt(context, ontology_turtle)198199# Phase 2: Generate with LLM200response = self.llm.generate(augmented_prompt)201202# Phase 3: Extract and validate triples203triples = self._extract_triples(response)204validated = self._validate_against_ontology(triples)205206if not validated['is_consistent']:207# Retry with feedback208return self._retry_with_feedback(context, validated['errors'])209210return validated['graph']211212def _build_augmented_prompt(self, context: str, ontology: str) -> str:213return f"""214You are a BDI mental state modeler. Given the following context, generate215RDF triples representing the agent's beliefs, desires, and intentions.216217## BDI Ontology (use these classes and properties):218{ontology}219220## Context to Model:221{context}222223## Instructions:2241. Identify world states from the context2252. Generate beliefs that refer to those world states2263. Generate desires motivated by those beliefs2274. Generate intentions that fulfill desires and are supported by beliefs2285. Include justifications for each mental state2296. Include temporal validity intervals230231Output valid Turtle RDF triples only.232"""233234def _extract_triples(self, response: str) -> str:235"""Extract Turtle content from LLM response."""236# Find turtle block in response237if "```turtle" in response:238start = response.find("```turtle") + 9239end = response.find("```", start)240return response[start:end].strip()241return response242243def _validate_against_ontology(self, triples: str) -> dict:244"""Validate generated triples against BDI ontology."""245result = {'is_consistent': True, 'errors': [], 'graph': None}246247try:248generated = Graph()249generated.parse(data=triples, format='turtle')250result['graph'] = generated251252# Validate constraints253errors = []254255# Check: Every intention must fulfill a desire256for intention in generated.subjects(RDF.type, BDI.Intention):257if not list(generated.objects(intention, BDI.fulfils)):258errors.append(f"Intention {intention} does not fulfill any desire")259260# Check: Every belief should reference a world state261for belief in generated.subjects(RDF.type, BDI.Belief):262if not list(generated.objects(belief, BDI.refersTo)):263errors.append(f"Belief {belief} does not reference a world state")264265# Check: Desires should be motivated by beliefs266for desire in generated.subjects(RDF.type, BDI.Desire):267if not list(generated.objects(desire, BDI.isMotivatedBy)):268errors.append(f"Desire {desire} has no motivating belief")269270if errors:271result['is_consistent'] = False272result['errors'] = errors273274except BadSyntax as e:275result['is_consistent'] = False276result['errors'] = [f"Invalid Turtle syntax: {e}"]277278return result279280def _retry_with_feedback(self, context: str, errors: list) -> Graph:281"""Retry generation with error feedback."""282feedback_prompt = f"""283Previous generation had errors:284{chr(10).join(errors)}285286Please regenerate the mental states fixing these issues.287288Context: {context}289"""290response = self.llm.generate(feedback_prompt)291triples = self._extract_triples(response)292result = self._validate_against_ontology(triples)293294if result['is_consistent']:295return result['graph']296else:297raise ValueError(f"Failed to generate valid mental states: {result['errors']}")298```299300### Inconsistency Detection Example301302```python303def detect_location_inconsistency(graph: Graph) -> list[str]:304"""305Detect inconsistencies where agent cannot be in two places.306"""307inconsistencies = []308309# Query for location beliefs310query = """311PREFIX bdi: <https://w3id.org/fossr/ontology/bdi/>312313SELECT ?agent ?belief1 ?belief2 ?loc1 ?loc2 WHERE {314?agent bdi:hasBelief ?belief1 , ?belief2 .315?belief1 bdi:refersTo ?ws1 .316?belief2 bdi:refersTo ?ws2 .317?ws1 bdi:hasLocation ?loc1 .318?ws2 bdi:hasLocation ?loc2 .319FILTER(?belief1 != ?belief2 && ?loc1 != ?loc2)320321# Check temporal overlap322?belief1 bdi:hasValidity ?interval1 .323?belief2 bdi:hasValidity ?interval2 .324?interval1 bdi:hasStartTime ?start1 ; bdi:hasEndTime ?end1 .325?interval2 bdi:hasStartTime ?start2 ; bdi:hasEndTime ?end2 .326FILTER(?start1 < ?end2 && ?start2 < ?end1)327}328"""329330for row in graph.query(query):331inconsistencies.append(332f"Agent {row.agent} has conflicting location beliefs: "333f"{row.loc1} and {row.loc2} at overlapping times"334)335336return inconsistencies337```338339## JADE/JADEX Integration340341Map BDI ontology to JADE/JADEX agent platform structures.342343### JADE Agent Structure344345```java346public class BDIAgent extends Agent {347// Mental state storage (maps to ontology individuals)348private Set<Belief> beliefs = new HashSet<>();349private Set<Desire> desires = new HashSet<>();350private Set<Intention> intentions = new HashSet<>();351352// Ontology-backed mental state management353private Graph mentalStateGraph;354355public void addBelief(Belief belief) {356beliefs.add(belief);357358// Add to RDF graph359Resource beliefResource = mentalStateGraph.createResource(belief.getUri());360beliefResource.addProperty(RDF.type, BDI.Belief);361beliefResource.addProperty(BDI.refersTo, belief.getWorldState().getUri());362beliefResource.addProperty(BDI.hasValidity, createInterval(belief.getValidity()));363364// Trigger desire formation365triggerDesireProcess(belief);366}367368public void commitIntention(Intention intention) {369intentions.add(intention);370371Resource intentionResource = mentalStateGraph.createResource(intention.getUri());372intentionResource.addProperty(RDF.type, BDI.Intention);373intentionResource.addProperty(BDI.fulfils, intention.getDesire().getUri());374375for (Belief support : intention.getSupportingBeliefs()) {376intentionResource.addProperty(BDI.isSupportedBy, support.getUri());377}378379// Trigger planning380triggerPlanning(intention);381}382383// Export mental states as RDF384public String exportMentalStates() {385return mentalStateGraph.serialize(Format.TURTLE);386}387388// Import mental states from RDF389public void importMentalStates(String turtle) {390Graph imported = new Graph();391imported.parse(turtle, Format.TURTLE);392393// Reconstruct Java objects from RDF394for (Resource belief : imported.listSubjectsWithProperty(RDF.type, BDI.Belief)) {395Belief b = reconstructBelief(belief);396beliefs.add(b);397}398// ... similar for desires and intentions399}400}401```402403### JADEX Goal Mapping404405```java406// Map BDI ontology goals to JADEX goals407@Goal408public class OntologyBackedGoal {409@GoalParameter410protected String goalUri;411412@GoalParameter413protected Graph ontologyGraph;414415public OntologyBackedGoal(Resource goalResource, Graph graph) {416this.goalUri = goalResource.getURI();417this.ontologyGraph = graph;418}419420@GoalTargetCondition421public boolean isAchieved() {422// Query ontology for goal achievement423String query = """424PREFIX bdi: <https://w3id.org/fossr/ontology/bdi/>425ASK {426?execution bdi:addresses <%s> ;427bdi:bringsAbout ?worldState .428}429""".formatted(goalUri);430431return ontologyGraph.ask(query);432}433434@GoalDropCondition435public boolean shouldDrop() {436// Check if supporting beliefs are invalidated437String query = """438PREFIX bdi: <https://w3id.org/fossr/ontology/bdi/>439ASK {440?intention bdi:specifies ?plan .441?plan bdi:addresses <%s> .442?intention bdi:isSupportedBy ?belief .443?belief bdi:hasValidity ?interval .444?interval bdi:hasEndTime ?end .445FILTER(?end < NOW())446}447""".formatted(goalUri);448449return ontologyGraph.ask(query);450}451}452```453454## RDF Triple Store Integration455456### Triple Store Configuration457458```python459from rdflib import Graph460from rdflib.plugins.stores.sparqlstore import SPARQLUpdateStore461462class BDIMentalStateStore:463def __init__(self, endpoint: str):464self.store = SPARQLUpdateStore()465self.store.open((endpoint + "/query", endpoint + "/update"))466self.graph = Graph(store=self.store, identifier="http://example.org/bdi")467468def add_belief(self, agent_uri: str, belief_data: dict):469"""Add belief to triple store."""470belief_uri = f"{agent_uri}/belief/{belief_data['id']}"471472self.graph.add((URIRef(belief_uri), RDF.type, BDI.Belief))473self.graph.add((URIRef(belief_uri), RDFS.label, Literal(belief_data['label'])))474self.graph.add((URIRef(belief_uri), BDI.refersTo, URIRef(belief_data['world_state'])))475self.graph.add((URIRef(agent_uri), BDI.hasMentalState, URIRef(belief_uri)))476477# Add temporal validity478interval_uri = f"{belief_uri}/validity"479self.graph.add((URIRef(belief_uri), BDI.hasValidity, URIRef(interval_uri)))480self.graph.add((URIRef(interval_uri), BDI.hasStartTime,481Literal(belief_data['start_time'], datatype=XSD.dateTime)))482self.graph.add((URIRef(interval_uri), BDI.hasEndTime,483Literal(belief_data['end_time'], datatype=XSD.dateTime)))484485def get_active_beliefs(self, agent_uri: str, at_time: datetime) -> list:486"""Query beliefs active at specific time."""487query = """488PREFIX bdi: <https://w3id.org/fossr/ontology/bdi/>489PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>490491SELECT ?belief ?label WHERE {492<%s> bdi:hasMentalState ?belief .493?belief a bdi:Belief ;494rdfs:label ?label ;495bdi:hasValidity ?interval .496?interval bdi:hasStartTime ?start ;497bdi:hasEndTime ?end .498FILTER(?start <= "%s"^^xsd:dateTime && ?end >= "%s"^^xsd:dateTime)499}500""" % (agent_uri, at_time.isoformat(), at_time.isoformat())501502return list(self.graph.query(query))503504def get_cognitive_chain(self, intention_uri: str) -> dict:505"""Trace complete cognitive chain for an intention."""506query = """507PREFIX bdi: <https://w3id.org/fossr/ontology/bdi/>508509SELECT ?intention ?desire ?belief ?worldState ?plan WHERE {510<%s> a bdi:Intention ;511bdi:fulfils ?desire ;512bdi:isSupportedBy ?belief .513OPTIONAL { <%s> bdi:specifies ?plan }514?desire bdi:isMotivatedBy ?belief .515?belief bdi:refersTo ?worldState .516}517""" % (intention_uri, intention_uri)518519results = list(self.graph.query(query))520if results:521row = results[0]522return {523'intention': str(row.intention),524'desire': str(row.desire),525'belief': str(row.belief),526'world_state': str(row.worldState),527'plan': str(row.plan) if row.plan else None528}529return None530```531532## FIPA ACL Integration533534Map BDI mental states to FIPA Agent Communication Language.535536```python537from fipa_acl import ACLMessage, Performative538539class BDICommunicator:540def __init__(self, agent_id: str, mental_state_store: BDIMentalStateStore):541self.agent_id = agent_id542self.store = mental_state_store543544def share_belief(self, belief_uri: str, receiver: str) -> ACLMessage:545"""Create INFORM message to share belief."""546belief_triples = self.store.get_belief_as_turtle(belief_uri)547548message = ACLMessage()549message.performative = Performative.INFORM550message.sender = self.agent_id551message.receiver = receiver552message.content = belief_triples553message.ontology = "https://w3id.org/fossr/ontology/bdi/"554message.language = "turtle"555556return message557558def request_belief_confirmation(self, belief_uri: str, receiver: str) -> ACLMessage:559"""Create QUERY-IF message to confirm shared belief."""560message = ACLMessage()561message.performative = Performative.QUERY_IF562message.sender = self.agent_id563message.receiver = receiver564message.content = f"ASK {{ <{belief_uri}> a bdi:Belief }}"565message.language = "sparql"566567return message568569def propose_intention(self, intention_uri: str, receiver: str) -> ACLMessage:570"""Create PROPOSE message for coordinated intention."""571intention_triples = self.store.get_intention_as_turtle(intention_uri)572573message = ACLMessage()574message.performative = Performative.PROPOSE575message.sender = self.agent_id576message.receiver = receiver577message.content = intention_triples578message.ontology = "https://w3id.org/fossr/ontology/bdi/"579580return message581```582583