Files
smartguide/llm_evaluations/AD_CD_llm/CD_to_llm.py
T
Roman 13f4924092
LocationBasedServices/smartguide/pipeline/head This commit looks good
AD/CD vLLM extraction and gold standard evaluation
2026-06-08 21:58:01 +02:00

347 lines
8.8 KiB
Python

from pathlib import Path
import getpass
import json
import os
import requests
API_URL = "https://project.nes.uni-due.de/llm2/v1/chat/completions"
MODEL = "gemma4-e4b"
SCRIPT_DIR = Path(__file__).resolve().parent
ROOT_DIR = SCRIPT_DIR
SYSTEM_PROMPT_PATH = SCRIPT_DIR / "prompt_template_cd_vllm.txt"
CD_INPUT_FILE_NAME = "CD_relevant_tables.txt"
AD_RESULT_FILE_NAME = "AD_llm_result_vllm.json"
CD_OUTPUT_FILE_NAME = "CD_llm_result_vllm.json"
DEBUG_FILE_NAME = "CD_vllm_debug.json"
# PAIR_IDS = [
# "154115",
# "154117",
# "154129",
# "154131",
# "154136",
# "154149",
# "154152",
# "154168",
# "154174",
# "154177",
# "154180",
# "154203",
# "154204",
# "154220",
# "154232",
# "154240",
# "154241",
# "154244",
# "154246",
# "154247",
# "154250",
# "154254",
# "154273",
# "154277",
# "154282",
# "188274",
# ]
PAIR_IDS = []
CD_SCHEMA = {
"type": "object",
"additionalProperties": False,
"properties": {
"roles": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": False,
"properties": {
"name": {"type": ["string", "null"]},
"title": {"type": ["string", "null"]},
"birth_date": {"type": ["string", "null"]},
"city": {"type": ["string", "null"]},
"role": {"type": ["string", "null"]},
"start_date": {"type": ["string", "null"]},
"end_date": {"type": ["string", "null"]},
"status": {"type": ["string", "null"]},
"initial_marker": {"type": "boolean"},
},
"required": [
"name",
"title",
"birth_date",
"city",
"role",
"start_date",
"end_date",
"status",
"initial_marker",
],
},
},
},
"required": [
"roles",
],
}
def get_pair_ids():
if PAIR_IDS:
return PAIR_IDS
pair_ids = []
for item in ROOT_DIR.iterdir():
cd_input = item / "CD_relevant_tables.txt"
ad_result = item / "AD_llm_result_vllm.json"
if item.is_dir() and cd_input.exists() and ad_result.exists():
pair_ids.append(item.name)
return sorted(pair_ids)
def get_api_key():
api_key = os.getenv("LLM_API_KEY")
if api_key:
return api_key
return getpass.getpass("API key: ")
def load_json(path):
with path.open("r", encoding="utf-8") as file:
return json.load(file)
def save_json(path, data):
path.write_text(
json.dumps(data, ensure_ascii=False, indent=2),
encoding="utf-8",
)
def get_usage(data):
usage = data.get("usage", {})
prompt_tokens = usage.get("prompt_tokens", 0) or 0
completion_tokens = usage.get("completion_tokens", 0) or 0
total_tokens = usage.get("total_tokens", prompt_tokens + completion_tokens) or 0
return {
"prompt_tokens": prompt_tokens,
"completion_tokens": completion_tokens,
"total_tokens": total_tokens,
}
def call_api(system_prompt, cd_text, api_key):
response = requests.post(
API_URL,
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}",
},
json={
"model": MODEL,
"messages": [
{
"role": "system",
"content": system_prompt,
},
{
"role": "user",
"content": cd_text,
},
],
"temperature": 0,
"max_tokens": 8192,
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "cd_roles_result",
"strict": True,
"schema": CD_SCHEMA,
},
},
},
timeout=300,
)
return response.json()
def make_debug_data(
pair_id, cd_input_path, ad_result_path, output_path, system_prompt, cd_text, data
):
choice = {}
if "choices" in data and data["choices"]:
choice = data["choices"][0]
message = choice.get("message", {})
return {
"pair_id": pair_id,
"status": "error" if "error" in data else "ok",
"model": MODEL,
"api_url": API_URL,
"files": {
"cd_input": str(cd_input_path),
"ad_company_source": str(ad_result_path),
"system_prompt": SYSTEM_PROMPT_PATH,
"output_json": str(output_path),
},
"settings": {
"temperature": 0,
"max_tokens": 8192,
"response_format": "json_schema",
"schema_name": "cd_roles_result",
"strict_schema": True,
},
"input": {
"system_prompt": system_prompt,
"user_text": cd_text,
},
"usage": get_usage(data),
"response": {
"id": data.get("id"),
"created": data.get("created"),
"finish_reason": choice.get("finish_reason"),
"stop_reason": choice.get("stop_reason"),
"system_fingerprint": data.get("system_fingerprint"),
"content_preview": message.get("content", "")[:500],
},
"error": data.get("error"),
}
def process_pair(pair_id, system_prompt, api_key):
pair_dir = ROOT_DIR / pair_id
cd_input_path = pair_dir / CD_INPUT_FILE_NAME
ad_result_path = pair_dir / AD_RESULT_FILE_NAME
output_path = pair_dir / CD_OUTPUT_FILE_NAME
debug_path = pair_dir / DEBUG_FILE_NAME
if not ad_result_path.exists():
error_data = {
"pair_id": pair_id,
"status": "error",
"error": f"Missing file: {ad_result_path}",
}
save_json(debug_path, error_data)
return {
"pair_id": pair_id,
"status": "error",
"usage": {
"prompt_tokens": 0,
"completion_tokens": 0,
"total_tokens": 0,
},
"error": error_data["error"],
}
cd_text = cd_input_path.read_text(encoding="utf-8")
ad_result = load_json(ad_result_path)
data = call_api(system_prompt, cd_text, api_key)
debug_data = make_debug_data(
pair_id,
cd_input_path,
ad_result_path,
output_path,
system_prompt,
cd_text,
data,
)
if "error" in data:
save_json(debug_path, debug_data)
return {
"pair_id": pair_id,
"status": "error",
"usage": get_usage(data),
"error": data["error"],
}
answer = data["choices"][0]["message"]["content"].strip()
cd_roles_result = json.loads(answer)
final_result = {
"company": ad_result["company"],
"roles": cd_roles_result["roles"],
}
save_json(output_path, final_result)
debug_data["result_keys"] = list(final_result.keys())
debug_data["roles_count"] = len(final_result["roles"])
save_json(debug_path, debug_data)
return {
"pair_id": pair_id,
"status": "ok",
"usage": get_usage(data),
"output_path": str(output_path),
}
def main():
pair_ids = get_pair_ids()
api_key = get_api_key()
system_prompt = Path(SYSTEM_PROMPT_PATH).read_text(encoding="utf-8")
total_prompt_tokens = 0
total_completion_tokens = 0
results = []
for pair_id in pair_ids:
result = process_pair(pair_id, system_prompt, api_key)
usage = result["usage"]
total_prompt_tokens += usage["prompt_tokens"]
total_completion_tokens += usage["completion_tokens"]
results.append(result)
print("=" * 80)
print("TOTAL TOKEN USAGE")
print(f" prompt_tokens: {total_prompt_tokens}")
print(f" completion_tokens: {total_completion_tokens}")
print(f" total_tokens: {total_prompt_tokens + total_completion_tokens}")
print(f" processed_folders: {len(results)}")
print()
print("PROCESSED FOLDERS")
for index, result in enumerate(results, start=1):
usage = result["usage"]
print(
f" {index:02d}. {result['pair_id']} | {result['status']} | "
f"prompt: {usage['prompt_tokens']} | "
f"completion: {usage['completion_tokens']} | "
f"total: {usage['total_tokens']}"
)
errors = [result for result in results if result["status"] != "ok"]
if errors:
print()
print("ERRORS")
for result in errors:
print(f" {result['pair_id']}: {result['error']}")
if __name__ == "__main__":
main()