Spaces:
Sleeping
Sleeping
File size: 2,692 Bytes
d55dd4d ed66e0a d55dd4d 30856c8 d55dd4d 30856c8 d55dd4d ed66e0a 30856c8 ed66e0a 30856c8 ed66e0a d55dd4d ea4c488 30856c8 46b9a9b 31c41b5 ed66e0a d55dd4d ed66e0a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | 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()
|