Exam Question Answerer

import os
import re
import asyncio
import aiohttp
from tkinter import Tk, filedialog

For GUI dialogs in a script that runs from the command line

import tkinter as tk
root = tk.Tk()
root.withdraw()

async def processquestionwithchatapi(session, apikey, question, model="gpt-4-turbo-preview"):
question
number, questiontext = question
messages = [
{"role": "system", "content": "You are a helpful psychiatry multiple-choice exam tutor. Clean up and correct sample questions in markdown format. Use bulletted lists for answer options. After each question, teach me the knowledge necessary to correctly answer the question."},
{"role": "user", "content": f"{question
text}"}
]
response = await session.post(
"https://api.openai.com/v1/chat/completions",
headers={"Authorization": f"Bearer {apikey}"},
json={"model": model, "messages": messages},
)
response
data = await response.json()
answertext = responsedata['choices'][0]['message']['content'] if responsedata['choices'] else "No response received."
return question
number, questiontext, answertext

def splittextinto_questions(text):
questions = re.findall(r'(\d+.)\s(.*?)\n(?=\d+.|\Z)', text, re.DOTALL)
return questions

def writeresponsestofile(responses, outputfilename):
with open(outputfilename, "w", encoding="utf-8") as f:
for question
number, questiontext, response in responses:
f.write(f"{question
number} {questiontext}\n\nResponse: {response}\n\n")
print(f"Output written to {output
filename}")

async def main():
apikey = os.getenv("OPENAIAPIKEY")
if not api
key:
apikey = input("Enter your OpenAI API key: ")
if not api
key:
print("No API key provided. Exiting.")
return

filename = filedialog.askopenfilename(title='Select a file', filetypes=(('Text files', '.txt'), ('Markdown files', '.md'),))
if not filename:
print("No file selected.")
return

with open(filename, "r", encoding="utf-8") as f:
text = f.read()

questions = splittextinto_questions(text)

base, ext = os.path.splitext(filename)
outputfilename = f"{base}gpt_answers{ext}"

async with aiohttp.ClientSession() as session:
tasks = [processquestionwithchatapi(session, api_key, question) for question in questions]
responses = await asyncio.gather(*tasks)

writeresponsestofile(responses, outputfilename)

if name == "main":
asyncio.run(main())