-
Notifications
You must be signed in to change notification settings - Fork 86
feat: add bounded graph extraction concurrency #370
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from 2 commits
3719fb3
fd572e3
182e1a3
5e3ac82
fea7c35
e80f434
43d9bd6
8f43b44
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -19,11 +19,13 @@ | |
|
|
||
| import json | ||
| import re | ||
| from concurrent.futures import ThreadPoolExecutor, as_completed | ||
| from typing import Any, Dict, List | ||
|
|
||
| from hugegraph_llm.config import prompt | ||
| from hugegraph_llm.document.chunk_split import ChunkSplitter | ||
| from hugegraph_llm.models.llms.base import BaseLLM | ||
| from hugegraph_llm.utils.graph_extract_config import validate_graph_extract_max_workers | ||
| from hugegraph_llm.utils.log import log | ||
|
|
||
| # TODO: It is not clear whether there is any other dependence on the SCHEMA_EXAMPLE_PROMPT variable. | ||
|
|
@@ -78,9 +80,15 @@ def filter_item(schema, items) -> List[Dict[str, Any]]: | |
|
|
||
|
|
||
| class PropertyGraphExtract: | ||
| def __init__(self, llm: BaseLLM, example_prompt: str = prompt.extract_graph_prompt) -> None: | ||
| def __init__( | ||
| self, | ||
| llm: BaseLLM, | ||
| example_prompt: str = prompt.extract_graph_prompt, | ||
| max_workers: int = 1, | ||
| ) -> None: | ||
| self.llm = llm | ||
| self.example_prompt = example_prompt | ||
| self.max_workers = validate_graph_extract_max_workers(max_workers) | ||
| self.NECESSARY_ITEM_KEYS = {"label", "type", "properties"} # pylint: disable=invalid-name | ||
|
|
||
| def run(self, context: Dict[str, Any]) -> Dict[str, List[Any]]: | ||
|
|
@@ -90,26 +98,86 @@ def run(self, context: Dict[str, Any]) -> Dict[str, List[Any]]: | |
| context["vertices"] = [] | ||
| if "edges" not in context: | ||
| context["edges"] = [] | ||
|
|
||
| items = [] | ||
| for chunk in chunks: | ||
| proceeded_chunk = self.extract_property_graph_by_llm(schema, chunk) | ||
| log.debug( | ||
| "[LLM] %s input: %s \n output:%s", | ||
| self.__class__.__name__, | ||
| chunk, | ||
| proceeded_chunk, | ||
| ) | ||
| items.extend(self._extract_and_filter_label(schema, proceeded_chunk)) | ||
| if self.max_workers == 1 or len(chunks) <= 1: | ||
| chunk_results = [ | ||
| self._extract_chunk_items(schema, chunk, index, len(chunks)) for index, chunk in enumerate(chunks) | ||
| ] | ||
| else: | ||
| chunk_results = self._extract_chunks_concurrently(schema, chunks) | ||
|
|
||
| for chunk_items in chunk_results: | ||
| items.extend(chunk_items) | ||
|
|
||
| items = filter_item(schema, items) | ||
| for item in items: | ||
| if item["type"] == "vertex": | ||
| context["vertices"].append(item) | ||
| elif item["type"] == "edge": | ||
| context["edges"].append(item) | ||
|
|
||
| context["call_count"] = context.get("call_count", 0) + len(chunks) | ||
| return context | ||
|
|
||
| def _extract_chunks_concurrently(self, schema, chunks): | ||
| worker_count = min(self.max_workers, len(chunks)) | ||
| chunk_results = [None] * len(chunks) | ||
| with ThreadPoolExecutor(max_workers=worker_count) as executor: | ||
| future_to_index = { | ||
| executor.submit( | ||
| self._extract_chunk_items, | ||
| schema, | ||
| chunk, | ||
| index, | ||
| len(chunks), | ||
| ): index | ||
| for index, chunk in enumerate(chunks) | ||
| } | ||
| for future in as_completed(future_to_index): | ||
| index = future_to_index[future] | ||
| chunk_results[index] = future.result() | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| return chunk_results | ||
|
|
||
| def _extract_chunk_items(self, schema, chunk, chunk_index, chunk_count): | ||
| try: | ||
| proceeded_chunk = self.extract_property_graph_by_llm(schema, chunk) | ||
| self._extract_property_graph_json(proceeded_chunk) | ||
| self._extract_property_graph_json(proceeded_chunk) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🧹 The same response is parsed and validated twice consecutively, and both return values are discarded. This doubles the regex and JSON-decoding work for every chunk without adding coverage. Please remove the duplicate call or parse once and reuse the result. |
||
| except Exception as exc: | ||
| raise RuntimeError(f"Graph extraction failed for chunk {chunk_index + 1}/{chunk_count}: {exc}") from exc | ||
|
|
||
| log.debug( | ||
| "[LLM] %s input: %s \noutput:%s", | ||
| self.__class__.__name__, | ||
| chunk, | ||
| proceeded_chunk, | ||
| ) | ||
| return self._extract_and_filter_label(schema, proceeded_chunk) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This still treats malformed model output as a successful empty chunk in several cases. _extract_chunk_items only wraps exceptions raised by extract_property_graph_by_llm, but _extract_and_filter_label returns [] when no JSON is found, when the graph shape is invalid, or when JSON decoding fails. With multiple chunks, one bad chunk can therefore be silently dropped and the overall extraction still returns success, which loses the chunk-level failure visibility described in the PR. Please make parse/format failures distinguishable from a valid empty extraction and raise or report them with the chunk index.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thanks for the review. I updated the chunk extraction path so malformed LLM responses are no longer silently treated as empty results. Each chunk response is now validated for JSON extraction and expected property-graph shape before filtering. If a chunk returns malformed JSON or an invalid graph format, extraction fails with chunk context such as I also added regression tests for malformed chunk output, backend concurrency cap validation, and REST request validation. |
||
|
|
||
| @staticmethod | ||
| def _extract_property_graph_json(text): | ||
| text = re.sub(r"```\w*\n?", "", text) | ||
| text = re.sub(r"```", "", text) | ||
| text = text.strip() | ||
|
|
||
| json_match = re.search(r"(\{.*\}|\[.*\])", text, re.DOTALL) | ||
| if not json_match: | ||
| raise ValueError("No JSON found in property graph extraction response") | ||
|
|
||
| json_str = json_match.group(1).strip() | ||
| try: | ||
| property_graph = json.loads(json_str) | ||
| except json.JSONDecodeError as exc: | ||
| raise ValueError(f"Invalid property graph JSON: {exc.msg}") from exc | ||
|
|
||
| if isinstance(property_graph, list): | ||
| return property_graph | ||
|
|
||
| if not (isinstance(property_graph, dict) and "vertices" in property_graph and "edges" in property_graph): | ||
| raise ValueError("Invalid property graph format; expecting 'vertices' and 'edges'") | ||
|
|
||
| return property_graph | ||
|
|
||
| def extract_property_graph_by_llm(self, schema, chunk): | ||
| prompt = generate_extract_property_graph_prompt(chunk, schema) | ||
| if self.example_prompt is not None: | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| # Licensed to the Apache Software Foundation (ASF) under one or more | ||
| # contributor license agreements. See the NOTICE file distributed with | ||
| # this work for additional information regarding copyright ownership. | ||
| # The ASF licenses this file to You under the Apache License, Version 2.0 | ||
| # (the "License"); you may not use this file except in compliance with | ||
| # the License. You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| MAX_GRAPH_EXTRACT_WORKERS = 8 | ||
|
|
||
|
|
||
| def validate_graph_extract_max_workers(value) -> int: | ||
| try: | ||
| workers = int(value) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Medium: Reject fractional worker counts instead of truncating them
Evidence
Impact
Requested fix
|
||
| except (TypeError, ValueError) as exc: | ||
| raise ValueError( | ||
| f"graph_extract_max_workers must be an integer between 1 and {MAX_GRAPH_EXTRACT_WORKERS}" | ||
| ) from exc | ||
|
|
||
| if workers < 1 or workers > MAX_GRAPH_EXTRACT_WORKERS: | ||
| raise ValueError(f"graph_extract_max_workers must be an integer between 1 and {MAX_GRAPH_EXTRACT_WORKERS}") | ||
|
|
||
| return workers | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧹 REST validation coerces some raw inputs before the shared validator can enforce its contract. A direct probe shows
graph_extract_max_workers=trueand"1.0"are both accepted here as integer1, whilevalidate_graph_extract_max_workers()rejects those same raw values. This makes REST behavior inconsistent with the flow/helper entry points and can silently turn malformed input into a valid request. Please add amode="before"field validator (or equivalent strict raw-input validation) that applies the shared rules, and cover boolean and decimal-string request values with regression tests.