| |
| import os |
| import json |
| import math |
| import asyncio |
| import random |
| from typing import Dict, Any, List, Tuple, Optional |
| from dataclasses import dataclass |
| import re |
|
|
| from openai import AsyncOpenAI, BadRequestError |
| from tqdm import tqdm |
| from itertools import count |
|
|
| from prompts import CATEGORIES_SYSTEM_PROMPTS |
|
|
| |
| |
| |
| VLLM_BASE_URL = os.environ.get("VLLM_BASE_URL", "http://10.100.0.111:8020/v1") |
| VLLM_API_KEY = os.environ.get("VLLM_API_KEY", "no-key-needed") |
|
|
| |
| GEN_TEMPERATURE = float(os.environ.get("GEN_TEMPERATURE", "0.7")) |
| GEN_TOP_P = float(os.environ.get("GEN_TOP_P", "1.0")) |
| GEN_MAX_NEW_TOK = int(os.environ.get("GEN_MAX_NEW_TOK", "8192")) |
| STOP_STRINGS = ["<|im_end|>", "<|end_of_text|>"] |
| STOP_TOKEN_IDS = None |
|
|
| |
| RESP_TEMPERATURE = float(os.environ.get("RESP_TEMPERATURE", str(GEN_TEMPERATURE if GEN_TEMPERATURE else 0.3))) |
| RESP_TOP_P = float(os.environ.get("RESP_TOP_P", str(min(GEN_TOP_P, 0.9)))) |
| RESP_MAX_TOKENS = int(os.environ.get("RESP_MAX_TOKENS", "8192")) |
|
|
| Q_TEMPERATURE = float(os.environ.get("Q_TEMPERATURE", "0.7")) |
| Q_TOP_P = float(os.environ.get("Q_TOP_P", "0.95")) |
| Q_MAX_TOKENS = int(os.environ.get("Q_MAX_TOKENS", "8192")) |
|
|
| |
| |
| |
| NUM_ROWS = int(os.environ.get("NUM_ROWS", "600000")) |
| BATCH_SIZE = int(os.environ.get("BATCH_SIZE", "16")) |
| N_TURNS = int(os.environ.get("N_TURNS", "3")) |
| OUTPUT_FILE = os.environ.get("OUTPUT_FILE", "magpie_conversations_cemig.jsonl") |
| INCLUDE_SYSTEM = True |
| LOGITS_PROCESSORS: List[str] = [] |
|
|
| |
| MAX_ASYNC_TOTAL = int(os.environ.get("MAX_ASYNC", "256")) |
| CHAT_SHARE = float(os.environ.get("CHAT_SHARE", "0.8")) |
| MAX_ASYNC_CHAT = max(1, int(MAX_ASYNC_TOTAL * CHAT_SHARE)) |
| MAX_ASYNC_QGEN = max(1, MAX_ASYNC_TOTAL - MAX_ASYNC_CHAT) |
| QUEUE_MAXSIZE = int(os.environ.get("QUEUE_MAXSIZE", str(MAX_ASYNC_CHAT * 4))) |
|
|
| |
| |
| |
| WIKI_DATASET_ID = os.environ.get("WIKI_DATASET_ID", "cemig-ceia/energy_sft_ctx_dataset") |
| WIKI_SUBSET = os.environ.get("WIKI_SUBSET", "default") |
| WIKI_TEXT_FIELD = os.environ.get("WIKI_TEXT_FIELD", "text") |
| WIKI_MAX_CHARS = int(os.environ.get("WIKI_MAX_CHARS", "65000")) |
| WIKI_MIN_CHARS = int(os.environ.get("WIKI_MIN_CHARS", "600")) |
|
|
| |
| |
| |
| QUESTION_STYLE_PROMPTS: Dict[str, str] = { |
| "objetiva": ( |
| "Siga em pt-BR. Gere UMA pergunta objetiva e específica sobre o tema regulatório discutido, " |
| "apoiada no CONTEXTO, evitando 'o que é' e perguntas de sim/não. " |
| "Foque em critério, requisito, exceção ou definição normativa. Máx. 1 sentença. Termine com '?'." |
| ), |
| "analitica": ( |
| "Siga em pt-BR. Gere UMA pergunta analítica e comparativa, apoiada no CONTEXTO, " |
| "pedindo contraste entre regras, impactos práticos, trade-offs ou efeitos de alteração/revogação. " |
| "Evite sim/não e perguntas vagas. Máx. 1 sentença. Termine com '?'." |
| ), |
| } |
| _DEFAULT_STYLE_PROBS = {"objetiva": 0.5, "analitica": 0.5} |
|
|
| QUESTION_STYLE_KERNELS_PT = { |
| "objetiva": ( |
| "Siga em pt-BR. Gere UMA pergunta objetiva e específica ainda não respondida, " |
| "focada em critério, requisito, exceção ou passo procedimental presente no histórico. " |
| "Evite 'o que é', evite sim/não, não repita perguntas. Máx. 1 sentença; termine com '?'." |
| ), |
| "analitica": ( |
| "Siga em pt-BR. Gere UMA pergunta analítica pedindo contraste entre o ato vigente e anteriores " |
| "(diferenças materiais, impactos, justificativas ou riscos). Evite sim/não e generalidades. " |
| "Máx. 1 sentença; termine com '?'." |
| ), |
| } |
| DEFAULT_QUESTION_KERNEL_PT = QUESTION_STYLE_KERNELS_PT["objetiva"] |
| class DropSample(Exception): |
| """Sinaliza que a amostra/conversa deve ser descartada sem interromper o pipeline.""" |
| pass |
|
|
| try: |
| QUESTION_STYLE_PROBS = json.loads(os.environ.get("QUESTION_STYLE_PROBS", "")) or _DEFAULT_STYLE_PROBS |
| except Exception: |
| QUESTION_STYLE_PROBS = _DEFAULT_STYLE_PROBS |
|
|
| QUESTION_SAMPLES_PER_ROW = int(os.environ.get("QUESTION_SAMPLES_PER_ROW", "2")) |
|
|
| def _sample_question_style(k=2) -> List[str]: |
| keys = list(QUESTION_STYLE_PROMPTS.keys()) |
| weights = [QUESTION_STYLE_PROBS.get(k, 0.0) for k in keys] |
| s = sum(weights) |
| weights = [1.0/len(keys)]*len(keys) if s <= 0 else [w/s for w in weights] |
| return random.choices(keys, weights=weights, k=k) |
|
|
| |
| |
| |
| from itertools import cycle |
| TWO_STYLES = [s.strip() for s in os.environ.get("TWO_STYLES", "objetiva,instrucional").split(",") if s.strip()] |
| if len(TWO_STYLES) < 2: |
| TWO_STYLES = ["objetiva", "instrucional"] |
| _STYLE_RR = cycle(TWO_STYLES) |
|
|
| |
| |
| |
| client = AsyncOpenAI(base_url=VLLM_BASE_URL, api_key=VLLM_API_KEY) |
|
|
| |
| |
| |
| def _normalize_spaces(s: str) -> str: |
| return " ".join((s or "").split()) |
|
|
| def _truncate_context(txt: str) -> str: |
| if not isinstance(txt, str): return "" |
| t = _normalize_spaces(txt) |
| if len(t) <= WIKI_MAX_CHARS: return t |
| cut = t.rfind(".", 0, WIKI_MAX_CHARS) |
| if cut == -1 or cut < WIKI_MIN_CHARS: return t[:WIKI_MAX_CHARS] |
| return t[:cut+1] |
|
|
| def sample_system_prompt_key(prompts_with_probs: Dict[str, Tuple[str, float]]) -> str: |
| keys = list(prompts_with_probs.keys()) |
| probs = [prompts_with_probs[k][1] for k in keys] |
| s = sum(probs) |
| probs = [1.0/len(keys)]*len(keys) if s <= 0 else [p/s for p in probs] |
| return random.choices(keys, weights=probs, k=1)[0] |
|
|
| async def get_model_id() -> str: |
| models = await client.models.list() |
| if not models.data: |
| raise RuntimeError("Nenhum modelo disponível no endpoint vLLM.") |
| return models.data[0].id |
|
|
| |
| |
| |
| async def chat_call( |
| messages: List[Dict[str, str]], |
| model_id: str, |
| *, |
| use_magpie_user: bool = False, |
| question_style: Optional[str] = None, |
| followup_context_text: Optional[str] = None, |
| extra_body_override: Optional[dict] = None, |
| ) -> str: |
| if use_magpie_user: |
| kernel = QUESTION_STYLE_KERNELS_PT.get(question_style or "", DEFAULT_QUESTION_KERNEL_PT) |
| sys_msgs = [{"role": "system", "content": kernel}] |
| if followup_context_text: |
| sys_msgs.append({ |
| "role": "system", |
| "content": "Se necessário, use APENAS o CONTEXTO a seguir como base factual; " |
| "não cite literalmente.\n\n=== CONTEXTO ===\n" + followup_context_text |
| }) |
| final_messages = sys_msgs + messages |
| temperature = Q_TEMPERATURE |
| top_p = Q_TOP_P |
| max_tokens = Q_MAX_TOKENS |
| else: |
| final_messages = messages |
| temperature = RESP_TEMPERATURE |
| top_p = RESP_TOP_P |
| max_tokens = RESP_MAX_TOKENS |
|
|
| extra_body = { |
| "chat_template_kwargs": {"enable_thinking": False}, |
| "stop": STOP_STRINGS, |
| "stop_token_ids": STOP_TOKEN_IDS, |
| "logits_processors": LOGITS_PROCESSORS, |
| } |
| if extra_body_override: |
| for k, v in extra_body_override.items(): |
| extra_body[k] = v |
|
|
| resp = await client.chat.completions.create( |
| model=model_id, |
| messages=final_messages, |
| temperature=temperature, |
| top_p=top_p, |
| max_tokens=max_tokens, |
| extra_body=extra_body, |
| ) |
| return resp.choices[0].message.content or "" |
|
|
| async def safe_chat_call(*args, **kwargs) -> Optional[str]: |
| try: |
| return await chat_call(*args, **kwargs) |
| except BadRequestError: |
| try: |
| eb = kwargs.pop("extra_body_override", {}) or {} |
| eb2 = {"chat_template_kwargs": {"enable_thinking": True}} |
| eb2.update(eb) |
| return await chat_call(*args, extra_body_override=eb2, **kwargs) |
| except Exception: |
| pass |
| try: |
| eb = kwargs.pop("extra_body_override", {}) or {} |
| eb2 = dict(eb) |
| eb2.pop("chat_template_kwargs", None) |
| return await chat_call(*args, extra_body_override=eb2, **kwargs) |
| except Exception: |
| return None |
| except Exception: |
| return None |
|
|
| |
| |
| |
| @dataclass |
| class Ato: |
| title: str |
| body: str |
|
|
| _ATO_CURRENT_HDR = re.compile(r"Ato\s+normativo\s+em\s+vigor:\s*(.+?)\s*\n", re.IGNORECASE | re.UNICODE) |
| _ATO_PASTS_HDR = re.compile(r"Atos\s+normativos\s+que\s+são\s+alterados\s+pelo\s+ato\s+em\s+vigor:\s*", re.IGNORECASE | re.UNICODE) |
| _ATO_NOME_SPLIT = re.compile(r"\n{1,2}Nome:\s*", re.IGNORECASE | re.UNICODE) |
|
|
| def parse_ato_tree(txt: str) -> Tuple[Optional[Ato], List[Ato]]: |
| if not isinstance(txt, str) or not txt.strip(): |
| return None, [] |
|
|
| m = _ATO_CURRENT_HDR.search(txt) |
| if not m: |
| return None, [] |
| cur_title = m.group(1).strip() |
| start_body = m.end() |
| pasts_hdr = _ATO_PASTS_HDR.search(txt, start_body) |
| cur_body_end = pasts_hdr.start() if pasts_hdr else len(txt) |
| cur_body = txt[start_body:cur_body_end].strip() |
| current = Ato(title=cur_title, body=cur_body) |
|
|
| pasts: List[Ato] = [] |
| if not pasts_hdr: |
| return current, pasts |
|
|
| pasts_block = txt[pasts_hdr.end():].strip() |
| if not pasts_block: |
| return current, pasts |
|
|
| chunks = _ATO_NOME_SPLIT.split(pasts_block) |
| for ch in chunks: |
| ch = ch.strip() |
| if not ch: |
| continue |
| first_nl = ch.find("\n") |
| if first_nl == -1: |
| title = ch.strip() |
| body = "" |
| else: |
| title = ch[:first_nl].strip() |
| body = ch[first_nl+1:].strip() |
| if title: |
| pasts.append(Ato(title=title, body=body)) |
| return current, pasts |
|
|
| |
| |
| |
| def _mk_prompt_current(cur: Ato) -> str: |
| return ( |
| f"[Interação: Regulamentação atual]\n" |
| f"Ato vigente: {cur.title}\n" |
| "Objetivo: explicar o ato em vigor com base apenas no CONTEXTO.\n" |
| "Entregáveis:\n" |
| "1) finalidade e base legal citada;\n" |
| "2) principais dispositivos/critérios de aplicação;\n" |
| "3) impactos práticos para os agentes afetados.\n" |
| "Se algo não constar do CONTEXTO, responda: 'Informação não encontrada no contexto fornecido.'" |
| ) |
|
|
| def _mk_prompt_span_all(cur: Ato, pasts: List[Ato]) -> str: |
| nomes = "; ".join([cur.title] + [p.title for p in pasts]) |
| return ( |
| f"[Interação: Linha do tempo regulatória]\n" |
| f"Abrangência: {nomes}\n" |
| "Objetivo: integrar o histórico entre o ato vigente e os anteriores usando apenas o CONTEXTO.\n" |
| "Entregáveis:\n" |
| "1) cronologia (quem altera/regulamenta/revoga quem);\n" |
| "2) evolução das regras por tema;\n" |
| "3) pontos de consistência e ruptura e seus efeitos práticos.\n" |
| "Se faltar informação no CONTEXTO, declare: 'Informação não encontrada no contexto fornecido.'" |
| ) |
|
|
| def _mk_prompt_pair(cur: Ato, past: Ato) -> str: |
| return ( |
| f"[Interação: Comparação entre atos]\n" |
| f"Vigente: {cur.title}\n" |
| f"Anterior: {past.title}\n" |
| "Objetivo: comparar os atos com base apenas no CONTEXTO.\n" |
| "Entregáveis:\n" |
| "1) o que permanece igual;\n" |
| "2) o que mudou (âmbito, critérios, parâmetros de cálculo, prazos, exceções, obrigações, penalidades);\n" |
| "3) implicações práticas para os agentes.\n" |
| "Conclua com um resumo das diferenças materiais.\n" |
| "Se algo não constar do CONTEXTO, responda: 'Informação não encontrada no contexto fornecido.'" |
| ) |
|
|
| def build_reg_jobs(context_text: str) -> List[Tuple[str, str, Dict[str, Any]]]: |
| cur, pasts = parse_ato_tree(context_text) |
| if not cur: |
| return [] |
|
|
| jobs: List[Tuple[str, str, Dict[str, Any]]] = [] |
|
|
| |
| jobs.append(( |
| _mk_prompt_current(cur), |
| next(_STYLE_RR), |
| {"prompt_type": "current", "current_title": cur.title} |
| )) |
|
|
| |
| if len(pasts) >= 2: |
| jobs.append(( |
| _mk_prompt_span_all(cur, pasts), |
| next(_STYLE_RR), |
| {"prompt_type": "span_all", |
| "current_title": cur.title, |
| "past_titles": [p.title for p in pasts]} |
| )) |
|
|
| |
| for p in pasts: |
| jobs.append(( |
| _mk_prompt_pair(cur, p), |
| next(_STYLE_RR), |
| {"prompt_type": "pair", |
| "current_title": cur.title, |
| "past_title": p.title} |
| )) |
|
|
| return jobs |
|
|
| |
| |
| |
| async def generate_one_conversation( |
| model_id: str, |
| system_prompt_key: str, |
| system_prompt_text: str, |
| n_turns: int, |
| context_text: str, |
| initial_user: str, |
| question_style: str, |
| ) -> Dict[str, Any]: |
| conversation: List[Dict[str, str]] = [] |
|
|
| base_msgs: List[Dict[str, str]] = [] |
| if INCLUDE_SYSTEM and system_prompt_text: |
| base_msgs.append({"role": "system", "content": system_prompt_text}) |
| if context_text: |
| guard = ( |
| "Use PRIORITARIAMENTE o CONTEXTO a seguir. " |
| "Se faltar informação, responda de forma concisa; se não houver dados suficientes, diga: " |
| "'Informação não encontrada no contexto fornecido.'" |
| ) |
| base_msgs.append({"role": "system", "content": f"{guard}\n\n=== CONTEXTO ===\n{context_text}"}) |
|
|
| |
| conversation.append({"role": "user", "content": initial_user}) |
| first_answer = await safe_chat_call(base_msgs + [{"role": "user", "content": initial_user}], model_id, use_magpie_user=False) |
| conversation.append({"role": "assistant", "content": first_answer}) |
|
|
| |
| remaining = max(0, n_turns - 1) |
| hist_msgs = list(base_msgs) + conversation |
| for _ in range(remaining): |
| next_user = await safe_chat_call(hist_msgs, model_id, use_magpie_user=True, question_style=question_style) |
| conversation.append({"role": "user", "content": next_user}) |
| hist_msgs.append({"role": "user", "content": next_user}) |
|
|
| next_assistant = await safe_chat_call(hist_msgs, model_id, use_magpie_user=False) |
| conversation.append({"role": "assistant", "content": next_assistant}) |
| hist_msgs.append({"role": "assistant", "content": next_assistant}) |
|
|
| return {"conversation": conversation} |
|
|
| |
| |
| |
| def _wiki_stream_iter(): |
| from datasets import load_dataset |
| return load_dataset(WIKI_DATASET_ID, WIKI_SUBSET, split="train", streaming=True) |
|
|
| def _extract_context(record: Dict[str, Any]) -> Optional[Dict[str, Any]]: |
| txt = record.get(WIKI_TEXT_FIELD, "") |
| if not isinstance(txt, str): return None |
| context_text = _truncate_context(txt) |
| if len(context_text) < WIKI_MIN_CHARS: return None |
| title = record.get("title", "") |
| return {"context_text": context_text, "title": title} |
|
|
| |
| async def _execute_with_concurrency(coros: List[asyncio.Future], metas: List[dict], limit: int): |
| sem = asyncio.Semaphore(limit) |
| async def _runner(idx: int, coro): |
| async with sem: |
| res = await coro |
| return idx, res |
| tasks = [asyncio.create_task(_runner(i, c)) for i, c in enumerate(coros)] |
| try: |
| for done in asyncio.as_completed(tasks): |
| i, res = await done |
| yield res, metas[i] |
| finally: |
| for t in tasks: |
| if not t.done(): |
| t.cancel() |
|
|
| |
| def _read_resume_state(path: str) -> Tuple[int, int]: |
| if not os.path.exists(path) or os.path.getsize(path) == 0: |
| return 0, -1 |
| next_seq_id = 0 |
| last_ctx_id = -1 |
| with open(path, "r", encoding="utf-8") as fin: |
| for line in fin: |
| try: |
| obj = json.loads(line) |
| except Exception: |
| continue |
| if "seq_id" in obj: |
| next_seq_id = max(next_seq_id, int(obj["seq_id"]) + 1) |
| if "context_id" in obj: |
| last_ctx_id = max(last_ctx_id, int(obj["context_id"])) |
| return next_seq_id, last_ctx_id |
|
|
| async def _skip_accepted_contexts(ds_iter, n_to_skip: int) -> int: |
| skipped = 0 |
| if n_to_skip <= 0: |
| return 0 |
| for rec in ds_iter: |
| if _extract_context(rec): |
| skipped += 1 |
| if skipped >= n_to_skip: |
| break |
| return skipped |
|
|
| |
| |
| |
| async def run(): |
| os.makedirs(os.path.dirname(OUTPUT_FILE) or ".", exist_ok=True) |
| model_id = await get_model_id() |
|
|
| |
| next_seq_id, last_ctx_id = _read_resume_state(OUTPUT_FILE) |
| seq_id = next_seq_id |
|
|
| ds_iter = _wiki_stream_iter() |
| _ = await _skip_accepted_contexts(ds_iter, last_ctx_id + 1) |
|
|
| start_ctx = (last_ctx_id + 1) if last_ctx_id >= 0 else 0 |
| global_id = count(start_ctx) |
|
|
| total_remaining = max(0, NUM_ROWS - seq_id) |
| total_batches = math.ceil(total_remaining / BATCH_SIZE) if BATCH_SIZE > 0 else 0 |
|
|
| |
| with open(OUTPUT_FILE, "a", encoding="utf-8") as fout: |
| pbar = tqdm(total=total_batches, desc="Gerando conversas (Magpie + dataset regulatório)") |
|
|
| write_lock = asyncio.Lock() |
|
|
| while seq_id < NUM_ROWS: |
| |
| max_contexts_este_batch = BATCH_SIZE |
|
|
| |
| batch_contexts: List[dict] = [] |
| for rec in ds_iter: |
| context_dict = _extract_context(rec) |
| if context_dict: |
| |
| cur, _pasts = parse_ato_tree(context_dict["context_text"]) |
| if not cur: |
| continue |
| ctx_id = next(global_id) |
| batch_contexts.append({**context_dict, "ctx_sample_id": ctx_id}) |
| if len(batch_contexts) >= max_contexts_este_batch: |
| break |
|
|
| if not batch_contexts: |
| break |
|
|
| |
| key = sample_system_prompt_key(CATEGORIES_SYSTEM_PROMPTS) |
| sys_prompt_text = CATEGORIES_SYSTEM_PROMPTS[key][0] |
|
|
| |
| conv_queue: asyncio.Queue = asyncio.Queue(maxsize=QUEUE_MAXSIZE) |
|
|
| |
| qgen_sem = asyncio.Semaphore(MAX_ASYNC_QGEN) |
|
|
| async def qgen_runner(cinfo: dict): |
| async with qgen_sem: |
| ctx_text = cinfo["context_text"] |
| ctx_id = cinfo["ctx_sample_id"] |
| jobs = build_reg_jobs(ctx_text) |
| for prompt, q_style, meta in jobs: |
| await conv_queue.put((ctx_id, ctx_text, prompt, q_style, meta)) |
|
|
| producers = [asyncio.create_task(qgen_runner(cinfo)) for cinfo in batch_contexts] |
|
|
| |
| async def chat_worker(worker_id: int): |
| nonlocal seq_id |
| while True: |
| item = await conv_queue.get() |
| if item is None: |
| conv_queue.task_done() |
| break |
| ctx_id, ctx_text, question, q_style, meta = item |
| try: |
| async with write_lock: |
| if seq_id >= NUM_ROWS: |
| return |
| r = await generate_one_conversation( |
| model_id=model_id, |
| system_prompt_key=key, |
| system_prompt_text=sys_prompt_text, |
| n_turns=N_TURNS, |
| context_text=ctx_text, |
| initial_user=question, |
| question_style=q_style, |
| ) |
| async with write_lock: |
| if seq_id < NUM_ROWS: |
| record = { |
| "seq_id": seq_id, |
| "conversation": r["conversation"], |
| "question_style": q_style, |
| "prompt_type": meta.get("prompt_type"), |
| "current_title": meta.get("current_title"), |
| "past_title": meta.get("past_title"), |
| "past_titles": meta.get("past_titles"), |
| "context_id": ctx_id, |
| } |
| try: |
| fout.write(json.dumps(record, ensure_ascii=False) + "\n") |
| except Exception: |
| pass |
| seq_id += 1 |
| except DropSample: |
| pass |
| except Exception: |
| pass |
| finally: |
| conv_queue.task_done() |
|
|
| consumers = [asyncio.create_task(chat_worker(i)) for i in range(MAX_ASYNC_CHAT)] |
|
|
| |
| await asyncio.gather(*producers) |
| for _ in range(MAX_ASYNC_CHAT): |
| await conv_queue.put(None) |
|
|
| |
| await conv_queue.join() |
| await asyncio.gather(*consumers, return_exceptions=True) |
|
|
| pbar.update(1) |
|
|
| pbar.close() |
|
|
| if __name__ == "__main__": |
| asyncio.run(run()) |
|
|