DrishtiSharma commited on
Commit
d5d68fd
·
verified ·
1 Parent(s): e92ff41

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -45
app.py CHANGED
@@ -106,84 +106,73 @@ app = st.session_state["app"]
106
 
107
  # Function to invoke the agent and generate a response
108
  def enforce_word_limit(text, limit):
109
- """Enforces strict word limit by truncating extra words."""
110
  words = re.findall(r'\b\w+\b', text)
111
  return ' '.join(words[:limit]) if len(words) > limit else text
112
 
113
  def detect_unexpected_english(text, selected_language):
114
- """Detects unintended English words when another language is selected."""
115
  if selected_language != "English":
116
  english_words = re.findall(r'\b(?:is|the|and|or|in|on|at|to|with|for|of|by|it|that|this|was|he|she|they|we|you|I)\b', text)
117
- return len(english_words) > 5 # Allow a small tolerance
118
 
119
  def generate_response(topic, length, selected_language):
120
  if not app or not hasattr(app, "graph"):
121
- st.error("Agents are not initialized. Please check the system or restart the app.")
122
  return {"response": "Error: Agents not initialized."}
123
 
124
- # Dynamically adjust structure based on length
125
- if length <= 250:
126
- intro_limit, body_limit, conclusion_limit = length // 5, length // 2, length // 5
127
- num_sections = 2 # Shorter essays should have fewer sections
128
- elif length <= 350:
129
- intro_limit, body_limit, conclusion_limit = length // 6, length // 1.8, length // 6
130
- num_sections = 3
131
- else:
132
- intro_limit, body_limit, conclusion_limit = length // 7, length // 1.7, length // 7
133
- num_sections = 4
134
-
135
- # Optimized Structured Prompt
136
  refined_prompt = f"""
137
- Write a **well-structured, informative, and engaging** essay on "{topic}" **strictly in {selected_language}.**
138
 
139
- **Word Limit:** Exactly {length} words. **Do not exceed or fall short of this limit.**
140
- **Language Rules:** Use natural linguistic style from {selected_language}. **Do not use English** unless explicitly requested.
141
 
142
- **Essay Structure:**
143
- - **Title**: Max 10 words.
144
- - **Introduction ({intro_limit} words max)**:
145
- - Clearly define the topic and its significance.
146
- - Provide a strong thesis statement.
147
- - Preview the key points covered in the essay.
148
  - **Main Body ({body_limit} words max, {num_sections} sections)**:
149
- - Each section must have:
150
- - A **clear subheading**.
151
- - A concise topic sentence with supporting details.
152
- - Relevant **examples, statistics, or historical references**.
153
- - Maintain natural **flow** between sections.
154
  - **Conclusion ({conclusion_limit} words max)**:
155
- - Summarize key insights **without repetition**.
156
- - Reinforce the thesis **based on discussion**.
157
- - End with a strong **closing statement** (reflection or call to action).
158
-
159
- **Hard Rules:**
160
- - **Use only {selected_language}**. No English unless explicitly requested.
161
- - **Do not exceed {length} words.** Absolute limit.
162
- - **Write concisely and avoid fluff**. No redundancy.
163
- - **Merge similar ideas** to maintain smooth readability.
164
- - **Ensure strict adherence to section word limits**.
165
  """
166
 
167
- # Invoke AI model with enforced word limit
168
  response = app.graph.invoke(input={
169
  "topic": topic,
170
  "length": length,
171
  "prompt": refined_prompt,
172
  "language": selected_language,
173
- "max_tokens": length + 10 # Small buffer for better trimming
174
  })
175
 
176
- # Strict word limit enforcement
177
  essay_text = enforce_word_limit(response.get("essay", ""), length)
178
 
179
- # Detect unintended English words in non-English essays
180
  if detect_unexpected_english(essay_text, selected_language):
181
  return {"response": f"⚠️ Warning: Some English words were detected in the {selected_language} essay. Try regenerating."}
182
 
183
  return {"essay": essay_text}
184
 
185
 
186
-
187
  # Define Tabs
188
  tab1, tab2 = st.tabs(["📜 Essay Generation", "📊 Workflow Viz"])
189
 
 
106
 
107
  # Function to invoke the agent and generate a response
108
  def enforce_word_limit(text, limit):
109
+ """Strictly enforce the word limit by truncating extra words."""
110
  words = re.findall(r'\b\w+\b', text)
111
  return ' '.join(words[:limit]) if len(words) > limit else text
112
 
113
  def detect_unexpected_english(text, selected_language):
114
+ """Detect unintended English words when another language is selected."""
115
  if selected_language != "English":
116
  english_words = re.findall(r'\b(?:is|the|and|or|in|on|at|to|with|for|of|by|it|that|this|was|he|she|they|we|you|I)\b', text)
117
+ return len(english_words) > 5 # Allow minor tolerance
118
 
119
  def generate_response(topic, length, selected_language):
120
  if not app or not hasattr(app, "graph"):
121
+ st.error("⚠️ Agents are not initialized. Please check the system or restart the app.")
122
  return {"response": "Error: Agents not initialized."}
123
 
124
+ # **Dynamically Allocate Section Limits Based on Length**
125
+ intro_limit = max(40, length // 6)
126
+ body_limit = max(80, length - intro_limit - (length // 6))
127
+ conclusion_limit = length - (intro_limit + body_limit)
128
+ num_sections = min(4, max(2, length // 150)) # 2-4 sections based on length
129
+
130
+ # **Strict Prompt with Hard Stop**
 
 
 
 
 
131
  refined_prompt = f"""
132
+ Write a **structured, concise, and well-formed** essay on "{topic}" in {selected_language}.
133
 
134
+ **Word Limit:** EXACTLY {length} words. **DO NOT exceed or fall short.**
135
+ **Language:** Use only {selected_language}. **No English unless explicitly requested.**
136
 
137
+ **Essay Structure (STRICTLY FOLLOWED):**
138
+ - **Title:** Maximum 10 words.
139
+ - **Introduction ({intro_limit} words max)** – Define topic, give thesis, and preview key points.
 
 
 
140
  - **Main Body ({body_limit} words max, {num_sections} sections)**:
141
+ - Each section has **one key idea**.
142
+ - **DO NOT exceed section limits**.
143
+ - Use **simple, precise sentences**.
 
 
144
  - **Conclusion ({conclusion_limit} words max)**:
145
+ - Summarize key points **without repetition**.
146
+ - Reinforce thesis and end with a strong closing line.
147
+
148
+ **HARD RULES:**
149
+ - **STOP at exactly {length} words**. No extra words.
150
+ - **Do not exceed assigned section limits**.
151
+ - **Avoid redundancy and repetition**.
152
+ - **Keep sentences concise and natural**.
153
+
154
+ STOP WRITING IMMEDIATELY after {length} words.
155
  """
156
 
157
+ # **Invoke AI with a STRONG Limit on Tokens**
158
  response = app.graph.invoke(input={
159
  "topic": topic,
160
  "length": length,
161
  "prompt": refined_prompt,
162
  "language": selected_language,
163
+ "max_tokens": int(length * 0.75) # STRONG cap (75 tokens per 100 words)
164
  })
165
 
166
+ # **Final Hard Stop on Word Limit**
167
  essay_text = enforce_word_limit(response.get("essay", ""), length)
168
 
169
+ # **Check for Unwanted English Words**
170
  if detect_unexpected_english(essay_text, selected_language):
171
  return {"response": f"⚠️ Warning: Some English words were detected in the {selected_language} essay. Try regenerating."}
172
 
173
  return {"essay": essay_text}
174
 
175
 
 
176
  # Define Tabs
177
  tab1, tab2 = st.tabs(["📜 Essay Generation", "📊 Workflow Viz"])
178