key_word_Fast_API / services /grammar_analyzer.py
ihtesham0345's picture
fix: Improve prompts to return JSON object, add error for list response
5b10e71
Raw
History Blame Contribute Delete
1.89 kB
from services.utils import run_analysis
SYSTEM_PROMPT = """You are a professional grammar editor like Grammarly. Return ONLY a valid JSON object (not an array). Analyze every sentence for spelling, grammar, punctuation, tense, subject-verb agreement, articles, prepositions, word order, and style."""
DEFAULTS = {
"original_text": "",
"corrected_text": "",
"corrections": [{"original": "their", "corrected": "there", "error_type": "spelling", "explanation": "Homophone confusion: 'their' indicates possession, 'there' indicates a place."}],
"issues": [{"issue_type": "passive voice", "location": "sentence 1", "suggestion": "Consider using active voice for stronger impact."}],
"grammar_score": 85,
"readability_score": "Standard",
"word_count": 0,
"sentence_count": 0,
"tone": "Neutral",
"style_suggestions": ["Consider breaking long sentences for readability."]
}
def analyze_grammar(text: str) -> dict:
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": f'Text: "{text[:2000]}"\nReturn a JSON object (not an array) with these keys:\n- original_text (string, the input text verbatim)\n- corrected_text (string, the fully corrected version)\n- corrections (list of objects, each with "original", "corrected", "error_type" ["spelling"|"grammar"|"punctuation"|"tense"|"preposition"|"article"|"word_order"|"style"], "explanation")\n- issues (list of objects, each with "issue_type", "location", "suggestion")\n- grammar_score (integer 0-100)\n- readability_score (string: "Easy"|"Fairly Easy"|"Standard"|"Fairly Difficult"|"Difficult")\n- word_count (integer)\n- sentence_count (integer)\n- tone (string: "Formal"|"Neutral"|"Informal"|"Professional")\n- style_suggestions (list of strings)'}
]
return run_analysis(messages, defaults=DEFAULTS, temperature=0.2, max_new_tokens=1200)