import json from typing import Any from openai import OpenAI from src import settings def init_client() -> OpenAI: """Initialize the OpenAI client with the API key and model from settings.""" global client, model, api_key if not settings.openAI.api_key: raise ValueError("OpenAI API key is not set in the configuration.") if not settings.openAI.model: raise ValueError("OpenAI model is not set in the configuration.") model = settings.openAI.model api_key = settings.openAI.api_key client = OpenAI(api_key=api_key) return client def run_shortener(title: str, length: int) -> list[dict[str, Any]]: client = init_client() response = client.responses.create( # type: ignore 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}}}', ) answers = response.output_text 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) -> dict: client = init_client() response = client.responses.create( # type: ignore 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) -> str: client = init_client() response = client.responses.create( # type: ignore 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