api_server_response_identity.py 1.4 KB

12345678910111213141516171819202122232425262728293031
  1. """Stable presentation identity for a durable Responses admission.
  2. The model label, creation time and compact ID/index ordering survive response-body eviction.
  3. Item IDs derive from response identity and occurrence; no additional transcript/output copy is retained.
  4. """
  5. import hashlib
  6. import json
  7. _PREFIXES = {'function_call': 'fc', 'function_call_output': 'fco', 'reasoning': 'rs', 'message': 'msg'}
  8. def durable_response_id(request_key):
  9. """The public response id of an Idempotency-Key request; the store derives it again for an
  10. identity whose replay record was never written."""
  11. return 'resp_' + hashlib.sha256(request_key.encode()).hexdigest()[:28]
  12. def next_item_id(response_id, counters, kind, *, call_id=None, commentary=False):
  13. # The final message is distinct from any live commentary, which is not part of the answer.
  14. key = (kind, call_id, bool(commentary))
  15. occurrence = counters.get(key, 0)
  16. counters[key] = occurrence + 1
  17. digest = hashlib.sha256(json.dumps([response_id, *key, occurrence], separators=(',', ':')).encode()).hexdigest()
  18. return _PREFIXES[kind] + '_' + digest[:24]
  19. def identify_output(items, response_id):
  20. counters = {}
  21. return [dict(item, id=next_item_id(response_id, counters, item['type'],
  22. call_id=item.get('call_id'), commentary=item.get('phase') == 'commentary'))
  23. for item in items]