wchen22 commited on
Commit
ee92f49
·
verified ·
1 Parent(s): cb62fad

feat: preserve managed compression tool schemas

Browse files
Files changed (1) hide show
  1. app.py +86 -3
app.py CHANGED
@@ -309,9 +309,55 @@ def _receipt_id(payload: dict[str, Any]) -> str:
309
  return "tdcr_" + hashlib.sha256(encoded.encode("utf-8")).hexdigest()[:24]
310
 
311
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
312
  def _protected_spans(
313
  text: str,
314
  protected_values: list[str],
 
315
  *,
316
  preserve_code: bool,
317
  preserve_json: bool,
@@ -320,10 +366,16 @@ def _protected_spans(
320
  list[tuple[int, int]],
321
  list[tuple[int, int]],
322
  list[tuple[int, int]],
 
323
  ]:
324
  spans = []
325
  for value in protected_values:
326
  spans.extend(_find_spans(text, value))
 
 
 
 
 
327
  code_spans = (
328
  _regex_spans(text, r"```.*?```", re.MULTILINE | re.DOTALL)
329
  if preserve_code
@@ -342,7 +394,7 @@ def _protected_spans(
342
  spans.extend(code_spans)
343
  spans.extend(json_spans)
344
  spans.extend(system_spans)
345
- return _merge(spans), code_spans, json_spans, system_spans
346
 
347
 
348
  def _compress_text(payload: dict[str, Any]) -> dict[str, Any]:
@@ -357,6 +409,9 @@ def _compress_text(payload: dict[str, Any]) -> dict[str, Any]:
357
  isinstance(value, str) for value in protected_values
358
  ):
359
  raise HTTPException(status_code=400, detail="protected_spans must be strings")
 
 
 
360
  try:
361
  aggressiveness = float(settings.get("aggressiveness", 0.35))
362
  except Exception as exc:
@@ -367,9 +422,10 @@ def _compress_text(payload: dict[str, Any]) -> dict[str, Any]:
367
  started = time.perf_counter()
368
  preserve_code = bool(settings.get("preserve_code", True))
369
  preserve_json = bool(settings.get("preserve_json", True))
370
- protected, code_spans, json_spans, system_spans = _protected_spans(
371
  text,
372
  protected_values,
 
373
  preserve_code=preserve_code,
374
  preserve_json=preserve_json,
375
  )
@@ -428,8 +484,18 @@ def _compress_text(payload: dict[str, Any]) -> dict[str, Any]:
428
  code_preserved = all(text[start:end] in output for start, end in code_spans)
429
  json_preserved = all(text[start:end] in output for start, end in json_spans)
430
  system_preserved = all(text[start:end] in output for start, end in system_spans)
 
 
 
 
 
 
431
  decision = "reject" if (
432
- missing or not code_preserved or not json_preserved or not system_preserved
 
 
 
 
433
  ) else (
434
  "high_confidence" if saved > 0 and aggressiveness <= 0.65 else "no_op"
435
  )
@@ -447,6 +513,18 @@ def _compress_text(payload: dict[str, Any]) -> dict[str, Any]:
447
  "json_blocks_preserved": json_preserved,
448
  "system_prompt_spans_detected": len(system_spans),
449
  "system_prompts_preserved": system_preserved,
 
 
 
 
 
 
 
 
 
 
 
 
450
  "decision": decision,
451
  "compressor_latency_ms": round((time.perf_counter() - started) * 1000.0, 3),
452
  "deletion_only": _is_subsequence(output, text),
@@ -513,6 +591,7 @@ def _merge_batch_item_payload(
513
  "input": item,
514
  "compression_settings": payload.get("compression_settings"),
515
  "protected_spans": payload.get("protected_spans"),
 
516
  }
517
  if not isinstance(item, dict):
518
  raise ValueError(f"inputs[{index}] must be a string or an object")
@@ -538,6 +617,10 @@ def _merge_batch_item_payload(
538
  "input": item.get("input"),
539
  "compression_settings": settings,
540
  "protected_spans": item.get("protected_spans", payload.get("protected_spans")),
 
 
 
 
541
  }
542
 
543
 
 
309
  return "tdcr_" + hashlib.sha256(encoded.encode("utf-8")).hexdigest()[:24]
310
 
311
 
312
+ def _tool_schema_variants(schema: Any) -> list[str]:
313
+ if isinstance(schema, str):
314
+ return [schema] if schema else []
315
+ if not isinstance(schema, (dict, list)):
316
+ raise HTTPException(
317
+ status_code=400,
318
+ detail="tool_schemas entries must be strings, objects, or arrays",
319
+ )
320
+ variants: list[str] = []
321
+ for kwargs in (
322
+ {"ensure_ascii": False, "sort_keys": False, "separators": (",", ":")},
323
+ {"ensure_ascii": False, "sort_keys": True, "separators": (",", ":")},
324
+ {"ensure_ascii": False, "sort_keys": False, "indent": 2},
325
+ {"ensure_ascii": False, "sort_keys": True, "indent": 2},
326
+ ):
327
+ encoded = json.dumps(schema, **kwargs)
328
+ if encoded not in variants:
329
+ variants.append(encoded)
330
+ return variants
331
+
332
+
333
+ def _tool_schema_groups(tool_schemas: Any) -> list[list[str]]:
334
+ if tool_schemas is None:
335
+ return []
336
+ if not isinstance(tool_schemas, list):
337
+ raise HTTPException(status_code=400, detail="tool_schemas must be a list")
338
+ return [_tool_schema_variants(schema) for schema in tool_schemas]
339
+
340
+
341
+ def _schema_occurrences(text: str, group: list[str]) -> int:
342
+ return sum(len(_find_spans(text, candidate)) for candidate in group)
343
+
344
+
345
+ def _tool_schema_missing_groups(
346
+ input_text: str,
347
+ output: str,
348
+ groups: list[list[str]],
349
+ ) -> list[list[str]]:
350
+ missing = []
351
+ for group in groups:
352
+ if _schema_occurrences(input_text, group) > 0 and _schema_occurrences(output, group) == 0:
353
+ missing.append(group)
354
+ return missing
355
+
356
+
357
  def _protected_spans(
358
  text: str,
359
  protected_values: list[str],
360
+ tool_schema_groups: list[list[str]],
361
  *,
362
  preserve_code: bool,
363
  preserve_json: bool,
 
366
  list[tuple[int, int]],
367
  list[tuple[int, int]],
368
  list[tuple[int, int]],
369
+ list[tuple[int, int]],
370
  ]:
371
  spans = []
372
  for value in protected_values:
373
  spans.extend(_find_spans(text, value))
374
+ tool_schema_spans = []
375
+ for group in tool_schema_groups:
376
+ for candidate in group:
377
+ tool_schema_spans.extend(_find_spans(text, candidate))
378
+ spans.extend(tool_schema_spans)
379
  code_spans = (
380
  _regex_spans(text, r"```.*?```", re.MULTILINE | re.DOTALL)
381
  if preserve_code
 
394
  spans.extend(code_spans)
395
  spans.extend(json_spans)
396
  spans.extend(system_spans)
397
+ return _merge(spans), code_spans, json_spans, system_spans, _merge(tool_schema_spans)
398
 
399
 
400
  def _compress_text(payload: dict[str, Any]) -> dict[str, Any]:
 
409
  isinstance(value, str) for value in protected_values
410
  ):
411
  raise HTTPException(status_code=400, detail="protected_spans must be strings")
412
+ tool_schema_groups = _tool_schema_groups(
413
+ payload.get("tool_schemas", payload.get("tools"))
414
+ )
415
  try:
416
  aggressiveness = float(settings.get("aggressiveness", 0.35))
417
  except Exception as exc:
 
422
  started = time.perf_counter()
423
  preserve_code = bool(settings.get("preserve_code", True))
424
  preserve_json = bool(settings.get("preserve_json", True))
425
+ protected, code_spans, json_spans, system_spans, tool_schema_spans = _protected_spans(
426
  text,
427
  protected_values,
428
+ tool_schema_groups,
429
  preserve_code=preserve_code,
430
  preserve_json=preserve_json,
431
  )
 
484
  code_preserved = all(text[start:end] in output for start, end in code_spans)
485
  json_preserved = all(text[start:end] in output for start, end in json_spans)
486
  system_preserved = all(text[start:end] in output for start, end in system_spans)
487
+ missing_tool_schemas = _tool_schema_missing_groups(
488
+ text,
489
+ output,
490
+ tool_schema_groups,
491
+ )
492
+ tool_schemas_preserved = not missing_tool_schemas
493
  decision = "reject" if (
494
+ missing
495
+ or not code_preserved
496
+ or not json_preserved
497
+ or not system_preserved
498
+ or not tool_schemas_preserved
499
  ) else (
500
  "high_confidence" if saved > 0 and aggressiveness <= 0.65 else "no_op"
501
  )
 
513
  "json_blocks_preserved": json_preserved,
514
  "system_prompt_spans_detected": len(system_spans),
515
  "system_prompts_preserved": system_preserved,
516
+ "tool_schemas_checked": len(tool_schema_groups),
517
+ "tool_schema_occurrences": sum(
518
+ _schema_occurrences(text, group)
519
+ for group in tool_schema_groups
520
+ ),
521
+ "tool_schema_spans_detected": len(tool_schema_spans),
522
+ "tool_schemas_missing": len(missing_tool_schemas),
523
+ "tool_schemas_missing_preview": [
524
+ next((candidate[:120] for candidate in group if candidate), "")
525
+ for group in missing_tool_schemas
526
+ ],
527
+ "tool_schemas_preserved": tool_schemas_preserved,
528
  "decision": decision,
529
  "compressor_latency_ms": round((time.perf_counter() - started) * 1000.0, 3),
530
  "deletion_only": _is_subsequence(output, text),
 
591
  "input": item,
592
  "compression_settings": payload.get("compression_settings"),
593
  "protected_spans": payload.get("protected_spans"),
594
+ "tool_schemas": payload.get("tool_schemas", payload.get("tools")),
595
  }
596
  if not isinstance(item, dict):
597
  raise ValueError(f"inputs[{index}] must be a string or an object")
 
617
  "input": item.get("input"),
618
  "compression_settings": settings,
619
  "protected_spans": item.get("protected_spans", payload.get("protected_spans")),
620
+ "tool_schemas": item.get(
621
+ "tool_schemas",
622
+ item.get("tools", payload.get("tool_schemas", payload.get("tools"))),
623
+ ),
624
  }
625
 
626