You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Google Cloud AutoML Python客户端接入Streamlit应用实现推理?遇字段错误求助

解决AutoML Python客户端调用时的FieldDescriptorProto has no "proto3_optional" field错误

这个错误几乎可以肯定是protobuf版本不兼容导致的——旧版本的protobuf库不支持proto3_optional字段,但Google Cloud AutoML的客户端库依赖了支持该字段的新版本protobuf,或者反过来出现了版本冲突。下面是一步步的解决方法:

1. 优先升级/统一protobuf版本

首先检查当前安装的protobuf版本:

pip show protobuf

如果版本低于4.21.x,直接升级到兼容的稳定版本:

pip install --upgrade protobuf==4.21.12

这个版本是Google Cloud客户端库普遍兼容的版本,能避免大部分字段不兼容问题。

如果升级后还是报错,建议先卸载所有版本的protobuf,再重新安装指定版本:

pip uninstall -y protobuf
pip install protobuf==4.21.12

2. 统一Google Cloud AutoML客户端库版本

你的代码里同时导入了automl_v1beta1和automl两个版本的库,这很容易引发版本冲突。建议直接使用最新的v1正式版库,移除v1beta1的导入:

# 删掉这行:from google.cloud import automl_v1beta1
from google.cloud import automl

同时确保安装的是最新版的google-cloud-automl:

pip install --upgrade google-cloud-automl

3. 固化Streamlit环境依赖

Streamlit运行的环境可能和你的开发环境依赖版本不一致,建议在项目根目录创建requirements.txt文件,明确指定所有依赖的版本:

streamlit>=1.20.0
google-cloud-automl>=2.10.0
protobuf>=4.21.12
google-cloud-vision>=2.11.0

然后重新安装依赖:

pip install -r requirements.txt

4. 用最小化脚本测试排除问题

先写一个不依赖Streamlit的简单测试脚本,验证AutoML调用是否正常:

from google.cloud import automl

# 替换成你的项目信息
PROJECT_ID = "your-project-id"
MODEL_ID = "your-model-id"
LOCATION = "us-central1"

# 初始化预测客户端
client = automl.PredictionServiceClient()
model_full_id = client.model_path(PROJECT_ID, LOCATION, MODEL_ID)

# 读取测试图片
with open("test-image.jpg", "rb") as img_file:
    img_content = img_file.read()

# 构建预测请求
image = automl.Image(image_bytes=img_content)
payload = automl.ExamplePayload(image=image)
params = {"score_threshold": "0.5"}

# 发送请求并打印结果
response = client.predict(name=model_full_id, payload=payload, params=params)
for result in response.payload:
    print(f"类别: {result.display_name}, 置信度: {result.classification.score}")

如果这个脚本能正常运行,说明问题出在Streamlit的环境配置上;如果还是报错,那就是客户端库或protobuf的版本问题还没解决。

额外提醒

别忘了确保你的环境已经正确配置Google Cloud认证:

  • 设置GOOGLE_APPLICATION_CREDENTIALS环境变量指向你的服务账号密钥文件
  • 或者在代码里显式加载密钥:
import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/path/to/your/service-account-key.json"

内容的提问来源于stack exchange,提问作者Ayoola fakoya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 16:58:01