github-actions[bot] commited on
Commit
0ebf5d5
·
1 Parent(s): f14bdd2

Auto-sync from demo at Sun Nov 8 10:46:38 UTC 2026

Browse files
Files changed (29) hide show
  1. graphgen/bases/base_generator.py +29 -7
  2. graphgen/common/init_llm.py +14 -6
  3. graphgen/models/extractor/schema_guided_extractor.py +15 -0
  4. graphgen/models/generator/aggregated_generator.py +6 -9
  5. graphgen/models/generator/atomic_generator.py +4 -4
  6. graphgen/models/generator/cot_generator.py +6 -6
  7. graphgen/models/generator/fill_in_blank_generator.py +3 -3
  8. graphgen/models/generator/masked_fill_in_blank_generator.py +4 -4
  9. graphgen/models/generator/multi_answer_generator.py +3 -3
  10. graphgen/models/generator/multi_choice_generator.py +3 -3
  11. graphgen/models/generator/multi_hop_generator.py +4 -4
  12. graphgen/models/generator/quiz_generator.py +1 -2
  13. graphgen/models/generator/true_false_generator.py +3 -3
  14. graphgen/models/generator/vqa_generator.py +4 -4
  15. graphgen/models/llm/api/openai_client.py +58 -17
  16. graphgen/operators/generate/gates.py +48 -0
  17. graphgen/operators/generate/generate_service.py +81 -55
  18. graphgen/operators/generate/llm_concurrency.py +31 -0
  19. graphgen/templates/profiles/example.v1/aggregated.json +12 -0
  20. graphgen/templates/profiles/example.v1/atomic.json +4 -0
  21. graphgen/templates/profiles/example.v1/cot.json +10 -0
  22. graphgen/templates/profiles/example.v1/fill_in_blank.json +4 -0
  23. graphgen/templates/profiles/example.v1/multi_answer.json +4 -0
  24. graphgen/templates/profiles/example.v1/multi_choice.json +4 -0
  25. graphgen/templates/profiles/example.v1/multi_hop.json +4 -0
  26. graphgen/templates/profiles/example.v1/true_false.json +4 -0
  27. graphgen/templates/profiles/example.v1/vqa.json +4 -0
  28. graphgen/templates/prompt_profiles.py +119 -0
  29. graphgen/utils/log.py +3 -3
graphgen/bases/base_generator.py CHANGED
@@ -1,23 +1,45 @@
1
  from abc import ABC, abstractmethod
2
- from typing import Any
3
 
4
  from graphgen.bases.base_llm_wrapper import BaseLLMWrapper
5
 
6
 
7
  class BaseGenerator(ABC):
8
- """
9
- Generate QAs based on given prompts.
10
- """
11
 
12
  def __init__(self, llm_client: BaseLLMWrapper):
13
  self.llm_client = llm_client
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
- @staticmethod
16
  @abstractmethod
17
  def build_prompt(
18
- batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]]
19
  ) -> str:
20
- """Build prompt for LLM based on the given batch"""
21
 
22
  @staticmethod
23
  @abstractmethod
 
1
  from abc import ABC, abstractmethod
2
+ from typing import Any, Optional
3
 
4
  from graphgen.bases.base_llm_wrapper import BaseLLMWrapper
5
 
6
 
7
  class BaseGenerator(ABC):
8
+ """Generate QAs based on given prompts."""
9
+
10
+ TEMPLATE_KEY: Optional[str] = None
11
 
12
  def __init__(self, llm_client: BaseLLMWrapper):
13
  self.llm_client = llm_client
14
+ self._profile_templates: Optional[dict] = None
15
+
16
+ def apply_prompt_profile(self, profile: str) -> None:
17
+ """Attach a versioned prompt profile to this generator instance."""
18
+ from graphgen.templates.prompt_profiles import load_profile_template
19
+
20
+ if self.TEMPLATE_KEY is None:
21
+ raise ValueError(
22
+ f"prompt_profile_unsupported_generator:{type(self).__name__}"
23
+ )
24
+ self._profile_templates = load_profile_template(profile, self.TEMPLATE_KEY)
25
+
26
+ def template(self, language: str, key: Optional[str] = None) -> str:
27
+ """Resolve the effective template for this generator."""
28
+ from graphgen.templates.prompt_profiles import OFFICIAL_TEMPLATES
29
+
30
+ if self.TEMPLATE_KEY is None:
31
+ raise ValueError(f"prompt_template_key_missing:{type(self).__name__}")
32
+ if self._profile_templates is not None:
33
+ node = self._profile_templates[language]
34
+ else:
35
+ node = OFFICIAL_TEMPLATES[self.TEMPLATE_KEY][language]
36
+ return node[key] if key is not None else node
37
 
 
38
  @abstractmethod
39
  def build_prompt(
40
+ self, batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]]
41
  ) -> str:
42
+ """Build prompt for LLM based on the given batch."""
43
 
44
  @staticmethod
45
  @abstractmethod
graphgen/common/init_llm.py CHANGED
@@ -129,19 +129,27 @@ class LLMFactory:
129
  )
130
 
131
  actor_name = f"Actor_LLM_{model_type}"
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  try:
133
  actor_handle = ray.get_actor(actor_name)
134
  print(f"Using existing Ray actor: {actor_name}")
135
  except ValueError:
136
  print(f"Creating Ray actor for LLM {model_type} with backend {backend}.")
137
- num_gpus = float(config.pop("num_gpus", 0))
138
  actor_handle = (
139
  ray.remote(LLMServiceActor)
140
- .options(
141
- name=actor_name,
142
- num_gpus=num_gpus,
143
- get_if_exists=True,
144
- )
145
  .remote(backend, config)
146
  )
147
 
 
129
  )
130
 
131
  actor_name = f"Actor_LLM_{model_type}"
132
+ # Ray async actors default to max_concurrency=1: all workers' LLM
133
+ # requests serialize inside a single actor, which becomes the
134
+ # generation-throughput bottleneck. GRAPHGEN_LLM_ACTOR_MAX_CONCURRENCY
135
+ # raises it (async methods are concurrency-safe); unset keeps the
136
+ # official default behavior.
137
+ max_concurrency = int(os.environ.get("GRAPHGEN_LLM_ACTOR_MAX_CONCURRENCY", "1"))
138
+ actor_options: Dict[str, Any] = {
139
+ "name": actor_name,
140
+ "num_gpus": float(config.pop("num_gpus", 0)),
141
+ "get_if_exists": True,
142
+ }
143
+ if max_concurrency > 1:
144
+ actor_options["max_concurrency"] = max_concurrency
145
  try:
146
  actor_handle = ray.get_actor(actor_name)
147
  print(f"Using existing Ray actor: {actor_name}")
148
  except ValueError:
149
  print(f"Creating Ray actor for LLM {model_type} with backend {backend}.")
 
150
  actor_handle = (
151
  ray.remote(LLMServiceActor)
152
+ .options(**actor_options)
 
 
 
 
153
  .remote(backend, config)
154
  )
155
 
graphgen/models/extractor/schema_guided_extractor.py CHANGED
@@ -1,4 +1,5 @@
1
  import json
 
2
 
3
  from graphgen.bases import BaseExtractor, BaseLLMWrapper, Chunk
4
  from graphgen.templates import SCHEMA_GUIDED_EXTRACTION_PROMPT
@@ -63,6 +64,20 @@ class SchemaGuidedExtractor(BaseExtractor):
63
 
64
  prompt = self.build_prompt(text)
65
  response = await self.llm_client.generate_answer(prompt)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  try:
67
  extracted_info = json.loads(response)
68
  # Ensure all required keys are present
 
1
  import json
2
+ import os
3
 
4
  from graphgen.bases import BaseExtractor, BaseLLMWrapper, Chunk
5
  from graphgen.templates import SCHEMA_GUIDED_EXTRACTION_PROMPT
 
64
 
65
  prompt = self.build_prompt(text)
66
  response = await self.llm_client.generate_answer(prompt)
67
+
68
+ # Strict-prompt extraction backends occasionally hit EOS as the first
69
+ # token. When GRAPHGEN_EMPTY_EXTRACTION_PREFILL=1 and the first
70
+ # response is empty, retry once with a deterministic assistant prefill
71
+ # that seeds the opening of the expected JSON output; non-empty
72
+ # responses are never retried or modified.
73
+ if (
74
+ not response.strip()
75
+ and os.environ.get("GRAPHGEN_EMPTY_EXTRACTION_PREFILL", "0") == "1"
76
+ ):
77
+ logger.warning("Empty extraction response; retrying with assistant prefill")
78
+ response = await self.llm_client.generate_answer(
79
+ prompt, assistant_prefill="{"
80
+ )
81
  try:
82
  extracted_info = json.loads(response)
83
  # Ensure all required keys are present
graphgen/models/generator/aggregated_generator.py CHANGED
@@ -2,7 +2,6 @@ import re
2
  from typing import Any, Optional
3
 
4
  from graphgen.bases import BaseGenerator
5
- from graphgen.templates import AGGREGATED_GENERATION_PROMPT
6
  from graphgen.utils import detect_main_language, logger
7
 
8
 
@@ -14,9 +13,10 @@ class AggregatedGenerator(BaseGenerator):
14
  2. question generation: Generate relevant questions based on the rephrased text.
15
  """
16
 
17
- @staticmethod
 
18
  def build_prompt(
19
- batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]]
20
  ) -> str:
21
  """
22
  Build prompts for REPHRASE.
@@ -51,7 +51,7 @@ class AggregatedGenerator(BaseGenerator):
51
  # for index, text in enumerate(original_text)
52
  # ]
53
  # )
54
- prompt = AGGREGATED_GENERATION_PROMPT[language]["ANSWER_REPHRASING"].format(
55
  entities=entities_str, relationships=relations_str
56
  )
57
  return prompt
@@ -73,17 +73,14 @@ class AggregatedGenerator(BaseGenerator):
73
  return None
74
  return rephrased_text.strip('"').strip("'")
75
 
76
- @staticmethod
77
- def _build_prompt_for_question_generation(answer: str) -> str:
78
  """
79
  Build prompts for QUESTION GENERATION.
80
  :param answer:
81
  :return:
82
  """
83
  language = detect_main_language(answer)
84
- prompt = AGGREGATED_GENERATION_PROMPT[language]["QUESTION_GENERATION"].format(
85
- answer=answer
86
- )
87
  return prompt
88
 
89
  @staticmethod
 
2
  from typing import Any, Optional
3
 
4
  from graphgen.bases import BaseGenerator
 
5
  from graphgen.utils import detect_main_language, logger
6
 
7
 
 
13
  2. question generation: Generate relevant questions based on the rephrased text.
14
  """
15
 
16
+ TEMPLATE_KEY = "aggregated"
17
+
18
  def build_prompt(
19
+ self, batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]]
20
  ) -> str:
21
  """
22
  Build prompts for REPHRASE.
 
51
  # for index, text in enumerate(original_text)
52
  # ]
53
  # )
54
+ prompt = self.template(language, "ANSWER_REPHRASING").format(
55
  entities=entities_str, relationships=relations_str
56
  )
57
  return prompt
 
73
  return None
74
  return rephrased_text.strip('"').strip("'")
75
 
76
+ def _build_prompt_for_question_generation(self, answer: str) -> str:
 
77
  """
78
  Build prompts for QUESTION GENERATION.
79
  :param answer:
80
  :return:
81
  """
82
  language = detect_main_language(answer)
83
+ prompt = self.template(language, "QUESTION_GENERATION").format(answer=answer)
 
 
84
  return prompt
85
 
86
  @staticmethod
graphgen/models/generator/atomic_generator.py CHANGED
@@ -2,14 +2,14 @@ import re
2
  from typing import Any
3
 
4
  from graphgen.bases import BaseGenerator
5
- from graphgen.templates import ATOMIC_GENERATION_PROMPT
6
  from graphgen.utils import detect_main_language, logger
7
 
8
 
9
  class AtomicGenerator(BaseGenerator):
10
- @staticmethod
 
11
  def build_prompt(
12
- batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]]
13
  ) -> str:
14
  nodes, edges = batch
15
  context = ""
@@ -19,7 +19,7 @@ class AtomicGenerator(BaseGenerator):
19
  context += f"- {edge[0]} - {edge[1]}: {edge[2]['description']}\n"
20
  language = detect_main_language(context)
21
 
22
- prompt = ATOMIC_GENERATION_PROMPT[language].format(context=context)
23
  return prompt
24
 
25
  @staticmethod
 
2
  from typing import Any
3
 
4
  from graphgen.bases import BaseGenerator
 
5
  from graphgen.utils import detect_main_language, logger
6
 
7
 
8
  class AtomicGenerator(BaseGenerator):
9
+ TEMPLATE_KEY = "atomic"
10
+
11
  def build_prompt(
12
+ self, batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]]
13
  ) -> str:
14
  nodes, edges = batch
15
  context = ""
 
19
  context += f"- {edge[0]} - {edge[1]}: {edge[2]['description']}\n"
20
  language = detect_main_language(context)
21
 
22
+ prompt = self.template(language).format(context=context)
23
  return prompt
24
 
25
  @staticmethod
graphgen/models/generator/cot_generator.py CHANGED
@@ -2,14 +2,14 @@ import re
2
  from typing import Any
3
 
4
  from graphgen.bases import BaseGenerator
5
- from graphgen.templates import COT_GENERATION_PROMPT
6
  from graphgen.utils import detect_main_language, logger
7
 
8
 
9
  class CoTGenerator(BaseGenerator):
10
- @staticmethod
 
11
  def build_prompt(
12
- batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]]
13
  ) -> str:
14
  """
15
  Build prompts for COT Template Design.
@@ -30,13 +30,13 @@ class CoTGenerator(BaseGenerator):
30
  ]
31
  )
32
  language = detect_main_language(entities_str + relationships_str)
33
- prompt = COT_GENERATION_PROMPT[language]["COT_TEMPLATE_DESIGN"].format(
34
  entities=entities_str, relationships=relationships_str
35
  )
36
  return prompt
37
 
38
- @staticmethod
39
  def build_prompt_for_cot_generation(
 
40
  batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]],
41
  question: str,
42
  reasoning_path: str,
@@ -58,7 +58,7 @@ class CoTGenerator(BaseGenerator):
58
  ]
59
  )
60
  language = detect_main_language(entities_str + relationships_str)
61
- prompt = COT_GENERATION_PROMPT[language]["COT_GENERATION"].format(
62
  entities=entities_str,
63
  relationships=relationships_str,
64
  question=question,
 
2
  from typing import Any
3
 
4
  from graphgen.bases import BaseGenerator
 
5
  from graphgen.utils import detect_main_language, logger
6
 
7
 
8
  class CoTGenerator(BaseGenerator):
9
+ TEMPLATE_KEY = "cot"
10
+
11
  def build_prompt(
12
+ self, batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]]
13
  ) -> str:
14
  """
15
  Build prompts for COT Template Design.
 
30
  ]
31
  )
32
  language = detect_main_language(entities_str + relationships_str)
33
+ prompt = self.template(language, "COT_TEMPLATE_DESIGN").format(
34
  entities=entities_str, relationships=relationships_str
35
  )
36
  return prompt
37
 
 
38
  def build_prompt_for_cot_generation(
39
+ self,
40
  batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]],
41
  question: str,
42
  reasoning_path: str,
 
58
  ]
59
  )
60
  language = detect_main_language(entities_str + relationships_str)
61
+ prompt = self.template(language, "COT_GENERATION").format(
62
  entities=entities_str,
63
  relationships=relationships_str,
64
  question=question,
graphgen/models/generator/fill_in_blank_generator.py CHANGED
@@ -2,11 +2,12 @@ import re
2
  from typing import Any
3
 
4
  from graphgen.bases import BaseGenerator
5
- from graphgen.templates import FILL_IN_BLANK_GENERATION_PROMPT
6
  from graphgen.utils import detect_main_language, logger
7
 
8
 
9
  class FillInBlankGenerator(BaseGenerator):
 
 
10
  def __init__(self, llm_client, num_of_questions) -> None:
11
  super().__init__(llm_client)
12
  self.num_of_questions = num_of_questions
@@ -72,7 +73,6 @@ class FillInBlankGenerator(BaseGenerator):
72
 
73
  return qa_pairs
74
 
75
- # pylint: disable=W0221
76
  def build_prompt(
77
  self, batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]]
78
  ) -> str:
@@ -92,7 +92,7 @@ class FillInBlankGenerator(BaseGenerator):
92
  )
93
  context = entities_str + "\n" + relationships_str
94
  language = detect_main_language(entities_str + relationships_str)
95
- prompt = FILL_IN_BLANK_GENERATION_PROMPT[language].format(
96
  context=context,
97
  num_of_questions=self.num_of_questions,
98
  )
 
2
  from typing import Any
3
 
4
  from graphgen.bases import BaseGenerator
 
5
  from graphgen.utils import detect_main_language, logger
6
 
7
 
8
  class FillInBlankGenerator(BaseGenerator):
9
+ TEMPLATE_KEY = "fill_in_blank"
10
+
11
  def __init__(self, llm_client, num_of_questions) -> None:
12
  super().__init__(llm_client)
13
  self.num_of_questions = num_of_questions
 
73
 
74
  return qa_pairs
75
 
 
76
  def build_prompt(
77
  self, batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]]
78
  ) -> str:
 
92
  )
93
  context = entities_str + "\n" + relationships_str
94
  language = detect_main_language(entities_str + relationships_str)
95
+ prompt = self.template(language).format(
96
  context=context,
97
  num_of_questions=self.num_of_questions,
98
  )
graphgen/models/generator/masked_fill_in_blank_generator.py CHANGED
@@ -3,7 +3,6 @@ import re
3
  from typing import Any, Optional
4
 
5
  from graphgen.bases import BaseGenerator
6
- from graphgen.templates import AGGREGATED_GENERATION_PROMPT
7
  from graphgen.utils import detect_main_language, logger
8
 
9
  random.seed(42)
@@ -16,9 +15,10 @@ class MaskedFillInBlankGenerator(BaseGenerator):
16
  2. mask: Randomly select a node from the input nodes, and then mask the name of the node in the rephrased text.
17
  """
18
 
19
- @staticmethod
 
20
  def build_prompt(
21
- batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]]
22
  ) -> str:
23
  """
24
  Build prompts for REPHRASE.
@@ -53,7 +53,7 @@ class MaskedFillInBlankGenerator(BaseGenerator):
53
  # for index, text in enumerate(original_text)
54
  # ]
55
  # )
56
- prompt = AGGREGATED_GENERATION_PROMPT[language]["ANSWER_REPHRASING"].format(
57
  entities=entities_str, relationships=relations_str
58
  )
59
  return prompt
 
3
  from typing import Any, Optional
4
 
5
  from graphgen.bases import BaseGenerator
 
6
  from graphgen.utils import detect_main_language, logger
7
 
8
  random.seed(42)
 
15
  2. mask: Randomly select a node from the input nodes, and then mask the name of the node in the rephrased text.
16
  """
17
 
18
+ TEMPLATE_KEY = "masked_fill_in_blank"
19
+
20
  def build_prompt(
21
+ self, batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]]
22
  ) -> str:
23
  """
24
  Build prompts for REPHRASE.
 
53
  # for index, text in enumerate(original_text)
54
  # ]
55
  # )
56
+ prompt = self.template(language, "ANSWER_REPHRASING").format(
57
  entities=entities_str, relationships=relations_str
58
  )
59
  return prompt
graphgen/models/generator/multi_answer_generator.py CHANGED
@@ -2,11 +2,12 @@ import re
2
  from typing import Any
3
 
4
  from graphgen.bases import BaseGenerator
5
- from graphgen.templates import MAQ_GENERATION_PROMPT
6
  from graphgen.utils import detect_main_language, logger
7
 
8
 
9
  class MultiAnswerGenerator(BaseGenerator):
 
 
10
  def __init__(self, llm_client, num_of_questions) -> None:
11
  super().__init__(llm_client)
12
  self.num_of_questions = num_of_questions
@@ -93,7 +94,6 @@ class MultiAnswerGenerator(BaseGenerator):
93
 
94
  return qa_pairs
95
 
96
- # pylint: disable=W0221
97
  def build_prompt(
98
  self, batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]]
99
  ) -> str:
@@ -113,7 +113,7 @@ class MultiAnswerGenerator(BaseGenerator):
113
  )
114
  context = entities_str + "\n" + relationships_str
115
  language = detect_main_language(entities_str + relationships_str)
116
- prompt = MAQ_GENERATION_PROMPT[language].format(
117
  context=context,
118
  num_of_questions=self.num_of_questions,
119
  )
 
2
  from typing import Any
3
 
4
  from graphgen.bases import BaseGenerator
 
5
  from graphgen.utils import detect_main_language, logger
6
 
7
 
8
  class MultiAnswerGenerator(BaseGenerator):
9
+ TEMPLATE_KEY = "multi_answer"
10
+
11
  def __init__(self, llm_client, num_of_questions) -> None:
12
  super().__init__(llm_client)
13
  self.num_of_questions = num_of_questions
 
94
 
95
  return qa_pairs
96
 
 
97
  def build_prompt(
98
  self, batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]]
99
  ) -> str:
 
113
  )
114
  context = entities_str + "\n" + relationships_str
115
  language = detect_main_language(entities_str + relationships_str)
116
+ prompt = self.template(language).format(
117
  context=context,
118
  num_of_questions=self.num_of_questions,
119
  )
graphgen/models/generator/multi_choice_generator.py CHANGED
@@ -2,11 +2,12 @@ import re
2
  from typing import Any
3
 
4
  from graphgen.bases import BaseGenerator
5
- from graphgen.templates import MCQ_GENERATION_PROMPT
6
  from graphgen.utils import detect_main_language, logger
7
 
8
 
9
  class MultiChoiceGenerator(BaseGenerator):
 
 
10
  def __init__(self, llm_client, num_of_questions) -> None:
11
  super().__init__(llm_client)
12
  self.num_of_questions = num_of_questions
@@ -91,7 +92,6 @@ class MultiChoiceGenerator(BaseGenerator):
91
 
92
  return qa_pairs
93
 
94
- # pylint: disable=W0221
95
  def build_prompt(
96
  self, batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]]
97
  ) -> str:
@@ -111,7 +111,7 @@ class MultiChoiceGenerator(BaseGenerator):
111
  )
112
  context = entities_str + "\n" + relationships_str
113
  language = detect_main_language(entities_str + relationships_str)
114
- prompt = MCQ_GENERATION_PROMPT[language].format(
115
  context=context,
116
  num_of_questions=self.num_of_questions,
117
  )
 
2
  from typing import Any
3
 
4
  from graphgen.bases import BaseGenerator
 
5
  from graphgen.utils import detect_main_language, logger
6
 
7
 
8
  class MultiChoiceGenerator(BaseGenerator):
9
+ TEMPLATE_KEY = "multi_choice"
10
+
11
  def __init__(self, llm_client, num_of_questions) -> None:
12
  super().__init__(llm_client)
13
  self.num_of_questions = num_of_questions
 
92
 
93
  return qa_pairs
94
 
 
95
  def build_prompt(
96
  self, batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]]
97
  ) -> str:
 
111
  )
112
  context = entities_str + "\n" + relationships_str
113
  language = detect_main_language(entities_str + relationships_str)
114
+ prompt = self.template(language).format(
115
  context=context,
116
  num_of_questions=self.num_of_questions,
117
  )
graphgen/models/generator/multi_hop_generator.py CHANGED
@@ -2,14 +2,14 @@ import re
2
  from typing import Any
3
 
4
  from graphgen.bases import BaseGenerator
5
- from graphgen.templates import MULTI_HOP_GENERATION_PROMPT
6
  from graphgen.utils import detect_main_language, logger
7
 
8
 
9
  class MultiHopGenerator(BaseGenerator):
10
- @staticmethod
 
11
  def build_prompt(
12
- batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]]
13
  ) -> str:
14
  nodes, edges = batch
15
  entities_str = "\n".join(
@@ -26,7 +26,7 @@ class MultiHopGenerator(BaseGenerator):
26
  ]
27
  )
28
  language = detect_main_language(entities_str + relationships_str)
29
- prompt = MULTI_HOP_GENERATION_PROMPT[language].format(
30
  entities=entities_str, relationships=relationships_str
31
  )
32
  return prompt
 
2
  from typing import Any
3
 
4
  from graphgen.bases import BaseGenerator
 
5
  from graphgen.utils import detect_main_language, logger
6
 
7
 
8
  class MultiHopGenerator(BaseGenerator):
9
+ TEMPLATE_KEY = "multi_hop"
10
+
11
  def build_prompt(
12
+ self, batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]]
13
  ) -> str:
14
  nodes, edges = batch
15
  entities_str = "\n".join(
 
26
  ]
27
  )
28
  language = detect_main_language(entities_str + relationships_str)
29
+ prompt = self.template(language).format(
30
  entities=entities_str, relationships=relationships_str
31
  )
32
  return prompt
graphgen/models/generator/quiz_generator.py CHANGED
@@ -10,9 +10,8 @@ class QuizGenerator(BaseGenerator):
10
  Quiz Generator rephrases given descriptions to create quiz questions.
11
  """
12
 
13
- @staticmethod
14
  def build_prompt(
15
- batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]]
16
  ) -> str:
17
  """
18
  Build prompt for rephrasing the description.
 
10
  Quiz Generator rephrases given descriptions to create quiz questions.
11
  """
12
 
 
13
  def build_prompt(
14
+ self, batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]]
15
  ) -> str:
16
  """
17
  Build prompt for rephrasing the description.
graphgen/models/generator/true_false_generator.py CHANGED
@@ -2,11 +2,12 @@ import re
2
  from typing import Any
3
 
4
  from graphgen.bases import BaseGenerator
5
- from graphgen.templates import TF_GENERATION_PROMPT
6
  from graphgen.utils import detect_main_language, logger
7
 
8
 
9
  class TrueFalseGenerator(BaseGenerator):
 
 
10
  def __init__(self, llm_client, num_of_questions) -> None:
11
  super().__init__(llm_client)
12
  self.num_of_questions = num_of_questions
@@ -64,7 +65,6 @@ class TrueFalseGenerator(BaseGenerator):
64
 
65
  return qa_pairs
66
 
67
- # pylint: disable=W0221
68
  def build_prompt(
69
  self, batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]]
70
  ) -> str:
@@ -84,7 +84,7 @@ class TrueFalseGenerator(BaseGenerator):
84
  )
85
  context = entities_str + "\n" + relationships_str
86
  language = detect_main_language(entities_str + relationships_str)
87
- prompt = TF_GENERATION_PROMPT[language].format(
88
  context=context,
89
  num_of_questions=self.num_of_questions,
90
  )
 
2
  from typing import Any
3
 
4
  from graphgen.bases import BaseGenerator
 
5
  from graphgen.utils import detect_main_language, logger
6
 
7
 
8
  class TrueFalseGenerator(BaseGenerator):
9
+ TEMPLATE_KEY = "true_false"
10
+
11
  def __init__(self, llm_client, num_of_questions) -> None:
12
  super().__init__(llm_client)
13
  self.num_of_questions = num_of_questions
 
65
 
66
  return qa_pairs
67
 
 
68
  def build_prompt(
69
  self, batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]]
70
  ) -> str:
 
84
  )
85
  context = entities_str + "\n" + relationships_str
86
  language = detect_main_language(entities_str + relationships_str)
87
+ prompt = self.template(language).format(
88
  context=context,
89
  num_of_questions=self.num_of_questions,
90
  )
graphgen/models/generator/vqa_generator.py CHANGED
@@ -3,14 +3,14 @@ import re
3
  from typing import Any
4
 
5
  from graphgen.bases import BaseGenerator
6
- from graphgen.templates import VQA_GENERATION_PROMPT
7
  from graphgen.utils import detect_main_language, logger
8
 
9
 
10
  class VQAGenerator(BaseGenerator):
11
- @staticmethod
 
12
  def build_prompt(
13
- batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]]
14
  ) -> str:
15
  nodes, edges = batch
16
  entities_str = "\n".join(
@@ -27,7 +27,7 @@ class VQAGenerator(BaseGenerator):
27
  ]
28
  )
29
  language = detect_main_language(entities_str + relationships_str)
30
- prompt = VQA_GENERATION_PROMPT[language].format(
31
  entities=entities_str, relationships=relationships_str
32
  )
33
  return prompt
 
3
  from typing import Any
4
 
5
  from graphgen.bases import BaseGenerator
 
6
  from graphgen.utils import detect_main_language, logger
7
 
8
 
9
  class VQAGenerator(BaseGenerator):
10
+ TEMPLATE_KEY = "vqa"
11
+
12
  def build_prompt(
13
+ self, batch: tuple[list[tuple[str, dict]], list[tuple[Any, Any, dict]]]
14
  ) -> str:
15
  nodes, edges = batch
16
  entities_str = "\n".join(
 
27
  ]
28
  )
29
  language = detect_main_language(entities_str + relationships_str)
30
+ prompt = self.template(language).format(
31
  entities=entities_str, relationships=relationships_str
32
  )
33
  return prompt
graphgen/models/llm/api/openai_client.py CHANGED
@@ -1,4 +1,5 @@
1
  import math
 
2
  from typing import Any, Dict, List, Optional
3
 
4
  import openai
@@ -13,6 +14,7 @@ from tenacity import (
13
  from graphgen.bases.base_llm_wrapper import BaseLLMWrapper
14
  from graphgen.bases.datatypes import Token
15
  from graphgen.models.llm.limitter import RPM, TPM
 
16
 
17
 
18
  def get_top_response_tokens(response: openai.ChatCompletion) -> List[Token]:
@@ -86,7 +88,9 @@ class OpenAIClient(BaseLLMWrapper):
86
  else:
87
  raise ValueError(f"Unsupported backend {self.backend}. Use 'openai_api' or 'azure_openai_api'.")
88
 
89
- def _pre_generate(self, text: str, history: List[str]) -> Dict:
 
 
90
  kwargs = {
91
  "temperature": self.temperature,
92
  "top_p": self.top_p,
@@ -106,6 +110,11 @@ class OpenAIClient(BaseLLMWrapper):
106
  assert len(history) % 2 == 0, "History should have even number of elements."
107
  messages = history + messages
108
 
 
 
 
 
 
109
  kwargs["messages"] = messages
110
  return kwargs
111
 
@@ -130,6 +139,16 @@ class OpenAIClient(BaseLLMWrapper):
130
  # Limit max_tokens to 1 to avoid long completions
131
  kwargs["max_tokens"] = 1
132
 
 
 
 
 
 
 
 
 
 
 
133
  completion = await self.client.chat.completions.create( # pylint: disable=E1125
134
  model=self.model, **kwargs
135
  )
@@ -149,31 +168,53 @@ class OpenAIClient(BaseLLMWrapper):
149
  self,
150
  text: str,
151
  history: Optional[List[str]] = None,
 
152
  **extra: Any,
153
  ) -> str:
154
- kwargs = self._pre_generate(text, history)
155
 
156
  prompt_tokens = 0
157
  for message in kwargs["messages"]:
158
  prompt_tokens += len(self.tokenizer.encode(message["content"]))
159
  estimated_tokens = prompt_tokens + kwargs["max_tokens"]
160
 
161
- if self.request_limit:
162
- await self.rpm.wait(silent=True)
163
- await self.tpm.wait(estimated_tokens, silent=True)
164
-
165
- completion = await self.client.chat.completions.create( # pylint: disable=E1125
166
- model=self.model, **kwargs
167
- )
168
- if hasattr(completion, "usage"):
169
- self.token_usage.append(
170
- {
171
- "prompt_tokens": completion.usage.prompt_tokens,
172
- "completion_tokens": completion.usage.completion_tokens,
173
- "total_tokens": completion.usage.total_tokens,
174
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
  )
176
- return self.filter_think_tags(completion.choices[0].message.content)
177
 
178
  async def generate_inputs_prob(
179
  self, text: str, history: Optional[List[str]] = None, **extra: Any
 
1
  import math
2
+ import os
3
  from typing import Any, Dict, List, Optional
4
 
5
  import openai
 
14
  from graphgen.bases.base_llm_wrapper import BaseLLMWrapper
15
  from graphgen.bases.datatypes import Token
16
  from graphgen.models.llm.limitter import RPM, TPM
17
+ from graphgen.utils import logger
18
 
19
 
20
  def get_top_response_tokens(response: openai.ChatCompletion) -> List[Token]:
 
88
  else:
89
  raise ValueError(f"Unsupported backend {self.backend}. Use 'openai_api' or 'azure_openai_api'.")
90
 
91
+ def _pre_generate(
92
+ self, text: str, history: List[str], assistant_prefill: Optional[str] = None
93
+ ) -> Dict:
94
  kwargs = {
95
  "temperature": self.temperature,
96
  "top_p": self.top_p,
 
110
  assert len(history) % 2 == 0, "History should have even number of elements."
111
  messages = history + messages
112
 
113
+ # Optional deterministic assistant prefill for strict-prompt backends
114
+ # that occasionally emit EOS as the first token.
115
+ if assistant_prefill is not None:
116
+ messages.append({"role": "assistant", "content": assistant_prefill})
117
+
118
  kwargs["messages"] = messages
119
  return kwargs
120
 
 
139
  # Limit max_tokens to 1 to avoid long completions
140
  kwargs["max_tokens"] = 1
141
 
142
+ # Thinking models spend the first tokens inside <think> content, which
143
+ # makes next-token yes/no logprobs meaningless for judge/loss calls.
144
+ # GRAPHGEN_DISABLE_THINKING=1 asks the backend to disable thinking for
145
+ # these logprob-based calls only.
146
+ if os.environ.get("GRAPHGEN_DISABLE_THINKING", "0") == "1":
147
+ kwargs["extra_body"] = {
148
+ **kwargs.get("extra_body", {}),
149
+ "chat_template_kwargs": {"enable_thinking": False},
150
+ }
151
+
152
  completion = await self.client.chat.completions.create( # pylint: disable=E1125
153
  model=self.model, **kwargs
154
  )
 
168
  self,
169
  text: str,
170
  history: Optional[List[str]] = None,
171
+ assistant_prefill: Optional[str] = None,
172
  **extra: Any,
173
  ) -> str:
174
+ kwargs = self._pre_generate(text, history, assistant_prefill)
175
 
176
  prompt_tokens = 0
177
  for message in kwargs["messages"]:
178
  prompt_tokens += len(self.tokenizer.encode(message["content"]))
179
  estimated_tokens = prompt_tokens + kwargs["max_tokens"]
180
 
181
+ # Bounded retry on empty responses. Thinking backends occasionally
182
+ # return only <think> content that is stripped to nothing downstream;
183
+ # retry instead of propagating an empty string that would fail
184
+ # parsing. GRAPHGEN_EMPTY_RETRY=0 keeps the official single-attempt
185
+ # behavior.
186
+ try:
187
+ empty_retries = max(0, int(os.environ.get("GRAPHGEN_EMPTY_RETRY", "0")))
188
+ except ValueError:
189
+ empty_retries = 0
190
+
191
+ content = ""
192
+ for attempt in range(empty_retries + 1):
193
+ if self.request_limit:
194
+ await self.rpm.wait(silent=True)
195
+ await self.tpm.wait(estimated_tokens, silent=True)
196
+
197
+ completion = await self.client.chat.completions.create( # pylint: disable=E1125
198
+ model=self.model, **kwargs
199
+ )
200
+ if hasattr(completion, "usage"):
201
+ self.token_usage.append(
202
+ {
203
+ "prompt_tokens": completion.usage.prompt_tokens,
204
+ "completion_tokens": completion.usage.completion_tokens,
205
+ "total_tokens": completion.usage.total_tokens,
206
+ }
207
+ )
208
+ content = self.filter_think_tags(completion.choices[0].message.content)
209
+ if content.strip():
210
+ break
211
+ logger.warning(
212
+ "Empty LLM response (attempt %d/%d, model=%s)",
213
+ attempt + 1,
214
+ empty_retries + 1,
215
+ self.model,
216
  )
217
+ return content
218
 
219
  async def generate_inputs_prob(
220
  self, text: str, history: Optional[List[str]] = None, **extra: Any
graphgen/operators/generate/gates.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic output gates for generated QA pairs.
2
+
3
+ A gate is a pure, synchronous filter applied to the parsed QA list of one
4
+ generate call before results reach the native cache. Gates never modify or
5
+ fabricate model output; they only drop pairs that violate a declared
6
+ deterministic contract. Gates are registered by name via
7
+ :func:`register_gate` and selected by name through ``GenerateService``.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import Any, Callable
13
+
14
+ GATES: dict[str, Callable[[Any], list[dict]]] = {}
15
+
16
+
17
+ def register_gate(name: str) -> Callable:
18
+ """Register a gate function under a unique name."""
19
+
20
+ def _decorator(func: Callable[[Any], list[dict]]) -> Callable[[Any], list[dict]]:
21
+ if name in GATES:
22
+ raise ValueError(f"output_gate_already_registered:{name}")
23
+ GATES[name] = func
24
+ return func
25
+
26
+ return _decorator
27
+
28
+
29
+ @register_gate("non_empty_answer")
30
+ def non_empty_answer(qa_pairs: Any) -> list[dict]:
31
+ """Generic built-in gate: keep only pairs with a non-empty answer."""
32
+ if not isinstance(qa_pairs, list):
33
+ return []
34
+ return [
35
+ pair
36
+ for pair in qa_pairs
37
+ if isinstance(pair, dict)
38
+ and isinstance(pair.get("question"), str)
39
+ and isinstance(pair.get("answer"), str)
40
+ and pair["answer"].strip()
41
+ ]
42
+
43
+
44
+ def apply_output_gate(name: str, qa_pairs: Any) -> list[dict]:
45
+ """Apply a registered gate by name; fail-closed on unknown gates."""
46
+ if name not in GATES:
47
+ raise ValueError(f"output_gate_not_registered:{name}")
48
+ return GATES[name](qa_pairs)
graphgen/operators/generate/generate_service.py CHANGED
@@ -6,9 +6,83 @@ from graphgen.common.init_storage import init_storage
6
  from graphgen.utils import logger, run_concurrent
7
 
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  class GenerateService(BaseOperator):
10
  """
11
  Generate question-answer pairs based on nodes and edges.
 
 
 
 
 
 
 
12
  """
13
 
14
  def __init__(
@@ -17,6 +91,9 @@ class GenerateService(BaseOperator):
17
  kv_backend: str = "rocksdb",
18
  method: str = "aggregated",
19
  data_format: str = "ChatML",
 
 
 
20
  **generate_kwargs,
21
  ):
22
  super().__init__(
@@ -29,61 +106,10 @@ class GenerateService(BaseOperator):
29
 
30
  self.method = method
31
  self.data_format = data_format
32
-
33
- if self.method == "atomic":
34
- from graphgen.models import AtomicGenerator
35
-
36
- self.generator = AtomicGenerator(self.llm_client)
37
- elif self.method == "aggregated":
38
- from graphgen.models import AggregatedGenerator
39
-
40
- self.generator = AggregatedGenerator(self.llm_client)
41
- elif self.method == "multi_hop":
42
- from graphgen.models import MultiHopGenerator
43
-
44
- self.generator = MultiHopGenerator(self.llm_client)
45
- elif self.method == "cot":
46
- from graphgen.models import CoTGenerator
47
-
48
- self.generator = CoTGenerator(self.llm_client)
49
- elif self.method == "vqa":
50
- from graphgen.models import VQAGenerator
51
-
52
- self.generator = VQAGenerator(self.llm_client)
53
- elif self.method == "multi_choice":
54
- from graphgen.models import MultiChoiceGenerator
55
-
56
- self.generator = MultiChoiceGenerator(
57
- self.llm_client,
58
- num_of_questions=generate_kwargs.get("num_of_questions", 5),
59
- )
60
- elif self.method == "multi_answer":
61
- from graphgen.models import MultiAnswerGenerator
62
-
63
- self.generator = MultiAnswerGenerator(
64
- self.llm_client,
65
- num_of_questions=generate_kwargs.get("num_of_questions", 3),
66
- )
67
- elif self.method == "fill_in_blank":
68
- from graphgen.models import FillInBlankGenerator
69
-
70
- self.generator = FillInBlankGenerator(
71
- self.llm_client,
72
- num_of_questions=generate_kwargs.get("num_of_questions", 5),
73
- )
74
- elif self.method == "masked_fill_in_blank":
75
- from graphgen.models import MaskedFillInBlankGenerator
76
-
77
- self.generator = MaskedFillInBlankGenerator(self.llm_client)
78
- elif self.method == "true_false":
79
- from graphgen.models import TrueFalseGenerator
80
-
81
- self.generator = TrueFalseGenerator(
82
- self.llm_client,
83
- num_of_questions=generate_kwargs.get("num_of_questions", 5),
84
- )
85
- else:
86
- raise ValueError(f"Unsupported generation mode: {method}")
87
 
88
  def process(self, batch: list) -> Tuple[list, dict]:
89
  """
 
6
  from graphgen.utils import logger, run_concurrent
7
 
8
 
9
+ def _gated_generate(generate, gate):
10
+ """Wrap an async generate so its parsed QA list passes through ``gate``."""
11
+
12
+ async def _wrapper(batch: list) -> list[dict]:
13
+ return gate(await generate(batch))
14
+
15
+ return _wrapper
16
+
17
+
18
+ #: method -> (generator class name, default num_of_questions or None)
19
+ _GENERATOR_SPECS = {
20
+ "atomic": ("AtomicGenerator", None),
21
+ "aggregated": ("AggregatedGenerator", None),
22
+ "multi_hop": ("MultiHopGenerator", None),
23
+ "cot": ("CoTGenerator", None),
24
+ "vqa": ("VQAGenerator", None),
25
+ "multi_choice": ("MultiChoiceGenerator", 5),
26
+ "multi_answer": ("MultiAnswerGenerator", 3),
27
+ "fill_in_blank": ("FillInBlankGenerator", 5),
28
+ "masked_fill_in_blank": ("MaskedFillInBlankGenerator", None),
29
+ "true_false": ("TrueFalseGenerator", 5),
30
+ }
31
+
32
+
33
+ def _create_generator(llm_client: BaseLLMWrapper, method: str, generate_kwargs: dict):
34
+ """Instantiate the generator selected by ``method``."""
35
+ if method not in _GENERATOR_SPECS:
36
+ raise ValueError(f"Unsupported generation mode: {method}")
37
+ class_name, default_num_of_questions = _GENERATOR_SPECS[method]
38
+ from graphgen import models as graphgen_models
39
+
40
+ generator_cls = getattr(graphgen_models, class_name)
41
+ if default_num_of_questions is None:
42
+ return generator_cls(llm_client)
43
+ return generator_cls(
44
+ llm_client,
45
+ num_of_questions=generate_kwargs.get(
46
+ "num_of_questions", default_num_of_questions
47
+ ),
48
+ )
49
+
50
+
51
+ def _configure_generator(
52
+ generator,
53
+ prompt_profile: str | None,
54
+ output_gate: str | None,
55
+ llm_concurrency: int | None,
56
+ ) -> None:
57
+ """Apply optional profile / concurrency / gate configuration."""
58
+ if prompt_profile:
59
+ generator.apply_prompt_profile(prompt_profile)
60
+ if llm_concurrency is not None:
61
+ from graphgen.operators.generate.llm_concurrency import (
62
+ bound_llm_concurrency,
63
+ )
64
+
65
+ generator.generate = bound_llm_concurrency(
66
+ generator.generate, llm_concurrency
67
+ )
68
+ if output_gate:
69
+ from graphgen.operators.generate.gates import GATES
70
+
71
+ if output_gate not in GATES:
72
+ raise ValueError(f"output_gate_not_registered:{output_gate}")
73
+ generator.generate = _gated_generate(generator.generate, GATES[output_gate])
74
+
75
+
76
  class GenerateService(BaseOperator):
77
  """
78
  Generate question-answer pairs based on nodes and edges.
79
+
80
+ Optional additions (all default to official behavior when unset):
81
+ - ``prompt_profile``: versioned prompt override loaded via
82
+ graphgen.templates.prompt_profiles;
83
+ - ``output_gate``: deterministic QA filter registered in
84
+ graphgen.operators.generate.gates;
85
+ - ``llm_concurrency``: cap on in-flight LLM requests per event loop.
86
  """
87
 
88
  def __init__(
 
91
  kv_backend: str = "rocksdb",
92
  method: str = "aggregated",
93
  data_format: str = "ChatML",
94
+ prompt_profile: str | None = None,
95
+ output_gate: str | None = None,
96
+ llm_concurrency: int | None = None,
97
  **generate_kwargs,
98
  ):
99
  super().__init__(
 
106
 
107
  self.method = method
108
  self.data_format = data_format
109
+ self.generator = _create_generator(self.llm_client, method, generate_kwargs)
110
+ _configure_generator(
111
+ self.generator, prompt_profile, output_gate, llm_concurrency
112
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
 
114
  def process(self, batch: list) -> Tuple[list, dict]:
115
  """
graphgen/operators/generate/llm_concurrency.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bound in-flight LLM requests of a generator inside one event loop.
2
+
3
+ Official ``run_concurrent`` has no cross-batch concurrency cap; a busy LLM
4
+ endpoint can deadlock under high fan-out. This helper caps concurrent
5
+ ``generator.generate`` calls with an asyncio.Semaphore created lazily per
6
+ running loop (Ray actors create a fresh loop per batch).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ from typing import Any
13
+
14
+
15
+ def bound_llm_concurrency(generate: Any, limit: int) -> Any:
16
+ """Wrap an async ``generate(batch)`` so at most ``limit`` run in-flight."""
17
+ if limit < 1:
18
+ raise ValueError("llm_concurrency_must_be_positive")
19
+ state: dict[str, Any] = {}
20
+
21
+ async def _gated_generate(batch: Any) -> Any:
22
+ loop = asyncio.get_running_loop()
23
+ semaphore = state.get("semaphore")
24
+ if semaphore is None or state.get("loop") is not loop:
25
+ semaphore = asyncio.Semaphore(limit)
26
+ state["semaphore"] = semaphore
27
+ state["loop"] = loop
28
+ async with semaphore:
29
+ return await generate(batch)
30
+
31
+ return _gated_generate
graphgen/templates/profiles/example.v1/aggregated.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "en": {
3
+ "ANSWER_REPHRASING": "---Role---\nYou are an NLP expert responsible for generating a logically structured and coherent rephrased version of the TEXT based on ENTITIES and RELATIONSHIPS provided below.\nUse English as output language.\n\n---Goal---\nTo generate a version of the text that is rephrased and conveys the same meaning as the original entity and relationship descriptions, while:\n1. Following a clear logical flow and structure\n2. Establishing proper cause-and-effect relationships\n3. Ensuring temporal and sequential consistency\n4. Creating smooth transitions between ideas using conjunctions and appropriate linking words like \"firstly,\" \"however,\" \"therefore,\" etc.\n\n---Instructions---\n1. Analyze the provided ENTITIES and RELATIONSHIPS carefully to identify:\n - Key concepts and their hierarchies\n - Temporal sequences and chronological order\n - Cause-and-effect relationships\n - Dependencies between different elements\n\n2. Organize the information in a logical sequence by:\n - Starting with foundational concepts\n - Building up to more complex relationships\n - Grouping related ideas together\n - Creating clear transitions between sections\n\n3. Rephrase the text while maintaining:\n - Logical flow and progression\n - Clear connections between ideas\n - Proper context and background\n - Coherent narrative structure\n\n4. Review and refine the text to ensure:\n - Logical consistency throughout\n - Clear cause-and-effect relationships\n\n**Attention: Please directly provide the rephrased text without any additional content or analysis.**\n\n################\n-ENTITIES-\n################\n{entities}\n\n################\n-RELATIONSHIPS-\n################\n{relationships}\n\n\n################\nPlease directly output the coherent rephrased text below, without any additional content.\n\nOutput format:\n<rephrased_text>rephrased_text_here</rephrased_text>\n\nRephrased Text:\n",
4
+ "ANSWER_REPHRASING_CONTEXT": "---Role---\nYou are an NLP expert responsible for generating a logically structured and coherent rephrased version of the TEXT based on ENTITIES and RELATIONSHIPS provided below. You may refer to the original text to assist in generating the rephrased version, but ensure that the final output text meets the requirements.\nUse English as output language.\n\n---Goal---\nTo generate a version of the text that is rephrased and conveys the same meaning as the original entity and relationship descriptions, while:\n1. Following a clear logical flow and structure\n2. Establishing proper cause-and-effect relationships\n3. Ensuring temporal and sequential consistency\n4. Creating smooth transitions between ideas using conjunctions and appropriate linking words like \"firstly,\" \"however,\" \"therefore,\" etc.\n\n---Instructions---\n1. Analyze the provided ENTITIES and RELATIONSHIPS carefully to identify:\n - Key concepts and their hierarchies\n - Temporal sequences and chronological order\n - Cause-and-effect relationships\n - Dependencies between different elements\n\n2. Organize the information in a logical sequence by:\n - Starting with foundational concepts\n - Building up to more complex relationships\n - Grouping related ideas together\n - Creating clear transitions between sections\n\n3. Rephrase the text while maintaining:\n - Logical flow and progression\n - Clear connections between ideas\n - Proper context and background\n - Coherent narrative structure\n\n4. Review and refine the text to ensure:\n - Logical consistency throughout\n - Clear cause-and-effect relationships\n\n################\n-ORIGINAL TEXT-\n################\n{original_text}\n\n################\n-ENTITIES-\n################\n{entities}\n\n################\n-RELATIONSHIPS-\n################\n{relationships}\n\n\n################\nPlease directly output the coherent rephrased text below, without any additional content.\n\nOutput format:\n<rephrased_text>rephrased_text_here</rephrased_text>\n\nRephrased Text:\n",
5
+ "QUESTION_GENERATION": "The answer to a question is provided. Please generate a question that corresponds to the answer.\n\nThe answer for which a question needs to be generated is as follows:\n<answer>{answer}</answer>\n\nPlease note the following requirements:\n1. Only output one question text without any additional explanations or analysis.\n2. Do not repeat the content of the answer or any fragments of it.\n3. The question must be independently understandable and fully match the answer.\n\nOutput format:\n<question>question_text</question>\n\nQuestion:\n"
6
+ },
7
+ "zh": {
8
+ "ANSWER_REPHRASING": "---角色---\n你是一位NLP专家,负责根据下面提供的实体和关系生成逻辑结构清晰且连贯的文本重述版本。\n使用中文作为输出语言。\n\n---目标---\n生成文本的重述版本,使其传达与原始实体和关系描述相同的含义,同时:\n1. 遵循清晰的逻辑流和结构\n2. 建立适当的因果关系\n3. 确保时间和顺序的一致性\n4. 使用连词和适当的连接词(如\"首先\"、\"然而\"、\"因此\"等)创造流畅的过渡\n\n---说明---\n1. 仔细分析提供的实体和关系,以识别:\n - 关键概念及其层级关系\n - 时间序列和时间顺序\n - 因果关系\n - 不同元素之间的依赖关系\n2. 通过以下方式将信息组织成逻辑顺序:\n - 从基础概念开始\n - 逐步建立更复杂的关系\n - 将相关的想法分组在一起\n - 在各部分之间创建清晰的过渡\n3. 重述文本时保持:\n - 逻辑流畅\n - 概念之间的清晰联系\n - 适当的上下文和背景\n - 连贯的叙述结构\n4. 检查和完善文本以确保:\n - 整体逻辑一致性\n - 清晰的因果关系\n\n**注意: 请你直接给出重述文本,不要输出任何额外的内容,也不要进行任何分析。**\n\n################\n-实体-\n################\n{entities}\n\n################\n-关系-\n################\n{relationships}\n\n\n################\n请在下方直接输出连贯的重述文本,不要输出任何额外的内容。\n\n输出格式:\n<rephrased_text>rephrased_text_here</rephrased_text>\n\n重述文本:\n",
9
+ "ANSWER_REPHRASING_CONTEXT": "---角色---\n你是一位NLP专家,负责根据下面提供的实体和关系生成逻辑结构清晰且连贯的文本重述版本。你可以参考原始文本辅助生成,但需要确保最终输出的文本符合要求。\n使用中文作为输出语言。\n\n---目标---\n生成文本的重述版本,使其传达与原始实体和关系描述相同的含义,同时:\n1. 遵循清晰的逻辑流和结构\n2. 建立适当的因果关系\n3. 确保时间和顺序的一致性\n4. 使用连词和适当的连接词(如\"首先\"、\"然而\"、\"因此\"等)创造流畅的过渡\n\n---说明---\n1. 仔细分析提供的实体和关系,以识别:\n - 关键概念及其层级关系\n - 时间序列和时间顺序\n - 因果关系\n - 不同元素之间的依赖关系\n2. 通过以下方式将信息组织成逻辑顺序:\n - 从基础概念开始\n - 逐步建立更复杂的关系\n - 将相关的想法分组在一起\n - 在各部分之间创建清晰的过渡\n3. 重述文本时保持:\n - 逻辑流畅\n - 概念之间的清晰联系\n - 适当的上下文和背景\n - 连贯的叙述结构\n4. 检查和完善文本以确保:\n - 整体逻辑一致性\n - 清晰的因果关系\n\n################\n-原始文本-\n################\n{original_text}\n\n################\n-实体-\n################\n{entities}\n\n################\n-关系-\n################\n{relationships}\n\n\n################\n请在下方直接输出连贯的重述文本,不要输出任何额外的内容。\n\n输出格式:\n<rephrased_text>rephrased_text_here</rephrased_text>\n\n重述文本:\n",
10
+ "QUESTION_GENERATION": "下面提供了一个问题的答案,请生成一个与答案对应的问题。\n\n需要生成问题的答案如下:\n<answer>{answer}</answer>\n\n请注意下列要求:\n1. 仅输出一个问题文本,不得包含任何额外说明或分析\n2. 不得重复答案内容或其中任何片段\n3. 问题必须可独立理解且与答案完全匹配\n\n输出格式:\n<question>question_text</question>\n\n问题:\n"
11
+ }
12
+ }
graphgen/templates/profiles/example.v1/atomic.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "en": "You are given a text passage. Your task is to generate a question and answer (QA) pair based on the content of that text.\n\nPlease note the following requirements:\n1. Output only one QA pair without any additional explanations or analysis.\n2. Do not repeat the content of the answer or any part of it.\n3. The answer should be accurate and directly derived from the text. Make sure the QA pair is relevant to the main theme or important details of the given text.\n\nOutput format:\n<question>question_text</question>\n<answer>answer_text</answer>\n\nFor example:\n<question>What is the effect of overexpressing the BG1 gene on grain size and development?</question>\n<answer>Overexpression of the BG1 gene leads to significantly increased grain size, demonstrating its role in grain development.</answer>\n\nHere is the text passage you need to generate a QA pair for:\n{context}\n\nOutput:\n",
3
+ "zh": "给定一个文本段落。你的任务是根据该文本的内容生成一个问答(QA)对。\n\n请注意下列要求:\n1. 仅输出一个问答(QA)对,不得包含任何额外说明或分析\n2. 不得重复答案内容或其中任何片段\n3. 答案应准确且直接从文本中得出。确保QA对与给定文本的主题或重要细节相关。\n\n输出格式如下:\n<question>question_text</question>\n<answer>answer_text</answer>\n\n例如:\n<question>过表达BG1基因对谷粒大小和发育有什么影响?</question>\n<answer>BG1基因的过表达显著增加了谷粒大小,表明其在谷物发育中的作用。</answer>\n\n以下是你需要为其生成QA对的文本段落:\n{context}\n\n输出:\n"
4
+ }
graphgen/templates/profiles/example.v1/cot.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "en": {
3
+ "COT_GENERATION": "Given the raw knowledge graph information and the provided reasoning-path, produce one Chain-of-Thought (CoT) sample that strictly follows the template and can be directly used for downstream training or inference.\nCoT (Chain-of-Thought) means that when answering a complex question, the intermediate reasoning steps are explicitly written out one by one, making the reasoning process transparent and traceable instead of giving only the final answer.\n\n-Input Format-\n[Entities:]:\n(ENTITY_NAME: ENTITY_DESCRIPTION)\n...\n\n[Relationships:]:\n(ENTITY_SOURCE)-[RELATIONSHIP_DESCRIPTION]->(ENTITY_TARGET)\n...\n\n[Question and Reasoning Path:]:\n(QUESTION)\n(REASONING_PATH)\n\n-Output Requirements-\n1. Each step completes a single, indivisible sub-task and is naturally connected, avoiding abrupt transition words.\n2. Use English.\n3. Do not use ordered lists or numbering.\n4. Do not generate extraneous information, just provide the answer.\n\n-Real Data-\nInput:\n[Entities:]:\n{entities}\n\n[Relationships:]:\n{relationships}\n\n[Question:]:\n{question}\n\n[Reasoning_Template:]:\n{reasoning_template}\n\nOutput:\n",
4
+ "COT_TEMPLATE_DESIGN": "You are a “meta-reasoning architect”. Your task is NOT to answer the question, but to design a reusable, generalizable CoT reasoning-path template based solely on the names and descriptions of entities and relationships in the provided knowledge graph.\n\n- Steps -\n1. Entity Recognition\n- Accurately recognize entity information in the [Entities:] section, including entity names and descriptions.\n- The general formats for entity information are:\n(ENTITY_NAME: ENTITY_DESCRIPTION)\n\n2. Relationship Recognition\n- Accurately recognize relationship information in the [Relationships:] section, including source_entity_name, target_entity_name, and relationship descriptions.\n- The general formats for relationship information are:\n(SOURCE_ENTITY_NAME)-[RELATIONSHIP_DESCRIPTION]->(TARGET_ENTITY_NAME)\n\n3. Graph Structure Understanding\n- Correctly associate the source entity name in the relationship information with the entity information.\n- Reconstruct the graph structure based on the provided relationship information.\n\n4. Question Design\n- Design a question around the \"core theme\" expressed by the knowledge graph.\n- The question must be verifiable directly within the graph through entities, relationships, or attributes; avoid subjective judgments.\n- The question should allow the model to think sufficiently, fully utilizing the entities and relationships in the graph, avoiding overly simple or irrelevant questions.\n\n5. Reasoning-Path Design\n- Output a **blueprint that any later model can directly execute**.\n- Keep steps minimal: each step solves one indivisible sub-problem.\n\n\n- Constraints -\n1. Do NOT describe your thinking; output only the reasoning-path design.\n2. If the provided descriptions are contradictory, resolve conflicts and provide a single coherent logic.\n3. Avoid using stop words and overly common words.\n4. Do not include specific numerical values or conclusions, and DO NOT describing meaningless operations like \"Identify the entity\" or \"Identify the relationship\".\n5. Use English as the output language.\n6. The output format is:\n<question>question text</question>\n<reasoning_path>reasoning path design text</reasoning_path>\n\nPlease summarize the information expressed by the knowledge graph based on the following [Entities:] and [Relationships:] provided.\n\n- Real Data -\nInput:\n[Entities:]:\n{entities}\n\n[Relationships:]:\n{relationships}\n\nOutput:\n"
5
+ },
6
+ "zh": {
7
+ "COT_GENERATION": "根据给定的知识图谱原始信息及已生成的推理路径,产出一条符合模板要求、可直接用于下游训练或推理的 CoT 数据。CoT(Chain-of-Thought,思维链)指在回答复杂问题时,把中间推理步骤一步一步显式写出来,使推理过程透明、可追溯,而不是直接给出最终答案。\n\n-输入格式-\n[Entities:]\n(实体名:实体描述)\n...\n\n[Relationships:]\n(来源实体)-[关系描述]->(目标实体)\n...\n\n[Question and Reasoning Path:]\n(问题)\n(推理路径)\n\n-输出要求-\n1. 每一步只完成一个不可分割的子任务,并用自然语言衔接,但是要避免生硬的连接词。\n2. 使用中文。\n3. 不要使用有序列表或编号。\n4. 请直接给出答案,不要生成无关信息。\n\n-真实数据-\n输入:\n[Entities:]:\n{entities}\n\n[Relationships:]:\n{relationships}\n\n[Question:]:\n{question}\n\n[Reasoning_Template:]:\n{reasoning_template}\n\n输出:\n\n",
8
+ "COT_TEMPLATE_DESIGN": "你是一位“元推理架构师”。你的任务不是回答问题,而是根据给定的知识图谱中的实体和关系的名称以及描述信息,设计一条可复用、可泛化的 CoT 推理路径模板。\n-步骤-\n1. 实体识别\n- 准确地识别[Entities:]章节中的实体信息,包括实体名、实体描述信息。\n- 实体信息的一般格式为:\n(实体名:实体描述)\n\n2. 关系识��\n- 准确地识别[Relationships:]章节中的关系信息,包括来源实体名、目标实体名、关系描述信息。\n- 关系信息的一般格式为:\n(来源实体名)-[关系描述]->(目标实体名)\n\n3. 图结构理解\n- 正确地将关系信息中的来源实体名与实体信息关联。\n- 根据提供的关系信息还原出图结构。\n\n4. 问题设计\n- 围绕知识图谱所表达的“核心主题”设计一个问题。\n- 问题必须能在图谱内部通过实体、关系或属性直接验证;避免主观判断。\n- 问题应该能够模型足够的思考,充分利用图谱中的实体和关系,避免过于简单或无关的问题。\n\n5. 推理路径生成\n- 根据问题设计一个**可被后续模型直接执行的推理蓝图**。\n- 保持步骤最小化:每一步只解决一个“不可分割”的子问题。\n\n-约束条件-\n1. 不要在回答中描述你的思考过程,直接给出回复,只给出问题和推理路径设计,不要生成无关信息。\n2. 如果提供的描述信息相互矛盾,请解决矛盾并提供一个单一、连贯的逻辑。\n3. 避免使用停用词和过于常见的词汇。\n4. 不要出现具体数值或结论,不要出现“识别实体”、“识别关系”这类无意义的操作描述。\n5. 使用中文作为输出语言。\n6. 输出格式为:\n<question>问题文本</question>\n<reasoning_path>推理路径设计文本</reasoning_path>\n\n-真实数据-\n输入:\n[Entities:]:\n{entities}\n\n[Relationships:]:\n{relationships}\n\n输出:\n"
9
+ }
10
+ }
graphgen/templates/profiles/example.v1/fill_in_blank.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "zh": "请根据上下文资料生成独立的知识问答填空题。填空题的答案必须能在原文中直接找到。\n\n生成要求:\n1. **语言一致性**:若上下文资料为中文,则生成中文问题;若为英文,则生成英文问题\n2. **数量**:每个上下文资料生成{num_of_questions}个填空题\n3. **独立性**:每个问题必须完整独立,不依赖其他问题\n4. **准确性**:正确答案必须能从原文直接得出\n5. **占位符格式**:使用________(四个下划线)作为填空占位符\n\n输出格式:\n<qa_pairs>\n<qa_pair>\n<question>问题文本(使用________作为占位符)</question>\n<answer>正确答案文本(多个空用逗号分隔)</answer>\n</qa_pair>\n</qa_pairs>\n\n示例(根据iPad Air 2生成2题):\n<qa_pairs>\n<qa_pair>\n<question>iPad Air 2 是由________制造的?</question>\n<answer>美国苹果公司(Apple)</answer>\n</qa_pair>\n<qa_pair>\n<question>iPad Air 2 的发布日期是________,上市日期是________。</question>\n<answer>2014年10月16日,2014年10月22日</answer>\n</qa_pair>\n</qa_pairs>\n\n\n上下文资料:\n{context}\n\n请为以下资料生成{num_of_questions}个填空题:\n",
3
+ "en": "Generate independent fill-in-the-blank questions based on the provided context. Answers must be directly derivable from the text.\n\nRequirements:\n1. **Language Consistency**: Generate in the same language as the context (Chinese/English)\n2. **Quantity**: Generate {num_of_questions} questions per context\n3. **Independence**: Each question must be self-contained\n4. **Accuracy**: Correct answer must be directly found in the source text\n5. **Placeholder Format**: Use ________ (four underscores) as the blank placeholder\n\nOutput Format:\n<qa_pairs>\n<qa_pair>\n<question>Question text (use ________ as placeholder)</question>\n<answer>Correct answer text (separate multiple blanks with commas)</answer>\n</qa_pair>\n</qa_pairs>\n\nExample (2 questions):\n<qa_pairs>\n<qa_pair>\n<question>The iPad Air 2 was manufactured by ________?</question>\n<answer>Apple Inc.</answer>\n</qa_pair>\n<qa_pair>\n<question>The iPad Air 2 was released on ________ and launched on ________.</question>\n<answer>October 16, 2014, October 22, 2014</answer>\n</qa_pair>\n</qa_pairs>\n\nContext:\n{context}\n\nPlease generate {num_of_questions} fill-in-the-blank questions for the following context:\n"
4
+ }
graphgen/templates/profiles/example.v1/multi_answer.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "zh": "请根据上下文资料生成独立的知识问答不定项选择题,每个选择题包含四个选项,其中有若干个正确答案(至少一个),其他为干扰项。\n\n生成要求:\n1. **语言一致性**:若上下文资料为中文,则生成中文问题;若为英文,则生成英文问题\n2. **数量**:每个上下文资料生成{num_of_questions}个选择题\n3. **独立性**:每个问题必须完整独立,不依赖其他问题\n4. **准确性**:正确答案必须能从原文直接得出,干扰项需合理且有区分度\n5. **答案格式**:当有多个正确答案时,用逗号分隔选项字母,如\"A, B, C\"\n\n输出格式:\n<qa_pairs>\n<qa_pair>\n<question>问题文本</question>\n<options>A. 选项A文本\nB. 选项B文本\nC. 选项C文本\nD. 选项D文本</options>\n<answer>正确答案选项字母(多个答案用逗号分隔)</answer>\n</qa_pair>\n</qa_pairs>\n\n示例(根据iPad Air 2生成2题):\n<qa_pairs>\n<qa_pair>\n<question>iPad Air 2的发布年份是?</question>\n<options>A. 2012年\nB. 2014年\nC. 2015年\nD. 2017年</options>\n<answer>B</answer>\n</qa_pair>\n<qa_pair>\n<question>以下哪些是 iPad Air 2 的特点?</question>\n<options>A. Touch ID指纹识别功能\nB. A8X高效处理器\nC. 十百万像素前置相机\nD. 八百万像素后置相机镜头</options>\n<answer>A, B, D</answer>\n</qa_pair>\n</qa_pairs>\n\n\n上下文资料:\n{context}\n\n请为以下资料生成{num_of_questions}个不定项选择题:\n",
3
+ "en": "Generate independent multiple-select knowledge questions based on the provided context. Each question should contain four options with one or more correct answers and distractors.\n\nRequirements:\n1. **Language Consistency**: Generate in the same language as the context (Chinese/English)\n2. **Quantity**: Generate {num_of_questions} questions per context\n3. **Independence**: Each question must be self-contained\n4. **Accuracy**: Correct answer(s) must be derivable from text, distractors should be plausible\n5. **Answer Format**: For multiple correct answers, separate option letters with commas, e.g., \"A, B, C\"\n\nOutput Format:\n<qa_pairs>\n<qa_pair>\n<question>Question text</question>\n<options>A. Option A text\nB. Option B text\nC. Option C text\nD. Option D text</options>\n<answer>Correct option letter(s) (separate multiple answers with commas)</answer>\n</qa_pair>\n</qa_pairs>\n\nExample (2 questions):\n<qa_pairs>\n<qa_pair>\n<question>What are the features of iPad Air 2?</question>\n<options>A. Touch ID fingerprint recognition\nB. A8X processor\nC. Ten-megapixel front camera\nD. Eight-megapixel rear camera</options>\n<answer>A, B, D</answer>\n</qa_pair>\n<qa_pair>\n<question>When was iPad Air 2 discontinued?</question>\n<options>A. March 21, 2016\nB. March 21, 2017\nC. October 22, 2017\nD. October 16, 2016</options>\n<answer>B</answer>\n</qa_pair>\n</qa_pairs>\n\nContext:\n{context}\n\nPlease generate {num_of_questions} multiple-select questions for the following context:\n"
4
+ }
graphgen/templates/profiles/example.v1/multi_choice.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "zh": "请根据上下文资料生成独立的知识问答单选题,每个选择题包含四个选项,其中仅有一个正确答案,其他三个为干扰项。\n\n生成要求:\n1. **语言一致性**:若上下文资料为中文,则生成中文问题;若为英文,则生成英文问题\n2. **数量**:每个上下文资料生成{num_of_questions}个选择题\n3. **独立性**:每个问题必须完整独立,不依赖其他问题\n4. **准确性**:正确答案必须能从原文直接得出,干扰项需合理且有区分度\n\n输出格式:\n<qa_pairs>\n<qa_pair>\n<question>问题文本</question>\n<options>A. 选项A文本\nB. 选项B文本\nC. 选项C文本\nD. 选项D文本</options>\n<answer>正确答案选项字母</answer>\n</qa_pair>\n</qa_pairs>\n\n示例(根据iPad Air 2生成2题):\n<qa_pairs>\n<qa_pair>\n<question>iPad Air 2的发布年份是?</question>\n<options>A. 2012年\nB. 2014年\nC. 2015年\nD. 2017年</options>\n<answer>B</answer>\n</qa_pair>\n<qa_pair>\n<question>iPad Air 2搭载的处理器型号是?</question>\n<options>A. A8\nB. A9X\nC. A8X\nD. A10</options>\n<answer>C</answer>\n</qa_pair>\n</qa_pairs>\n\n\n上下文资料:\n{context}\n\n请为以下资料生成{num_of_questions}个选择题:\n",
3
+ "en": "Generate independent multiple-choice questions based on the provided context. Each question should contain four options with only one correct answer and three distractors.\n\nRequirements:\n1. **Language Consistency**: Generate in the same language as the context (Chinese/English)\n2. **Quantity**: Generate {num_of_questions} questions per context\n3. **Independence**: Each question must be self-contained\n4. **Accuracy**: Correct answer must be derivable from text, distractors should be plausible\n\nOutput Format:\n<qa_pairs>\n<qa_pair>\n<question>Question text</question>\n<options>A. Option A text\nB. Option B text\nC. Option C text\nD. Option D text</options>\n<answer>Correct option letter</answer>\n</qa_pair>\n</qa_pairs>\n\nExample (2 questions):\n<qa_pairs>\n<qa_pair>\n<question>What year was the iPad Air 2 released?</question>\n<options>A. 2012\nB. 2014\nC. 2015\nD. 2017</options>\n<answer>B</answer>\n</qa_pair>\n<qa_pair>\n<question>Which processor does iPad Air 2 use?</question>\n<options>A. A8\nB. A9X\nC. A8X\nD. A10</options>\n<answer>C</answer>\n</qa_pair>\n</qa_pairs>\n\nContext:\n{context}\n\nPlease generate {num_of_questions} questions for the following context:\n"
4
+ }
graphgen/templates/profiles/example.v1/multi_hop.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "en": "Please generate a multi-hop reasoning question and answer based on the following knowledge subgraph. You will be provided with a knowledge subgraph that contains a series of entities, relations, and facts.\nYour task is to generate a question-answer (QA) pair where the question requires multiple steps of reasoning to answer. The answer to the question should be inferred from the given knowledge subgraph. Ensure that the question is of moderate difficulty and requires multiple steps of reasoning to answer.\n\nPlease note the following requirements:\n1. Output only one QA pair without any additional explanations or analysis.\n2. Do not repeat the content of the answer or any part of it. Do not directly copy the example question and answer.\n3. The answer should be accurate and directly derived from the text. Make sure the QA pair is relevant to the main theme or important details of the given text.\n\nFor example:\nInput:\n--Entities--\n1. Apple\n2. Fruit\n3. Vitamin C\n--Relations--\n1. Apple-Fruit: Apple is a type of fruit\n2. Fruit-Vitamin C: Fruits are rich in Vitamin C\n\nOutput:\n<question>What substance, obtained by eating apples, helps maintain health?</question>\n<answer>Vitamin C</answer>\n\nReal input:\n--Entities--\n{entities}\n--Relations--\n{relationships}\n\nOutput:\n",
3
+ "zh": "请基于以下知识子图生成多跳推理问题和答案。你将获得一个知识子图,其中包含一系列实体、关系和事实。\n你的任务是生成一个问答对,其中问题需要经过多次推理才能回答。问题的答案应该是从给定的知识子图中推断出来的。确保问题的难度适中,需要多步推理才能回答。\n\n请注意下列要求:\n1. 仅输出一个问答(QA)对,不得包含任何额外说明或分析\n2. 不得重复答案内容或其中任何片段,不要直接复制示例问题和答案\n3. 答案应准确且直接从文本中得出。确保QA对与给定文本的主题或重要细节相关。\n\n输出格式:\n<question>question_text</question>\n<answer>answer_text</answer>\n\n例如:\n输入为:\n--实体--\n1. 苹果\n2. 水果\n3. 维生素C\n--关系--\n1. 苹果-水果:苹果是一种水果\n2. 水果-维生素C:水果中富含维生素C\n\n输出:\n<question>通过吃苹果补充的什么物质,有助于维持健康?</question>\n<answer>维生素C</answer>\n\n真实输入如下:\n--实体--\n{entities}\n--关系--\n{relationships}\n\n输出:\n"
4
+ }
graphgen/templates/profiles/example.v1/true_false.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "zh": "请根据上下文资料生成独立的知识判断题,每个判断题包含一个陈述句,答案只能是正确(True)或错误(False)。\n\n生成要求:\n1. **语言一致性**:若上下文资料为中文,则生成中文问题;若为英文,则生成英文问题\n2. **数量**:每个上下文资料生成{num_of_questions}个判断题\n3. **独立性**:每个问题必须完整独立,不依赖其他问题\n4. **准确性**:正确答案必须能从原文直接得出,陈述需有明确的判断依据\n\n输出格式:\n<qa_pairs>\n<qa_pair>\n<question>陈述句文本</question>\n<answer>True或False</answer>\n</qa_pair>\n</qa_pairs>\n\n示例(根据iPad Air 2生成2题):\n<qa_pairs>\n<qa_pair>\n<question>iPad Air 2于2014年发布。</question>\n<answer>True</answer>\n</qa_pair>\n<qa_pair>\n<question>iPad Air 2搭载的是A10处理器。</question>\n<answer>False</answer>\n</qa_pair>\n</qa_pairs>\n\n\n上下文资料:\n{context}\n\n请为以下资料生成{num_of_questions}个判断题:\n",
3
+ "en": "Generate independent true/false questions based on the provided context. Each question should be a factual statement that can be clearly determined as true or false.\n\nRequirements:\n1. **Language Consistency**: Generate in the same language as the context (Chinese/English)\n2. **Quantity**: Generate {num_of_questions} true/false questions per context\n3. **Independence**: Each question must be self-contained\n4. **Accuracy**: Correct answer must be directly derivable from the text with clear evidence\n\nOutput Format:\n<qa_pairs>\n<qa_pair>\n<question>Statement text</question>\n<answer>True or False</answer>\n</qa_pair>\n</qa_pairs>\n\nExample (2 questions):\n<qa_pairs>\n<qa_pair>\n<question>The iPad Air 2 was released in 2014.</question>\n<answer>True</answer>\n</qa_pair>\n<qa_pair>\n<question>The iPad Air 2 uses an A10 processor.</question>\n<options>True\nFalse</options>\n<answer>False</answer>\n</qa_pair>\n</qa_pairs>\n\nContext:\n{context}\n\nPlease generate {num_of_questions} true/false questions for the following context:\n"
4
+ }
graphgen/templates/profiles/example.v1/vqa.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "en": "You are a senior VQA data engineer. Your task is to generate logically coherent, verifiable and non-hallucinated question-answer pairs for the given multi-modal samples.\nUse English as the output language.\n\n---Objectives---\nCreate multiple sets of VQA question-answer pairs that satisfy the following:\n1. Only ask about objectively existing facts in the given data, avoiding subjective or ambiguous questions.\n2. Ensure that each question has a clear and verifiable answer, avoiding questions with no answer or uncertainty.\n3. Questions should cover various aspects of both image and text content, ensuring diversity and comprehensiveness.\n4. Avoid repetitive questions, ensuring that each question is unique and meaningful.\n5. Use clear and concise language, avoiding complex or ambiguous wording.\n\n---Instructions---\n1. Carefully analyze the provided entities and relationships to identify:\n - Key concepts and their hierarchical relationships\n - Temporal sequences and time order\n - Cause-and-effect relationships\n - Dependencies between different elements\n2. Organize the information into a logical sequence by:\n - Starting with foundational concepts\n - Gradually building up to more complex relationships\n - Grouping related ideas together\n - Creating clear transitions between sections\n3. Maintain the following when generating question-answer pairs:\n - Logical flow\n - Clear connections between concepts\n - Appropriate context and background\n - Coherent narrative structure\n4. Review and refine the question-answer pairs to ensure:\n - Overall logical consistency\n - Clear cause-and-effect relationships\n\n################\n-Entities-\n################\n{entities}\n################\n-Relationships-\n################\n{relationships}\n################\n\nPlease directly output the generated questions and answers, do not directly copy the example questions and answers, and do not provide irrelevant information.\n\nHere is the response format you should follow:\n<question>question1</question>\n<answer>answer1</answer>\n<question>question2</question>\n<answer>answer2</answer>\n\nOutput:\n",
3
+ "zh": "---角色---\n你是一位资深 VQA 数据工程师。你需要为给定的多模态样本生成逻辑连贯、可验证、无幻觉的问答对。\n使用中文作为输出语言。\n\n---目标---\n创建多组 VQA 问答对,满足:\n1. 仅询问给定数据中客观存在的事实,避免主观或模糊的问题。\n2. 确保每个问题都有明确且可验证的答案,避免无答案或不确定的问题。\n3. 问题应涵盖图像和文本内容的各个方面,确保多样性和全面性。\n4. 避免重复问题,确保每个问题都是独特且有意义的。\n5. 使用清晰简洁的语言,避免复杂或含糊的措辞。\n\n---说明---\n1. 仔细分析提供的实体和关系,以识别:\n - 关键概念及其层级关系\n - 时间序列和时间顺序\n - 因果关系\n - 不同元素之间的依赖关系\n2. 通过以下方式将信息组织成逻辑顺序:\n - 从基础概念开始\n - 逐步建立更复杂的关系\n - 将相关的想法分组在一起\n - 在各部分之间创建清晰的过渡\n3. 生成问答对时保持:\n - 逻辑流畅\n - 概念之间的清晰联系\n - 适当的上下文和背景\n - 连贯的叙述结构\n4. 检查和完善问答对以确保:\n - 整体逻辑一致性\n - 清晰的因果关系\n\n################\n-实体-\n################\n{entities}\n\n################\n-关系-\n################\n{relationships}\n################\n\n请直接输出生成的问题和答案,不要直接复制示例问题和答案,也不要提供无关信息。\n以下是你应遵循的响应格式:\n<question>question1</question>\n<answer>answer1</answer>\n<question>question2</question>\n<answer>answer2</answer>\n\n输出:\n"
4
+ }
graphgen/templates/prompt_profiles.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Versioned prompt profiles: config-driven prompt customization for generators.
2
+
3
+ Official GraphGen hard-codes all prompts as Python constants under
4
+ ``graphgen.templates``; this module adds a generic, fail-closed override
5
+ channel:
6
+
7
+ - a *profile* is a directory containing one JSON file per generator
8
+ ``TEMPLATE_KEY`` (e.g. ``atomic.json``);
9
+ - each JSON file must mirror the exact key structure of the corresponding
10
+ official template (same languages, same nested keys, leaf values are str);
11
+ - ``profile`` values are either built-in profile ids resolved against
12
+ ``graphgen/templates/profiles/`` or explicit filesystem paths (containing
13
+ a path separator).
14
+
15
+ Default behaviour is untouched: when no profile is applied every generator
16
+ falls back to the official template constant byte-for-byte.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import hashlib
22
+ import json
23
+ from pathlib import Path
24
+ from typing import Any
25
+
26
+ from graphgen.templates import (
27
+ AGGREGATED_GENERATION_PROMPT,
28
+ ATOMIC_GENERATION_PROMPT,
29
+ COT_GENERATION_PROMPT,
30
+ FILL_IN_BLANK_GENERATION_PROMPT,
31
+ MAQ_GENERATION_PROMPT,
32
+ MCQ_GENERATION_PROMPT,
33
+ MULTI_HOP_GENERATION_PROMPT,
34
+ TF_GENERATION_PROMPT,
35
+ VQA_GENERATION_PROMPT,
36
+ )
37
+
38
+ BUILTIN_PROFILE_ROOT = Path(__file__).resolve().parent / "profiles"
39
+
40
+ #: template_key -> official template constant (structure validation source).
41
+ OFFICIAL_TEMPLATES: dict[str, Any] = {
42
+ "atomic": ATOMIC_GENERATION_PROMPT,
43
+ "multi_hop": MULTI_HOP_GENERATION_PROMPT,
44
+ "aggregated": AGGREGATED_GENERATION_PROMPT,
45
+ "cot": COT_GENERATION_PROMPT,
46
+ "multi_choice": MCQ_GENERATION_PROMPT,
47
+ "multi_answer": MAQ_GENERATION_PROMPT,
48
+ "fill_in_blank": FILL_IN_BLANK_GENERATION_PROMPT,
49
+ "masked_fill_in_blank": AGGREGATED_GENERATION_PROMPT,
50
+ "true_false": TF_GENERATION_PROMPT,
51
+ "vqa": VQA_GENERATION_PROMPT,
52
+ }
53
+
54
+
55
+ def resolve_profile_dir(profile: str) -> Path:
56
+ """Resolve a profile id / path to its directory; fail-closed if missing."""
57
+ if not profile or not isinstance(profile, str):
58
+ raise ValueError("prompt_profile_must_be_non_empty_string")
59
+ if "/" in profile or "\\" in profile:
60
+ profile_dir = Path(profile)
61
+ else:
62
+ profile_dir = BUILTIN_PROFILE_ROOT / profile
63
+ if not profile_dir.is_dir():
64
+ raise ValueError(f"prompt_profile_not_found:{profile}")
65
+ return profile_dir
66
+
67
+
68
+ def _validate_structure(official: Any, override: Any, path: str) -> None:
69
+ """Override must mirror the official template's key structure exactly."""
70
+ if isinstance(official, dict):
71
+ if not isinstance(override, dict):
72
+ raise ValueError(f"prompt_profile_structure_mismatch:{path}")
73
+ if set(override.keys()) != set(official.keys()):
74
+ raise ValueError(
75
+ f"prompt_profile_structure_mismatch:{path}:"
76
+ f"keys={sorted(map(str, override.keys()))}"
77
+ )
78
+ for key in official:
79
+ _validate_structure(official[key], override[key], f"{path}.{key}")
80
+ return
81
+ if not isinstance(override, str) or not override.strip():
82
+ raise ValueError(f"prompt_profile_structure_mismatch:{path}:non_string_leaf")
83
+
84
+
85
+ def load_profile_template(profile: str, template_key: str) -> dict[str, Any]:
86
+ """Load one generator's template override from a profile.
87
+
88
+ :param profile: profile id (builtin) or filesystem path.
89
+ :param template_key: generator TEMPLATE_KEY, must exist in OFFICIAL_TEMPLATES.
90
+ :return: parsed override dict (same structure as the official template).
91
+ """
92
+ if template_key not in OFFICIAL_TEMPLATES:
93
+ raise ValueError(f"prompt_profile_unknown_template_key:{template_key}")
94
+ profile_file = resolve_profile_dir(profile) / f"{template_key}.json"
95
+ if not profile_file.is_file():
96
+ raise ValueError(f"prompt_profile_template_missing:{profile}/{template_key}")
97
+ try:
98
+ override = json.loads(profile_file.read_text(encoding="utf-8"))
99
+ except json.JSONDecodeError as error:
100
+ raise ValueError(f"prompt_profile_json_invalid:{profile_file}:{error}") from error
101
+ _validate_structure(OFFICIAL_TEMPLATES[template_key], override, template_key)
102
+ return override
103
+
104
+
105
+ def profile_template_sha256s(profile: str, template_keys: list[str]) -> dict[str, str]:
106
+ """Lineage fingerprint: SHA-256 of each override file actually in use."""
107
+ profile_dir = resolve_profile_dir(profile)
108
+ digests: dict[str, str] = {}
109
+ for template_key in template_keys:
110
+ profile_file = profile_dir / f"{template_key}.json"
111
+ if not profile_file.is_file():
112
+ continue
113
+ digests[template_key] = hashlib.sha256(profile_file.read_bytes()).hexdigest()
114
+ return digests
115
+
116
+
117
+ def apply_prompt_profile(generator: Any, profile: str) -> None:
118
+ """Attach profile templates to a generator instance (BaseGenerator API)."""
119
+ generator.apply_prompt_profile(profile)
graphgen/utils/log.py CHANGED
@@ -62,9 +62,9 @@ CURRENT_LOGGER_VAR = contextvars.ContextVar("current_logger")
62
 
63
 
64
  def get_current_logger() -> logging.Logger:
65
- current_logger = CURRENT_LOGGER_VAR.get()
66
- if not current_logger:
67
- raise RuntimeError("No logger is set in the current context.")
68
  return current_logger
69
 
70
 
 
62
 
63
 
64
  def get_current_logger() -> logging.Logger:
65
+ current_logger = CURRENT_LOGGER_VAR.get(None)
66
+ if current_logger is None:
67
+ return logging.getLogger("GraphGen")
68
  return current_logger
69
 
70