我有一个想要访问的 VertexAI 项目。我目前正在尝试两种方法,通过 React 前端和 Python 后端,然后我将其连接到 FE。我发布了一个关于从 Node here 向 VertexAI 发出请求的问题。
在 python 方法中,我能够发出请求并收到正确的响应。但是,为了让 FE 可以访问它,我需要将其转换为 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
将json.dumps
转换为json,因为:
TypeError: Object of type PredictResponse is not JSON serializable
这是在每次尝试中一直困扰我的错误。 DuetAI 只是告诉我使用
json.dumps
。
由于
json.dumps
需要序列化您的响应,我相信最好使用 json\_format.MessageToDict
而不是 json\_format.ParseDict
。
他们的工作原理恰恰相反:
ParseDict
采用 JSON 字典表示并将其合并到预先存在的 Protobuf 消息对象中。它解析 JSON 数据并填充 Protobuf 消息中的相应字段。
[MessageToDict][1]
采用 Protobuf 消息对象并将其转换为 Python 字典表示形式,然后可以使用 json.dumps
轻松将其序列化为 JSON。
我找到了一些讨论protobuf库的MessageToDict函数的在线资源。请查看它们以获取更多信息。
[无法在 python 中将 protobuf 二进制文件转换为 json - bytes' 对象没有属性 'DESCRIPTOR'][2]
[Python 中的 JSON 到 Protobuf][3]
[无法解析缺乏 Vertex 作业响应][4]
[1]: https://googleapis.dev/python/protobuf/latest/google/protobuf/json_format.html#:~:text=google.protobuf.json_format.-,MessageToDict,-(消息%2C [ 2]: 无法在 python 中将 protobuf 二进制文件转换为 json - bytes' 对象没有属性 'DESCRIPTOR' [3]: Python 中的 JSON 到 Protobuf [4]: https://cloud.google.com /knowledge/kb/无法解析顶点作业响应-lack-000004947