302 lines
11 KiB
Python
302 lines
11 KiB
Python
"""
|
|
Shared helpers for the organization-crawling pipeline.
|
|
|
|
Every stage script imports this module to:
|
|
- load pipeline_config.json
|
|
- resolve the per-entity run folder (runs/<entity>/out/...)
|
|
- resolve entity-specific input files (accepted hierarchy, problem orgs, ...)
|
|
- build Elasticsearch / LLM clients from shared config + env vars
|
|
|
|
This is the only place that should know about the on-disk layout, so adding a new
|
|
organization is a config-only change (see 'entity_template' in pipeline_config.json).
|
|
"""
|
|
import shutil
|
|
import os
|
|
import json
|
|
import argparse
|
|
import functools
|
|
import hashlib
|
|
|
|
import diskcache
|
|
from dotenv import load_dotenv
|
|
load_dotenv() # load .env file in cwd, if present
|
|
DEFAULT_CONFIG_FILENAME = "pipeline_config.json"
|
|
|
|
|
|
def _default_config_path():
|
|
return os.path.join(os.path.dirname(os.path.abspath(__file__)), DEFAULT_CONFIG_FILENAME)
|
|
|
|
|
|
def load_config(config_path=None):
|
|
path = os.path.abspath(config_path or _default_config_path())
|
|
with open(path, encoding="utf-8") as f:
|
|
config = json.load(f)
|
|
# remember where the config lives so relative paths inside it (ground truth files,
|
|
# crawler dirs, ...) resolve consistently no matter what the script's cwd is.
|
|
config["_config_dir"] = os.path.dirname(path)
|
|
return config
|
|
|
|
|
|
def resolve_path(config, path):
|
|
"""Resolve a path from the config relative to the config file's directory,
|
|
unless it is already absolute."""
|
|
if os.path.isabs(path):
|
|
return path
|
|
return os.path.join(config["_config_dir"], path)
|
|
|
|
|
|
def get_entity(config, entity_name):
|
|
entities = config.get("entities", {})
|
|
if entity_name not in entities:
|
|
raise SystemExit(
|
|
f"Entity '{entity_name}' not found in pipeline_config.json. "
|
|
f"Available entities: {list(entities.keys())}"
|
|
)
|
|
return entities[entity_name]
|
|
|
|
|
|
def run_dir(config, entity_name):
|
|
"""The per-entity, per-run folder: runs/<entity>/ (with an out/ subfolder)."""
|
|
d = resolve_path(config, os.path.join(config.get("runs_dir", "runs"), entity_name))
|
|
os.makedirs(os.path.join(d, "out"), exist_ok=True)
|
|
return d
|
|
|
|
|
|
def out_path(config, entity_name, key):
|
|
"""Resolve the path of a named output artifact for an entity's run.
|
|
'key' matches a key under entities.<entity>.output in pipeline_config.json,
|
|
e.g. out_path(config, 'ude', 'hierarchy_file')."""
|
|
entity = get_entity(config, entity_name)
|
|
filename = entity["output"][key]
|
|
return os.path.join(run_dir(config, entity_name), "out", filename)
|
|
|
|
|
|
def entity_input_path(config, entity_name, key):
|
|
"""Resolve an entity-specific input file path, e.g. 'ground_truth_file' or
|
|
'problem_orgs_file'."""
|
|
entity = get_entity(config, entity_name)
|
|
return resolve_path(config, entity[key])
|
|
|
|
|
|
def hierarchy_path(config, entity_name):
|
|
"""Resolve the accepted hierarchy shared with the service."""
|
|
entity = get_entity(config, entity_name)
|
|
return resolve_path(config, entity["hierarchy_file"])
|
|
def _first_env(*names):
|
|
"""Return the first non-empty environment variable among the given names."""
|
|
for name in names:
|
|
if name and os.environ.get(name):
|
|
return os.environ[name]
|
|
return None
|
|
|
|
|
|
def get_es_client(config):
|
|
from elasticsearch import Elasticsearch
|
|
es_conf = config["elasticsearch"]
|
|
|
|
host = (
|
|
_first_env("INSE_ELASTIC_URL", "ELASTICSEARCH_INSE_URL", es_conf.get("host_env"))
|
|
or es_conf.get("host")
|
|
)
|
|
if not host:
|
|
raise SystemExit("Elasticsearch host not set (INSE_ELASTIC_URL or elasticsearch.host).")
|
|
|
|
kwargs = {
|
|
"request_timeout": es_conf.get("request_timeout", 60),
|
|
"max_retries": es_conf.get("max_retries", 5),
|
|
"retry_on_timeout": True,
|
|
}
|
|
api_key = _first_env(
|
|
"INSE_ELASTIC_API_KEY",
|
|
"ELASTICSEARCH_INSE_API_KEY",
|
|
es_conf.get("api_key_env"),
|
|
)
|
|
username = es_conf.get("user") or os.getenv(es_conf.get("user_env", "ES_USERNAME"))
|
|
password = os.getenv(es_conf.get("password_env", "ES_PASSWORD"))
|
|
if api_key:
|
|
kwargs["api_key"] = api_key
|
|
elif username and password:
|
|
kwargs["basic_auth"] = (username, password)
|
|
else:
|
|
raise SystemExit(
|
|
"Elasticsearch credentials not set: provide INSE_ELASTIC_API_KEY, "
|
|
"or elasticsearch.user plus the ES_PASSWORD variable."
|
|
)
|
|
return Elasticsearch(host, **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# kwargs that only affect transport, not the answer - excluded from the cache
|
|
# key so a streamed call and a non-streamed call with the same prompt share
|
|
# one cache entry.
|
|
_TRANSPORT_KWARGS = ("stream", "stream_options", "timeout")
|
|
|
|
|
|
def _stable_key(func_name, kwargs):
|
|
kwargs = {k: v for k, v in kwargs.items() if k not in _TRANSPORT_KWARGS}
|
|
|
|
def default(o):
|
|
if isinstance(o, type):
|
|
# e.g. a pydantic response_format class -> key on its schema,
|
|
if hasattr(o, "model_json_schema"):
|
|
return o.model_json_schema()
|
|
return f"{o.__module__}.{o.__qualname__}"
|
|
if hasattr(o, "model_dump"):
|
|
return o.model_dump()
|
|
return str(o)
|
|
|
|
payload = json.dumps({"func": func_name, **kwargs}, default=default, sort_keys=True)
|
|
return hashlib.sha256(payload.encode()).hexdigest()
|
|
|
|
|
|
def _collect_stream(stream):
|
|
"""Consume a chat.completions stream and assemble it into a regular
|
|
ChatCompletion object (first choice only, tool calls ignored).
|
|
|
|
We stream purely as a keep-alive: the Apache reverse proxy in front of
|
|
vLLM drops idle connections after ~300s, and a long generation with
|
|
stream=False sends nothing until it is finished -> 502 Proxy Error.
|
|
With streaming, chunks flow continuously and the proxy stays happy.
|
|
"""
|
|
from openai.types.chat import ChatCompletion, ChatCompletionMessage
|
|
from openai.types.chat.chat_completion import Choice
|
|
|
|
meta = {"id": "", "model": "", "created": 0}
|
|
content, reasoning, finish_reason, usage = [], [], None, None
|
|
for chunk in stream:
|
|
for k in meta:
|
|
meta[k] = meta[k] or getattr(chunk, k, None) or meta[k]
|
|
if getattr(chunk, "usage", None):
|
|
usage = chunk.usage
|
|
for choice in chunk.choices or []:
|
|
if choice.index != 0:
|
|
continue
|
|
delta = choice.delta
|
|
if delta is not None:
|
|
if delta.content:
|
|
content.append(delta.content)
|
|
r = getattr(delta, "reasoning", None) or getattr(delta, "reasoning_content", None)
|
|
if r:
|
|
reasoning.append(r)
|
|
if choice.finish_reason:
|
|
finish_reason = choice.finish_reason
|
|
|
|
if finish_reason is None:
|
|
# Connection dropped mid-generation - never hand back a truncated
|
|
# answer as if it were complete; let the caller's retry loop handle it.
|
|
raise RuntimeError("LLM stream ended without a finish_reason (connection dropped?)")
|
|
|
|
message = ChatCompletionMessage(role="assistant", content="".join(content))
|
|
completion = ChatCompletion(
|
|
id=meta["id"], object="chat.completion", created=meta["created"], model=meta["model"],
|
|
choices=[Choice(index=0, finish_reason=finish_reason, message=message)],
|
|
usage=usage,
|
|
)
|
|
if reasoning:
|
|
completion.reasoning = "".join(reasoning) # keep for debugging (extra attr, not part of the schema)
|
|
return completion
|
|
|
|
|
|
def _wrap_stream_collect(method):
|
|
"""stream=True still returns a fully assembled ChatCompletion, so callers
|
|
(and the cache) never have to deal with Stream objects."""
|
|
@functools.wraps(method)
|
|
def wrapper(*args, **kwargs):
|
|
if kwargs.get("stream"):
|
|
return _collect_stream(method(*args, **kwargs))
|
|
return method(*args, **kwargs)
|
|
return wrapper
|
|
|
|
|
|
def _wrap_cached(method, cache, func_name):
|
|
@functools.wraps(method)
|
|
def wrapper(*args, **kwargs):
|
|
key = _stable_key(func_name, kwargs)
|
|
if key in cache:
|
|
return cache[key]
|
|
result = method(*args, **kwargs)
|
|
if _is_complete(result):
|
|
cache[key] = result
|
|
return result
|
|
return wrapper
|
|
|
|
|
|
def _is_complete(completion):
|
|
"""Only cache answers the model actually finished. A truncated answer
|
|
(finish_reason == "length": max_tokens hit, possibly by a reasoning
|
|
trace alone) would otherwise be replayed from the cache on every retry."""
|
|
try:
|
|
return all(c.finish_reason == "stop" for c in completion.choices)
|
|
except Exception:
|
|
return True
|
|
|
|
|
|
def get_llm_client(config, use_cache=True):
|
|
from openai import OpenAI
|
|
llm_conf = config["llm"]
|
|
base_url = _first_env("INSE_LLM_BASE_URL", llm_conf.get("base_url_env", "llm_api"))
|
|
api_key = _first_env("INSE_LLM_API_KEY", llm_conf.get("api_key_env", "llm_key"))
|
|
model_name = _first_env("INSE_LLM_MODEL", llm_conf.get("model_name", "model_name"))
|
|
if not (base_url and api_key and model_name):
|
|
raise SystemExit("LLM settings missing (INSE_LLM_BASE_URL, INSE_LLM_API_KEY, INSE_LLM_MODEL).")
|
|
|
|
client = OpenAI(base_url=base_url, api_key=api_key, max_retries=0)
|
|
client.chat.completions.create = _wrap_stream_collect(client.chat.completions.create)
|
|
|
|
if use_cache:
|
|
cache_dir = resolve_path(
|
|
config, config.get("cache_dir") or llm_conf.get("cache_dir", ".llm_cache")
|
|
)
|
|
cache = diskcache.Cache(cache_dir)
|
|
|
|
client.chat.completions.create = _wrap_cached(
|
|
client.chat.completions.create, cache, "chat.completions.create"
|
|
)
|
|
# if content_extractor_pydantic.py uses structured outputs via .parse()
|
|
if hasattr(client.beta.chat.completions, "parse"):
|
|
client.beta.chat.completions.parse = _wrap_cached(
|
|
client.beta.chat.completions.parse, cache, "beta.chat.completions.parse"
|
|
)
|
|
|
|
return client, model_name
|
|
|
|
|
|
def add_common_args(parser: argparse.ArgumentParser):
|
|
"""Every stage script accepts --entity (required) and --config (optional override)."""
|
|
parser.add_argument("--entity", required=True, help="Entity name as defined in pipeline_config.json")
|
|
parser.add_argument("--config", default=None, help="Path to pipeline_config.json (default: alongside this file)")
|
|
return parser
|
|
|
|
def generated_entities_path(config, entity_name):
|
|
"""Generated crawl-seed JSON: runs/<entity>/entities.json."""
|
|
entity = get_entity(config, entity_name)
|
|
filename = entity.get("crawl", {}).get("generated_entities_file", "entities.json")
|
|
return os.path.join(run_dir(config, entity_name), filename)
|
|
|
|
|
|
def warc_dir(config, entity_name):
|
|
"""Entity-specific WARC output: runs/<entity>/warc/."""
|
|
path = os.path.join(run_dir(config, entity_name), "warc")
|
|
os.makedirs(path, exist_ok=True)
|
|
return path
|
|
|
|
|
|
def crawl_state_dir(config, entity_name):
|
|
"""Entity-specific resumable Scrapy state: runs/<entity>/crawl-state/."""
|
|
path = os.path.join(run_dir(config, entity_name), "crawl-state")
|
|
os.makedirs(path, exist_ok=True)
|
|
return path
|
|
|
|
|
|
def reset_entity_run(config, entity_name):
|
|
"""Delete all generated data for one entity, including WARC and crawl state."""
|
|
path = resolve_path(
|
|
config,
|
|
os.path.join(config.get("runs_dir", "runs"), entity_name),
|
|
)
|
|
if os.path.exists(path):
|
|
shutil.rmtree(path)
|
|
return run_dir(config, entity_name) |