feat(phase-9): semantic enrichment — polarity + annotations
Browse filesPhase 9 ajoute la sémantique riche de JDM aux triplets exposés à l'agent :
=== Polarité (poids signés) ===
Chaque triplet contient maintenant un champ `polarity` ('affirmation' |
'négation') dérivé du signe de `w`. Conformément à la sémantique JDM, un
poids négatif est une assertion *explicite* de négation (votes joueurs
contre), pas une absence de donnée (UNKNOWN).
Le fact-checker bénéficie directement :
- match direct positif (w>0) avec claim positive → SUPPORTED (inchangé)
- match direct NÉGATIF (w<0) avec claim positive → CONTRADICTED (NEW)
- Confidence calibrée sur |w| (tanh(|w|/100))
Smoke vérifié :
- autruche r_agent-1 voler (w=-173) → CONTRADICTED conf=0.94
- femme r_has_part pénis (w=-262) → CONTRADICTED conf=0.99
- baleine r_isa poisson (w=-35) → CONTRADICTED via match direct
(au lieu de r_isa-incompatible heuristique)
=== Annotations sémantiques (mécanisme :r{id}) ===
Découverte du mécanisme JDM : un triplet d'id `rel_id` a un nœud d'ancrage
nommé `:r{rel_id}` (type 10) dont les relations sortantes 996/997/998
attachent des annotations sémantiques.
Smoke confirmé sur cas réels :
- chat r_isa mammifère → annotations: contrastif(w=1003), peu pertinent(w=17)
- autruche r_agent-1 voler → annotation: contrastif(w=33)
- femme r_has_part pénis → annotation: contrastif(w=10)
- homme r_has_part pénis → 4 annotations: non spécifique(835), peu pertinent(209)...
Bug JDM contourné : passer types_ids multi-valeur sur un nœud :r{id} renvoie
500. Solution : récupérer sans filter, trier Python (filtre .type==1 pour
exclure r_pos structurel).
Modifs :
- models.py : Annotation Pydantic (kind/value/w)
- client.py : get_annotations_for_triplet(rel_id) + ANNOTATION_KINDS mapping
- tools/jdm_tools.py :
* _resolve_targets : ajout polarity, N+1 annotations, tri par |w|,
filtrage des chunks type 8 (non exposés en Phase 9)
* _polarity(w) helper
* Tous les @tool : min_weight default 25→0 (cf. décision: LLM filtre lui-même)
- factcheck/verifier.py : cascade enrichie incluant w<0 direct + lookup
d'annotations pour explication enrichie
- enrich/models.py : GapType.NEGATIVE_FILLED
- enrich/detectors.py : distinction MISSING vs NEGATIVE_FILLED selon présence
de triplets négatifs
- tools/jdm_agent.py : system prompt §4-5 expliquant polarity et annotations,
exige préfacement explicite des négations
Doc :
- relation_definitions.md §19 : sémantique des poids signés
- relation_definitions.md §20 : annotations (:r{id}, vocabulaire courant
observé : contrastif/constitutif/pertinent/non spécifique/etc.)
Tests : 48/48 verts (+4 Phase 9 : get_annotations_for_triplet x2,
direct negative match CONTRADICTED, annotations in explanation).
- .gitignore +1 -0
- relation_definitions.md +95 -0
- src/jdm_agent/client/__init__.py +2 -0
- src/jdm_agent/client/client.py +46 -0
- src/jdm_agent/client/models.py +12 -0
- src/jdm_agent/enrich/detectors.py +49 -6
- src/jdm_agent/enrich/models.py +4 -3
- src/jdm_agent/factcheck/verifier.py +75 -35
- src/jdm_agent/tools/jdm_agent.py +35 -7
- src/jdm_agent/tools/jdm_tools.py +54 -18
- tests/test_client.py +48 -0
- tests/test_factcheck.py +56 -0
|
@@ -11,3 +11,4 @@ venv/
|
|
| 11 |
dist/
|
| 12 |
build/
|
| 13 |
*.log
|
|
|
|
|
|
| 11 |
dist/
|
| 12 |
build/
|
| 13 |
*.log
|
| 14 |
+
erreurs_a_corriger.md
|
|
@@ -965,3 +965,98 @@ Informations diverses d'ordre lexical attach
|
|
| 965 |
* chat | r_data | fr�quence=�lev�e
|
| 966 |
* prendre | r_data | irr�gulier
|
| 967 |
* hier | r_data | invariable
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 965 |
* chat | r_data | fr�quence=�lev�e
|
| 966 |
* prendre | r_data | irr�gulier
|
| 967 |
* hier | r_data | invariable
|
| 968 |
+
|
| 969 |
+
|
| 970 |
+
## 19. S�mantique des poids sign�s
|
| 971 |
+
|
| 972 |
+
Le poids `w` d'un triplet JDM r�sulte des votes collectifs des joueurs. Il porte
|
| 973 |
+
une information de **POLARIT�** en plus de son amplitude :
|
| 974 |
+
|
| 975 |
+
| Plage de `w` | Polarit� | Interpr�tation |
|
| 976 |
+
|---|---|---|
|
| 977 |
+
| `w > 0` | affirmation | Le triplet est vot� comme tenant |
|
| 978 |
+
| `w = 0` | (neutre) | Cas marginal (jamais vot� ou exactement nul) |
|
| 979 |
+
| `w < 0` | **n�gation** | Le triplet est vot� comme explicitement FAUX |
|
| 980 |
+
|
| 981 |
+
L'amplitude `|w|` refl�te l'intensit� du consensus, jamais sa direction.
|
| 982 |
+
Le projet JDMAgent expose `polarity` comme champ explicite dans chaque triplet
|
| 983 |
+
pour que les mod�les LLM lisent la s�mantique sans avoir � inf�rer le signe.
|
| 984 |
+
|
| 985 |
+
Un triplet � `w < 0` n'est **pas** une absence de donn�e (UNKNOWN) : c'est une
|
| 986 |
+
assertion n�gative consensuelle, distincte de l'absence de relation. C'est un
|
| 987 |
+
signal fort pour le fact-checker.
|
| 988 |
+
|
| 989 |
+
Le projet est **agnostique sur l'amplitude** : pas de seuil minimal pour d�cider
|
| 990 |
+
qu'un triplet est une affirmation ou une n�gation. Le LLM filtre selon le contexte.
|
| 991 |
+
|
| 992 |
+
### Exemples observ�s
|
| 993 |
+
* baleine | r_isa | mammif�re (w=265) ? affirmation forte
|
| 994 |
+
* autruche | r_agent-1 | voler (w=-173) ? n�gation explicite
|
| 995 |
+
* femme | r_has_part | p�nis (w=-262) ? n�gation explicite (consensus contrastif)
|
| 996 |
+
* chat | r_telic_role | manger (w=-25) ? n�gation mod�r�e
|
| 997 |
+
|
| 998 |
+
---
|
| 999 |
+
|
| 1000 |
+
## 20. Annotations s�mantiques sur les triplets
|
| 1001 |
+
|
| 1002 |
+
### M�canisme
|
| 1003 |
+
|
| 1004 |
+
Quand un triplet JDM a l'identifiant `rel_id` (champ `Relation.id`), JDM expose
|
| 1005 |
+
un **n�ud d'ancrage** dont le nom suit le pattern :
|
| 1006 |
+
|
| 1007 |
+
name = ":r{rel_id}" (exemple : ":r650620")
|
| 1008 |
+
|
| 1009 |
+
Ce n�ud est de **type 10** dans le mod�le JDM (� ne PAS confondre avec les
|
| 1010 |
+
chunks de type 8 qui sont des agr�gats syntaxiques distincts du m�canisme
|
| 1011 |
+
d'annotation). Trois types de relations d'annotation peuvent partir de ce n�ud
|
| 1012 |
+
vers une cible (le contenu de l'annotation) :
|
| 1013 |
+
|
| 1014 |
+
| Type | Id | S�mantique |
|
| 1015 |
+
|---|---|---|
|
| 1016 |
+
| `r_annotation_context` | 996 | Contexte dans lequel le triplet tient |
|
| 1017 |
+
| `r_annotation_exception` | 997 | Exception au triplet (� sauf dans X �) |
|
| 1018 |
+
| `r_annotation` | 998 | Annotation libre / qualification g�n�rale |
|
| 1019 |
+
|
| 1020 |
+
En pratique, **998 est de loin le plus fr�quent** ; 996/997 plus rares.
|
| 1021 |
+
|
| 1022 |
+
### R�cup�ration depuis l'API
|
| 1023 |
+
|
| 1024 |
+
GET /v0/relations/from/:r{rel_id}?types_ids=996,997,998
|
| 1025 |
+
|
| 1026 |
+
Filtrer les targets sur `node.type == 1` (terme lexical) � JDM renvoie aussi
|
| 1027 |
+
un `r_pos` structurel `Relation:` de type 4 qu'on ignore.
|
| 1028 |
+
|
| 1029 |
+
Si le n�ud `:r{rel_id}` n'existe pas (triplet non annot�), JDM renvoie
|
| 1030 |
+
**HTTP 500** (et non 404). � traiter gracefully c�t� client.
|
| 1031 |
+
|
| 1032 |
+
### Valeurs s�mantiques courantes (cibles d'annotation)
|
| 1033 |
+
|
| 1034 |
+
Vocabulaire �mergent � non normatif, observ� sur cas r�els JDM, � �toffer
|
| 1035 |
+
au fil du temps :
|
| 1036 |
+
|
| 1037 |
+
| Label | S�mantique | Observ� sur |
|
| 1038 |
+
|---|---|---|
|
| 1039 |
+
| **constitutif** | Trait d�finitionnel, essentiel � l'entit� | typiquement triplets positifs forts |
|
| 1040 |
+
| **contrastif** | Trait diff�renciateur entre cat�gories � peut �tre positif (ce qui distingue d'autres) ou n�gatif (ce qui distingue par exclusion) | `autruche r_agent-1 voler` (w=-173), `chat r_agent-1 manger` (w=168), `femme r_has_part p�nis` (w=-262) |
|
| 1041 |
+
| **pertinent** | Confirmation que le triplet est utile/significatif | toutes polarit�s |
|
| 1042 |
+
| **non pertinent** | Le triplet existe techniquement mais peu utile en pratique | toutes polarit�s |
|
| 1043 |
+
| **peu pertinent** | Variante de � non pertinent � | toutes polarit�s |
|
| 1044 |
+
| **non sp�cifique** | Trait qui ne caract�rise pas particuli�rement l'entit� (vrai de beaucoup d'autres) | typiquement triplets positifs banals |
|
| 1045 |
+
| **probable** | Trait fr�quent mais non garanti | positif |
|
| 1046 |
+
| **improbable** | Trait rare mais possible | positif faible |
|
| 1047 |
+
| **incertain** | Valeur variable selon contexte / individus | positif moyen |
|
| 1048 |
+
| *(� compl�ter)* | � | � |
|
| 1049 |
+
|
| 1050 |
+
Important : **`contrastif` n'est pas synonyme de n�gatif**. Il marque un trait
|
| 1051 |
+
diff�renciateur, ind�pendamment de la polarit�. Un trait constitutif est
|
| 1052 |
+
d�finitionnel ; un trait contrastif distingue de cat�gories voisines.
|
| 1053 |
+
|
| 1054 |
+
### Distinction chunks vs annotations
|
| 1055 |
+
|
| 1056 |
+
Les chunks (type 8, nom `::>type:id>type:id`) sont des **agr�gats syntaxiques**
|
| 1057 |
+
ind�pendants du m�canisme d'annotation. Ils repr�sentent des unit�s
|
| 1058 |
+
linguistiques compos�es (syntagmes, expressions). Ils seront expos�s dans une
|
| 1059 |
+
phase ult�rieure comme outil s�par�.
|
| 1060 |
+
|
| 1061 |
+
Le syst�me d'annotation d�crit ici (`:r{id}` + relations 996/997/998) est
|
| 1062 |
+
**l'unique m�canisme** pour attacher de la s�mantique meta � un triplet JDM.
|
|
@@ -1,5 +1,6 @@
|
|
| 1 |
from jdm_agent.client.client import JDMClient
|
| 2 |
from jdm_agent.client.models import (
|
|
|
|
| 3 |
DecodedRefinement,
|
| 4 |
Node,
|
| 5 |
NodeType,
|
|
@@ -18,4 +19,5 @@ __all__ = [
|
|
| 18 |
"RelationsResult",
|
| 19 |
"RefinementsResult",
|
| 20 |
"DecodedRefinement",
|
|
|
|
| 21 |
]
|
|
|
|
| 1 |
from jdm_agent.client.client import JDMClient
|
| 2 |
from jdm_agent.client.models import (
|
| 3 |
+
Annotation,
|
| 4 |
DecodedRefinement,
|
| 5 |
Node,
|
| 6 |
NodeType,
|
|
|
|
| 19 |
"RelationsResult",
|
| 20 |
"RefinementsResult",
|
| 21 |
"DecodedRefinement",
|
| 22 |
+
"Annotation",
|
| 23 |
]
|
|
@@ -24,6 +24,7 @@ from tenacity import (
|
|
| 24 |
|
| 25 |
from jdm_agent.client.cache import DiskJSONCache
|
| 26 |
from jdm_agent.client.models import (
|
|
|
|
| 27 |
DecodedRefinement,
|
| 28 |
Node,
|
| 29 |
NodeType,
|
|
@@ -268,6 +269,51 @@ class JDMClient:
|
|
| 268 |
))
|
| 269 |
return out
|
| 270 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 271 |
# ---------- Relations ----------
|
| 272 |
|
| 273 |
def _relations_params(
|
|
|
|
| 24 |
|
| 25 |
from jdm_agent.client.cache import DiskJSONCache
|
| 26 |
from jdm_agent.client.models import (
|
| 27 |
+
Annotation,
|
| 28 |
DecodedRefinement,
|
| 29 |
Node,
|
| 30 |
NodeType,
|
|
|
|
| 269 |
))
|
| 270 |
return out
|
| 271 |
|
| 272 |
+
# ---------- Annotations (Phase 9) ----------
|
| 273 |
+
|
| 274 |
+
# Mapping id de relation d'annotation → 'kind' lisible exposé au LLM
|
| 275 |
+
_ANNOTATION_KINDS = {
|
| 276 |
+
996: "context", # r_annotation_context
|
| 277 |
+
997: "exception", # r_annotation_exception
|
| 278 |
+
998: "annotation", # r_annotation (général)
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
def get_annotations_for_triplet(self, rel_id: int) -> list[Annotation]:
|
| 282 |
+
"""Récupère les annotations sémantiques attachées au triplet d'id `rel_id`.
|
| 283 |
+
|
| 284 |
+
Mécanisme JDM (cf. relation_definitions.md §20) :
|
| 285 |
+
Un nœud d'ancrage existe avec name = f":r{rel_id}". Les annotations
|
| 286 |
+
sortantes sont les relations de type 996/997/998 vers une cible
|
| 287 |
+
lexicale (type 1).
|
| 288 |
+
|
| 289 |
+
Renvoie [] si le triplet n'a aucune annotation (JDM répond HTTP 500 dans
|
| 290 |
+
ce cas, qu'on traite gracefully).
|
| 291 |
+
"""
|
| 292 |
+
annot_node_name = f":r{rel_id}"
|
| 293 |
+
try:
|
| 294 |
+
# NOTE: JDM a un bug — passer types_ids avec plusieurs valeurs sur un
|
| 295 |
+
# nœud `:r{id}` retourne 500. On récupère TOUT et on filtre Python.
|
| 296 |
+
res = self.relations_from(annot_node_name)
|
| 297 |
+
except Exception:
|
| 298 |
+
# Soit le nœud d'ancrage n'existe pas (triplet jamais annoté → 500),
|
| 299 |
+
# soit réseau. Dans tous les cas : pas d'annotations exploitables.
|
| 300 |
+
return []
|
| 301 |
+
idx = res.node_index()
|
| 302 |
+
out: list[Annotation] = []
|
| 303 |
+
for r in res.relations:
|
| 304 |
+
kind = self._ANNOTATION_KINDS.get(r.type)
|
| 305 |
+
if kind is None:
|
| 306 |
+
continue # skip r_pos (type 4 "Relation:") et autres
|
| 307 |
+
target = idx.get(r.node2)
|
| 308 |
+
# On ne garde que les annotations dont la cible est un terme lexical
|
| 309 |
+
# (n.type == 1). Skip les structures internes (type 4 etc.).
|
| 310 |
+
if target is None or target.type != 1:
|
| 311 |
+
continue
|
| 312 |
+
out.append(Annotation(kind=kind, value=target.name, w=r.w))
|
| 313 |
+
# Tri par |w| décroissant : annotations les plus consensuelles d'abord
|
| 314 |
+
out.sort(key=lambda a: -abs(a.w))
|
| 315 |
+
return out
|
| 316 |
+
|
| 317 |
# ---------- Relations ----------
|
| 318 |
|
| 319 |
def _relations_params(
|
|
@@ -98,3 +98,15 @@ class RefinementsResult(BaseModel):
|
|
| 98 |
|
| 99 |
nodes: List[Node] = Field(default_factory=list)
|
| 100 |
refinements: List[Node] = Field(default_factory=list)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
|
| 99 |
nodes: List[Node] = Field(default_factory=list)
|
| 100 |
refinements: List[Node] = Field(default_factory=list)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class Annotation(BaseModel):
|
| 104 |
+
"""Une annotation sémantique attachée à un triplet JDM.
|
| 105 |
+
|
| 106 |
+
Voir §20 de relation_definitions.md pour le mécanisme complet.
|
| 107 |
+
Le triplet annoté est référencé via son rel_id ; ce modèle représente UNE
|
| 108 |
+
annotation parmi N qui peuvent lui être attachées.
|
| 109 |
+
"""
|
| 110 |
+
kind: str = Field(..., description="'context' (996) | 'exception' (997) | 'annotation' (998)")
|
| 111 |
+
value: str = Field(..., description="Contenu de l'annotation (ex: 'contrastif', 'non spécifique')")
|
| 112 |
+
w: float = Field(0.0, description="Poids du vote sur cette annotation spécifique")
|
|
@@ -60,23 +60,66 @@ def _count_relations(client: JDMClient, term: str, relation: str,
|
|
| 60 |
return len(res.relations)
|
| 61 |
|
| 62 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
def _detect_missing(client: JDMClient, term: str,
|
| 64 |
relations: Iterable[str], min_to_consider: int = 1) -> list[Gap]:
|
| 65 |
-
"""Pour chaque relation cible, signale celle qui a < min_to_consider triplets.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
gaps: list[Gap] = []
|
| 67 |
for rel in relations:
|
| 68 |
-
|
| 69 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
gaps.append(Gap(
|
| 71 |
term=term, relation=rel, gap_type=GapType.MISSING,
|
| 72 |
severity=1.0,
|
| 73 |
-
detail=f"Aucun triplet `{term} | {rel} | ?` (
|
| 74 |
))
|
| 75 |
-
elif
|
| 76 |
gaps.append(Gap(
|
| 77 |
term=term, relation=rel, gap_type=GapType.LOW_COVERAGE,
|
| 78 |
severity=0.6,
|
| 79 |
-
detail=f"Seulement {
|
| 80 |
))
|
| 81 |
return gaps
|
| 82 |
|
|
|
|
| 60 |
return len(res.relations)
|
| 61 |
|
| 62 |
|
| 63 |
+
def _get_relations_signed(client: JDMClient, term: str, relation: str,
|
| 64 |
+
limit: int = 50) -> list[tuple[str, float]]:
|
| 65 |
+
"""Récupère les triplets avec leur poids (signé), pour Phase 9.
|
| 66 |
+
|
| 67 |
+
Renvoie [(target_name, w), ...] incluant les négatifs.
|
| 68 |
+
"""
|
| 69 |
+
rid = client.relation_type_id(relation)
|
| 70 |
+
if rid is None:
|
| 71 |
+
return []
|
| 72 |
+
try:
|
| 73 |
+
res = client.relations_from(term, types_ids=[rid],
|
| 74 |
+
min_weight=-1e6, limit=limit)
|
| 75 |
+
except Exception:
|
| 76 |
+
return []
|
| 77 |
+
idx = res.node_index()
|
| 78 |
+
out = []
|
| 79 |
+
for r in res.relations:
|
| 80 |
+
n = idx.get(r.node2)
|
| 81 |
+
if n is not None:
|
| 82 |
+
out.append((n.name, r.w))
|
| 83 |
+
return out
|
| 84 |
+
|
| 85 |
+
|
| 86 |
def _detect_missing(client: JDMClient, term: str,
|
| 87 |
relations: Iterable[str], min_to_consider: int = 1) -> list[Gap]:
|
| 88 |
+
"""Pour chaque relation cible, signale celle qui a < min_to_consider triplets.
|
| 89 |
+
|
| 90 |
+
Phase 9 — distingue maintenant :
|
| 91 |
+
- MISSING strict : aucun triplet (positif NI négatif)
|
| 92 |
+
- NEGATIVE_FILLED : que des triplets négatifs (JDM a regardé et dit non)
|
| 93 |
+
- LOW_COVERAGE : peu de triplets positifs
|
| 94 |
+
"""
|
| 95 |
gaps: list[Gap] = []
|
| 96 |
for rel in relations:
|
| 97 |
+
signed = _get_relations_signed(client, term, rel)
|
| 98 |
+
positives = [w for _, w in signed if w >= 25]
|
| 99 |
+
negatives = [(n, w) for n, w in signed if w < 0]
|
| 100 |
+
n_pos = len(positives)
|
| 101 |
+
if n_pos == 0 and len(negatives) > 0:
|
| 102 |
+
# Pas de positif mais des négatifs existent → c'est rempli en négatif
|
| 103 |
+
top_neg = sorted(negatives, key=lambda x: x[1])[:3]
|
| 104 |
+
detail_extras = "; ".join(f"{n} (w={w:.0f})" for n, w in top_neg)
|
| 105 |
+
gaps.append(Gap(
|
| 106 |
+
term=term, relation=rel, gap_type=GapType.NEGATIVE_FILLED,
|
| 107 |
+
severity=0.3,
|
| 108 |
+
detail=(f"JDM contient {len(negatives)} triplet(s) NÉGATIFS pour "
|
| 109 |
+
f"`{term} | {rel} | ?` : {detail_extras}. Pas un gap au "
|
| 110 |
+
f"sens strict — déjà rempli avec des assertions négatives."),
|
| 111 |
+
))
|
| 112 |
+
elif n_pos == 0:
|
| 113 |
gaps.append(Gap(
|
| 114 |
term=term, relation=rel, gap_type=GapType.MISSING,
|
| 115 |
severity=1.0,
|
| 116 |
+
detail=f"Aucun triplet `{term} | {rel} | ?` (w≥25) dans JDM.",
|
| 117 |
))
|
| 118 |
+
elif n_pos < min_to_consider:
|
| 119 |
gaps.append(Gap(
|
| 120 |
term=term, relation=rel, gap_type=GapType.LOW_COVERAGE,
|
| 121 |
severity=0.6,
|
| 122 |
+
detail=f"Seulement {n_pos} triplets `{term} | {rel} | ?` positifs (w≥25).",
|
| 123 |
))
|
| 124 |
return gaps
|
| 125 |
|
|
@@ -8,9 +8,10 @@ from pydantic import BaseModel, Field
|
|
| 8 |
|
| 9 |
|
| 10 |
class GapType(str, Enum):
|
| 11 |
-
MISSING
|
| 12 |
-
LOW_COVERAGE
|
| 13 |
-
ASYMMETRY
|
|
|
|
| 14 |
|
| 15 |
|
| 16 |
class Gap(BaseModel):
|
|
|
|
| 8 |
|
| 9 |
|
| 10 |
class GapType(str, Enum):
|
| 11 |
+
MISSING = "missing" # aucune triplet pour (term, relation)
|
| 12 |
+
LOW_COVERAGE = "low_coverage" # < N triplets alors que des paires similaires en ont beaucoup
|
| 13 |
+
ASYMMETRY = "asymmetry" # A r_X B existe, mais B r_inverse(X) A manque
|
| 14 |
+
NEGATIVE_FILLED = "negative_filled" # triplet existe mais avec w<0 (négation explicite, pas un gap au sens strict)
|
| 15 |
|
| 16 |
|
| 17 |
class Gap(BaseModel):
|
|
@@ -48,79 +48,119 @@ def _matches(target_name: str, expected: str) -> bool:
|
|
| 48 |
|
| 49 |
|
| 50 |
def _relations_from_by_type(client: JDMClient, subject: str, relation_name: str,
|
| 51 |
-
min_weight: float =
|
|
|
|
| 52 |
"""Helper : liste les triplets sortants de subject pour ce type de relation.
|
| 53 |
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
"""
|
| 56 |
rid = client.relation_type_id(relation_name)
|
| 57 |
if rid is None:
|
| 58 |
return []
|
| 59 |
try:
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
except Exception:
|
| 63 |
-
# Nœud inexistant (500), réseau, etc. — on traite comme absence de données.
|
| 64 |
return []
|
| 65 |
idx = res.node_index()
|
| 66 |
out = []
|
| 67 |
for r in res.relations:
|
| 68 |
n = idx.get(r.node2)
|
| 69 |
if n is not None:
|
| 70 |
-
out.append((n.name, r.w))
|
| 71 |
return out
|
| 72 |
|
| 73 |
|
| 74 |
def verify_claim(client: JDMClient, claim: Claim,
|
| 75 |
support_min_w: float = DEFAULT_SUPPORT_MIN_W) -> Verdict:
|
| 76 |
-
"""Vérifie une claim atomique contre JDM. Pas d'appel LLM.
|
| 77 |
-
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
if not triples and not client.relation_type_id(claim.relation):
|
| 80 |
return Verdict(
|
| 81 |
claim=claim, status=Status.UNKNOWN, confidence=0.0,
|
| 82 |
explanation=f"Relation inconnue dans JDM : {claim.relation!r}.",
|
| 83 |
)
|
| 84 |
|
| 85 |
-
#
|
| 86 |
-
direct_hit = None
|
| 87 |
-
for name, w in triples:
|
| 88 |
if _matches(name, claim.object):
|
| 89 |
-
direct_hit = (name, w)
|
| 90 |
break
|
| 91 |
-
# Vérifie aussi la forme décodée d'un refinement.
|
| 92 |
dec = client.decode_node_name(name)
|
| 93 |
if dec["is_refinement"] and _matches(dec["decoded"], claim.object):
|
| 94 |
-
direct_hit = (name, w)
|
| 95 |
break
|
| 96 |
|
| 97 |
if direct_hit is not None:
|
| 98 |
-
name, w = direct_hit
|
| 99 |
-
#
|
| 100 |
-
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
ev = _to_evidence(client, claim.subject, claim.relation, name, w)
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
return Verdict(
|
| 105 |
-
claim=claim, status=
|
| 106 |
-
evidence_for=[ev] if
|
| 107 |
-
evidence_against=[] if
|
| 108 |
-
explanation=
|
| 109 |
-
f"JDM contient directement le triplet "
|
| 110 |
-
f"`{claim.subject} | {claim.relation} | {ev.target}` "
|
| 111 |
-
f"avec poids {w:.0f}."
|
| 112 |
-
),
|
| 113 |
)
|
| 114 |
|
| 115 |
-
#
|
| 116 |
-
# Évite les faux positifs du type "animal aquatique ~ poisson" qui
|
| 117 |
-
# conduiraient à valider à tort "baleine r_isa poisson".
|
| 118 |
if claim.relation == "r_isa":
|
| 119 |
-
|
|
|
|
|
|
|
|
|
|
| 120 |
if contradicted_evidence:
|
| 121 |
return contradicted_evidence
|
| 122 |
|
| 123 |
-
#
|
| 124 |
syn_id = client.relation_type_id("r_syn")
|
| 125 |
if syn_id is not None:
|
| 126 |
try:
|
|
@@ -129,7 +169,7 @@ def verify_claim(client: JDMClient, claim: Claim,
|
|
| 129 |
syn_names = {n.name for n in syns_res.nodes}
|
| 130 |
except Exception:
|
| 131 |
syn_names = set()
|
| 132 |
-
for name, w in triples:
|
| 133 |
if name in syn_names and w >= support_min_w:
|
| 134 |
ev = _to_evidence(client, claim.subject, claim.relation, name, w)
|
| 135 |
import math
|
|
@@ -152,7 +192,7 @@ def verify_claim(client: JDMClient, claim: Claim,
|
|
| 152 |
# Le top des génériques peut servir d'evidence_against indicative.
|
| 153 |
top_against = [
|
| 154 |
_to_evidence(client, claim.subject, claim.relation, n, w)
|
| 155 |
-
for n, w in sorted(triples, key=lambda x: -x[1])[:5]
|
| 156 |
]
|
| 157 |
return Verdict(
|
| 158 |
claim=claim, status=Status.UNKNOWN, confidence=0.3,
|
|
|
|
| 48 |
|
| 49 |
|
| 50 |
def _relations_from_by_type(client: JDMClient, subject: str, relation_name: str,
|
| 51 |
+
min_weight: Optional[float] = None,
|
| 52 |
+
limit: int = 500) -> list[tuple[str, float, int]]:
|
| 53 |
"""Helper : liste les triplets sortants de subject pour ce type de relation.
|
| 54 |
|
| 55 |
+
Phase 9 : renvoie maintenant des tuples (name, w, rel_id) — l'id est
|
| 56 |
+
nécessaire pour lookup d'annotations. min_weight=None par défaut → on
|
| 57 |
+
récupère TOUT, y compris les négatifs (cf. relation_definitions.md §19).
|
| 58 |
+
|
| 59 |
+
Renvoie [] silencieusement si le subject n'existe pas dans JDM (500).
|
| 60 |
"""
|
| 61 |
rid = client.relation_type_id(relation_name)
|
| 62 |
if rid is None:
|
| 63 |
return []
|
| 64 |
try:
|
| 65 |
+
# min_weight très bas pour avoir aussi les négatifs ; JDM tolère.
|
| 66 |
+
res = client.relations_from(
|
| 67 |
+
subject, types_ids=[rid],
|
| 68 |
+
min_weight=-1e6 if min_weight is None else min_weight,
|
| 69 |
+
limit=limit,
|
| 70 |
+
)
|
| 71 |
except Exception:
|
|
|
|
| 72 |
return []
|
| 73 |
idx = res.node_index()
|
| 74 |
out = []
|
| 75 |
for r in res.relations:
|
| 76 |
n = idx.get(r.node2)
|
| 77 |
if n is not None:
|
| 78 |
+
out.append((n.name, r.w, r.id))
|
| 79 |
return out
|
| 80 |
|
| 81 |
|
| 82 |
def verify_claim(client: JDMClient, claim: Claim,
|
| 83 |
support_min_w: float = DEFAULT_SUPPORT_MIN_W) -> Verdict:
|
| 84 |
+
"""Vérifie une claim atomique contre JDM. Pas d'appel LLM.
|
| 85 |
+
|
| 86 |
+
Cascade enrichie (Phase 9) :
|
| 87 |
+
1. Match direct positif (w > 0) → SUPPORTED ou CONTRADICTED selon polarity
|
| 88 |
+
2. Match direct NÉGATIF (w < 0) → polarité INVERSE (JDM dit explicitement non)
|
| 89 |
+
3. Pour r_isa : check r_isa-incompatible via top hyperonymes
|
| 90 |
+
4. Match via synonymes de l'object (positifs uniquement)
|
| 91 |
+
5. UNKNOWN
|
| 92 |
+
|
| 93 |
+
Pour les matches directs, les annotations du triplet (r_annotation_exception
|
| 94 |
+
notamment) sont remontées dans l'explication pour nuance.
|
| 95 |
+
"""
|
| 96 |
+
import math
|
| 97 |
+
|
| 98 |
+
triples = _relations_from_by_type(client, claim.subject, claim.relation)
|
| 99 |
if not triples and not client.relation_type_id(claim.relation):
|
| 100 |
return Verdict(
|
| 101 |
claim=claim, status=Status.UNKNOWN, confidence=0.0,
|
| 102 |
explanation=f"Relation inconnue dans JDM : {claim.relation!r}.",
|
| 103 |
)
|
| 104 |
|
| 105 |
+
# 1) + 2) Match exact (signe positif OU négatif)
|
| 106 |
+
direct_hit = None # tuple (name, w, rel_id)
|
| 107 |
+
for name, w, rid in triples:
|
| 108 |
if _matches(name, claim.object):
|
| 109 |
+
direct_hit = (name, w, rid)
|
| 110 |
break
|
|
|
|
| 111 |
dec = client.decode_node_name(name)
|
| 112 |
if dec["is_refinement"] and _matches(dec["decoded"], claim.object):
|
| 113 |
+
direct_hit = (name, w, rid)
|
| 114 |
break
|
| 115 |
|
| 116 |
if direct_hit is not None:
|
| 117 |
+
name, w, rid = direct_hit
|
| 118 |
+
# JDM dit OUI (w>0) ou NON (w<0) sur ce triplet.
|
| 119 |
+
jdm_says_yes = w > 0
|
| 120 |
+
claim_says_yes = claim.polarity
|
| 121 |
+
|
| 122 |
+
# SUPPORTED ssi JDM et la claim sont d'accord (oui-oui ou non-non)
|
| 123 |
+
status = Status.SUPPORTED if (jdm_says_yes == claim_says_yes) else Status.CONTRADICTED
|
| 124 |
+
conf = round(math.tanh(abs(w) / STRONG_SUPPORT_W), 3)
|
| 125 |
+
|
| 126 |
+
# Cherche les annotations (notamment r_annotation_exception)
|
| 127 |
+
try:
|
| 128 |
+
annotations = client.get_annotations_for_triplet(rid)
|
| 129 |
+
except Exception:
|
| 130 |
+
annotations = []
|
| 131 |
+
annot_str = ""
|
| 132 |
+
if annotations:
|
| 133 |
+
tops = ", ".join(f"{a.value} (w={a.w:.0f})" for a in annotations[:3])
|
| 134 |
+
annot_str = f" Annotations JDM : {tops}."
|
| 135 |
+
# Exceptions explicites : signal supplémentaire à mentionner
|
| 136 |
+
exceptions = [a for a in annotations if a.kind == "exception"]
|
| 137 |
+
if exceptions:
|
| 138 |
+
exc_str = ", ".join(a.value for a in exceptions[:3])
|
| 139 |
+
annot_str += f" Exception(s) annotée(s) : {exc_str}."
|
| 140 |
+
|
| 141 |
ev = _to_evidence(client, claim.subject, claim.relation, name, w)
|
| 142 |
+
explanation = (
|
| 143 |
+
f"JDM contient directement le triplet "
|
| 144 |
+
f"`{claim.subject} | {claim.relation} | {ev.target}` avec poids "
|
| 145 |
+
f"{w:.0f} ({'affirmation' if jdm_says_yes else 'négation'} consensuelle).{annot_str}"
|
| 146 |
+
)
|
| 147 |
return Verdict(
|
| 148 |
+
claim=claim, status=status, confidence=conf,
|
| 149 |
+
evidence_for=[ev] if status == Status.SUPPORTED else [],
|
| 150 |
+
evidence_against=[ev] if status == Status.CONTRADICTED else [],
|
| 151 |
+
explanation=explanation,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
)
|
| 153 |
|
| 154 |
+
# 3) Pour r_isa : vérification d'incompatibilité AVANT la fallback synonymes.
|
|
|
|
|
|
|
| 155 |
if claim.relation == "r_isa":
|
| 156 |
+
# On filtre les triples sur w>0 pour le calcul d'incompatibilité
|
| 157 |
+
# (les hyperonymes négatifs ne servent pas à dériver incompatibilité)
|
| 158 |
+
positive_triples = [(n, w) for n, w, _ in triples if w > 0]
|
| 159 |
+
contradicted_evidence = _check_isa_contradiction(client, claim, positive_triples)
|
| 160 |
if contradicted_evidence:
|
| 161 |
return contradicted_evidence
|
| 162 |
|
| 163 |
+
# 4) Match via synonymes de l'object (folk-taxonomy fallback, positifs uniquement)
|
| 164 |
syn_id = client.relation_type_id("r_syn")
|
| 165 |
if syn_id is not None:
|
| 166 |
try:
|
|
|
|
| 169 |
syn_names = {n.name for n in syns_res.nodes}
|
| 170 |
except Exception:
|
| 171 |
syn_names = set()
|
| 172 |
+
for name, w, _rid in triples:
|
| 173 |
if name in syn_names and w >= support_min_w:
|
| 174 |
ev = _to_evidence(client, claim.subject, claim.relation, name, w)
|
| 175 |
import math
|
|
|
|
| 192 |
# Le top des génériques peut servir d'evidence_against indicative.
|
| 193 |
top_against = [
|
| 194 |
_to_evidence(client, claim.subject, claim.relation, n, w)
|
| 195 |
+
for n, w, _rid in sorted(triples, key=lambda x: -abs(x[1]))[:5]
|
| 196 |
]
|
| 197 |
return Verdict(
|
| 198 |
claim=claim, status=Status.UNKNOWN, confidence=0.3,
|
|
@@ -24,25 +24,53 @@ EXCLUSIVEMENT sur la base de connaissance JeuxDeMots (JDM), un graphe lexico-sé
|
|
| 24 |
du français.
|
| 25 |
|
| 26 |
RÈGLES STRICTES :
|
|
|
|
| 27 |
1. Pour toute affirmation factuelle, tu DOIS d'abord la vérifier via un outil JDM.
|
|
|
|
| 28 |
2. Tu DOIS citer les triplets JDM qui justifient ta réponse au format :
|
| 29 |
`source | r_xxx | target (w=...)`. Tous les `source` et `target` que tu reçois
|
| 30 |
des outils sont DÉJÀ DÉCODÉS en français lisible — cite-les tels quels.
|
|
|
|
| 31 |
3. Si JDM ne contient pas l'information, dis explicitement : "JDM ne contient pas
|
| 32 |
cette information." N'invente JAMAIS.
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
TOUJOURS par `disambiguate`. Le résultat contient `sense` (forme lisible)
|
| 37 |
et `sense_id` (identifiant brut à passer dans les outils suivants pour
|
| 38 |
requêter ce sens précis).
|
| 39 |
-
|
|
|
|
| 40 |
désigne un sens raffiné. Cite la forme lisible (`source`/`target`), mais
|
| 41 |
garde l'`*_id` si tu dois rappeler un outil sur ce sens spécifique.
|
| 42 |
-
|
|
|
|
| 43 |
`list_relation_types(prefix=...)`.
|
| 44 |
-
|
| 45 |
-
|
|
|
|
| 46 |
"""
|
| 47 |
|
| 48 |
|
|
|
|
| 24 |
du français.
|
| 25 |
|
| 26 |
RÈGLES STRICTES :
|
| 27 |
+
|
| 28 |
1. Pour toute affirmation factuelle, tu DOIS d'abord la vérifier via un outil JDM.
|
| 29 |
+
|
| 30 |
2. Tu DOIS citer les triplets JDM qui justifient ta réponse au format :
|
| 31 |
`source | r_xxx | target (w=...)`. Tous les `source` et `target` que tu reçois
|
| 32 |
des outils sont DÉJÀ DÉCODÉS en français lisible — cite-les tels quels.
|
| 33 |
+
|
| 34 |
3. Si JDM ne contient pas l'information, dis explicitement : "JDM ne contient pas
|
| 35 |
cette information." N'invente JAMAIS.
|
| 36 |
+
|
| 37 |
+
4. POLARITÉ : chaque triplet a un champ `polarity` qui vaut `"affirmation"` ou
|
| 38 |
+
`"négation"` (selon le signe de `w`). Quand `polarity == "négation"`, cela
|
| 39 |
+
signifie que JDM affirme explicitement que CE triplet est FAUX (consensus de
|
| 40 |
+
joueurs ayant voté contre). Tu DOIS dans ce cas préfacer la citation par un
|
| 41 |
+
avertissement clair, par exemple : « ⚠️ JDM affirme explicitement que
|
| 42 |
+
X N'EST PAS Y » ou « JDM rejette explicitement le triplet … ». NE PAS mêler
|
| 43 |
+
tacitement les négations aux affirmations — c'est crucial pour ne pas induire
|
| 44 |
+
l'utilisateur en erreur. Pour les affirmations (`polarity == "affirmation"`,
|
| 45 |
+
cas par défaut), pas besoin de préfacer — cite normalement.
|
| 46 |
+
|
| 47 |
+
5. ANNOTATIONS : un triplet peut avoir un champ `annotations` (liste de
|
| 48 |
+
`{kind, value, w}`). Les `value` courantes sont :
|
| 49 |
+
* `constitutif` : trait définitionnel de l'entité
|
| 50 |
+
* `contrastif` : trait différenciateur (par opposition à des catégories voisines)
|
| 51 |
+
* `pertinent` / `non pertinent` / `peu pertinent` : jugement sur l'utilité
|
| 52 |
+
* `non spécifique` : trait qui ne caractérise pas particulièrement l'entité
|
| 53 |
+
Lorsque tu cites un triplet annoté, mentionne brièvement l'annotation la
|
| 54 |
+
plus consensuelle (poids le plus fort) pour nuancer ta réponse.
|
| 55 |
+
|
| 56 |
+
6. Les poids (`w`) reflètent la pertinence selon JDM. La valeur ABSOLUE indique
|
| 57 |
+
l'intensité du consensus ; le SIGNE est déjà capté par `polarity`. Privilégie
|
| 58 |
+
les triplets de `|w|` élevé (signaux forts, positifs OU négatifs).
|
| 59 |
+
|
| 60 |
+
7. Pour les termes polysémiques (avocat, souris, police, chat, …), commence
|
| 61 |
TOUJOURS par `disambiguate`. Le résultat contient `sense` (forme lisible)
|
| 62 |
et `sense_id` (identifiant brut à passer dans les outils suivants pour
|
| 63 |
requêter ce sens précis).
|
| 64 |
+
|
| 65 |
+
8. Quand un triplet renvoyé contient `source_id` ou `target_id`, c'est qu'il
|
| 66 |
désigne un sens raffiné. Cite la forme lisible (`source`/`target`), mais
|
| 67 |
garde l'`*_id` si tu dois rappeler un outil sur ce sens spécifique.
|
| 68 |
+
|
| 69 |
+
9. Si tu ne connais pas le nom technique d'une relation, utilise
|
| 70 |
`list_relation_types(prefix=...)`.
|
| 71 |
+
|
| 72 |
+
10. Réponds en français concis : réponse synthétique d'abord, puis section
|
| 73 |
+
"Sources JDM :" listant les triplets (en marquant clairement les négations).
|
| 74 |
"""
|
| 75 |
|
| 76 |
|
|
@@ -41,31 +41,58 @@ def _client() -> JDMClient:
|
|
| 41 |
|
| 42 |
# ---------- Helpers ----------
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
def _make_triplet(
|
| 45 |
src_display: str, src_id: Optional[str],
|
| 46 |
rel: str,
|
| 47 |
tgt_display: str, tgt_id: Optional[str],
|
| 48 |
w: float,
|
|
|
|
| 49 |
) -> dict:
|
| 50 |
"""Construit un triplet exposé au LLM.
|
| 51 |
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
| 55 |
"""
|
| 56 |
-
out: dict = {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
if src_id is not None:
|
| 58 |
out["source_id"] = src_id
|
| 59 |
if tgt_id is not None:
|
| 60 |
out["target_id"] = tgt_id
|
|
|
|
|
|
|
| 61 |
return out
|
| 62 |
|
| 63 |
|
| 64 |
def _resolve_targets(client: JDMClient, source_name: str, rel_name: str, result,
|
| 65 |
-
incoming: bool = False
|
|
|
|
| 66 |
"""Construit la liste de triplets en résolvant les noms d'autres bouts
|
| 67 |
ET en décodant tout refinement opaque (`avocat>116477>66699`) en clair.
|
| 68 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
Si incoming=True (direction "to"), le terme `source_name` correspond au
|
| 70 |
node2 des relations renvoyées, et l'autre bout à exposer est node1.
|
| 71 |
"""
|
|
@@ -78,7 +105,8 @@ def _resolve_targets(client: JDMClient, source_name: str, rel_name: str, result,
|
|
| 78 |
src_id_root = source_name if src_dec["is_refinement"] else None
|
| 79 |
|
| 80 |
triplets: list[dict] = []
|
| 81 |
-
|
|
|
|
| 82 |
other_id = r.node1 if incoming else r.node2
|
| 83 |
node = idx.get(other_id)
|
| 84 |
if node is None:
|
|
@@ -86,20 +114,28 @@ def _resolve_targets(client: JDMClient, source_name: str, rel_name: str, result,
|
|
| 86 |
node = client.node_by_id(other_id)
|
| 87 |
except Exception:
|
| 88 |
continue
|
|
|
|
|
|
|
|
|
|
| 89 |
other_dec = client.decode_node_name(node.name, local_nodes=idx)
|
| 90 |
other_display = other_dec["decoded"]
|
| 91 |
other_id_str = node.name if other_dec["is_refinement"] else None
|
| 92 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
if incoming:
|
| 94 |
-
# Le terme racine est la CIBLE ; l'autre bout est la source.
|
| 95 |
triplets.append(_make_triplet(
|
| 96 |
other_display, other_id_str, rel_name,
|
| 97 |
-
src_display, src_id_root, r.w,
|
| 98 |
))
|
| 99 |
else:
|
| 100 |
triplets.append(_make_triplet(
|
| 101 |
src_display, src_id_root, rel_name,
|
| 102 |
-
other_display, other_id_str, r.w,
|
| 103 |
))
|
| 104 |
return triplets
|
| 105 |
|
|
@@ -154,7 +190,7 @@ def get_synonyms(term: str, min_weight: Optional[float] = None, limit: Optional[
|
|
| 154 |
c = _client()
|
| 155 |
rid = c.relation_type_id("r_syn")
|
| 156 |
res = c.relations_from(term, types_ids=[rid] if rid else None,
|
| 157 |
-
min_weight=_mw(min_weight,
|
| 158 |
return _resolve_targets(c, term, "r_syn", res)
|
| 159 |
|
| 160 |
|
|
@@ -167,7 +203,7 @@ def get_antonyms(term: str, min_weight: Optional[float] = None, limit: Optional[
|
|
| 167 |
c = _client()
|
| 168 |
rid = c.relation_type_id("r_anto")
|
| 169 |
res = c.relations_from(term, types_ids=[rid] if rid else None,
|
| 170 |
-
min_weight=_mw(min_weight,
|
| 171 |
return _resolve_targets(c, term, "r_anto", res)
|
| 172 |
|
| 173 |
|
|
@@ -182,7 +218,7 @@ def get_hypernyms(term: str, min_weight: Optional[float] = None, limit: Optional
|
|
| 182 |
c = _client()
|
| 183 |
rid = c.relation_type_id("r_isa")
|
| 184 |
res = c.relations_from(term, types_ids=[rid] if rid else None,
|
| 185 |
-
min_weight=_mw(min_weight,
|
| 186 |
return _resolve_targets(c, term, "r_isa", res)
|
| 187 |
|
| 188 |
|
|
@@ -197,7 +233,7 @@ def get_hyponyms(term: str, min_weight: Optional[float] = None, limit: Optional[
|
|
| 197 |
c = _client()
|
| 198 |
rid = c.relation_type_id("r_hypo")
|
| 199 |
res = c.relations_from(term, types_ids=[rid] if rid else None,
|
| 200 |
-
min_weight=_mw(min_weight,
|
| 201 |
return _resolve_targets(c, term, "r_hypo", res)
|
| 202 |
|
| 203 |
|
|
@@ -211,7 +247,7 @@ def get_parts(term: str, min_weight: Optional[float] = None, limit: Optional[int
|
|
| 211 |
c = _client()
|
| 212 |
rid = c.relation_type_id("r_has_part")
|
| 213 |
res = c.relations_from(term, types_ids=[rid] if rid else None,
|
| 214 |
-
min_weight=_mw(min_weight,
|
| 215 |
return _resolve_targets(c, term, "r_has_part", res)
|
| 216 |
|
| 217 |
|
|
@@ -225,7 +261,7 @@ def get_characteristics(term: str, min_weight: Optional[float] = None, limit: Op
|
|
| 225 |
c = _client()
|
| 226 |
rid = c.relation_type_id("r_carac")
|
| 227 |
res = c.relations_from(term, types_ids=[rid] if rid else None,
|
| 228 |
-
min_weight=_mw(min_weight,
|
| 229 |
return _resolve_targets(c, term, "r_carac", res)
|
| 230 |
|
| 231 |
|
|
@@ -256,7 +292,7 @@ def get_relations_of_type(
|
|
| 256 |
if rid is None:
|
| 257 |
return [{"error": f"relation inconnue: {relation_name!r}"}]
|
| 258 |
incoming = direction == "to"
|
| 259 |
-
mw, lm = _mw(min_weight,
|
| 260 |
if incoming:
|
| 261 |
res = c.relations_to(term, types_ids=[rid], min_weight=mw, limit=lm)
|
| 262 |
else:
|
|
@@ -274,7 +310,7 @@ def get_relations_between(term1: str, term2: str, min_weight: Optional[float] =
|
|
| 274 |
`source_id`/`target_id`.
|
| 275 |
"""
|
| 276 |
c = _client()
|
| 277 |
-
res = c.relations_between(term1, term2, min_weight=_mw(min_weight,
|
| 278 |
idx = res.node_index()
|
| 279 |
src_dec = c.decode_node_name(term1, local_nodes=idx)
|
| 280 |
tgt_dec = c.decode_node_name(term2, local_nodes=idx)
|
|
@@ -330,7 +366,7 @@ def disambiguate(term: str) -> list[dict]:
|
|
| 330 |
def _predicative_lookup(
|
| 331 |
term: str, relation: str, direction: str,
|
| 332 |
min_weight: Optional[float], limit: Optional[int],
|
| 333 |
-
default_mw: float =
|
| 334 |
) -> list[dict]:
|
| 335 |
"""Helper factor pour tous les outils prédicatifs."""
|
| 336 |
c = _client()
|
|
|
|
| 41 |
|
| 42 |
# ---------- Helpers ----------
|
| 43 |
|
| 44 |
+
def _polarity(w: float) -> str:
|
| 45 |
+
"""Dérive la polarité du signe du poids (cf. relation_definitions.md §19)."""
|
| 46 |
+
if w < 0:
|
| 47 |
+
return "négation"
|
| 48 |
+
return "affirmation"
|
| 49 |
+
|
| 50 |
+
|
| 51 |
def _make_triplet(
|
| 52 |
src_display: str, src_id: Optional[str],
|
| 53 |
rel: str,
|
| 54 |
tgt_display: str, tgt_id: Optional[str],
|
| 55 |
w: float,
|
| 56 |
+
annotations: Optional[list[dict]] = None,
|
| 57 |
) -> dict:
|
| 58 |
"""Construit un triplet exposé au LLM.
|
| 59 |
|
| 60 |
+
Phase 9 — ajoute `polarity` (affirmation/négation) et `annotations`.
|
| 61 |
+
|
| 62 |
+
Les `*_id` ne sont inclus QUE si le nom est un refinement JDM (= valeur
|
| 63 |
+
informative à passer pour requêter ce sens précis). Pour les termes
|
| 64 |
+
simples, on garde le payload minimal.
|
| 65 |
"""
|
| 66 |
+
out: dict = {
|
| 67 |
+
"source": src_display,
|
| 68 |
+
"relation": rel,
|
| 69 |
+
"target": tgt_display,
|
| 70 |
+
"w": w,
|
| 71 |
+
"polarity": _polarity(w),
|
| 72 |
+
}
|
| 73 |
if src_id is not None:
|
| 74 |
out["source_id"] = src_id
|
| 75 |
if tgt_id is not None:
|
| 76 |
out["target_id"] = tgt_id
|
| 77 |
+
if annotations:
|
| 78 |
+
out["annotations"] = annotations
|
| 79 |
return out
|
| 80 |
|
| 81 |
|
| 82 |
def _resolve_targets(client: JDMClient, source_name: str, rel_name: str, result,
|
| 83 |
+
incoming: bool = False,
|
| 84 |
+
with_annotations: bool = True) -> list[dict]:
|
| 85 |
"""Construit la liste de triplets en résolvant les noms d'autres bouts
|
| 86 |
ET en décodant tout refinement opaque (`avocat>116477>66699`) en clair.
|
| 87 |
|
| 88 |
+
Phase 9 — ajoute :
|
| 89 |
+
- tri par |w| décroissant (au lieu de w décroissant) pour faire remonter
|
| 90 |
+
les signaux forts négatifs en même temps que les positifs
|
| 91 |
+
- filtre des chunks (type 8) comme targets : ils ne sont pas exposés
|
| 92 |
+
en Phase 9, cf. plan d'évolution
|
| 93 |
+
- lookup des annotations par triplet via get_annotations_for_triplet
|
| 94 |
+
(N+1 HTTP cached) si with_annotations=True
|
| 95 |
+
|
| 96 |
Si incoming=True (direction "to"), le terme `source_name` correspond au
|
| 97 |
node2 des relations renvoyées, et l'autre bout à exposer est node1.
|
| 98 |
"""
|
|
|
|
| 105 |
src_id_root = source_name if src_dec["is_refinement"] else None
|
| 106 |
|
| 107 |
triplets: list[dict] = []
|
| 108 |
+
# Tri |w| décroissant : positifs forts ET négatifs forts en tête de liste
|
| 109 |
+
for r in sorted(result.relations, key=lambda x: -abs(x.w)):
|
| 110 |
other_id = r.node1 if incoming else r.node2
|
| 111 |
node = idx.get(other_id)
|
| 112 |
if node is None:
|
|
|
|
| 114 |
node = client.node_by_id(other_id)
|
| 115 |
except Exception:
|
| 116 |
continue
|
| 117 |
+
# Skip les chunks (type 8) — agrégats syntaxiques non exposés en Phase 9.
|
| 118 |
+
if node.type == 8:
|
| 119 |
+
continue
|
| 120 |
other_dec = client.decode_node_name(node.name, local_nodes=idx)
|
| 121 |
other_display = other_dec["decoded"]
|
| 122 |
other_id_str = node.name if other_dec["is_refinement"] else None
|
| 123 |
|
| 124 |
+
# Lookup annotations (N+1 HTTP, cached)
|
| 125 |
+
annotations: list[dict] = []
|
| 126 |
+
if with_annotations:
|
| 127 |
+
for a in client.get_annotations_for_triplet(r.id):
|
| 128 |
+
annotations.append({"kind": a.kind, "value": a.value, "w": a.w})
|
| 129 |
+
|
| 130 |
if incoming:
|
|
|
|
| 131 |
triplets.append(_make_triplet(
|
| 132 |
other_display, other_id_str, rel_name,
|
| 133 |
+
src_display, src_id_root, r.w, annotations,
|
| 134 |
))
|
| 135 |
else:
|
| 136 |
triplets.append(_make_triplet(
|
| 137 |
src_display, src_id_root, rel_name,
|
| 138 |
+
other_display, other_id_str, r.w, annotations,
|
| 139 |
))
|
| 140 |
return triplets
|
| 141 |
|
|
|
|
| 190 |
c = _client()
|
| 191 |
rid = c.relation_type_id("r_syn")
|
| 192 |
res = c.relations_from(term, types_ids=[rid] if rid else None,
|
| 193 |
+
min_weight=_mw(min_weight, 0.0), limit=_lim(limit, 20))
|
| 194 |
return _resolve_targets(c, term, "r_syn", res)
|
| 195 |
|
| 196 |
|
|
|
|
| 203 |
c = _client()
|
| 204 |
rid = c.relation_type_id("r_anto")
|
| 205 |
res = c.relations_from(term, types_ids=[rid] if rid else None,
|
| 206 |
+
min_weight=_mw(min_weight, 0.0), limit=_lim(limit, 20))
|
| 207 |
return _resolve_targets(c, term, "r_anto", res)
|
| 208 |
|
| 209 |
|
|
|
|
| 218 |
c = _client()
|
| 219 |
rid = c.relation_type_id("r_isa")
|
| 220 |
res = c.relations_from(term, types_ids=[rid] if rid else None,
|
| 221 |
+
min_weight=_mw(min_weight, 0.0), limit=_lim(limit, 20))
|
| 222 |
return _resolve_targets(c, term, "r_isa", res)
|
| 223 |
|
| 224 |
|
|
|
|
| 233 |
c = _client()
|
| 234 |
rid = c.relation_type_id("r_hypo")
|
| 235 |
res = c.relations_from(term, types_ids=[rid] if rid else None,
|
| 236 |
+
min_weight=_mw(min_weight, 0.0), limit=_lim(limit, 30))
|
| 237 |
return _resolve_targets(c, term, "r_hypo", res)
|
| 238 |
|
| 239 |
|
|
|
|
| 247 |
c = _client()
|
| 248 |
rid = c.relation_type_id("r_has_part")
|
| 249 |
res = c.relations_from(term, types_ids=[rid] if rid else None,
|
| 250 |
+
min_weight=_mw(min_weight, 0.0), limit=_lim(limit, 30))
|
| 251 |
return _resolve_targets(c, term, "r_has_part", res)
|
| 252 |
|
| 253 |
|
|
|
|
| 261 |
c = _client()
|
| 262 |
rid = c.relation_type_id("r_carac")
|
| 263 |
res = c.relations_from(term, types_ids=[rid] if rid else None,
|
| 264 |
+
min_weight=_mw(min_weight, 0.0), limit=_lim(limit, 30))
|
| 265 |
return _resolve_targets(c, term, "r_carac", res)
|
| 266 |
|
| 267 |
|
|
|
|
| 292 |
if rid is None:
|
| 293 |
return [{"error": f"relation inconnue: {relation_name!r}"}]
|
| 294 |
incoming = direction == "to"
|
| 295 |
+
mw, lm = _mw(min_weight, 0.0), _lim(limit, 30)
|
| 296 |
if incoming:
|
| 297 |
res = c.relations_to(term, types_ids=[rid], min_weight=mw, limit=lm)
|
| 298 |
else:
|
|
|
|
| 310 |
`source_id`/`target_id`.
|
| 311 |
"""
|
| 312 |
c = _client()
|
| 313 |
+
res = c.relations_between(term1, term2, min_weight=_mw(min_weight, 0.0))
|
| 314 |
idx = res.node_index()
|
| 315 |
src_dec = c.decode_node_name(term1, local_nodes=idx)
|
| 316 |
tgt_dec = c.decode_node_name(term2, local_nodes=idx)
|
|
|
|
| 366 |
def _predicative_lookup(
|
| 367 |
term: str, relation: str, direction: str,
|
| 368 |
min_weight: Optional[float], limit: Optional[int],
|
| 369 |
+
default_mw: float = 0.0, default_limit: int = 20,
|
| 370 |
) -> list[dict]:
|
| 371 |
"""Helper factor pour tous les outils prédicatifs."""
|
| 372 |
c = _client()
|
|
@@ -101,6 +101,54 @@ def test_retry_on_5xx(client):
|
|
| 101 |
assert route.call_count == 2
|
| 102 |
|
| 103 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
@respx.mock
|
| 105 |
def test_refinements_decoded(client):
|
| 106 |
"""Décode `avocat>116477>66699` → "avocat (personne, juriste)" via lookups node_by_id."""
|
|
|
|
| 101 |
assert route.call_count == 2
|
| 102 |
|
| 103 |
|
| 104 |
+
@respx.mock
|
| 105 |
+
def test_get_annotations_for_triplet(client):
|
| 106 |
+
"""Phase 9 : récupération des annotations via :r{id}.
|
| 107 |
+
|
| 108 |
+
Vérifie que :
|
| 109 |
+
- on appelle bien /v0/relations/from/:r{id} sans types_ids (bug JDM)
|
| 110 |
+
- on filtre les targets sur node.type==1 (skip r_pos type 4)
|
| 111 |
+
- on mappe les types 996/997/998 vers les bons 'kind'
|
| 112 |
+
"""
|
| 113 |
+
respx.get(f"{BASE}/v0/relations_types").mock(return_value=httpx.Response(200, json=REL_TYPES))
|
| 114 |
+
respx.get(f"{BASE}/v0/nodes_types").mock(return_value=httpx.Response(200, json=NODE_TYPES))
|
| 115 |
+
# Le node :r12345 a 3 outgoing :
|
| 116 |
+
# type=4 (r_pos) "Relation:" type=4 → à ignorer
|
| 117 |
+
# type=998 (r_annotation) "contrastif" type=1 → conservé
|
| 118 |
+
# type=996 (r_annotation_context) "constitutif" type=1 → conservé
|
| 119 |
+
respx.get(f"{BASE}/v0/relations/from/:r12345").mock(return_value=httpx.Response(200, json={
|
| 120 |
+
"nodes": [
|
| 121 |
+
{"id": 999, "name": ":r12345", "type": 10, "w": 0},
|
| 122 |
+
{"id": 100, "name": "Relation:", "type": 4, "w": 100},
|
| 123 |
+
{"id": 101, "name": "contrastif", "type": 1, "w": 200},
|
| 124 |
+
{"id": 102, "name": "constitutif", "type": 1, "w": 80},
|
| 125 |
+
],
|
| 126 |
+
"relations": [
|
| 127 |
+
{"id": 1, "node1": 999, "node2": 100, "type": 4, "w": 100}, # r_pos - skip
|
| 128 |
+
{"id": 2, "node1": 999, "node2": 101, "type": 998, "w": 200},
|
| 129 |
+
{"id": 3, "node1": 999, "node2": 102, "type": 996, "w": 80},
|
| 130 |
+
],
|
| 131 |
+
}))
|
| 132 |
+
annots = client.get_annotations_for_triplet(12345)
|
| 133 |
+
assert len(annots) == 2
|
| 134 |
+
# Tri par |w| desc : contrastif (200) puis constitutif (80)
|
| 135 |
+
assert annots[0].kind == "annotation"
|
| 136 |
+
assert annots[0].value == "contrastif"
|
| 137 |
+
assert annots[0].w == 200
|
| 138 |
+
assert annots[1].kind == "context"
|
| 139 |
+
assert annots[1].value == "constitutif"
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
@respx.mock
|
| 143 |
+
def test_get_annotations_returns_empty_on_500(client):
|
| 144 |
+
"""Le pattern :r{id} 500-fail gracieusement si le triplet n'est pas annoté."""
|
| 145 |
+
respx.get(f"{BASE}/v0/relations_types").mock(return_value=httpx.Response(200, json=REL_TYPES))
|
| 146 |
+
respx.get(f"{BASE}/v0/nodes_types").mock(return_value=httpx.Response(200, json=NODE_TYPES))
|
| 147 |
+
respx.get(f"{BASE}/v0/relations/from/:r999999").mock(return_value=httpx.Response(500, json={}))
|
| 148 |
+
annots = client.get_annotations_for_triplet(999999)
|
| 149 |
+
assert annots == []
|
| 150 |
+
|
| 151 |
+
|
| 152 |
@respx.mock
|
| 153 |
def test_refinements_decoded(client):
|
| 154 |
"""Décode `avocat>116477>66699` → "avocat (personne, juriste)" via lookups node_by_id."""
|
|
@@ -115,6 +115,62 @@ def test_unknown_relation_name(client):
|
|
| 115 |
assert "inconnue" in v.explanation.lower()
|
| 116 |
|
| 117 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
@respx.mock
|
| 119 |
def test_factcheck_claims_batch(client):
|
| 120 |
"""Mode batch : plusieurs claims, un report consolidé."""
|
|
|
|
| 115 |
assert "inconnue" in v.explanation.lower()
|
| 116 |
|
| 117 |
|
| 118 |
+
@respx.mock
|
| 119 |
+
def test_phase9_direct_negative_match_contradicted(client):
|
| 120 |
+
"""Phase 9 : un triplet présent dans JDM avec w<0 doit donner CONTRADICTED
|
| 121 |
+
pour une claim positive (et non plus UNKNOWN comme avant)."""
|
| 122 |
+
_meta_mocks()
|
| 123 |
+
# baleine r_isa poisson existe à w=-35 dans JDM
|
| 124 |
+
respx.get(f"{BASE}/v0/relations/from/baleine").mock(return_value=httpx.Response(200, json={
|
| 125 |
+
"nodes": [
|
| 126 |
+
{"id": 10, "name": "baleine", "type": 1, "w": 100},
|
| 127 |
+
{"id": 20, "name": "poisson", "type": 1, "w": 800},
|
| 128 |
+
],
|
| 129 |
+
"relations": [{"id": 9001, "node1": 10, "node2": 20, "type": 6, "w": -35.0}],
|
| 130 |
+
}))
|
| 131 |
+
# Pas d'annotation
|
| 132 |
+
respx.get(f"{BASE}/v0/relations/from/:r9001").mock(return_value=httpx.Response(500, json={}))
|
| 133 |
+
v = verify_claim(client, Claim(
|
| 134 |
+
text="baleine est un poisson",
|
| 135 |
+
subject="baleine", relation="r_isa", object="poisson",
|
| 136 |
+
))
|
| 137 |
+
assert v.status == Status.CONTRADICTED
|
| 138 |
+
assert "négation consensuelle" in v.explanation
|
| 139 |
+
assert v.evidence_against
|
| 140 |
+
assert v.evidence_against[0].w == -35.0
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
@respx.mock
|
| 144 |
+
def test_phase9_factcheck_includes_annotations_in_explanation(client):
|
| 145 |
+
"""Si le triplet trouvé est annoté, l'explication mentionne les annotations."""
|
| 146 |
+
_meta_mocks()
|
| 147 |
+
respx.get(f"{BASE}/v0/relations/from/chat").mock(return_value=httpx.Response(200, json={
|
| 148 |
+
"nodes": [
|
| 149 |
+
{"id": 1, "name": "chat", "type": 1, "w": 100},
|
| 150 |
+
{"id": 2, "name": "mammifère", "type": 1, "w": 1000},
|
| 151 |
+
],
|
| 152 |
+
"relations": [{"id": 4242, "node1": 1, "node2": 2, "type": 6, "w": 1000.0}],
|
| 153 |
+
}))
|
| 154 |
+
# Annotations attachées au triplet 4242
|
| 155 |
+
respx.get(f"{BASE}/v0/relations/from/:r4242").mock(return_value=httpx.Response(200, json={
|
| 156 |
+
"nodes": [
|
| 157 |
+
{"id": 901, "name": "contrastif", "type": 1, "w": 1003},
|
| 158 |
+
{"id": 902, "name": "non spécifique", "type": 1, "w": 3},
|
| 159 |
+
],
|
| 160 |
+
"relations": [
|
| 161 |
+
{"id": 91, "node1": 99, "node2": 901, "type": 998, "w": 1003},
|
| 162 |
+
{"id": 92, "node1": 99, "node2": 902, "type": 998, "w": 3},
|
| 163 |
+
],
|
| 164 |
+
}))
|
| 165 |
+
v = verify_claim(client, Claim(
|
| 166 |
+
text="le chat est un mammifère",
|
| 167 |
+
subject="chat", relation="r_isa", object="mammifère",
|
| 168 |
+
))
|
| 169 |
+
assert v.status == Status.SUPPORTED
|
| 170 |
+
assert "contrastif" in v.explanation
|
| 171 |
+
assert "Annotations JDM" in v.explanation
|
| 172 |
+
|
| 173 |
+
|
| 174 |
@respx.mock
|
| 175 |
def test_factcheck_claims_batch(client):
|
| 176 |
"""Mode batch : plusieurs claims, un report consolidé."""
|