import streamlit as st import requests import os from dotenv import load_dotenv from gptcache import cache from gptcache.adapter import openai model = "gpt-4" constraints_filename = "constraints.md" template_filename = "template.md" load_dotenv() stored_api_key = os.getenv("OPENAI_API_KEY") stored_password = os.getenv("PASSWORD") openai_api_key = None # GPT Cache cache.init() cache.set_openai_key() def get_filetext(filename, filecache={}): if filename not in filecache: if not os.path.exists(filename): raise ValueError(f"ファイル '{filename}' が見つかりませんでした") with open(filename, "r") as f: filecache[filename] = f.read() return filecache[filename] def validate_api_key(api_key): try: response = requests.get( "https://api.openai.com/v1/models", headers={"Authorization": f"Bearer {api_key}"} ) response.raise_for_status() return True except requests.exceptions.HTTPError: return False def generate_question(): constraints = get_filetext(filename=constraints_filename) data = { "model": model, "messages": [ {"role": "system", "content": constraints}, {"role": "user", "content": "出題してください。"}, ], "max_tokens": 1024, "n": 1, "stop": None, "temperature": 0.7, } response = requests.post( "https://api.openai.com/v1/chat/completions", headers={ "Content-Type": "application/json", "Authorization": f"Bearer {openai_api_key}" }, json=data ) response.raise_for_status() choice = response.json()['choices'][0] question = choice['message']['content'].strip() return question def check_answer(question, answer): template = get_filetext(filename=template_filename) data = { "model": model, "messages": [ {"role": "system", "content": template}, {"role": "user", "content": f"問題: {question}\n回答: {answer}"}, ], "max_tokens": 1024, "n": 1, "stop": None, "temperature": 0.7, } response = requests.post( "https://api.openai.com/v1/chat/completions", headers={ "Content-Type": "application/json", "Authorization": f"Bearer {openai_api_key}" }, json=data ) response.raise_for_status() choice = response.json()['choices'][0] evaluation = choice['message']['content'].strip() return evaluation st.title("受験勉強支援AI") # パスワード認証、もしくは、ユーザーのAPIキーの入力でシステム利用を解放する if stored_api_key: password_or_api_key = st.text_input("パスワードまたはOpenAIのAPIキーを入力してください:") if password_or_api_key: if password_or_api_key == stored_password: openai_api_key = stored_api_key elif validate_api_key(password_or_api_key): openai_api_key = password_or_api_key else: st.write("無効なパスワードまたはAPIキーです。再度お試しください。") else: st.write("APIキーが設定されていません。設定を確認してください。") # 以下、主処理 if openai_api_key: question = st.session_state.get("question", None) if st.button("出題"): question = generate_question() st.session_state.question = question st.session_state.answer = "" st.experimental_rerun() if question: st.write("問題:") st.write(question) if "answer" not in st.session_state: st.session_state.answer = "" answer = st.text_area("回答を入力してください:", value=st.session_state.answer, key="answer_field") if st.button("添削"): evaluation = check_answer(question, answer) st.write("添削結果:") st.write(evaluation) st.session_state.answer = answer st.markdown( """