如何将VertexAI的PredictResponse转换为JSON格式?
VertexAI PredictResponse 无法序列化为JSON的解决方案
我正在开发一个VertexAI项目,尝试两种访问路径:一是通过React前端直接调用,二是通过Python后端调用后将结果返回给前端。在Python方案中,我能成功向模型发送请求并获取正确响应,但在将响应转换为JSON格式供前端使用时遇到了问题。
原代码及问题
以下是我最初使用的代码:
# The AI Platform services require regional API endpoints. client_options = {"api_endpoint": api_endpoint} # Initialize client that will be used to create and send requests. # This client only needs to be created once, and can be reused for multiple requests. client = PredictionServiceClient( client_options=client_options, credentials=credentials ) instance = schema.predict.instance.TextClassificationPredictionInstance( content=content, ).to_value() instances = [instance] parameters_dict = {} parameters = json_format.ParseDict(parameters_dict, Value()) endpoint = client.endpoint_path( project=project_id, location=compute_region, endpoint=endpoint_id ) response = client.predict( endpoint=endpoint, instances=instances, parameters=parameters ) response_dict = [dict(prediction) for prediction in response.predictions]
虽然response_dict可以正常打印,但直接对response(PredictResponse类型对象)使用json.dumps()时会报错:
TypeError: Object of type PredictResponse is not JSON serializable
可行解决方案
通过将PredictResponse的protobuf底层对象转换为字典,再进行JSON序列化即可解决问题。以下是修正后的可行代码:
... response = client.predict( endpoint=endpoint, instances=instances, parameters=parameters ) predictions = MessageToDict(response._pb) predictions = predictions["predictions"][0]
这里利用MessageToDict将response._pb(原生protobuf消息对象)转换为可被json.dumps()处理的Python字典,之后就能正常将结果返回给前端。
内容的提问来源于stack exchange,提问作者Tuma
相关产品推荐
相关产品推荐

