nvikou commited on
Commit
da21448
·
verified ·
1 Parent(s): ccf256d

Deploy TechDocs GraphRAG

Browse files
.dockerignore ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .env
2
+ __pycache__/
3
+ *.py[cod]
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ .venv/
7
+ *.egg-info/
8
+ dist/
9
+ build/
10
+ tests/
11
+ .git/
.env.example ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ OPENAI_API_KEY=sk-...
2
+ CHAT_MODEL=gpt-4o-mini
3
+ EMBEDDING_MODEL=text-embedding-3-small
4
+
5
+ NEO4J_URI=neo4j+s://xxxxxxxx.databases.neo4j.io
6
+ NEO4J_USERNAME=neo4j
7
+ NEO4J_PASSWORD=...
8
+ NEO4J_DATABASE=neo4j
.gitignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ .env
2
+ __pycache__/
3
+ *.py[cod]
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ .venv/
7
+ *.egg-info/
8
+ dist/
9
+ build/
.streamlit/config.toml ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ [server]
2
+ headless = true
3
+ maxUploadSize = 20
4
+
5
+ [browser]
6
+ gatherUsageStats = false
7
+
8
+ [theme]
9
+ primaryColor = "#4F46E5"
Dockerfile ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.12-slim-bookworm
2
+
3
+ ARG NEO4J_VERSION=5.26.0
4
+
5
+ ENV PYTHONDONTWRITEBYTECODE=1 \
6
+ PYTHONUNBUFFERED=1 \
7
+ PIP_NO_CACHE_DIR=1
8
+
9
+ RUN apt-get update \
10
+ && apt-get install -y --no-install-recommends openjdk-17-jre-headless curl \
11
+ && rm -rf /var/lib/apt/lists/*
12
+
13
+ RUN useradd --create-home --uid 1000 user
14
+ USER user
15
+ ENV HOME=/home/user
16
+ ENV NEO4J_HOME=$HOME/neo4j \
17
+ PATH=$HOME/neo4j/bin:$HOME/.local/bin:$PATH \
18
+ NEO4J_URI=bolt://localhost:7687 \
19
+ NEO4J_USERNAME=neo4j
20
+ WORKDIR $HOME
21
+
22
+ RUN curl -fsSL "https://dist.neo4j.org/neo4j-community-${NEO4J_VERSION}-unix.tar.gz" | tar -xz \
23
+ && mv "neo4j-community-${NEO4J_VERSION}" neo4j \
24
+ && printf '%s\n' \
25
+ 'server.memory.heap.initial_size=512m' \
26
+ 'server.memory.heap.max_size=1g' \
27
+ 'server.memory.pagecache.size=512m' \
28
+ 'dbms.usage_report.enabled=false' >> neo4j/conf/neo4j.conf
29
+
30
+ WORKDIR $HOME/app
31
+ COPY --chown=user pyproject.toml README.md ./
32
+ COPY --chown=user src ./src
33
+ RUN pip install --user --upgrade pip && pip install --user .
34
+
35
+ COPY --chown=user . .
36
+ RUN chmod +x entrypoint.sh
37
+
38
+ EXPOSE 7860
39
+ CMD ["./entrypoint.sh"]
README.md CHANGED
@@ -1,10 +1,111 @@
1
  ---
2
- title: Techdocs Graphrag
3
- emoji: 🌖
4
- colorFrom: purple
5
- colorTo: gray
6
  sdk: docker
 
7
  pinned: false
 
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: TechDocs GraphRAG
3
+ emoji: 🕸️
4
+ colorFrom: indigo
5
+ colorTo: blue
6
  sdk: docker
7
+ app_port: 7860
8
  pinned: false
9
+ license: mit
10
+ short_description: GraphRAG sur documentation technique (Neo4j + OpenAI)
11
  ---
12
 
13
+ # 🕸️ TechDocs GraphRAG
14
+
15
+ Assistant de documentation technique qui combine **recherche vectorielle** et **graphe de connaissances Neo4j**
16
+ pour répondre à des questions multi-hop avec des sources traçables.
17
+
18
+ Un RAG classique retrouve des passages similaires à la question. TechDocs GraphRAG extrait en plus les
19
+ entités et relations du corpus (`StateGraph —PERSISTS_WITH→ Checkpointer —ENABLES→ Persistence`) et
20
+ suit ces liens au moment de répondre.
21
+
22
+ ## Fonctionnalités
23
+
24
+ - Ingestion Markdown, découpage par paragraphes avec chevauchement.
25
+ - Extraction LLM d'entités typées et de relations avec preuve textuelle.
26
+ - Déduplication des entités par clé canonique (`State Graph`, `state_graph` → `stategraph`).
27
+ - Neo4j Community embarqué dans le conteneur, corpus indexé automatiquement au démarrage.
28
+ - Neo4j comme store unique : documents, chunks, index vectoriel, index plein texte, graphe.
29
+ - Recherche hybride : chunks proches → entités mentionnées + entités citées dans la question → traversée multi-hop.
30
+ - Interface Streamlit : sous-graphe utilisé, relations, extraits, sources.
31
+ - Mode comparaison RAG vectoriel vs GraphRAG.
32
+
33
+ ## Architecture
34
+
35
+ ```mermaid
36
+ flowchart LR
37
+ A[Markdown] --> B[ParagraphSplitter]
38
+ B --> C[Embeddings OpenAI]
39
+ B --> D[Extraction LLM]
40
+ C --> E[(Neo4j<br/>index vectoriel)]
41
+ D --> F[(Neo4j<br/>graphe d'entités)]
42
+ Q[Question] --> R[HybridRetriever]
43
+ E --> R
44
+ F --> R
45
+ R --> G[GraphRAGAssistant]
46
+ G --> S[Réponse sourcée]
47
+ ```
48
+
49
+ ### Modèle de graphe
50
+
51
+ ```text
52
+ (:Document)-[:HAS_CHUNK]->(:Chunk {embedding})-[:MENTIONS]->(:Entity:Component)
53
+ (:Entity)-[:USES | PERSISTS_WITH | DEPENDS_ON | ...]->(:Entity)
54
+ ```
55
+
56
+ Chaque relation porte `evidence` et `documents`, ce qui rend chaque fait vérifiable.
57
+
58
+ ## Structure
59
+
60
+ ```text
61
+ ├── app.py
62
+ ├── Dockerfile
63
+ ├── data/
64
+ ├── src/techdocs_graphrag/
65
+ │ ├── config.py
66
+ │ ├── models.py
67
+ │ ├── ports.py
68
+ │ ├── ingestion.py
69
+ │ ├── llm.py
70
+ │ ├── prompts.py
71
+ │ ├── extraction.py
72
+ │ ├── graph_store.py
73
+ │ ├── indexing.py
74
+ │ ├── retrieval.py
75
+ │ ├── answering.py
76
+ │ ├── visualization.py
77
+ │ ├── services.py
78
+ │ └── cli.py
79
+ └── tests/
80
+ ```
81
+
82
+ ## Configuration
83
+
84
+ | Variable | Défaut | Rôle |
85
+ |---|---|---|
86
+ | `OPENAI_API_KEY` | requis | Clé OpenAI |
87
+ | `NEO4J_URI` | `bolt://localhost:7687` | Neo4j embarqué dans le conteneur |
88
+ | `NEO4J_USERNAME` | `neo4j` | Utilisateur Neo4j |
89
+ | `NEO4J_PASSWORD` | `techdocs-local-password` | Mot de passe Neo4j (secret conseillé) |
90
+ | `NEO4J_DATABASE` | `neo4j` | Base Neo4j |
91
+ | `CHAT_MODEL` | `gpt-4o-mini` | Modèle de génération |
92
+ | `EMBEDDING_MODEL` | `text-embedding-3-small` | Modèle d'embeddings |
93
+ | `GRAPH_MAX_HOPS` | `2` | Profondeur de traversée |
94
+ | `VECTOR_TOP_K` | `5` | Nombre de chunks récupérés |
95
+
96
+ ## Lancer en local
97
+
98
+ ```bash
99
+ cp .env.example .env
100
+ pip install -e ".[dev]"
101
+ pytest
102
+ techdocs-index data --reset
103
+ streamlit run app.py
104
+ ```
105
+
106
+ ## Feuille de route
107
+
108
+ - Jeu d'évaluation annoté (30 à 50 questions) et métriques de fidélité.
109
+ - Fusion d'entités par similarité d'embeddings.
110
+ - Résumés de communautés (approche Microsoft GraphRAG) pour les questions globales.
111
+ - API FastAPI `POST /ask`.
app.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Sequence
2
+ from pathlib import Path
3
+
4
+ import streamlit as st
5
+ from neo4j.exceptions import DriverError, Neo4jError
6
+ from pydantic import ValidationError
7
+
8
+ from techdocs_graphrag import (
9
+ Answer,
10
+ RetrievalMode,
11
+ Services,
12
+ SourceDocument,
13
+ build_services,
14
+ load_documents,
15
+ )
16
+ from techdocs_graphrag.visualization import facts_to_dot
17
+
18
+ SAMPLE_CORPUS = Path(__file__).parent / "data"
19
+
20
+ MODE_LABELS = {
21
+ RetrievalMode.GRAPH: "GraphRAG",
22
+ RetrievalMode.VECTOR: "RAG vectoriel",
23
+ }
24
+
25
+ DISPLAY_MODES: dict[str, tuple[RetrievalMode, ...]] = {
26
+ "GraphRAG": (RetrievalMode.GRAPH,),
27
+ "RAG vectoriel": (RetrievalMode.VECTOR,),
28
+ "Comparaison côte à côte": (RetrievalMode.VECTOR, RetrievalMode.GRAPH),
29
+ }
30
+
31
+ EXAMPLE_QUESTIONS = (
32
+ "Comment persister l'état d'un workflow StateGraph ?",
33
+ "Quel est le rôle des reducers dans les channels ?",
34
+ "Comment reprendre un workflow après une interruption humaine ?",
35
+ )
36
+
37
+ st.set_page_config(page_title="TechDocs GraphRAG", page_icon="🕸️", layout="wide")
38
+
39
+
40
+ @st.cache_resource(show_spinner="Connexion à Neo4j et OpenAI…")
41
+ def get_services() -> Services:
42
+ services = build_services()
43
+ services.store.verify_connectivity()
44
+ services.store.ensure_schema()
45
+ return services
46
+
47
+
48
+ def load_services() -> Services:
49
+ try:
50
+ return get_services()
51
+ except ValidationError as error:
52
+ missing = ", ".join(sorted({str(item["loc"][0]).upper() for item in error.errors()}))
53
+ st.error(f"Configuration incomplète. Variables à définir dans les secrets : {missing}")
54
+ except (Neo4jError, DriverError) as error:
55
+ st.error(f"Connexion à Neo4j impossible : {error}")
56
+ st.stop()
57
+
58
+
59
+ def index_documents(services: Services, documents: Sequence[SourceDocument]) -> None:
60
+ progress = st.progress(0.0, text="Calcul des embeddings…")
61
+
62
+ def report_progress(done: int, total: int) -> None:
63
+ progress.progress(done / total, text=f"Extraction du graphe : {done}/{total} chunks")
64
+
65
+ report = services.indexer.run(documents, on_progress=report_progress)
66
+ progress.empty()
67
+ st.success(
68
+ f"{report.documents} documents · {report.chunks} chunks · "
69
+ f"{report.entities} entités · {report.relations} relations"
70
+ )
71
+
72
+
73
+ def render_sidebar(services: Services) -> tuple[RetrievalMode, ...]:
74
+ with st.sidebar:
75
+ st.header("Base de connaissances")
76
+
77
+ uploads = st.file_uploader(
78
+ "Ajouter des documents",
79
+ type=["md", "markdown", "txt"],
80
+ accept_multiple_files=True,
81
+ )
82
+ if st.button("Indexer les documents ajoutés", disabled=not uploads):
83
+ index_documents(
84
+ services,
85
+ [SourceDocument(name=file.name, text=file.getvalue().decode("utf-8")) for file in uploads],
86
+ )
87
+ if st.button("Indexer le corpus d'exemple"):
88
+ index_documents(services, load_documents(SAMPLE_CORPUS))
89
+
90
+ st.divider()
91
+ display_mode = st.radio("Mode de recherche", options=list(DISPLAY_MODES))
92
+
93
+ st.divider()
94
+ render_stats(services)
95
+ if st.button("Effacer la conversation"):
96
+ st.session_state.turns = []
97
+ st.rerun()
98
+
99
+ return DISPLAY_MODES[display_mode]
100
+
101
+
102
+ def render_stats(services: Services) -> None:
103
+ stats = services.store.stats()
104
+ first, second = st.columns(2)
105
+ first.metric("Documents", stats["documents"])
106
+ second.metric("Chunks", stats["chunks"])
107
+ first.metric("Entités", stats["entities"])
108
+ second.metric("Relations", stats["relations"])
109
+
110
+
111
+ def render_answer(answer: Answer) -> None:
112
+ st.markdown(answer.text)
113
+ context = answer.context
114
+ if context.sources:
115
+ st.caption("Sources : " + " · ".join(context.sources))
116
+
117
+ with st.expander(f"Contexte · {len(context.chunks)} extraits · {len(context.facts)} relations"):
118
+ graph_tab, facts_tab, chunks_tab = st.tabs(["Sous-graphe", "Relations", "Extraits"])
119
+ with graph_tab:
120
+ if context.facts:
121
+ st.graphviz_chart(facts_to_dot(context.facts, context.seed_entities))
122
+ else:
123
+ st.info("Aucune relation du graphe n'a été utilisée.")
124
+ with facts_tab:
125
+ if context.facts:
126
+ st.dataframe([fact.model_dump() for fact in context.facts], hide_index=True)
127
+ else:
128
+ st.info("Aucune relation.")
129
+ with chunks_tab:
130
+ for chunk in context.chunks:
131
+ st.markdown(f"**{chunk.document}** · chunk {chunk.position} · score {chunk.score:.3f}")
132
+ st.text(chunk.text)
133
+
134
+
135
+ def render_turn(answers: Sequence[Answer]) -> None:
136
+ with st.chat_message("user"):
137
+ st.markdown(answers[0].question)
138
+ with st.chat_message("assistant"):
139
+ for column, answer in zip(st.columns(len(answers)), answers, strict=True):
140
+ with column:
141
+ if len(answers) > 1:
142
+ st.subheader(MODE_LABELS[answer.mode])
143
+ render_answer(answer)
144
+
145
+
146
+ def pick_example_question() -> str | None:
147
+ st.markdown("##### Exemples de questions")
148
+ columns = st.columns(len(EXAMPLE_QUESTIONS))
149
+ clicked = [
150
+ question
151
+ for column, question in zip(columns, EXAMPLE_QUESTIONS, strict=True)
152
+ if column.button(question)
153
+ ]
154
+ return clicked[0] if clicked else None
155
+
156
+
157
+ def main() -> None:
158
+ services = load_services()
159
+ modes = render_sidebar(services)
160
+
161
+ st.title("🕸️ TechDocs GraphRAG")
162
+ st.caption(
163
+ "Assistant de documentation technique : recherche vectorielle et graphe de connaissances "
164
+ "Neo4j pour des réponses multi-hop sourcées."
165
+ )
166
+
167
+ turns: list[list[Answer]] = st.session_state.setdefault("turns", [])
168
+ for answers in turns:
169
+ render_turn(answers)
170
+
171
+ typed_question = st.chat_input("Pose une question sur la documentation…")
172
+ question = typed_question or (None if turns else pick_example_question())
173
+ if not question:
174
+ return
175
+
176
+ with st.spinner("Recherche dans le graphe et les documents…"):
177
+ answers = [services.assistant.ask(question, mode) for mode in modes]
178
+ turns.append(answers)
179
+ render_turn(answers)
180
+
181
+
182
+ main()
data/channels.md ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Channels et reducers
2
+
3
+ Un Channel stocke la valeur d'une clé de l'état d'un StateGraph.
4
+ Par défaut, un Channel remplace l'ancienne valeur par la nouvelle valeur renvoyée par un Node.
5
+
6
+ Un Reducer définit comment un Channel combine l'ancienne valeur et la nouvelle.
7
+ Un Reducer se déclare avec typing.Annotated dans le schéma d'état.
8
+
9
+ La fonction add_messages est un Reducer fourni par LangGraph.
10
+ add_messages ajoute les nouveaux messages à la liste existante au lieu de la remplacer.
11
+
12
+ ```python
13
+ from typing import Annotated, TypedDict
14
+ from langgraph.graph.message import add_messages
15
+
16
+ class State(TypedDict):
17
+ messages: Annotated[list, add_messages]
18
+ ```
19
+
20
+ MessagesState est un schéma d'état prédéfini qui utilise add_messages sur la clé messages.
data/checkpointer.md ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Checkpointer
2
+
3
+ Un Checkpointer sauvegarde un Checkpoint de l'état du graphe après chaque étape d'exécution.
4
+ Le Checkpointer active la Persistence, le Human-in-the-loop, le Time Travel et la mémoire conversationnelle.
5
+
6
+ Les checkpoints sont regroupés par Thread.
7
+ Un Thread est identifié par le paramètre thread_id passé dans la configuration d'exécution.
8
+
9
+ ```python
10
+ config = {"configurable": {"thread_id": "conversation-42"}}
11
+ graph.invoke({"messages": [("user", "Bonjour")]}, config)
12
+ ```
13
+
14
+ InMemorySaver est un Checkpointer qui stocke les checkpoints en mémoire. Il convient aux tests.
15
+ SqliteSaver est un Checkpointer qui stocke les checkpoints dans une base SQLite.
16
+ PostgresSaver est un Checkpointer qui stocke les checkpoints dans PostgreSQL. Il est recommandé en production.
17
+
18
+ SqliteSaver dépend du package langgraph-checkpoint-sqlite.
19
+ PostgresSaver dépend du package langgraph-checkpoint-postgres.
20
+
21
+ La méthode get_state d'un CompiledGraph lit le dernier Checkpoint d'un Thread.
22
+ La méthode get_state_history liste tous les checkpoints d'un Thread.
data/nodes.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Nodes et Edges
2
+
3
+ Un Node est une fonction Python qui reçoit l'état courant et renvoie une mise à jour partielle de l'état.
4
+ Les mises à jour renvoyées par un Node sont appliquées aux Channels via leurs Reducers.
5
+
6
+ Un Edge relie deux Nodes et définit l'ordre d'exécution.
7
+ START et END sont des Nodes virtuels qui marquent l'entrée et la sortie du graphe.
8
+
9
+ Un Conditional Edge utilise une fonction de routage pour choisir dynamiquement le Node suivant.
10
+ L'API Send permet à un Conditional Edge de lancer plusieurs Nodes en parallèle (map-reduce).
11
+
12
+ La classe Command permet à un Node de mettre à jour l'état et de choisir le Node suivant en une seule instruction.
data/stategraph.md ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # StateGraph
2
+
3
+ StateGraph est la classe centrale de LangGraph pour construire des workflows orientés état.
4
+ Un StateGraph est paramétré par un schéma d'état, généralement un TypedDict ou un modèle Pydantic.
5
+
6
+ StateGraph utilise des Channels pour stocker et transmettre l'état entre les nodes.
7
+ Chaque clé du schéma d'état correspond à un Channel.
8
+
9
+ Un StateGraph contient des Nodes reliés par des Edges.
10
+ La méthode add_node enregistre un Node, la méthode add_edge crée un Edge fixe
11
+ et la méthode add_conditional_edges crée un routage dynamique.
12
+
13
+ Avant l'exécution, un StateGraph doit être compilé avec la méthode compile.
14
+ La méthode compile retourne un CompiledGraph qui expose invoke, stream et get_state.
15
+
16
+ La méthode compile accepte un paramètre checkpointer.
17
+ Un StateGraph compilé avec un Checkpointer persiste son état entre plusieurs exécutions.
18
+
19
+ ```python
20
+ from langgraph.graph import StateGraph, START, END
21
+
22
+ builder = StateGraph(State)
23
+ builder.add_node("agent", call_model)
24
+ builder.add_edge(START, "agent")
25
+ builder.add_edge("agent", END)
26
+ graph = builder.compile()
27
+ ```
data/tutorials/human_in_the_loop.md ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Tutoriel : Human-in-the-loop
2
+
3
+ Le Human-in-the-loop permet de mettre un workflow en pause pour obtenir une validation humaine.
4
+
5
+ La fonction interrupt suspend l'exécution d'un Node et renvoie une valeur à l'appelant.
6
+ La fonction interrupt nécessite un Checkpointer, car l'état doit être sauvegardé pendant la pause.
7
+
8
+ Pour reprendre, on invoque le graphe avec Command(resume=valeur) et le même thread_id.
9
+ Le Node interrompu redémarre et interrupt renvoie la valeur fournie par l'humain.
10
+
11
+ ```python
12
+ from langgraph.types import interrupt, Command
13
+
14
+ def review(state):
15
+ decision = interrupt({"draft": state["draft"]})
16
+ return {"approved": decision == "ok"}
17
+
18
+ graph.invoke(Command(resume="ok"), config)
19
+ ```
20
+
21
+ Les paramètres interrupt_before et interrupt_after de compile permettent aussi de s'arrêter
22
+ avant ou après des Nodes précis, principalement pour le débogage.
data/tutorials/multi_agent.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Tutoriel : systèmes multi-agents
2
+
3
+ Un système multi-agents LangGraph combine plusieurs agents, chacun implémenté comme un Node ou un Subgraph.
4
+
5
+ Un Subgraph est un StateGraph compilé utilisé comme Node d'un autre StateGraph.
6
+ Un Subgraph partage les clés d'état communes avec le graphe parent.
7
+
8
+ Dans l'architecture Supervisor, un agent Supervisor route les tâches vers des agents spécialisés.
9
+ Le Supervisor utilise la classe Command pour désigner l'agent suivant.
10
+
11
+ Dans l'architecture Swarm, les agents se transmettent le contrôle directement par handoff.
12
+
13
+ Un Checkpointer défini sur le graphe parent est propagé automatiquement aux Subgraphs.
data/tutorials/persistence.md ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Tutoriel : persister un workflow
2
+
3
+ Ce tutoriel montre comment rendre un StateGraph persistant.
4
+
5
+ Étape 1 : choisir un Checkpointer. En développement, InMemorySaver suffit.
6
+ En production, PostgresSaver garantit que l'état survit au redémarrage du serveur.
7
+
8
+ Étape 2 : passer le Checkpointer à la méthode compile.
9
+
10
+ ```python
11
+ from langgraph.checkpoint.memory import InMemorySaver
12
+
13
+ graph = builder.compile(checkpointer=InMemorySaver())
14
+ ```
15
+
16
+ Étape 3 : fournir un thread_id à chaque appel.
17
+ Deux appels avec le même thread_id partagent le même état ; le Channel messages conserve l'historique
18
+ grâce au Reducer add_messages.
19
+
20
+ Étape 4 : inspecter l'état avec get_state pour vérifier ce qui a été sauvegardé.
21
+
22
+ Sans Checkpointer, un StateGraph repart d'un état vide à chaque invocation.
entrypoint.sh ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ export NEO4J_PASSWORD="${NEO4J_PASSWORD:-techdocs-local-password}"
5
+
6
+ neo4j-admin dbms set-initial-password "$NEO4J_PASSWORD" > /dev/null 2>&1 || true
7
+ neo4j start
8
+
9
+ techdocs-index data --wait 120 --if-empty \
10
+ || echo "Indexation initiale impossible : l'application démarre sans corpus."
11
+
12
+ exec streamlit run app.py --server.port=7860 --server.address=0.0.0.0
pyproject.toml ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["hatchling>=1.24"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "techdocs-graphrag"
7
+ version = "0.1.0"
8
+ description = "Assistant de documentation technique : recherche hybride vectorielle et graphe de connaissances Neo4j."
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ license = { text = "MIT" }
12
+ dependencies = [
13
+ "neo4j>=5.20",
14
+ "openai>=1.40",
15
+ "pydantic>=2.7",
16
+ "pydantic-settings>=2.3",
17
+ "streamlit>=1.38",
18
+ "tenacity>=8.3",
19
+ ]
20
+
21
+ [project.optional-dependencies]
22
+ dev = ["pytest>=8.2", "ruff>=0.6"]
23
+
24
+ [project.scripts]
25
+ techdocs-index = "techdocs_graphrag.cli:main"
26
+
27
+ [tool.hatch.build.targets.wheel]
28
+ packages = ["src/techdocs_graphrag"]
29
+
30
+ [tool.pytest.ini_options]
31
+ pythonpath = ["src"]
32
+ testpaths = ["tests"]
33
+
34
+ [tool.ruff]
35
+ line-length = 100
36
+ target-version = "py312"
37
+
38
+ [tool.ruff.lint]
39
+ select = ["E", "F", "I", "B", "UP", "SIM", "RUF"]
40
+ ignore = ["E501", "RUF001", "RUF002", "RUF003"]
src/techdocs_graphrag/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from techdocs_graphrag.ingestion import SourceDocument, load_documents
2
+ from techdocs_graphrag.models import Answer, RetrievalMode
3
+ from techdocs_graphrag.services import Services, build_services
4
+
5
+ __version__ = "0.1.0"
6
+
7
+ __all__ = [
8
+ "Answer",
9
+ "RetrievalMode",
10
+ "Services",
11
+ "SourceDocument",
12
+ "build_services",
13
+ "load_documents",
14
+ ]
src/techdocs_graphrag/answering.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from techdocs_graphrag.models import Answer, RetrievalMode
2
+ from techdocs_graphrag.ports import LanguageModel
3
+ from techdocs_graphrag.prompts import ANSWER_SYSTEM_PROMPT, render_answer_prompt
4
+ from techdocs_graphrag.retrieval import HybridRetriever
5
+
6
+ NO_CONTEXT_ANSWER = (
7
+ "Je ne trouve aucune information pertinente dans la base indexée. "
8
+ "Indexe d'abord un corpus ou reformule la question."
9
+ )
10
+
11
+
12
+ class GraphRAGAssistant:
13
+ def __init__(self, *, retriever: HybridRetriever, llm: LanguageModel) -> None:
14
+ self._retriever = retriever
15
+ self._llm = llm
16
+
17
+ def ask(self, question: str, mode: RetrievalMode = RetrievalMode.GRAPH) -> Answer:
18
+ context = self._retriever.retrieve(question, mode)
19
+ text = (
20
+ NO_CONTEXT_ANSWER
21
+ if context.is_empty
22
+ else self._llm.complete(ANSWER_SYSTEM_PROMPT, render_answer_prompt(question, context))
23
+ )
24
+ return Answer(question=question, text=text, mode=mode, context=context)
src/techdocs_graphrag/cli.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import logging
3
+ import time
4
+ from pathlib import Path
5
+
6
+ from neo4j.exceptions import DriverError, Neo4jError
7
+
8
+ from techdocs_graphrag.ingestion import load_documents
9
+ from techdocs_graphrag.services import Services, build_services
10
+
11
+ RETRY_DELAY_SECONDS = 2
12
+
13
+
14
+ def parse_arguments() -> argparse.Namespace:
15
+ parser = argparse.ArgumentParser(description="Indexe un corpus Markdown dans Neo4j.")
16
+ parser.add_argument("data_dir", type=Path, nargs="?", default=Path("data"))
17
+ parser.add_argument("--reset", action="store_true", help="Vide la base avant indexation.")
18
+ parser.add_argument("--if-empty", action="store_true", help="N'indexe que si la base est vide.")
19
+ parser.add_argument("--wait", type=int, default=0, metavar="SECONDS", help="Attend Neo4j.")
20
+ return parser.parse_args()
21
+
22
+
23
+ def wait_for_database(services: Services, timeout_seconds: int) -> None:
24
+ deadline = time.monotonic() + timeout_seconds
25
+ while True:
26
+ try:
27
+ services.store.verify_connectivity()
28
+ return
29
+ except (DriverError, Neo4jError):
30
+ if time.monotonic() >= deadline:
31
+ raise
32
+ time.sleep(RETRY_DELAY_SECONDS)
33
+
34
+
35
+ def main() -> None:
36
+ logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
37
+ arguments = parse_arguments()
38
+ services = build_services()
39
+ try:
40
+ wait_for_database(services, arguments.wait)
41
+ if arguments.if_empty and services.store.stats()["chunks"]:
42
+ print("Base déjà indexée.")
43
+ return
44
+ if arguments.reset:
45
+ services.store.reset()
46
+ report = services.indexer.run(
47
+ load_documents(arguments.data_dir),
48
+ on_progress=lambda done, total: print(f"\r{done}/{total} chunks", end="", flush=True),
49
+ )
50
+ print(f"\n{report}")
51
+ finally:
52
+ services.close()
53
+
54
+
55
+ if __name__ == "__main__":
56
+ main()
src/techdocs_graphrag/config.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import lru_cache
2
+
3
+ from pydantic import Field, SecretStr
4
+ from pydantic_settings import BaseSettings, SettingsConfigDict
5
+
6
+
7
+ class Settings(BaseSettings):
8
+ model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")
9
+
10
+ openai_api_key: SecretStr
11
+ chat_model: str = "gpt-4o-mini"
12
+ chat_temperature: float | None = 0.0
13
+ embedding_model: str = "text-embedding-3-small"
14
+ embedding_dimensions: int = Field(default=1536, gt=0)
15
+
16
+ neo4j_uri: str
17
+ neo4j_username: str = "neo4j"
18
+ neo4j_password: SecretStr
19
+ neo4j_database: str = "neo4j"
20
+
21
+ chunk_size: int = Field(default=900, gt=0)
22
+ chunk_overlap: int = Field(default=150, ge=0)
23
+ extraction_workers: int = Field(default=4, ge=1, le=16)
24
+
25
+ vector_top_k: int = Field(default=5, ge=1, le=50)
26
+ graph_max_hops: int = Field(default=2, ge=1, le=4)
27
+ graph_max_facts: int = Field(default=40, ge=1, le=200)
28
+
29
+
30
+ @lru_cache
31
+ def get_settings() -> Settings:
32
+ return Settings()
src/techdocs_graphrag/extraction.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ from pydantic import ValidationError
4
+
5
+ from techdocs_graphrag.models import Chunk, GraphExtraction
6
+ from techdocs_graphrag.ports import LanguageModel
7
+ from techdocs_graphrag.prompts import EXTRACTION_SYSTEM_PROMPT
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ class GraphExtractor:
13
+ def __init__(self, llm: LanguageModel) -> None:
14
+ self._llm = llm
15
+
16
+ def extract(self, chunk: Chunk) -> GraphExtraction:
17
+ payload = self._llm.complete(EXTRACTION_SYSTEM_PROMPT, chunk.text, json_mode=True)
18
+ try:
19
+ return GraphExtraction.model_validate_json(payload)
20
+ except ValidationError as error:
21
+ logger.warning(
22
+ "Graph extraction rejected for chunk %s (%s errors)", chunk.id, error.error_count()
23
+ )
24
+ return GraphExtraction()
src/techdocs_graphrag/graph_store.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from collections import defaultdict
3
+ from collections.abc import Sequence
4
+ from itertools import batched
5
+ from typing import Any, Self
6
+
7
+ from neo4j import GraphDatabase
8
+
9
+ from techdocs_graphrag.config import Settings
10
+ from techdocs_graphrag.models import Chunk, GraphExtraction, GraphFact, RetrievedChunk
11
+
12
+ VECTOR_INDEX = "chunk_embeddings"
13
+ FULLTEXT_INDEX = "entity_names"
14
+ WRITE_BATCH_SIZE = 200
15
+ MIN_SEARCH_TERM_LENGTH = 3
16
+ INDEX_TIMEOUT_SECONDS = 300
17
+ CYPHER_IDENTIFIER = re.compile(r"^[A-Za-z][A-Za-z0-9_]*$")
18
+
19
+
20
+ def cypher_identifier(value: str) -> str:
21
+ if not CYPHER_IDENTIFIER.fullmatch(value):
22
+ raise ValueError(f"Unsafe Cypher identifier: {value!r}")
23
+ return value
24
+
25
+
26
+ class Neo4jGraphStore:
27
+ def __init__(self, settings: Settings) -> None:
28
+ self._driver = GraphDatabase.driver(
29
+ settings.neo4j_uri,
30
+ auth=(settings.neo4j_username, settings.neo4j_password.get_secret_value()),
31
+ )
32
+ self._database = settings.neo4j_database
33
+ self._embedding_dimensions = settings.embedding_dimensions
34
+
35
+ def __enter__(self) -> Self:
36
+ return self
37
+
38
+ def __exit__(self, *exc_info: object) -> None:
39
+ self.close()
40
+
41
+ def close(self) -> None:
42
+ self._driver.close()
43
+
44
+ def verify_connectivity(self) -> None:
45
+ self._driver.verify_connectivity()
46
+
47
+ def ensure_schema(self) -> None:
48
+ statements = (
49
+ "CREATE CONSTRAINT document_name IF NOT EXISTS "
50
+ "FOR (d:Document) REQUIRE d.name IS UNIQUE",
51
+ "CREATE CONSTRAINT chunk_id IF NOT EXISTS FOR (c:Chunk) REQUIRE c.id IS UNIQUE",
52
+ "CREATE CONSTRAINT entity_key IF NOT EXISTS FOR (e:Entity) REQUIRE e.key IS UNIQUE",
53
+ f"CREATE FULLTEXT INDEX {FULLTEXT_INDEX} IF NOT EXISTS "
54
+ "FOR (e:Entity) ON EACH [e.name]",
55
+ f"""
56
+ CREATE VECTOR INDEX {VECTOR_INDEX} IF NOT EXISTS
57
+ FOR (c:Chunk) ON c.embedding
58
+ OPTIONS {{indexConfig: {{
59
+ `vector.dimensions`: {int(self._embedding_dimensions)},
60
+ `vector.similarity_function`: 'cosine'
61
+ }}}}
62
+ """,
63
+ )
64
+ for statement in statements:
65
+ self._run(statement)
66
+
67
+ def await_indexes(self) -> None:
68
+ self._run("CALL db.awaitIndexes($timeout)", timeout=INDEX_TIMEOUT_SECONDS)
69
+
70
+ def upsert_chunks(self, chunks: Sequence[Chunk], embeddings: Sequence[list[float]]) -> None:
71
+ rows = [
72
+ {**chunk.model_dump(), "embedding": embedding}
73
+ for chunk, embedding in zip(chunks, embeddings, strict=True)
74
+ ]
75
+ for batch in batched(rows, WRITE_BATCH_SIZE):
76
+ self._run(
77
+ """
78
+ UNWIND $rows AS row
79
+ MERGE (d:Document {name: row.document})
80
+ MERGE (c:Chunk {id: row.id})
81
+ SET c.document = row.document,
82
+ c.position = row.position,
83
+ c.text = row.text,
84
+ c.embedding = row.embedding
85
+ MERGE (d)-[:HAS_CHUNK]->(c)
86
+ """,
87
+ rows=list(batch),
88
+ )
89
+
90
+ def upsert_extraction(self, chunk: Chunk, extraction: GraphExtraction) -> None:
91
+ self._upsert_entities(chunk, extraction)
92
+ self._upsert_relations(chunk, extraction)
93
+
94
+ def _upsert_entities(self, chunk: Chunk, extraction: GraphExtraction) -> None:
95
+ rows_by_type: dict[str, list[dict[str, str]]] = defaultdict(list)
96
+ for entity in extraction.entities:
97
+ rows_by_type[entity.type.value].append({"key": entity.key, "name": entity.name})
98
+ for entity_type, rows in rows_by_type.items():
99
+ self._run(
100
+ f"""
101
+ MATCH (c:Chunk {{id: $chunk_id}})
102
+ UNWIND $rows AS row
103
+ MERGE (e:Entity {{key: row.key}})
104
+ ON CREATE SET e.name = row.name, e.type = $entity_type
105
+ SET e:{cypher_identifier(entity_type)}
106
+ MERGE (c)-[:MENTIONS]->(e)
107
+ """,
108
+ chunk_id=chunk.id,
109
+ rows=rows,
110
+ entity_type=entity_type,
111
+ )
112
+
113
+ def _upsert_relations(self, chunk: Chunk, extraction: GraphExtraction) -> None:
114
+ rows_by_type: dict[str, list[dict[str, str]]] = defaultdict(list)
115
+ for relation in extraction.relations:
116
+ rows_by_type[relation.relation].append(
117
+ {
118
+ "source": relation.source_key,
119
+ "target": relation.target_key,
120
+ "evidence": relation.evidence,
121
+ "document": chunk.document,
122
+ }
123
+ )
124
+ for relation_type, rows in rows_by_type.items():
125
+ self._run(
126
+ f"""
127
+ UNWIND $rows AS row
128
+ MATCH (s:Entity {{key: row.source}})
129
+ MATCH (t:Entity {{key: row.target}})
130
+ MERGE (s)-[r:{cypher_identifier(relation_type)}]->(t)
131
+ ON CREATE SET r.evidence = [], r.documents = []
132
+ SET r.evidence = CASE
133
+ WHEN row.evidence = '' OR row.evidence IN r.evidence THEN r.evidence
134
+ ELSE r.evidence + row.evidence
135
+ END,
136
+ r.documents = CASE
137
+ WHEN row.document IN r.documents THEN r.documents
138
+ ELSE r.documents + row.document
139
+ END
140
+ """,
141
+ rows=rows,
142
+ )
143
+
144
+ def vector_search(self, embedding: list[float], top_k: int) -> list[RetrievedChunk]:
145
+ rows = self._run(
146
+ """
147
+ CALL db.index.vector.queryNodes($index, $top_k, $embedding) YIELD node, score
148
+ OPTIONAL MATCH (node)-[:MENTIONS]->(entity:Entity)
149
+ RETURN node.id AS id,
150
+ node.document AS document,
151
+ node.position AS position,
152
+ node.text AS text,
153
+ score,
154
+ collect(entity.key) AS entity_keys
155
+ ORDER BY score DESC
156
+ """,
157
+ index=VECTOR_INDEX,
158
+ top_k=top_k,
159
+ embedding=embedding,
160
+ )
161
+ return [RetrievedChunk.model_validate(row) for row in rows]
162
+
163
+ def search_entities(self, text: str, limit: int) -> list[str]:
164
+ terms = sorted(
165
+ {term.lower() for term in re.findall(r"\w+", text) if len(term) >= MIN_SEARCH_TERM_LENGTH}
166
+ )
167
+ if not terms:
168
+ return []
169
+ rows = self._run(
170
+ """
171
+ CALL db.index.fulltext.queryNodes($index, $query) YIELD node, score
172
+ RETURN node.key AS key
173
+ ORDER BY score DESC
174
+ LIMIT $limit
175
+ """,
176
+ index=FULLTEXT_INDEX,
177
+ query=" OR ".join(terms),
178
+ limit=limit,
179
+ )
180
+ return [row["key"] for row in rows]
181
+
182
+ def expand(self, seed_keys: Sequence[str], max_hops: int, limit: int) -> list[GraphFact]:
183
+ if not seed_keys:
184
+ return []
185
+ rows = self._run(
186
+ f"""
187
+ MATCH (seed:Entity) WHERE seed.key IN $keys
188
+ MATCH path = (seed)-[*1..{int(max_hops)}]-(:Entity)
189
+ WHERE all(node IN nodes(path) WHERE node:Entity)
190
+ UNWIND relationships(path) AS rel
191
+ WITH rel, min(length(path)) AS distance
192
+ RETURN startNode(rel).name AS source,
193
+ type(rel) AS relation,
194
+ endNode(rel).name AS target,
195
+ coalesce(rel.evidence, []) AS evidence,
196
+ coalesce(rel.documents, []) AS documents,
197
+ distance
198
+ ORDER BY distance, source, relation, target
199
+ LIMIT $limit
200
+ """,
201
+ keys=list(seed_keys),
202
+ limit=limit,
203
+ )
204
+ return [GraphFact.model_validate(row) for row in rows]
205
+
206
+ def stats(self) -> dict[str, int]:
207
+ rows = self._run(
208
+ """
209
+ RETURN COUNT { (:Document) } AS documents,
210
+ COUNT { (:Chunk) } AS chunks,
211
+ COUNT { (:Entity) } AS entities,
212
+ COUNT { (:Entity)-[]->(:Entity) } AS relations
213
+ """
214
+ )
215
+ return rows[0]
216
+
217
+ def reset(self) -> None:
218
+ self._run("MATCH (n) DETACH DELETE n")
219
+
220
+ def _run(self, query: str, **parameters: Any) -> list[dict[str, Any]]:
221
+ records, _, _ = self._driver.execute_query(
222
+ query,
223
+ parameters_=parameters,
224
+ database_=self._database,
225
+ )
226
+ return [record.data() for record in records]
src/techdocs_graphrag/indexing.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable, Sequence
2
+ from concurrent.futures import ThreadPoolExecutor
3
+ from dataclasses import dataclass
4
+
5
+ from techdocs_graphrag.extraction import GraphExtractor
6
+ from techdocs_graphrag.ingestion import ParagraphSplitter, SourceDocument, chunk_documents
7
+ from techdocs_graphrag.ports import KnowledgeGraph, LanguageModel
8
+
9
+ ProgressCallback = Callable[[int, int], None]
10
+
11
+
12
+ @dataclass(frozen=True, slots=True)
13
+ class IndexingReport:
14
+ documents: int
15
+ chunks: int
16
+ entities: int
17
+ relations: int
18
+
19
+
20
+ class IndexingPipeline:
21
+ def __init__(
22
+ self,
23
+ *,
24
+ splitter: ParagraphSplitter,
25
+ llm: LanguageModel,
26
+ extractor: GraphExtractor,
27
+ store: KnowledgeGraph,
28
+ workers: int,
29
+ ) -> None:
30
+ self._splitter = splitter
31
+ self._llm = llm
32
+ self._extractor = extractor
33
+ self._store = store
34
+ self._workers = workers
35
+
36
+ def run(
37
+ self,
38
+ documents: Sequence[SourceDocument],
39
+ on_progress: ProgressCallback | None = None,
40
+ ) -> IndexingReport:
41
+ chunks = chunk_documents(documents, self._splitter)
42
+ if not chunks:
43
+ return IndexingReport(documents=len(documents), chunks=0, entities=0, relations=0)
44
+
45
+ self._store.ensure_schema()
46
+ self._store.upsert_chunks(chunks, self._llm.embed([chunk.text for chunk in chunks]))
47
+
48
+ entities = relations = 0
49
+ with ThreadPoolExecutor(max_workers=self._workers) as executor:
50
+ extractions = executor.map(self._extractor.extract, chunks)
51
+ for completed, (chunk, extraction) in enumerate(
52
+ zip(chunks, extractions, strict=True), start=1
53
+ ):
54
+ self._store.upsert_extraction(chunk, extraction)
55
+ entities += len(extraction.entities)
56
+ relations += len(extraction.relations)
57
+ if on_progress:
58
+ on_progress(completed, len(chunks))
59
+
60
+ self._store.await_indexes()
61
+ return IndexingReport(
62
+ documents=len(documents),
63
+ chunks=len(chunks),
64
+ entities=entities,
65
+ relations=relations,
66
+ )
src/techdocs_graphrag/ingestion.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import re
3
+ from collections.abc import Iterable
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+
7
+ from techdocs_graphrag.models import Chunk
8
+
9
+ SUPPORTED_SUFFIXES = frozenset({".md", ".markdown", ".txt"})
10
+ PARAGRAPH_SEPARATOR = "\n\n"
11
+
12
+
13
+ @dataclass(frozen=True, slots=True)
14
+ class SourceDocument:
15
+ name: str
16
+ text: str
17
+
18
+
19
+ def load_documents(root: Path) -> list[SourceDocument]:
20
+ return [
21
+ SourceDocument(name=path.relative_to(root).as_posix(), text=path.read_text(encoding="utf-8"))
22
+ for path in sorted(root.rglob("*"))
23
+ if path.is_file() and path.suffix.lower() in SUPPORTED_SUFFIXES
24
+ ]
25
+
26
+
27
+ class ParagraphSplitter:
28
+ def __init__(self, chunk_size: int, chunk_overlap: int) -> None:
29
+ if not 0 <= chunk_overlap < chunk_size:
30
+ raise ValueError("chunk_overlap must be in [0, chunk_size)")
31
+ self._chunk_size = chunk_size
32
+ self._chunk_overlap = chunk_overlap
33
+
34
+ def split(self, text: str) -> list[str]:
35
+ chunks: list[str] = []
36
+ buffer = ""
37
+ for paragraph in self._paragraphs(text):
38
+ candidate = self._join(buffer, paragraph)
39
+ if len(candidate) <= self._chunk_size:
40
+ buffer = candidate
41
+ continue
42
+ if buffer:
43
+ chunks.append(buffer)
44
+ candidate = self._join(self._overlap_of(buffer), paragraph)
45
+ while len(candidate) > self._chunk_size:
46
+ chunks.append(candidate[: self._chunk_size])
47
+ candidate = candidate[self._chunk_size - self._chunk_overlap :]
48
+ buffer = candidate
49
+ if buffer:
50
+ chunks.append(buffer)
51
+ return chunks
52
+
53
+ @staticmethod
54
+ def _paragraphs(text: str) -> Iterable[str]:
55
+ return (block.strip() for block in re.split(r"\n\s*\n", text) if block.strip())
56
+
57
+ @staticmethod
58
+ def _join(head: str, tail: str) -> str:
59
+ return f"{head}{PARAGRAPH_SEPARATOR}{tail}" if head else tail
60
+
61
+ def _overlap_of(self, text: str) -> str:
62
+ if not self._chunk_overlap or len(text) <= self._chunk_overlap:
63
+ return ""
64
+ tail = text[-self._chunk_overlap :]
65
+ return tail.partition(" ")[2] or tail
66
+
67
+
68
+ def chunk_id(document: str, position: int, text: str) -> str:
69
+ return hashlib.sha256(f"{document}\x00{position}\x00{text}".encode()).hexdigest()[:16]
70
+
71
+
72
+ def chunk_documents(documents: Iterable[SourceDocument], splitter: ParagraphSplitter) -> list[Chunk]:
73
+ return [
74
+ Chunk(id=chunk_id(document.name, position, text), document=document.name, position=position, text=text)
75
+ for document in documents
76
+ for position, text in enumerate(splitter.split(document.text))
77
+ ]
src/techdocs_graphrag/llm.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Sequence
2
+ from itertools import batched
3
+ from typing import Any
4
+
5
+ from openai import APIConnectionError, APITimeoutError, InternalServerError, OpenAI, RateLimitError
6
+ from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_random_exponential
7
+
8
+ from techdocs_graphrag.config import Settings
9
+
10
+ EMBEDDING_BATCH_SIZE = 96
11
+ TRANSIENT_ERRORS = (APIConnectionError, APITimeoutError, InternalServerError, RateLimitError)
12
+
13
+ with_retry = retry(
14
+ retry=retry_if_exception_type(TRANSIENT_ERRORS),
15
+ wait=wait_random_exponential(min=1, max=30),
16
+ stop=stop_after_attempt(5),
17
+ reraise=True,
18
+ )
19
+
20
+
21
+ class OpenAIGateway:
22
+ def __init__(self, settings: Settings) -> None:
23
+ self._client = OpenAI(api_key=settings.openai_api_key.get_secret_value())
24
+ self._chat_model = settings.chat_model
25
+ self._chat_temperature = settings.chat_temperature
26
+ self._embedding_model = settings.embedding_model
27
+ self._embedding_dimensions = settings.embedding_dimensions
28
+
29
+ @with_retry
30
+ def complete(self, system_prompt: str, user_prompt: str, *, json_mode: bool = False) -> str:
31
+ options: dict[str, Any] = {}
32
+ if json_mode:
33
+ options["response_format"] = {"type": "json_object"}
34
+ if self._chat_temperature is not None:
35
+ options["temperature"] = self._chat_temperature
36
+ response = self._client.chat.completions.create(
37
+ model=self._chat_model,
38
+ messages=[
39
+ {"role": "system", "content": system_prompt},
40
+ {"role": "user", "content": user_prompt},
41
+ ],
42
+ **options,
43
+ )
44
+ return response.choices[0].message.content or ""
45
+
46
+ def embed(self, texts: Sequence[str]) -> list[list[float]]:
47
+ return [
48
+ vector
49
+ for batch in batched(texts, EMBEDDING_BATCH_SIZE)
50
+ for vector in self._embed_batch(batch)
51
+ ]
52
+
53
+ @with_retry
54
+ def _embed_batch(self, texts: Sequence[str]) -> list[list[float]]:
55
+ response = self._client.embeddings.create(
56
+ model=self._embedding_model,
57
+ input=list(texts),
58
+ dimensions=self._embedding_dimensions,
59
+ )
60
+ return [item.embedding for item in sorted(response.data, key=lambda item: item.index)]
src/techdocs_graphrag/models.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import unicodedata
3
+ from enum import StrEnum
4
+ from typing import Annotated
5
+
6
+ from pydantic import BaseModel, ConfigDict, Field, StringConstraints, field_validator, model_validator
7
+
8
+ NonEmptyStr = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1)]
9
+
10
+ RESERVED_RELATIONS = frozenset({"MENTIONS", "HAS_CHUNK"})
11
+ FALLBACK_RELATION = "RELATED_TO"
12
+
13
+
14
+ def to_ascii(value: str) -> str:
15
+ return unicodedata.normalize("NFKD", value).encode("ascii", "ignore").decode()
16
+
17
+
18
+ def canonical_key(name: str) -> str:
19
+ return re.sub(r"[^a-z0-9]", "", to_ascii(name).lower()) or name.strip().casefold()
20
+
21
+
22
+ class EntityType(StrEnum):
23
+ COMPONENT = "Component"
24
+ CLASS = "Class"
25
+ FUNCTION = "Function"
26
+ LIBRARY = "Library"
27
+ CONCEPT = "Concept"
28
+ FEATURE = "Feature"
29
+ ERROR = "Error"
30
+ DATABASE = "Database"
31
+ API = "API"
32
+
33
+
34
+ ENTITY_TYPES_BY_NAME = {entity_type.value.lower(): entity_type for entity_type in EntityType}
35
+
36
+
37
+ class RetrievalMode(StrEnum):
38
+ VECTOR = "vector"
39
+ GRAPH = "graphrag"
40
+
41
+
42
+ class Chunk(BaseModel):
43
+ model_config = ConfigDict(frozen=True)
44
+
45
+ id: str
46
+ document: str
47
+ position: int
48
+ text: str
49
+
50
+
51
+ class RetrievedChunk(Chunk):
52
+ score: float
53
+ entity_keys: list[str] = Field(default_factory=list)
54
+
55
+
56
+ class Entity(BaseModel):
57
+ name: NonEmptyStr
58
+ type: EntityType = EntityType.CONCEPT
59
+
60
+ @field_validator("type", mode="before")
61
+ @classmethod
62
+ def coerce_type(cls, value: object) -> EntityType:
63
+ return ENTITY_TYPES_BY_NAME.get(str(value).strip().lower(), EntityType.CONCEPT)
64
+
65
+ @property
66
+ def key(self) -> str:
67
+ return canonical_key(self.name)
68
+
69
+
70
+ class Relation(BaseModel):
71
+ source: NonEmptyStr
72
+ relation: str
73
+ target: NonEmptyStr
74
+ evidence: str = ""
75
+
76
+ @field_validator("relation", mode="before")
77
+ @classmethod
78
+ def normalize_relation(cls, value: object) -> str:
79
+ normalized = re.sub(r"[^A-Z0-9]+", "_", to_ascii(str(value)).upper()).strip("_")
80
+ if not normalized or not normalized[0].isalpha() or normalized in RESERVED_RELATIONS:
81
+ return FALLBACK_RELATION
82
+ return normalized
83
+
84
+ @field_validator("evidence", mode="before")
85
+ @classmethod
86
+ def normalize_evidence(cls, value: object) -> str:
87
+ return " ".join(str(value or "").split())
88
+
89
+ @property
90
+ def source_key(self) -> str:
91
+ return canonical_key(self.source)
92
+
93
+ @property
94
+ def target_key(self) -> str:
95
+ return canonical_key(self.target)
96
+
97
+
98
+ class GraphExtraction(BaseModel):
99
+ entities: list[Entity] = Field(default_factory=list)
100
+ relations: list[Relation] = Field(default_factory=list)
101
+
102
+ @model_validator(mode="after")
103
+ def reconcile(self) -> "GraphExtraction":
104
+ self.relations = [
105
+ relation for relation in self.relations if relation.source_key != relation.target_key
106
+ ]
107
+ entities = {entity.key: entity for entity in self.entities}
108
+ for relation in self.relations:
109
+ entities.setdefault(relation.source_key, Entity(name=relation.source))
110
+ entities.setdefault(relation.target_key, Entity(name=relation.target))
111
+ self.entities = list(entities.values())
112
+ return self
113
+
114
+
115
+ class GraphFact(BaseModel):
116
+ source: str
117
+ relation: str
118
+ target: str
119
+ evidence: list[str] = Field(default_factory=list)
120
+ documents: list[str] = Field(default_factory=list)
121
+ distance: int = 1
122
+
123
+
124
+ class RetrievalContext(BaseModel):
125
+ chunks: list[RetrievedChunk] = Field(default_factory=list)
126
+ facts: list[GraphFact] = Field(default_factory=list)
127
+ seed_entities: list[str] = Field(default_factory=list)
128
+
129
+ @property
130
+ def is_empty(self) -> bool:
131
+ return not self.chunks and not self.facts
132
+
133
+ @property
134
+ def sources(self) -> list[str]:
135
+ documents = {chunk.document for chunk in self.chunks}
136
+ documents.update(document for fact in self.facts for document in fact.documents)
137
+ return sorted(documents)
138
+
139
+
140
+ class Answer(BaseModel):
141
+ question: str
142
+ text: str
143
+ mode: RetrievalMode
144
+ context: RetrievalContext
src/techdocs_graphrag/ports.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Sequence
2
+ from typing import Protocol
3
+
4
+ from techdocs_graphrag.models import Chunk, GraphExtraction, GraphFact, RetrievedChunk
5
+
6
+
7
+ class LanguageModel(Protocol):
8
+ def complete(self, system_prompt: str, user_prompt: str, *, json_mode: bool = False) -> str: ...
9
+
10
+ def embed(self, texts: Sequence[str]) -> list[list[float]]: ...
11
+
12
+
13
+ class KnowledgeGraph(Protocol):
14
+ def ensure_schema(self) -> None: ...
15
+
16
+ def await_indexes(self) -> None: ...
17
+
18
+ def upsert_chunks(self, chunks: Sequence[Chunk], embeddings: Sequence[list[float]]) -> None: ...
19
+
20
+ def upsert_extraction(self, chunk: Chunk, extraction: GraphExtraction) -> None: ...
21
+
22
+ def vector_search(self, embedding: list[float], top_k: int) -> list[RetrievedChunk]: ...
23
+
24
+ def search_entities(self, text: str, limit: int) -> list[str]: ...
25
+
26
+ def expand(self, seed_keys: Sequence[str], max_hops: int, limit: int) -> list[GraphFact]: ...
src/techdocs_graphrag/prompts.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Sequence
2
+
3
+ from techdocs_graphrag.models import EntityType, GraphFact, RetrievalContext, RetrievedChunk
4
+
5
+ ENTITY_TYPES = ", ".join(entity_type.value for entity_type in EntityType)
6
+
7
+ EXTRACTION_SYSTEM_PROMPT = f"""\
8
+ Tu es un système d'extraction de graphe de connaissances pour de la documentation technique.
9
+
10
+ À partir du texte fourni par l'utilisateur, extrais :
11
+ 1. les entités techniques importantes (composants, classes, fonctions, bibliothèques, concepts...) ;
12
+ 2. le type de chaque entité, choisi parmi : {ENTITY_TYPES} ;
13
+ 3. les relations factuelles explicitement affirmées par le texte ;
14
+ 4. une preuve textuelle courte (25 mots maximum) recopiée du texte pour chaque relation.
15
+
16
+ Règles :
17
+ - Nomme chaque entité sous sa forme canonique, telle qu'écrite dans le code (ex. StateGraph, MemorySaver).
18
+ - Utilise le singulier pour les concepts (Channel et non Channels).
19
+ - Écris les relations en anglais, en UPPER_SNAKE_CASE, orientées source -> cible
20
+ (ex. USES, PERSISTS_WITH, PART_OF, DEPENDS_ON, CONFIGURES, RETURNS, RAISES, EXTENDS, ENABLES).
21
+ - N'invente aucune relation absente du texte.
22
+ - Si le texte ne contient rien d'exploitable, renvoie des listes vides.
23
+
24
+ Réponds uniquement avec un objet JSON valide de cette forme :
25
+ {{
26
+ "entities": [{{"name": "StateGraph", "type": "Component"}}],
27
+ "relations": [
28
+ {{
29
+ "source": "StateGraph",
30
+ "relation": "USES",
31
+ "target": "Channel",
32
+ "evidence": "StateGraph utilise des Channels pour gérer l'état"
33
+ }}
34
+ ]
35
+ }}
36
+ """
37
+
38
+ ANSWER_SYSTEM_PROMPT = """\
39
+ Tu es un assistant expert en documentation technique.
40
+
41
+ Règles :
42
+ - Réponds uniquement à partir du contexte fourni : faits du graphe et extraits documentaires.
43
+ - Réponds dans la langue de la question.
44
+ - Explique clairement comment les composants sont reliés entre eux lorsque c'est utile.
45
+ - Cite tes sources en ligne sous la forme [nom_du_document].
46
+ - Ajoute un court exemple de code uniquement s'il est présent ou directement déductible du contexte.
47
+ - Si le contexte ne suffit pas, dis-le explicitement au lieu d'inventer.
48
+ """
49
+
50
+ NO_FACTS = "Aucun fait pertinent."
51
+ NO_CHUNKS = "Aucun extrait pertinent."
52
+
53
+
54
+ def render_answer_prompt(question: str, context: RetrievalContext) -> str:
55
+ return "\n\n".join(
56
+ (
57
+ f"Question :\n{question}",
58
+ f"Faits du graphe de connaissances :\n{render_facts(context.facts)}",
59
+ f"Extraits documentaires :\n{render_chunks(context.chunks)}",
60
+ )
61
+ )
62
+
63
+
64
+ def render_facts(facts: Sequence[GraphFact]) -> str:
65
+ if not facts:
66
+ return NO_FACTS
67
+ return "\n".join(
68
+ f"- {fact.source} --{fact.relation}--> {fact.target}"
69
+ f" | preuve : {' / '.join(fact.evidence[:2]) or 'n/a'}"
70
+ f" | sources : {', '.join(fact.documents) or 'n/a'}"
71
+ for fact in facts
72
+ )
73
+
74
+
75
+ def render_chunks(chunks: Sequence[RetrievedChunk]) -> str:
76
+ if not chunks:
77
+ return NO_CHUNKS
78
+ return "\n\n".join(f"[{chunk.document}]\n{chunk.text}" for chunk in chunks)
src/techdocs_graphrag/retrieval.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import Counter
2
+ from collections.abc import Sequence
3
+
4
+ from techdocs_graphrag.models import RetrievalContext, RetrievalMode, RetrievedChunk
5
+ from techdocs_graphrag.ports import KnowledgeGraph, LanguageModel
6
+
7
+ MAX_LEXICAL_SEEDS = 5
8
+ MAX_MENTION_SEEDS = 8
9
+
10
+
11
+ class HybridRetriever:
12
+ def __init__(
13
+ self,
14
+ *,
15
+ llm: LanguageModel,
16
+ store: KnowledgeGraph,
17
+ top_k: int,
18
+ max_hops: int,
19
+ max_facts: int,
20
+ ) -> None:
21
+ self._llm = llm
22
+ self._store = store
23
+ self._top_k = top_k
24
+ self._max_hops = max_hops
25
+ self._max_facts = max_facts
26
+
27
+ def retrieve(self, question: str, mode: RetrievalMode = RetrievalMode.GRAPH) -> RetrievalContext:
28
+ embedding = self._llm.embed([question])[0]
29
+ chunks = self._store.vector_search(embedding, self._top_k)
30
+ if mode is RetrievalMode.VECTOR:
31
+ return RetrievalContext(chunks=chunks)
32
+
33
+ seeds = self._seed_entities(question, chunks)
34
+ facts = self._store.expand(seeds, self._max_hops, self._max_facts)
35
+ return RetrievalContext(chunks=chunks, facts=facts, seed_entities=seeds)
36
+
37
+ def _seed_entities(self, question: str, chunks: Sequence[RetrievedChunk]) -> list[str]:
38
+ lexical_matches = self._store.search_entities(question, MAX_LEXICAL_SEEDS)
39
+ mentions = Counter(key for chunk in chunks for key in chunk.entity_keys)
40
+ most_mentioned = [key for key, _ in mentions.most_common(MAX_MENTION_SEEDS)]
41
+ return list(dict.fromkeys([*lexical_matches, *most_mentioned]))
src/techdocs_graphrag/services.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+
3
+ from techdocs_graphrag.answering import GraphRAGAssistant
4
+ from techdocs_graphrag.config import Settings, get_settings
5
+ from techdocs_graphrag.extraction import GraphExtractor
6
+ from techdocs_graphrag.graph_store import Neo4jGraphStore
7
+ from techdocs_graphrag.indexing import IndexingPipeline
8
+ from techdocs_graphrag.ingestion import ParagraphSplitter
9
+ from techdocs_graphrag.llm import OpenAIGateway
10
+ from techdocs_graphrag.retrieval import HybridRetriever
11
+
12
+
13
+ @dataclass(frozen=True, slots=True)
14
+ class Services:
15
+ settings: Settings
16
+ store: Neo4jGraphStore
17
+ assistant: GraphRAGAssistant
18
+ indexer: IndexingPipeline
19
+
20
+ def close(self) -> None:
21
+ self.store.close()
22
+
23
+
24
+ def build_services(settings: Settings | None = None) -> Services:
25
+ settings = settings or get_settings()
26
+ llm = OpenAIGateway(settings)
27
+ store = Neo4jGraphStore(settings)
28
+ retriever = HybridRetriever(
29
+ llm=llm,
30
+ store=store,
31
+ top_k=settings.vector_top_k,
32
+ max_hops=settings.graph_max_hops,
33
+ max_facts=settings.graph_max_facts,
34
+ )
35
+ indexer = IndexingPipeline(
36
+ splitter=ParagraphSplitter(settings.chunk_size, settings.chunk_overlap),
37
+ llm=llm,
38
+ extractor=GraphExtractor(llm),
39
+ store=store,
40
+ workers=settings.extraction_workers,
41
+ )
42
+ return Services(
43
+ settings=settings,
44
+ store=store,
45
+ assistant=GraphRAGAssistant(retriever=retriever, llm=llm),
46
+ indexer=indexer,
47
+ )
src/techdocs_graphrag/visualization.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Iterable, Sequence
2
+
3
+ from techdocs_graphrag.models import GraphFact, canonical_key
4
+
5
+ SEED_COLOR = "#C7D2FE"
6
+ NODE_COLOR = "#F1F5F9"
7
+
8
+
9
+ def facts_to_dot(facts: Sequence[GraphFact], highlighted_keys: Iterable[str] = ()) -> str:
10
+ highlighted = set(highlighted_keys)
11
+ names = sorted({name for fact in facts for name in (fact.source, fact.target)})
12
+ nodes = [
13
+ f" {quote(name)} [fillcolor={quote(SEED_COLOR if canonical_key(name) in highlighted else NODE_COLOR)}];"
14
+ for name in names
15
+ ]
16
+ edges = [
17
+ f" {quote(fact.source)} -> {quote(fact.target)} [label={quote(fact.relation)}];"
18
+ for fact in facts
19
+ ]
20
+ return "\n".join(
21
+ (
22
+ "digraph KnowledgeGraph {",
23
+ " rankdir=LR;",
24
+ ' node [shape=box, style="rounded,filled", fontname="Helvetica", fontcolor="#0F172A"];',
25
+ ' edge [fontname="Helvetica", fontsize=10, color="#64748B", fontcolor="#64748B"];',
26
+ *nodes,
27
+ *edges,
28
+ "}",
29
+ )
30
+ )
31
+
32
+
33
+ def quote(value: str) -> str:
34
+ escaped = value.replace("\\", "\\\\").replace('"', '\\"').replace("\n", " ")
35
+ return f'"{escaped}"'
tests/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
tests/conftest.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Sequence
2
+
3
+ import pytest
4
+
5
+ from techdocs_graphrag.models import Chunk, GraphExtraction, GraphFact, RetrievedChunk
6
+
7
+
8
+ class FakeLanguageModel:
9
+ def __init__(self, completion: str = "réponse") -> None:
10
+ self.completion = completion
11
+ self.completions: list[tuple[str, str]] = []
12
+
13
+ def complete(self, system_prompt: str, user_prompt: str, *, json_mode: bool = False) -> str:
14
+ self.completions.append((system_prompt, user_prompt))
15
+ return self.completion
16
+
17
+ def embed(self, texts: Sequence[str]) -> list[list[float]]:
18
+ return [[float(len(text))] for text in texts]
19
+
20
+
21
+ class FakeKnowledgeGraph:
22
+ def __init__(
23
+ self,
24
+ chunks: list[RetrievedChunk] | None = None,
25
+ lexical_matches: list[str] | None = None,
26
+ facts: list[GraphFact] | None = None,
27
+ ) -> None:
28
+ self.chunks = chunks or []
29
+ self.lexical_matches = lexical_matches or []
30
+ self.facts = facts or []
31
+ self.expanded_with: list[str] | None = None
32
+ self.extractions: list[tuple[Chunk, GraphExtraction]] = []
33
+ self.indexes_awaited = False
34
+
35
+ def ensure_schema(self) -> None:
36
+ pass
37
+
38
+ def await_indexes(self) -> None:
39
+ self.indexes_awaited = True
40
+
41
+ def upsert_chunks(self, chunks: Sequence[Chunk], embeddings: Sequence[list[float]]) -> None:
42
+ pass
43
+
44
+ def upsert_extraction(self, chunk: Chunk, extraction: GraphExtraction) -> None:
45
+ self.extractions.append((chunk, extraction))
46
+
47
+ def vector_search(self, embedding: list[float], top_k: int) -> list[RetrievedChunk]:
48
+ return self.chunks[:top_k]
49
+
50
+ def search_entities(self, text: str, limit: int) -> list[str]:
51
+ return self.lexical_matches[:limit]
52
+
53
+ def expand(self, seed_keys: Sequence[str], max_hops: int, limit: int) -> list[GraphFact]:
54
+ self.expanded_with = list(seed_keys)
55
+ return self.facts[:limit]
56
+
57
+
58
+ def retrieved_chunk(document: str, entity_keys: list[str]) -> RetrievedChunk:
59
+ return RetrievedChunk(
60
+ id=f"{document}-0",
61
+ document=document,
62
+ position=0,
63
+ text=f"contenu de {document}",
64
+ score=0.9,
65
+ entity_keys=entity_keys,
66
+ )
67
+
68
+
69
+ @pytest.fixture
70
+ def fake_llm() -> FakeLanguageModel:
71
+ return FakeLanguageModel()
tests/test_ingestion.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+
3
+ import pytest
4
+
5
+ from techdocs_graphrag.ingestion import (
6
+ ParagraphSplitter,
7
+ SourceDocument,
8
+ chunk_documents,
9
+ load_documents,
10
+ )
11
+
12
+
13
+ def test_splitter_respects_chunk_size_and_covers_every_paragraph() -> None:
14
+ paragraphs = [f"P{index:02d} " + "mot " * 40 for index in range(10)]
15
+ chunks = ParagraphSplitter(chunk_size=120, chunk_overlap=20).split("\n\n".join(paragraphs))
16
+ joined = " ".join(chunks)
17
+
18
+ assert all(len(chunk) <= 120 for chunk in chunks)
19
+ assert all(f"P{index:02d}" in joined for index in range(10))
20
+
21
+
22
+ def test_splitter_keeps_short_paragraphs_together() -> None:
23
+ chunks = ParagraphSplitter(chunk_size=100, chunk_overlap=10).split("Un.\n\nDeux.\n\nTrois.")
24
+ assert chunks == ["Un.\n\nDeux.\n\nTrois."]
25
+
26
+
27
+ def test_splitter_rejects_overlap_larger_than_chunk() -> None:
28
+ with pytest.raises(ValueError):
29
+ ParagraphSplitter(chunk_size=10, chunk_overlap=10)
30
+
31
+
32
+ def test_load_documents_reads_supported_files_recursively(tmp_path: Path) -> None:
33
+ (tmp_path / "guides").mkdir()
34
+ (tmp_path / "intro.md").write_text("Intro", encoding="utf-8")
35
+ (tmp_path / "guides" / "setup.md").write_text("Setup", encoding="utf-8")
36
+ (tmp_path / "image.png").write_bytes(b"\x89PNG")
37
+
38
+ documents = load_documents(tmp_path)
39
+
40
+ assert [document.name for document in documents] == ["guides/setup.md", "intro.md"]
41
+
42
+
43
+ def test_chunk_ids_are_deterministic_and_unique() -> None:
44
+ documents = [SourceDocument("a.md", "Alpha.\n\nBeta."), SourceDocument("b.md", "Alpha.")]
45
+ splitter = ParagraphSplitter(chunk_size=8, chunk_overlap=0)
46
+
47
+ first_run = chunk_documents(documents, splitter)
48
+ second_run = chunk_documents(documents, splitter)
49
+
50
+ assert [chunk.id for chunk in first_run] == [chunk.id for chunk in second_run]
51
+ assert len({chunk.id for chunk in first_run}) == len(first_run)
tests/test_models.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from techdocs_graphrag.models import (
4
+ FALLBACK_RELATION,
5
+ Entity,
6
+ EntityType,
7
+ GraphExtraction,
8
+ GraphFact,
9
+ Relation,
10
+ RetrievalContext,
11
+ canonical_key,
12
+ )
13
+
14
+
15
+ @pytest.mark.parametrize("name", ["StateGraph", "State Graph", "state_graph", " stategraph "])
16
+ def test_canonical_key_merges_spelling_variants(name: str) -> None:
17
+ assert canonical_key(name) == "stategraph"
18
+
19
+
20
+ @pytest.mark.parametrize(
21
+ ("raw", "expected"),
22
+ [
23
+ ("persists with", "PERSISTS_WITH"),
24
+ ("dépend-de", "DEPEND_DE"),
25
+ ("MENTIONS", FALLBACK_RELATION),
26
+ ("42_uses", FALLBACK_RELATION),
27
+ ("", FALLBACK_RELATION),
28
+ ],
29
+ )
30
+ def test_relation_type_is_normalized_to_a_safe_identifier(raw: str, expected: str) -> None:
31
+ relation = Relation(source="A", relation=raw, target="B")
32
+ assert relation.relation == expected
33
+
34
+
35
+ def test_unknown_entity_type_falls_back_to_concept() -> None:
36
+ assert Entity(name="Reducer", type="Pattern").type is EntityType.CONCEPT
37
+ assert Entity(name="StateGraph", type="component").type is EntityType.COMPONENT
38
+
39
+
40
+ def test_extraction_adds_missing_endpoints_and_drops_self_loops() -> None:
41
+ extraction = GraphExtraction.model_validate(
42
+ {
43
+ "entities": [{"name": "StateGraph", "type": "Component"}],
44
+ "relations": [
45
+ {"source": "StateGraph", "relation": "USES", "target": "Channel"},
46
+ {"source": "StateGraph", "relation": "IS", "target": "State Graph"},
47
+ ],
48
+ }
49
+ )
50
+
51
+ assert {entity.key for entity in extraction.entities} == {"stategraph", "channel"}
52
+ assert [relation.relation for relation in extraction.relations] == ["USES"]
53
+
54
+
55
+ def test_context_sources_combine_chunks_and_facts() -> None:
56
+ context = RetrievalContext(
57
+ facts=[GraphFact(source="A", relation="USES", target="B", documents=["b.md", "a.md"])]
58
+ )
59
+ assert context.sources == ["a.md", "b.md"]
60
+ assert not context.is_empty
tests/test_pipeline.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from techdocs_graphrag.answering import NO_CONTEXT_ANSWER, GraphRAGAssistant
2
+ from techdocs_graphrag.extraction import GraphExtractor
3
+ from techdocs_graphrag.indexing import IndexingPipeline
4
+ from techdocs_graphrag.ingestion import ParagraphSplitter, SourceDocument
5
+ from techdocs_graphrag.models import Chunk, GraphFact, RetrievalMode
6
+ from techdocs_graphrag.retrieval import HybridRetriever
7
+ from techdocs_graphrag.visualization import facts_to_dot
8
+
9
+ from .conftest import FakeKnowledgeGraph, FakeLanguageModel, retrieved_chunk
10
+
11
+ EXTRACTION_PAYLOAD = """
12
+ {
13
+ "entities": [{"name": "StateGraph", "type": "Component"}],
14
+ "relations": [{"source": "StateGraph", "relation": "uses", "target": "Channel", "evidence": "x"}]
15
+ }
16
+ """
17
+
18
+
19
+ def build_retriever(llm: FakeLanguageModel, store: FakeKnowledgeGraph) -> HybridRetriever:
20
+ return HybridRetriever(llm=llm, store=store, top_k=5, max_hops=2, max_facts=10)
21
+
22
+
23
+ def test_graph_mode_seeds_expansion_with_lexical_then_mentioned_entities(
24
+ fake_llm: FakeLanguageModel,
25
+ ) -> None:
26
+ store = FakeKnowledgeGraph(
27
+ chunks=[
28
+ retrieved_chunk("a.md", ["checkpointer", "stategraph"]),
29
+ retrieved_chunk("b.md", ["checkpointer"]),
30
+ ],
31
+ lexical_matches=["stategraph"],
32
+ )
33
+
34
+ context = build_retriever(fake_llm, store).retrieve("question", RetrievalMode.GRAPH)
35
+
36
+ assert store.expanded_with == ["stategraph", "checkpointer"]
37
+ assert context.seed_entities == ["stategraph", "checkpointer"]
38
+
39
+
40
+ def test_vector_mode_never_touches_the_graph(fake_llm: FakeLanguageModel) -> None:
41
+ store = FakeKnowledgeGraph(chunks=[retrieved_chunk("a.md", ["stategraph"])])
42
+
43
+ context = build_retriever(fake_llm, store).retrieve("question", RetrievalMode.VECTOR)
44
+
45
+ assert store.expanded_with is None
46
+ assert context.facts == []
47
+
48
+
49
+ def test_assistant_does_not_call_the_llm_without_context(fake_llm: FakeLanguageModel) -> None:
50
+ assistant = GraphRAGAssistant(retriever=build_retriever(fake_llm, FakeKnowledgeGraph()), llm=fake_llm)
51
+
52
+ answer = assistant.ask("question")
53
+
54
+ assert answer.text == NO_CONTEXT_ANSWER
55
+ assert fake_llm.completions == []
56
+
57
+
58
+ def test_assistant_sends_graph_facts_to_the_llm(fake_llm: FakeLanguageModel) -> None:
59
+ store = FakeKnowledgeGraph(
60
+ chunks=[retrieved_chunk("a.md", ["stategraph"])],
61
+ facts=[GraphFact(source="StateGraph", relation="USES", target="Channel", documents=["a.md"])],
62
+ )
63
+ assistant = GraphRAGAssistant(retriever=build_retriever(fake_llm, store), llm=fake_llm)
64
+
65
+ answer = assistant.ask("Comment fonctionne StateGraph ?")
66
+
67
+ _, user_prompt = fake_llm.completions[0]
68
+ assert "StateGraph --USES--> Channel" in user_prompt
69
+ assert answer.context.sources == ["a.md"]
70
+
71
+
72
+ def test_extractor_returns_empty_graph_on_invalid_json() -> None:
73
+ chunk = Chunk(id="1", document="a.md", position=0, text="texte")
74
+ assert GraphExtractor(FakeLanguageModel("pas du json")).extract(chunk).entities == []
75
+
76
+
77
+ def test_indexing_pipeline_reports_extracted_graph() -> None:
78
+ llm = FakeLanguageModel(EXTRACTION_PAYLOAD)
79
+ store = FakeKnowledgeGraph()
80
+ pipeline = IndexingPipeline(
81
+ splitter=ParagraphSplitter(chunk_size=50, chunk_overlap=0),
82
+ llm=llm,
83
+ extractor=GraphExtractor(llm),
84
+ store=store,
85
+ workers=2,
86
+ )
87
+ progress: list[int] = []
88
+
89
+ report = pipeline.run(
90
+ [SourceDocument("a.md", "Premier paragraphe.\n\nSecond paragraphe assez long pour couper.")],
91
+ on_progress=lambda done, _: progress.append(done),
92
+ )
93
+
94
+ assert (report.chunks, report.entities, report.relations) == (2, 4, 2)
95
+ assert progress == [1, 2]
96
+ assert store.indexes_awaited
97
+
98
+
99
+ def test_dot_output_escapes_quotes() -> None:
100
+ dot = facts_to_dot([GraphFact(source='Say "hi"', relation="USES", target="B")])
101
+ assert '"Say \\"hi\\""' in dot