MCPcopy Create free account
hub / github.com/PAIR-code/lit / make_handler

Method make_handler

lit_nlp/app.py:866–914  ·  view source on GitHub ↗

Convenience wrapper to handle args and serialization. This is a thin shim between server (handler, request, environ) and model logic (inputs, args, outputs). Args: fn: function (JsonDict, **kw) -> JsonDict Returns: fn wrapped as a request handler

(self, fn)

Source from the content-addressed store, hash-verified

864 base=dataset, examples=datapoints, spec=annotated_spec)
865
866 def make_handler(self, fn):
867 """Convenience wrapper to handle args and serialization.
868
869 This is a thin shim between server (handler, request, environ) and model
870 logic (inputs, args, outputs).
871
872 Args:
873 fn: function (JsonDict, **kw) -> JsonDict
874
875 Returns:
876 fn wrapped as a request handler
877 """
878
879 @functools.wraps(fn)
880 def _handler(app: wsgi_app.App, request, environ):
881 kw = request.args.to_dict()
882 # The frontend needs "simple" data (e.g. NumPy arrays converted to lists),
883 # but for requests from Python we may want to use the invertible encoding
884 # so that datatypes from remote models are the same as local ones.
885 response_simple_json = utils.coerce_bool(
886 kw.pop('response_simple_json', True)
887 )
888 data = serialize.from_json(request.data) if len(request.data) else None
889 # Special handling to dereference IDs.
890 if (
891 data
892 and 'inputs' in data.keys()
893 and data.get('inputs')
894 and 'dataset_name' in kw
895 ):
896 data['inputs'] = self._reconstitute_inputs(
897 data['inputs'], kw['dataset_name']
898 )
899 # Validate that id and data._id match.
900 # TODO(b/171513556): consider removing this if we can simplify the
901 # data representation on the frontend so id and meta are not replicated.
902 for ex in data['inputs']:
903 if ex['id'] != ex['data'].get('_id'):
904 raise ValueError(
905 'Error: malformed example with inconsistent ids:'
906 f' {str(ex)}\nfrom request'
907 f' {request.path} {str(request.args.to_dict())}'
908 )
909
910 outputs = fn(data, **kw)
911 response_body = serialize.to_json(outputs, simple=response_simple_json)
912 return app.respond(request, response_body, 'application/json', 200)
913
914 return _handler
915
916 def __init__(
917 self,

Callers 1

__init__Method · 0.95

Calls

no outgoing calls

Tested by

no test coverage detected