pykara commited on
Commit
43c3b55
·
verified ·
1 Parent(s): 83edd7c

Update chat.py

Browse files
Files changed (1) hide show
  1. chat.py +63 -43
chat.py CHANGED
@@ -24,29 +24,49 @@ def home():
24
  return "Welcome to the Flask app! The server is running."
25
 
26
  # API configuration for AI-based question generation
27
- # COHERE_API_KEY = 'WjnDKknACe0zxHvczdo7q4vwF4WAXn2429hcPHIB'
28
  COHERE_API_KEY = os.getenv("COHERE_API_KEY", "")
29
- COHERE_API_URL = 'https://api.cohere.ai/v1/generate'
30
-
31
-
32
 
33
  # Dictionary to store user conversations
34
  user_sessions = {}
35
  # Endpoint to explain grammar topics
36
  movie_bp = Blueprint("movie", __name__)
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  def _cohere_generate(prompt: str, max_tokens: int = 1000, temperature: float = 0.7):
39
  api_key = current_app.config.get("COHERE_API_KEY") or COHERE_API_KEY
40
  if not api_key:
41
  return None, ("COHERE_API_KEY not set on the server", 500)
42
 
43
  headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
44
- payload = {"model": "command-r-08-2024", "prompt": prompt, "max_tokens": max_tokens, "temperature": temperature}
 
 
 
 
 
 
 
 
45
  try:
46
  r = requests.post(COHERE_API_URL, headers=headers, json=payload, timeout=30)
47
  if r.status_code != 200:
48
  return None, (f"Cohere API error: {r.text}", 502)
49
- text = r.json().get("generations", [{}])[0].get("text", "").strip()
 
50
  return text, None
51
  except Exception as e:
52
  current_app.logger.exception("Cohere request failed: %s", e)
@@ -95,16 +115,20 @@ def explain_grammar():
95
  'Content-Type': 'application/json'
96
  }
97
 
 
98
  payload = {
99
  'model': 'command-r-08-2024',
100
- 'prompt': prompt,
101
- 'max_tokens': 1000 # Increased to allow better explanations
 
 
102
  }
103
 
104
  response = requests.post(COHERE_API_URL, headers=headers, json=payload)
105
 
106
  if response.status_code == 200:
107
- ai_response = response.json().get('generations', [{}])[0].get('text', '').strip()
 
108
 
109
  # Store conversation history to maintain context
110
  conversation_history.append(f"User: {topic}\nAI: {ai_response}")
@@ -128,20 +152,18 @@ def suggest_grammar_questions():
128
  if not user_input:
129
  return jsonify({'error': 'Input is required'}), 400
130
 
131
-
132
-
133
  prompt = f"""
134
- You are a grammar expert. Given the user's input "{user_input}", generate **3 natural grammar-related questions** that people might ask.
135
 
136
- - The user's input is a **partial or full grammar-related query**.
137
- - AI must **infer the most likely grammar topic** based on the input.
138
- - AI must **ensure all suggestions are strictly related to English grammar**.
139
- - **If the input is incomplete, intelligently complete it** with the most likely grammar concept.
140
- - Ensure all **questions are fully formed and relevant**.
141
 
142
- **User input:** "{user_input}"
143
- Provide exactly 3 well-structured, grammar-related questions:
144
- """
145
 
146
  # Call Cohere API
147
  headers = {
@@ -149,20 +171,24 @@ def suggest_grammar_questions():
149
  'Content-Type': 'application/json'
150
  }
151
 
 
152
  payload = {
153
  'model': 'command-r-08-2024',
154
- 'prompt': prompt,
155
- 'max_tokens': 100, # Only short responses needed
156
- 'temperature': 0.9, # Some randomness for variety
157
- 'frequency_penalty': 0.8, # Reduce repeated words
158
- 'presence_penalty': 0.8 # Encourage diverse questions
159
  }
160
 
161
  response = requests.post(COHERE_API_URL, headers=headers, json=payload)
162
 
163
  if response.status_code == 200:
164
- suggestions = response.json().get('generations', [{}])[0].get('text', '').strip().split("\n")
165
- return jsonify({'suggestions': suggestions})
 
 
 
166
  else:
167
  return jsonify({'error': 'Failed to fetch suggestions', 'details': response.text}), 500
168
 
@@ -171,9 +197,6 @@ def suggest_grammar_questions():
171
 
172
 
173
  def validate_topic(topic):
174
-
175
-
176
-
177
  validation_prompt = f"""
178
  You are an AI grammar expert. Your task is to determine if a given topic is related to **English grammar** or not.
179
 
@@ -188,27 +211,27 @@ def validate_topic(topic):
188
  **Your response must be exactly either "Grammar", "Not Grammar", or "ask grammar topics". No extra text.**
189
  """
190
 
191
-
192
-
193
-
194
-
195
  headers = {
196
  'Authorization': f'Bearer {COHERE_API_KEY}',
197
  'Content-Type': 'application/json'
198
  }
199
 
 
200
  payload = {
201
  'model': 'command-r-08-2024',
202
- 'prompt': validation_prompt,
203
- 'max_tokens': 5 # Minimal token usage for classification
 
 
204
  }
205
 
206
  try:
207
  response = requests.post(COHERE_API_URL, json=payload, headers=headers)
208
- validation_result = response.json().get('generations', [{}])[0].get('text', '').strip()
209
-
210
- # Ensure the response is strictly "Grammar" or "Not Grammar"
211
- if validation_result not in ["Grammar", "Not Grammar"]:
 
212
  return "Not Grammar" # Fallback to avoid incorrect responses
213
 
214
  return validation_result
@@ -217,9 +240,6 @@ def validate_topic(topic):
217
  return f"Error: {str(e)}"
218
 
219
 
220
-
221
-
222
-
223
  if __name__ == '__main__':
224
  # app.run(debug=True)
225
  app.register_blueprint(movie_bp, url_prefix='') # expose /explain-grammar locally
 
24
  return "Welcome to the Flask app! The server is running."
25
 
26
  # API configuration for AI-based question generation
 
27
  COHERE_API_KEY = os.getenv("COHERE_API_KEY", "")
28
+ # (1) UPDATED URL: v2 endpoint on api.cohere.com
29
+ COHERE_API_URL = 'https://api.cohere.com/v2/chat'
 
30
 
31
  # Dictionary to store user conversations
32
  user_sessions = {}
33
  # Endpoint to explain grammar topics
34
  movie_bp = Blueprint("movie", __name__)
35
 
36
+ def _extract_text_v2(resp_json: dict) -> str:
37
+ """
38
+ v2 /chat returns:
39
+ { "message": { "content": [ { "type": "text", "text": "..." } ] } }
40
+ """
41
+ msg = resp_json.get("message", {})
42
+ content = msg.get("content", [])
43
+ if isinstance(content, list) and content:
44
+ block = content[0]
45
+ if isinstance(block, dict):
46
+ return (block.get("text") or "").strip()
47
+ return ""
48
+
49
  def _cohere_generate(prompt: str, max_tokens: int = 1000, temperature: float = 0.7):
50
  api_key = current_app.config.get("COHERE_API_KEY") or COHERE_API_KEY
51
  if not api_key:
52
  return None, ("COHERE_API_KEY not set on the server", 500)
53
 
54
  headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
55
+ # (2) UPDATED PAYLOAD: use messages instead of prompt
56
+ payload = {
57
+ "model": "command-r-08-2024",
58
+ "messages": [
59
+ {"role": "user", "content": prompt}
60
+ ],
61
+ "max_tokens": max_tokens,
62
+ "temperature": temperature
63
+ }
64
  try:
65
  r = requests.post(COHERE_API_URL, headers=headers, json=payload, timeout=30)
66
  if r.status_code != 200:
67
  return None, (f"Cohere API error: {r.text}", 502)
68
+ # (3) UPDATED PARSING: read message.content[0].text
69
+ text = _extract_text_v2(r.json())
70
  return text, None
71
  except Exception as e:
72
  current_app.logger.exception("Cohere request failed: %s", e)
 
115
  'Content-Type': 'application/json'
116
  }
117
 
118
+ # (2) UPDATED PAYLOAD: messages array
119
  payload = {
120
  'model': 'command-r-08-2024',
121
+ 'messages': [
122
+ {'role': 'user', 'content': prompt}
123
+ ],
124
+ 'max_tokens': 1000
125
  }
126
 
127
  response = requests.post(COHERE_API_URL, headers=headers, json=payload)
128
 
129
  if response.status_code == 200:
130
+ # (3) UPDATED PARSING
131
+ ai_response = _extract_text_v2(response.json())
132
 
133
  # Store conversation history to maintain context
134
  conversation_history.append(f"User: {topic}\nAI: {ai_response}")
 
152
  if not user_input:
153
  return jsonify({'error': 'Input is required'}), 400
154
 
 
 
155
  prompt = f"""
156
+ You are a grammar expert. Given the user's input "{user_input}", generate **3 natural grammar-related questions** that people might ask.
157
 
158
+ - The user's input is a **partial or full grammar-related query**.
159
+ - AI must **infer the most likely grammar topic** based on the input.
160
+ - AI must **ensure all suggestions are strictly related to English grammar**.
161
+ - **If the input is incomplete, intelligently complete it** with the most likely grammar concept.
162
+ - Ensure all **questions are fully formed and relevant**.
163
 
164
+ **User input:** "{user_input}"
165
+ Provide exactly 3 well-structured, grammar-related questions:
166
+ """
167
 
168
  # Call Cohere API
169
  headers = {
 
171
  'Content-Type': 'application/json'
172
  }
173
 
174
+ # (2) UPDATED PAYLOAD: messages array
175
  payload = {
176
  'model': 'command-r-08-2024',
177
+ 'messages': [
178
+ {'role': 'user', 'content': prompt}
179
+ ],
180
+ 'max_tokens': 100,
181
+ 'temperature': 0.9
182
  }
183
 
184
  response = requests.post(COHERE_API_URL, headers=headers, json=payload)
185
 
186
  if response.status_code == 200:
187
+ # (3) UPDATED PARSING
188
+ text = _extract_text_v2(response.json())
189
+ suggestions = [s for s in (text or "").split("\n") if s.strip()]
190
+ return jsonify({'suggestions': suggestions[:3]})
191
+ # keep exactly 3 if more lines present
192
  else:
193
  return jsonify({'error': 'Failed to fetch suggestions', 'details': response.text}), 500
194
 
 
197
 
198
 
199
  def validate_topic(topic):
 
 
 
200
  validation_prompt = f"""
201
  You are an AI grammar expert. Your task is to determine if a given topic is related to **English grammar** or not.
202
 
 
211
  **Your response must be exactly either "Grammar", "Not Grammar", or "ask grammar topics". No extra text.**
212
  """
213
 
 
 
 
 
214
  headers = {
215
  'Authorization': f'Bearer {COHERE_API_KEY}',
216
  'Content-Type': 'application/json'
217
  }
218
 
219
+ # (2) UPDATED PAYLOAD: messages array
220
  payload = {
221
  'model': 'command-r-08-2024',
222
+ 'messages': [
223
+ {'role': 'user', 'content': validation_prompt}
224
+ ],
225
+ 'max_tokens': 5
226
  }
227
 
228
  try:
229
  response = requests.post(COHERE_API_URL, json=payload, headers=headers)
230
+ # (3) UPDATED PARSING
231
+ validation_result = _extract_text_v2(response.json())
232
+
233
+ # Ensure the response is strictly "Grammar" or "Not Grammar" or "ask grammar topics"
234
+ if validation_result not in ["Grammar", "Not Grammar", "ask grammar topics"]:
235
  return "Not Grammar" # Fallback to avoid incorrect responses
236
 
237
  return validation_result
 
240
  return f"Error: {str(e)}"
241
 
242
 
 
 
 
243
  if __name__ == '__main__':
244
  # app.run(debug=True)
245
  app.register_blueprint(movie_bp, url_prefix='') # expose /explain-grammar locally