Table of Contents
Question content
Workaround
Home Backend Development Golang aiplatformb.PredictRequest.Instances requires type *structpb.Value (GCP golang client library; aiplatform)

aiplatformb.PredictRequest.Instances requires type *structpb.Value (GCP golang client library; aiplatform)

Feb 10, 2024 pm 03:00 PM
go language

aiplatformb.PredictRequest.Instances 需要类型 *structpb.Value (GCP golang 客户端库;aiplatform)

php Editor Apple AI Platform B is a powerful prediction request instance, which requires parameters of type structpb.Value. This is a Go language client library for GCP (Google Cloud Platform), specially designed for aiplatform. It provides users with convenient prediction functions to quickly make model predictions during the development process. By using this library, users can easily integrate AI technology into their applications and obtain accurate and efficient prediction results.

Question content

I'm trying to access my Vertex AI endpoint from a Golang web application (the web server/application is running on a cloud run build). The web application has a form where I am submitting details, my question is, how can I get the structure received from the web application and convert it to the type accepted in the Instances field of the aiplatformb.PredictRequest structure?

type Submission struct {
        MonthlyIncome                 int
        Age                           int
        Passport                      int
    }

    var Details = Submission{}


    Ctx := context.Background()
        C, err := aiplatform.NewPredictionClient(Ctx)
    
        if err != nil {
            log.Fatalf("Error 1: %v", err)
        }

        defer C.Close()

        reqs := &aiplatformpb.PredictRequest{
            Endpoint:  "{{my endpoint that is formatted correctly}",
            Instances: []*structpb.Value{},
Copy after login

I tried accessing this endpoint externally using Postman and the request below confirms the endpoint is up and running. These values ​​are the values ​​submitted by the details

{
        "instances": [
            [
                29823,
                43.5,
                1
            ]
        ]
    }
Copy after login

Workaround

After multiple attempts using the client library and consulting the documentation, the .Predict() method [acting on a pointer to a PredictionClient type] does not allow you to specify a vertex AI model endpoint architecture. So the solution is to send the request through the .RawPredict() method, so the serialized JSON (structpb) request will only work if the schema implemented by the golang GCP client library matches your deployed model. Here is the GCP documentation for PredictionClient:

https ://cloud.google.com/go/docs/reference/cloud.google.com/go/aiplatform/1.0.0/apiv1#cloud_google_com_go_aiplatform_apiv1_PredictionClient

The following are the libraries required to form and use the RawPredict() method:

import (
    "context"
    "fmt"
    "log"
    "reflect"
    "strconv"

    aiplatform "cloud.google.com/go/aiplatform/apiv1"
    "cloud.google.com/go/aiplatform/apiv1/aiplatformpb"
    "google.golang.org/api/option"
    "google.golang.org/genproto/googleapis/api/httpbody"
)
Copy after login

This is the code:

// Get the form values from the web applicaiton
    income, _ := strconv.Atoi(r.FormValue("MonthlyIncome")) 
    age, _ := strconv.Atoi(r.FormValue("Age"))
    passport, _ := strconv.Atoi(r.FormValue("Passport"))


//create our struct from the form values

    Details = Submission{
        MonthlyIncome:                 income,
        Age:                           age,
        Passport:                      passport,
    }

    v := reflect.ValueOf(Details)
    body = ""


    for i := 0; i < v.NumField(); i++ {

        body = body + fmt.Sprintf("%v", v.Field(i).Interface()) + ","

    }

    if last := len(body) - 1; last >= 0 && body[last] == ',' {
        body = body[:last]
    }

    Requestb = pre + body + post
    log.Println("The request string was:", Requestb)

// structure the body of the raw request
    Raw := &httpbody.HttpBody{}
    Raw.Data = []byte(Requestb)

// indentify the post request using the raw body and the endpoint
    reqs := &aiplatformpb.RawPredictRequest{
// Note  GCP Project ID, Region, and endpoint ID
        Endpoint: "projects/<PROJECT-HERE>/locations/<REGDION-HERE>/endpoints/<ENDPOINT-ID-HERE>",
        HttpBody: Raw,
    }


// CTX gets the credentials of the application service account - NOTE THE REGION
    Ctx := context.Background()
    C, err := aiplatform.NewPredictionClient(Ctx, option.WithEndpoint("<REGION-HERE>-aiplatform.googleapis.com:443"))

    if err != nil {
        log.Println("Error 1, connectrion:", err)
    }
    defer C.Close()

// gets the response using the credentials of the application service account
    resp, err := C.RawPredict(Ctx, reqs)
    if err != nil {
        log.Fatalf("Error 2, response: %v", err)
    }
    log.Println(resp)


    RespString := fmt.Sprintf("%+v", resp)
    log.Println("The Response String was:", resp)
Copy after login

The above is the detailed content of aiplatformb.PredictRequest.Instances requires type *structpb.Value (GCP golang client library; aiplatform). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

What is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

When using sql.Open, why does not report an error when DSN passes empty? When using sql.Open, why does not report an error when DSN passes empty? Apr 02, 2025 pm 12:54 PM

When using sql.Open, why doesn’t the DSN report an error? In Go language, sql.Open...

See all articles