Rathapoom commited on
Commit
a6c2e61
·
verified ·
1 Parent(s): 2cbd7c8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -31
app.py CHANGED
@@ -100,51 +100,70 @@ if 'vocabulary_used' not in st.session_state:
100
 
101
  def get_ai_story_continuation(story_context, level):
102
  """Get story continuation from OpenAI API"""
103
- # Define level-specific parameters
104
- level_params = {
105
- 'beginner': {
106
- 'complexity': "Use simple present tense and basic vocabulary. Keep sentences short (8-12 words).",
107
- 'examples': "Example: 'The dog runs to the park.' or 'She likes to read books.'"
108
- },
109
- 'intermediate': {
110
- 'complexity': "Use present and past tense, compound sentences, and intermediate vocabulary.",
111
- 'examples': "Example: 'The excited dog rushed to the park, where his friends were waiting.'"
112
- },
113
- 'advanced': {
114
- 'complexity': "Use varied tenses, complex sentences, and advanced vocabulary appropriately.",
115
- 'examples': "Example: 'Having spotted his friends at the park, the enthusiastic dog bounded over with unbridled joy.'"
116
- }
117
- }
118
-
119
  try:
120
  response = openai.ChatCompletion.create(
121
- model="gpt-4o-mini", # หรือ model ที่ถูกต้องตามที่คุณใช้
122
  messages=[
123
  {"role": "system", "content": f"""You are helping a {level} level English student write a story.
124
- {level_params[level]['complexity']}
125
- {level_params[level]['examples']}
 
 
 
 
126
 
127
  Provide a JSON response with:
128
- 1. continuation: A single sentence continuing the story (matching the specified level)
129
- 2. creative_prompt: A short question (3-8 words) to guide the student's next sentence
130
- 3. vocabulary_suggestions: 3 relevant words they might use next (appropriate for {level} level)
131
- 4. translation: Thai translation of the continuation sentence
132
-
133
- Ensure the story stays coherent with the context."""},
134
- {"role": "user", "content": f"Story context: {story_context}\n\nProvide the next part of the story and a guiding question."}
135
  ],
136
  temperature=0.7
137
  )
138
- return json.loads(response.choices[0].message.content)
 
 
 
 
 
 
 
 
 
 
139
  except Exception as e:
140
  st.error(f"Error with AI response: {e}")
141
  return {
142
- "continuation": "The story continues...",
143
- "creative_prompt": "What happens next?",
144
- "vocabulary_suggestions": ["word1", "word2", "word3"],
145
- "translation": "เรื่องราวดำเนินต่อไป..."
146
  }
147
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  def start_story(level):
149
  """Get the first sentence from AI"""
150
  # Define level-specific starting prompts
@@ -318,6 +337,13 @@ def process_player_input(user_input):
318
  story_context + "\n" + user_input,
319
  st.session_state.current_level
320
  )
 
 
 
 
 
 
 
321
 
322
  # Add AI's response to story
323
  st.session_state.story.append({
 
100
 
101
  def get_ai_story_continuation(story_context, level):
102
  """Get story continuation from OpenAI API"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  try:
104
  response = openai.ChatCompletion.create(
105
+ model="gpt-4o-mini",
106
  messages=[
107
  {"role": "system", "content": f"""You are helping a {level} level English student write a story.
108
+ Follow these rules strictly:
109
+ 1. Read the story context carefully
110
+ 2. Continue the story logically from the last sentence
111
+ 3. Never repeat the exact same sentence
112
+ 4. Make sure each continuation adds new information
113
+ 5. Suggest vocabulary that fits the current story context
114
 
115
  Provide a JSON response with:
116
+ 1. continuation: A new sentence that continues the story logically
117
+ 2. creative_prompt: A specific question about possible next events
118
+ 3. vocabulary_suggestions: 3 relevant words that could be used next
119
+ 4. translation: Thai translation of your continuation sentence"""},
120
+ {"role": "user", "content": f"""Current story context: {story_context}
121
+ Continue the story and ensure it connects with what happened before."""}
 
122
  ],
123
  temperature=0.7
124
  )
125
+
126
+ # Validate the response
127
+ result = json.loads(response.choices[0].message.content)
128
+
129
+ # Check if continuation is not too similar to previous content
130
+ if story_context and result['continuation'].lower() in story_context.lower():
131
+ # Try to get a new response
132
+ return get_ai_story_continuation(story_context, level)
133
+
134
+ return result
135
+
136
  except Exception as e:
137
  st.error(f"Error with AI response: {e}")
138
  return {
139
+ "continuation": "Suddenly, something unexpected happened...",
140
+ "creative_prompt": "What did our character discover?",
141
+ "vocabulary_suggestions": ["discover", "surprise", "mystery"],
142
+ "translation": "ทันใดนั้น บางสิ่งที่ไม่คาดคิดก็เกิดขึ้น..."
143
  }
144
 
145
+ def validate_story_quality(story_context, new_continuation):
146
+ """Validate that the story maintains quality and coherence"""
147
+ try:
148
+ validation = openai.ChatCompletion.create(
149
+ model="gpt-4o-mini",
150
+ messages=[
151
+ {"role": "system", "content": """Validate story coherence and quality.
152
+ Return JSON with:
153
+ 1. is_coherent: boolean
154
+ 2. reason: string explanation if not coherent"""},
155
+ {"role": "user", "content": f"""Previous: {story_context}
156
+ New continuation: {new_continuation}
157
+ Is this a logical and non-repetitive continuation?"""}
158
+ ]
159
+ )
160
+
161
+ result = json.loads(validation.choices[0].message.content)
162
+ return result['is_coherent'], result.get('reason', '')
163
+
164
+ except Exception:
165
+ return True, "" # Default to accepting if validation fails
166
+
167
  def start_story(level):
168
  """Get the first sentence from AI"""
169
  # Define level-specific starting prompts
 
337
  story_context + "\n" + user_input,
338
  st.session_state.current_level
339
  )
340
+
341
+ # Validate the continuation
342
+ is_coherent, reason = validate_story_quality(story_context, ai_response['continuation'])
343
+
344
+ if not is_coherent:
345
+ # Try getting a new response
346
+ ai_response = get_ai_story_continuation(story_context + "\n" + user_input, st.session_state.current_level)
347
 
348
  # Add AI's response to story
349
  st.session_state.story.append({