From 86493bebb139c5a9316c592bcad977f64b3bf4a7 Mon Sep 17 00:00:00 2001 From: Volker Stampa Date: Fri, 17 Feb 2023 10:53:34 +0100 Subject: [PATCH] Make json deserialization forward compatible Ignore additional fields in json responses --- aleph_alpha_client/completion.py | 14 +++++++++++++- aleph_alpha_client/detokenization.py | 2 +- aleph_alpha_client/search.py | 6 +++++- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/aleph_alpha_client/completion.py b/aleph_alpha_client/completion.py index 46443c0..318aaba 100644 --- a/aleph_alpha_client/completion.py +++ b/aleph_alpha_client/completion.py @@ -218,6 +218,16 @@ class CompletionResult(NamedTuple): finish_reason: Optional[str] = None raw_completion: Optional[str] = None + @staticmethod + def from_json(json: Dict[str, Any]) -> "CompletionResult": + return CompletionResult( + log_probs=json.get("log_probs"), + completion=json.get("completion"), + completion_tokens=json.get("completion_tokens"), + finish_reason=json.get("finish_reason"), + raw_completion=json.get("raw_completion"), + ) + class CompletionResponse(NamedTuple): model_version: str @@ -228,7 +238,9 @@ class CompletionResponse(NamedTuple): def from_json(json: Dict[str, Any]) -> "CompletionResponse": return CompletionResponse( model_version=json["model_version"], - completions=[CompletionResult(**item) for item in json["completions"]], + completions=[ + CompletionResult.from_json(item) for item in json["completions"] + ], optimized_prompt=json.get("optimized_prompt"), ) diff --git a/aleph_alpha_client/detokenization.py b/aleph_alpha_client/detokenization.py index eea8a72..e63a5aa 100644 --- a/aleph_alpha_client/detokenization.py +++ b/aleph_alpha_client/detokenization.py @@ -24,4 +24,4 @@ class DetokenizationResponse(NamedTuple): @staticmethod def from_json(json: Dict[str, Any]) -> "DetokenizationResponse": - return DetokenizationResponse(**json) + return DetokenizationResponse(result=json["result"]) diff --git a/aleph_alpha_client/search.py b/aleph_alpha_client/search.py index 9956215..683b92d 100644 --- a/aleph_alpha_client/search.py +++ b/aleph_alpha_client/search.py @@ -58,6 +58,10 @@ class SearchResult(NamedTuple): id: str score: float + @staticmethod + def from_json(json: Dict[str, Any]) -> "SearchResult": + return SearchResult(id=json["id"], score=json["score"]) + class SearchResponse(NamedTuple): model_version: str @@ -67,5 +71,5 @@ class SearchResponse(NamedTuple): def from_json(json: Dict[str, Any]) -> "SearchResponse": return SearchResponse( model_version=json["model_version"], - results=[SearchResult(**item) for item in json["results"]], + results=[SearchResult.from_json(item) for item in json["results"]], )