add openai implementation to take over some parsing functionality

This commit is contained in:
2025-06-03 13:17:36 +02:00
parent b874656eba
commit 771062ab7f

42
src/logic/openai.py Normal file
View File

@@ -0,0 +1,42 @@
from openai import OpenAI
from src import settings
import json
model = "gpt-4o"
api_key = settings.openAI.api_key
client = OpenAI(api_key = api_key)
def run_shortener(title:str, length:int):
response = client.responses.create(
model = model,
instructions = """you are a sentence shortener. The next message will contain the string to shorten and the length limit.
You need to shorten the string to be under the length limit, while keeping as much detail as possible. The result may NOT be longer than the length limit.
based on that, please reply only the shortened string. Give me 5 choices. if the length is too long, discard the string and try another one.Return the data as a python list containing the result as {"shortened_string": shortened_string, "length": lengthasInt}. Do not return the answer in a codeblock, use a pure string. Before answering, check the results and if ANY is longer than the needed_length, discard all and try again""",
input = f'{{"string":"{title}", "needed_length":{length}}}'
)
print(length)
answers = response.output_text
print(answers)
return eval(answers) # type: ignore
#answers are strings in json format, so we need to convert them to a list of dicts
def name_tester(name: str):
response = client.responses.create(
model = model,
instructions="""you are a name tester, You are given a name and will have to split the name into first name, last name, and if present the title. Return the name in a json format with the keys "title", "first_name", "last_name". If no title is present, set title to none. Do NOt return the answer in a codeblock, use a pure json string. Assume the names are in the usual german naming scheme""",
input = f'{{"name":"{name}"}}'
)
answers = response.output_text
return json.loads(answers)
def semester_converter(semester:str):
response = client.responses.create(
model = model,
instructions="""you are a semester converter. You will be given a string. Convert this into a string like this: SoSe YY or WiSe YY/YY+1. Do not return the answer in a codeblock, use a pure string.""",
input = semester
)
answers = response.output_text
return answers