134 lines
4.8 KiB
Python
134 lines
4.8 KiB
Python
import os
|
||
import json
|
||
from concurrent.futures import ThreadPoolExecutor
|
||
from time import time
|
||
|
||
from openai import OpenAI, APIConnectionError
|
||
|
||
DATA_FOLDER = "data2"
|
||
BATCH_SIZE = 6
|
||
|
||
""" PARAMETER_COMBINATIONS = [
|
||
# current
|
||
{"temperature": 1, "top_p": 0.95},
|
||
# experiments
|
||
{"temperature": 1, "top_p": 1},
|
||
{"temperature": 1, "top_p": 0.975},
|
||
{"temperature": 1, "top_p": 0.95},
|
||
{"temperature": 1, "top_p": 0.925},
|
||
{"temperature": 1, "top_p": 0.9},
|
||
{"temperature": 1.3, "top_p": 0.95},
|
||
{"temperature": 1.2, "top_p": 0.95},
|
||
{"temperature": 1.1, "top_p": 0.95},
|
||
{"temperature": 1, "top_p": 0.95},
|
||
{"temperature": 0.9, "top_p": 0.95},
|
||
{"temperature": 0.8, "top_p": 0.95},
|
||
{"temperature": 0.7, "top_p": 0.95},
|
||
{"temperature": 0.6, "top_p": 0.95},
|
||
{"temperature": 0.5, "top_p": 0.95},
|
||
{"temperature": 0.4, "top_p": 0.95},
|
||
{"temperature": 0.3, "top_p": 0.95},
|
||
{"temperature": 0.2, "top_p": 0.95},
|
||
{"temperature": 0.1, "top_p": 0.95},
|
||
{"temperature": 0.0, "top_p": 0.95}
|
||
] """
|
||
|
||
PARAMETER_COMBINATIONS = [
|
||
{"temperature": 0.3, "top_p": 0.95},
|
||
{"temperature": 0.7, "top_p": 0.95},
|
||
{"temperature": 1.0, "top_p": 0.95},
|
||
]
|
||
RUNS_PER_PARAMETER_COMBINATION = 5
|
||
|
||
|
||
def call( system_prompt: str, user_prompt: str, model: str = "gemma4-e4b", timeout: int = 30, temperature: float = 1.0, top_p: float = 0.95) -> str | None:
|
||
|
||
client = OpenAI(
|
||
base_url="https://project.nes.uni-due.de/llm2/v1/",
|
||
api_key="c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212",
|
||
timeout=timeout,
|
||
)
|
||
|
||
try:
|
||
response = client.chat.completions.create(
|
||
model=model,
|
||
messages=[
|
||
{"role": "system", "content": system_prompt},
|
||
{"role": "user", "content": user_prompt},
|
||
],
|
||
|
||
temperature=temperature,
|
||
top_p=top_p,
|
||
extra_body={"top_k": 64},
|
||
)
|
||
except APIConnectionError:
|
||
return None
|
||
|
||
return response.choices[0].message.content or None
|
||
|
||
|
||
def generate_bio_with_retries(user_prompt: str, parameter: dict, max_attempts: int = 3):
|
||
|
||
for attempt in range(1, max_attempts + 1):
|
||
bio = call(
|
||
system_prompt,
|
||
user_prompt,
|
||
temperature=parameter["temperature"],
|
||
top_p=parameter["top_p"],
|
||
)
|
||
if bio is not None:
|
||
return bio
|
||
print(f"Versuch {attempt}/{max_attempts} fehlgeschlagen")
|
||
return None
|
||
|
||
|
||
system_prompt = """\
|
||
Beschreibe in zwei Sätzen das Hauptforschungsfeld des Autors. Formuliere dabei allgemeinverständlich, sodass auch Personen ohne Fachwissen einen Einblick in die Forschung gewinnen. Nenne keine konkreten Publikationen oder Einzelwerke, sondern konzentriere dich auf die übergeordneten Forschungsinteressen und Themen. Verzichte auf bloße Aufzählungen und verbinde die Informationen zu einem flüssigen Text.
|
||
Beschreibe anschließend in ein bis zwei Sätzen die wirtschaftliche Relevanz der Forschung anhand von Anwendungen, Technologien oder Branchen, die davon profitieren könnten.
|
||
Verwende insgesamt maximal 100 bis 120 Wörter. Formuliere die Antwort so, dass sie ohne weitere Anpassungen direkt als Kurzbiografie verwendet werden kann. Verwende keine Superlative oder übertriebene Formulierungen, sondern bleibe sachlich und informativ. Gebe den Text als One-Liner zurück, ohne Zeilenumbrüche oder Aufzählungen. Verwende keine Gedankenstriche (– oder —) zur Gliederung von Sätzen. Formuliere stattdessen mit Kommas, Klammern oder zwei getrennten Sätzen.
|
||
"""
|
||
|
||
|
||
def generate_result_for_task(task: tuple[str, dict, int]) -> dict:
|
||
file_name, parameter, run = task
|
||
|
||
with open(os.path.join(DATA_FOLDER, file_name), "r") as f:
|
||
file_content = f.read()
|
||
|
||
author_id = file_name.removesuffix(".json")
|
||
author_name = json.loads(file_content).get("display_name", "")
|
||
bio = generate_bio_with_retries(file_content, parameter)
|
||
|
||
return {
|
||
"author": author_id,
|
||
"author_name": author_name,
|
||
"parameter": parameter,
|
||
"run": run,
|
||
"output": bio,
|
||
}
|
||
|
||
|
||
start_time = time()
|
||
|
||
tasks = []
|
||
for file_name in sorted(os.listdir(DATA_FOLDER)):
|
||
if file_name.endswith(".json"):
|
||
for parameter in PARAMETER_COMBINATIONS:
|
||
for run in range(RUNS_PER_PARAMETER_COMBINATION):
|
||
tasks.append((file_name, parameter, run))
|
||
|
||
with ThreadPoolExecutor(max_workers=BATCH_SIZE) as executor:
|
||
results = list(executor.map(generate_result_for_task, tasks))
|
||
|
||
for result in results:
|
||
if result["output"] is None:
|
||
print(f"{result['author']} {result['parameter']}: Leere Antwort erhalten.")
|
||
|
||
with open("output.json", "w", encoding="utf-8") as f:
|
||
json.dump(results, f, ensure_ascii=False, indent=2)
|
||
|
||
end_time = time()
|
||
|
||
print(f"{len(results)} Ergebnisse in output.json geschrieben.")
|
||
print(f"Benötigte Zeit: {end_time - start_time:.2f} Sekunden")
|