| from fastapi import FastAPI |
| from pydantic import BaseModel |
| from fastapi.middleware.cors import CORSMiddleware |
| from langchain_community.chat_models import ChatOpenAI |
| from langchain.output_parsers import StructuredOutputParser, ResponseSchema |
| from langchain.prompts import ChatPromptTemplate |
| from dotenv import load_dotenv |
| import os |
|
|
| |
| load_dotenv() |
|
|
| |
| app = FastAPI() |
|
|
| |
| app.add_middleware( |
| CORSMiddleware, |
| allow_origins=["*"], |
| allow_credentials=True, |
| allow_methods=["*"], |
| allow_headers=["*"], |
| ) |
|
|
| |
| class FeedbackRequest(BaseModel): |
| exam_type: str |
| essay_text: str |
|
|
| |
| response_schemas = [ |
| ResponseSchema(name="logic", description="Feedback on logic and relevance"), |
| ResponseSchema(name="grammar", description="Feedback on grammar and writing style"), |
| ResponseSchema(name="score", description="Overall score out of 10"), |
| ResponseSchema(name="suggestions", description="Suggestions for improvement") |
| ] |
|
|
| parser = StructuredOutputParser.from_response_schemas(response_schemas) |
|
|
| |
| prompt = ChatPromptTemplate.from_messages([ |
| ("system", "You are an English examiner. Provide detailed structured feedback on the student's essay."), |
| ("user", "Essay Type: {exam_type}\nEssay: {essay_text}\n{format_instructions}") |
| ]) |
|
|
| |
| model = ChatOpenAI( |
| openai_api_key=os.getenv("OPENAI_API_KEY"), |
| model="gpt-4o-mini", |
| temperature=0.3 |
| ) |
|
|
| |
| @app.post("/feedback") |
| async def get_feedback(req: FeedbackRequest): |
| try: |
| formatted_prompt = prompt.format( |
| exam_type=req.exam_type, |
| essay_text=req.essay_text, |
| format_instructions=parser.get_format_instructions() |
| ) |
|
|
| |
| response = model.invoke(formatted_prompt) |
| output = parser.parse(response.content) |
| return output |
|
|
| except Exception as e: |
| return {"error": str(e)} |
|
|
|
|
|
|
| @app.get("/") |
| async def root(): |
| return {"message": "English Writting Analyst is running 🎯"} |
|
|
| if __name__ == "__main__": |
| uvicorn.run("main:app", host="0.0.0.0", port=7860, reload=True) |