File size: 7,633 Bytes
4c67792 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 | """
OpenIE extraction (NER + triple extraction) using QAFD-RAG's LLM functions.
Follows the original openie_openai.py logic but calls the async LLM wrappers
from ``QAFD-RAG/src/llm.py`` synchronously via ``asyncio.run``.
"""
import asyncio
import json
import logging
import re
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
from typing import Dict, Any, List, Tuple, TypedDict, Callable
from tqdm import tqdm
from .prompts import make_ner_messages, make_triple_messages
from .utils import (
NerRawOutput,
TripleRawOutput,
fix_broken_generated_json,
filter_invalid_triples,
)
logger = logging.getLogger(__name__)
class ChunkInfo(TypedDict):
num_tokens: int
content: str
def _run_sync(coro):
"""Run async coroutine from sync context."""
try:
loop = asyncio.get_running_loop()
except RuntimeError:
loop = None
if loop is not None and loop.is_running():
import concurrent.futures
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
return pool.submit(asyncio.run, coro).result()
else:
return asyncio.run(coro)
def _extract_ner_from_response(response_text: str) -> List[str]:
pattern = r'\{[^{}]*"named_entities"\s*:\s*\[[^\]]*\][^{}]*\}'
match = re.search(pattern, response_text, re.DOTALL)
if match is None:
return []
try:
return eval(match.group())["named_entities"]
except Exception:
return []
def _extract_triples_from_response(response_text: str) -> List[List[str]]:
pattern = r'\{[^{}]*"triples"\s*:\s*\[[^\]]*\][^{}]*\}'
match = re.search(pattern, response_text, re.DOTALL)
if match is None:
return []
try:
return eval(match.group())["triples"]
except Exception:
return []
class OpenIE:
"""Synchronous OpenIE using QAFD-RAG's async LLM function.
Parameters
----------
llm_func : callable
An async function with the signature::
async def llm_func(prompt, system_prompt=None,
history_messages=[], **kwargs) -> str
Typically one of the ``gpt_*_complete`` helpers from ``src/llm.py``.
"""
def __init__(self, llm_func: Callable):
self.llm_func = llm_func
def _call_llm(self, messages: List[Dict[str, str]]) -> str:
"""Convert chat messages to a single LLM call."""
system_prompt = None
history = []
user_prompt = ""
for msg in messages:
if msg["role"] == "system":
system_prompt = msg["content"]
elif msg["role"] == "assistant":
history.append(msg)
elif msg["role"] == "user":
# All user messages except the last go into history
if user_prompt:
history.append({"role": "user", "content": user_prompt})
user_prompt = msg["content"]
return _run_sync(
self.llm_func(
prompt=user_prompt,
system_prompt=system_prompt,
history_messages=history,
max_tokens=2048,
)
)
# ------------------------------------------------------------------
def ner(self, chunk_key: str, passage: str) -> NerRawOutput:
messages = make_ner_messages(passage)
raw_response = ""
metadata: Dict[str, Any] = {}
try:
raw_response = self._call_llm(messages)
real_response = fix_broken_generated_json(raw_response)
extracted = _extract_ner_from_response(real_response)
unique_entities = list(dict.fromkeys(extracted))
except Exception as e:
logger.warning(f"NER error for chunk {chunk_key}: {e}")
metadata["error"] = str(e)
return NerRawOutput(
chunk_id=chunk_key,
response=raw_response,
unique_entities=[],
metadata=metadata,
)
return NerRawOutput(
chunk_id=chunk_key,
response=raw_response,
unique_entities=unique_entities,
metadata=metadata,
)
# ------------------------------------------------------------------
def triple_extraction(
self, chunk_key: str, passage: str, named_entities: List[str]
) -> TripleRawOutput:
messages = make_triple_messages(passage, named_entities)
raw_response = ""
metadata: Dict[str, Any] = {}
try:
raw_response = self._call_llm(messages)
real_response = fix_broken_generated_json(raw_response)
extracted = _extract_triples_from_response(real_response)
triplets = filter_invalid_triples(triples=extracted)
except Exception as e:
logger.warning(f"Triple extraction error for chunk {chunk_key}: {e}")
metadata["error"] = str(e)
return TripleRawOutput(
chunk_id=chunk_key,
response=raw_response,
metadata=metadata,
triples=[],
)
return TripleRawOutput(
chunk_id=chunk_key,
response=raw_response,
metadata=metadata,
triples=triplets,
)
# ------------------------------------------------------------------
def openie(self, chunk_key: str, passage: str) -> Dict[str, Any]:
ner_output = self.ner(chunk_key=chunk_key, passage=passage)
triple_output = self.triple_extraction(
chunk_key=chunk_key,
passage=passage,
named_entities=ner_output.unique_entities,
)
return {"ner": ner_output, "triplets": triple_output}
# ------------------------------------------------------------------
def batch_openie(
self, chunks: Dict[str, dict]
) -> Tuple[Dict[str, NerRawOutput], Dict[str, TripleRawOutput]]:
"""Run NER + triple extraction over all chunks using multithreading.
Parameters
----------
chunks : dict
Mapping ``chunk_hash_id -> {"content": text, ...}``.
Returns
-------
(ner_dict, triple_dict)
"""
chunk_passages = {k: v["content"] for k, v in chunks.items()}
# ---- NER pass ----
ner_results: List[NerRawOutput] = []
with ThreadPoolExecutor() as executor:
ner_futures = {
executor.submit(self.ner, ckey, passage): ckey
for ckey, passage in chunk_passages.items()
}
for future in tqdm(
as_completed(ner_futures), total=len(ner_futures), desc="NER"
):
ner_results.append(future.result())
# ---- Triple extraction pass ----
triple_results: List[TripleRawOutput] = []
with ThreadPoolExecutor() as executor:
re_futures = {
executor.submit(
self.triple_extraction,
nr.chunk_id,
chunk_passages[nr.chunk_id],
nr.unique_entities,
): nr.chunk_id
for nr in ner_results
}
for future in tqdm(
as_completed(re_futures),
total=len(re_futures),
desc="Triple extraction",
):
triple_results.append(future.result())
ner_dict = {r.chunk_id: r for r in ner_results}
triple_dict = {r.chunk_id: r for r in triple_results}
return ner_dict, triple_dict
|