Skip to content

Commit b393169

Browse files
authored
Handle cases where the LLM produces a valid JSON array (#263)
* Handle cases where the LLM produces a valid JSON array * Ruff
1 parent 5fbb694 commit b393169

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

src/neo4j_graphrag/experimental/components/entity_relation_extractor.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,7 @@ async def extract_for_chunk(
225225
logger.debug(f"Invalid JSON: {llm_result.content}")
226226
result = {"nodes": [], "relationships": []}
227227
try:
228-
chunk_graph = Neo4jGraph(**result)
228+
chunk_graph = Neo4jGraph.model_validate(result)
229229
except ValidationError as e:
230230
if self.on_error == OnError.RAISE:
231231
raise LLMGenerationError("LLM response has improper format") from e

tests/unit/experimental/components/test_entity_relation_extractor.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,24 @@ async def test_extractor_llm_invalid_json() -> None:
178178
await extractor.run(chunks=chunks)
179179

180180

181+
@pytest.mark.asyncio
182+
async def test_extractor_llm_invalid_json_is_a_list() -> None:
183+
"""Test what happens when the returned JSON is a valid JSON list,
184+
but it does not match the expected Pydantic model"""
185+
llm = MagicMock(spec=LLMInterface)
186+
llm.ainvoke.return_value = LLMResponse(
187+
# missing "label" for entity
188+
content='[{"nodes": [{"id": 0, "entity_type": "Person", "properties": {}}], "relationships": []}]'
189+
)
190+
191+
extractor = LLMEntityRelationExtractor(
192+
llm=llm,
193+
)
194+
chunks = TextChunks(chunks=[TextChunk(text="some text", index=0)])
195+
with pytest.raises(LLMGenerationError):
196+
await extractor.run(chunks=chunks)
197+
198+
181199
@pytest.mark.asyncio
182200
async def test_extractor_llm_badly_formatted_json_gets_fixed() -> None:
183201
llm = MagicMock(spec=LLMInterface)

0 commit comments

Comments
 (0)