david167 commited on
Commit
8860e75
·
1 Parent(s): 1ba70a2

Fix JSON array generation - add explicit array requirements and improve JSON parsing

Browse files
Files changed (1) hide show
  1. gradio_app.py +25 -5
gradio_app.py CHANGED
@@ -152,9 +152,16 @@ def create_json_prompt(message, template_type):
152
 
153
  {template["instruction"]}
154
 
 
 
155
  {template["schema"]}
156
 
157
- Ensure the response is valid JSON that can be parsed. Do not include any text outside the JSON structure.
 
 
 
 
 
158
 
159
  <|eot_id|><|start_header_id|>assistant<|end_header_id|>
160
 
@@ -163,16 +170,29 @@ Ensure the response is valid JSON that can be parsed. Do not include any text ou
163
  def prettify_json_response(response_text):
164
  """Try to extract and prettify JSON from response"""
165
  try:
 
 
 
 
 
 
 
 
 
 
166
  # Try to find JSON in the response - look for both objects and arrays
 
167
  json_patterns = [
168
- r'\[.*\]', # Array pattern
169
- r'\{.*\}' # Object pattern
 
 
170
  ]
171
 
172
  for pattern in json_patterns:
173
- json_match = re.search(pattern, response_text, re.DOTALL)
174
  if json_match:
175
- json_str = json_match.group()
176
  try:
177
  parsed_json = json.loads(json_str)
178
  return json.dumps(parsed_json, indent=2, ensure_ascii=False)
 
152
 
153
  {template["instruction"]}
154
 
155
+ IMPORTANT: You must respond with EXACTLY this format:
156
+
157
  {template["schema"]}
158
 
159
+ Requirements:
160
+ - Start with [ and end with ]
161
+ - Include multiple items in the array
162
+ - Use valid JSON syntax
163
+ - Do not include any text before or after the JSON
164
+ - Complete the entire JSON structure
165
 
166
  <|eot_id|><|start_header_id|>assistant<|end_header_id|>
167
 
 
170
  def prettify_json_response(response_text):
171
  """Try to extract and prettify JSON from response"""
172
  try:
173
+ # Clean the response first
174
+ cleaned = response_text.strip()
175
+
176
+ # Try to parse the entire response as JSON first
177
+ try:
178
+ parsed_json = json.loads(cleaned)
179
+ return json.dumps(parsed_json, indent=2, ensure_ascii=False)
180
+ except json.JSONDecodeError:
181
+ pass
182
+
183
  # Try to find JSON in the response - look for both objects and arrays
184
+ # Use non-greedy matching and better patterns
185
  json_patterns = [
186
+ r'\[[\s\S]*?\](?=\s*$)', # Array pattern - non-greedy, end of string
187
+ r'\{[\s\S]*?\}(?=\s*$)', # Object pattern - non-greedy, end of string
188
+ r'\[[\s\S]*\]', # Array pattern - greedy fallback
189
+ r'\{[\s\S]*\}' # Object pattern - greedy fallback
190
  ]
191
 
192
  for pattern in json_patterns:
193
+ json_match = re.search(pattern, cleaned, re.MULTILINE)
194
  if json_match:
195
+ json_str = json_match.group().strip()
196
  try:
197
  parsed_json = json.loads(json_str)
198
  return json.dumps(parsed_json, indent=2, ensure_ascii=False)