如何将Golang结构体转换为Vertex AI PredictRequest.Instances类型?
将Submission结构体转换为Vertex AI PredictRequest实例的方法
需求背景
我在Cloud Run上部署了Golang Web应用,通过表单收集用户提交的Submission结构体数据,需要调用Vertex AI端点。当前需要解决的是如何将Submission结构体转换为aiplatformpb.PredictRequest的Instances字段接受的[]*structpb.Value类型。已知Vertex AI端点接受的请求格式如下:
{ "instances": [ [ 29823, 43.5, 1 ] ] }
解决步骤
要完成转换,需使用google.golang.org/protobuf/types/known/structpb包构建符合要求的structpb.Value对象,具体步骤:
- 调整
Submission结构体字段类型,与Vertex AI端点期望的类型匹配(示例中Age为浮点数,建议将结构体中Age字段从int改为float64) - 将
Submission的每个字段转换为对应的*structpb.Value - 把字段值组合成数组类型的
structpb.Value - 将该数组值放入
Instances切片中
完整代码示例
import ( "context" "log" aiplatformpb "google.golang.org/genproto/googleapis/cloud/aiplatform/v1" "google.golang.org/protobuf/types/known/structpb" ) // 调整Age字段类型为float64,匹配端点要求的数值类型 type Submission struct { MonthlyIncome int Age float64 Passport int } func main() { // 假设已通过表单获取到用户提交的Details数据 var Details = Submission{ MonthlyIncome: 29823, Age: 43.5, Passport: 1, } Ctx := context.Background() C, err := aiplatformpb.NewPredictionClient(Ctx) if err != nil { log.Fatalf("Error 1: %v", err) } defer C.Close() // 逐个将字段转换为structpb.Value incomeVal, err := structpb.NewValue(int64(Details.MonthlyIncome)) if err != nil { log.Fatalf("Failed to create income value: %v", err) } ageVal, err := structpb.NewValue(Details.Age) if err != nil { log.Fatalf("Failed to create age value: %v", err) } passportVal, err := structpb.NewValue(int64(Details.Passport)) if err != nil { log.Fatalf("Failed to create passport value: %v", err) } // 构建数组类型的实例对象 instanceList := &structpb.ListValue{ Values: []*structpb.Value{incomeVal, ageVal, passportVal}, } instanceValue := structpb.NewListValue(instanceList) // 组装PredictRequest reqs := &aiplatformpb.PredictRequest{ Endpoint: "你的Vertex AI端点地址", Instances: []*structpb.Value{instanceValue}, } // 后续调用端点逻辑 // resp, err := C.Predict(Ctx, reqs) // ... }
关键说明
structpb.NewValue可将int64、float64等基础类型直接转换为*structpb.Value- 必须保证字段顺序与Vertex AI模型训练时的特征顺序完全一致(示例中为
MonthlyIncome→Age→Passport) - 若端点期望的是其他结构(如对象而非数组),只需调整为构建
structpb.Struct而非structpb.ListValue即可
内容的提问来源于stack exchange,提问作者BBlank
相关产品推荐
相关产品推荐

