import os import gradio as gr # Try the new SDK first, fall back to legacy if unavailable NEW_SDK = False try: from openai import OpenAI # v1+ client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) NEW_SDK = True except Exception: import openai # legacy (< v1) openai.api_key = os.getenv("OPENAI_API_KEY") # Optional LangChain prompt (falls back to plain string if LC not installed) try: from langchain.prompts import PromptTemplate prompt = PromptTemplate( input_variables=["student_input"], template=( "You are a helpful writing coach. " "Give supportive, specific, and actionable feedback on the following student writing:\n\n{student_input}" ), ) def build_prompt(text: str) -> str: return prompt.format(student_input=text) except Exception: def build_prompt(text: str) -> str: return ( "You are a helpful writing coach. " "Give supportive, specific, and actionable feedback on the following student writing:\n\n" + text ) def generate_feedback(student_input: str) -> str: text = (student_input or "").strip() if not text: return "Please paste some writing first 🙂" full_prompt = build_prompt(text) try: if NEW_SDK: resp = client.chat.completions.create( model=os.getenv("OPENAI_MODEL_NEW", "gpt-4o-mini"), temperature=0.4, messages=[ {"role": "system", "content": "You are a helpful writing coach."}, {"role": "user", "content": full_prompt}, ], ) return resp.choices[0].message.content.strip() else: resp = openai.ChatCompletion.create( model=os.getenv("OPENAI_MODEL_OLD", "gpt-3.5-turbo"), temperature=0.4, messages=[ {"role": "system", "content": "You are a helpful writing coach."}, {"role": "user", "content": full_prompt}, ], ) return resp["choices"][0]["message"]["content"].strip() except Exception as e: return f"Oops—couldn't generate feedback: {e}" with gr.Blocks() as demo: gr.Markdown("## ✍️ AI Feedback System\nEnter your writing to receive helpful feedback.") input_text = gr.Textbox(lines=12, label="Your Writing", placeholder="Paste your text here…") output_text = gr.Textbox(lines=4, label="AI Feedback") submit_btn = gr.Button("Get Feedback", variant="primary") submit_btn.click(fn=generate_feedback, inputs=input_text, outputs=output_text) demo.queue().launch()