Adicionar a lógica de processamento usando as funções do Cloud Run
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Com as funções do Cloud Run, é possível processar os dados de saída do modelo treinado sob medida da Vertex AI e dos nós de apps do BigQuery.
É possível usar essas integrações com nós de app das seguintes maneiras:
Nó Modelo personalizado da Vertex AI: use funções do Cloud Run para
processar os resultados da previsão do modelo personalizado da Vertex AI.
Nó BigQuery: use as funções do Cloud Run para gerar linhas personalizadas do BigQuery com as anotações originais.
Todas as funções do Cloud Run que você usa com a App Platform precisam atender aos seguintes
requisitos:
As funções do Cloud Run precisam fornecer o gatilho HTTP.
O esquema de payload da anotação armazenado na solicitação e a resposta
precisa seguir a especificação do modelo de destino.
Definições de API: AppPlatformMetadata, AppPlatformCloudFunctionRequest, AppPlatformCloudFunctionResponse
//MessageofessentialmetadataofAppPlatform.//Thismessageisusuallyattachedtoacertainmodeloutputannotationfor//customertoidentifythesourceofthedata.messageAppPlatformMetadata{//Theapplicationresourcename.stringapplication=1;//Theinstanceresourceid.Instanceisthenestedresourceofapplication//undercollection'instances'.stringinstance_id=2;//Thenodenameoftheapplicationgraph.stringnode=3;//Thereferredmodelresourcenameoftheapplicationnode.stringprocessor=4;}//ForanyCloudRunfunctionbasedcustomerprocessinglogic,customer's cloud//functionisexpectedtoreceiveAppPlatformCloudFunctionRequestasrequest//andsendbackAppPlatformCloudFunctionResponseasresponse.//MessageofrequestfromAppPlatformtoCloudRunfunctions.messageAppPlatformCloudFunctionRequest{//ThemetadataoftheAppPlatformforcustomertoidentifythesourceofthe//payload.AppPlatformMetadataapp_platform_metadata=1;//Ageneralannotationmessagethatusesstructformattorepresentdifferent//concreteannotationprotobufs.messageStructedInputAnnotation{//Theingestiontimeofthecurrentannotation.int64ingestion_time_micros=1;//Thestructformatoftheactualannotation.protobuf.Structannotation=2;}//TheactualannotationstobeprocessedbythecustomizedCloudRunfunction.repeatedStructedInputAnnotationannotations=2;}//Messageoftheresponsefromcustomer's Cloud Run function to AppPlatform.messageAppPlatformCloudFunctionResponse{//Ageneralannotationmessagethatusesstructformattorepresentdifferent//concreteannotationprotobufs.messageStructedOutputAnnotation{//Thestructformatoftheactualannotation.protobuf.Structannotation=1;}//ThemodifiedannotationsthatisreturnedbacktoAppPlatform.//Iftheannotationsfieldsareempty,thenthoseannotationswillbedropped//byAppPlatform.repeatedStructedOutputAnnotationannotations=2;}
Exemplo de uso
Use o código abaixo para processar as anotações do modelo treinado personalizado da Vertex AI e substituí-las por um par de chave-valor constante.
Python
importfunctions_frameworkfromflaskimportjsonify@functions_framework.httpdefhello_http(request):request_json=request.get_json(silent=True)request_args=request.argsifrequest_jsonand'annotations'inrequest_json:annotations=[]foreleinrequest_json['annotations']:fork,vinele.items():ifk=="annotation":if"predictions"inv:# Replace the annotation.v["predictions"][0]={"user":"googler"}annotations.append({"annotation":v})else:annotations='Failure'returnjsonify(annotations=annotations)
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-09-04 UTC."],[],[],null,["# Add processing logic using Cloud Run functions\n\nWith Cloud Run functions you can further process output data from\nVertex AI custom-trained model and BigQuery app nodes.\nYou can use these integrations with app nodes in the following ways:\n\n- **Vertex AI custom model** node: Use Cloud Run functions to post-process prediction results from the original Vertex AI custom model.\n- **BigQuery** node: Use Cloud Run functions to generate customized BigQuery rows with the original annotations.\n\nAll the Cloud Run functions you use with App Platform must meet the following\nrequirements:\n\n- Cloud Run functions must provide the [Http trigger](/functions/docs/calling/http).\n- Cloud Run functions must receive a [`AppPlatformCloudFunctionRequest`](/vision-ai/docs/reference/rpc/google.cloud.visionai.v1alpha1#appplatformcloudfunctionrequest) JSON string, and must return a [`AppPlatformCloudFunctionResponse`](/vision-ai/docs/reference/rpc/google.cloud.visionai.v1alpha1#appplatformcloudfunctionresponse) JSON string back.\n- The annotation payload schema stored in the request *and* the response must follow the specification of the target model.\n\n#### API definitions: `AppPlatformMetadata`, `AppPlatformCloudFunctionRequest`, `AppPlatformCloudFunctionResponse`\n\n```gdscript\n// Message of essential metadata of App Platform.\n// This message is usually attached to a certain model output annotation for\n// customer to identify the source of the data.\nmessage AppPlatformMetadata {\n // The application resource name.\n string application = 1;\n // The instance resource id. Instance is the nested resource of application\n // under collection 'instances'.\n string instance_id = 2;\n // The node name of the application graph.\n string node = 3;\n // The referred model resource name of the application node.\n string processor = 4;\n}\n\n// For any Cloud Run function based customer processing logic, customer's cloud\n// function is expected to receive AppPlatformCloudFunctionRequest as request\n// and send back AppPlatformCloudFunctionResponse as response.\n// Message of request from AppPlatform to Cloud Run functions.\nmessage AppPlatformCloudFunctionRequest {\n // The metadata of the AppPlatform for customer to identify the source of the\n // payload.\n AppPlatformMetadata app_platform_metadata = 1;\n // A general annotation message that uses struct format to represent different\n // concrete annotation protobufs.\n message StructedInputAnnotation {\n // The ingestion time of the current annotation.\n int64 ingestion_time_micros = 1;\n // The struct format of the actual annotation.\n protobuf.Struct annotation = 2;\n }\n // The actual annotations to be processed by the customized Cloud Run function.\n repeated StructedInputAnnotation annotations = 2;\n}\n\n// Message of the response from customer's Cloud Run function to AppPlatform.\nmessage AppPlatformCloudFunctionResponse {\n // A general annotation message that uses struct format to represent different\n // concrete annotation protobufs.\n message StructedOutputAnnotation {\n // The struct format of the actual annotation.\n protobuf.Struct annotation = 1;\n }\n\n // The modified annotations that is returned back to AppPlatform.\n // If the annotations fields are empty, then those annotations will be dropped\n // by AppPlatform.\n repeated StructedOutputAnnotation annotations = 2;\n}\n```\n\n### Sample usage\n\nUse the following code to post-process Vertex AI custom-trained model\nannotations and replace annotations with a constant key-value pair. \n\n### Python\n\n import functions_framework\n from flask import jsonify\n\n @functions_framework.http\n def hello_http(request):\n request_json = request.get_json(silent=True)\n request_args = request.args\n\n if request_json and 'annotations' in request_json:\n annotations = []\n for ele in request_json['annotations']:\n for k, v in ele.items():\n if k == \"annotation\":\n if \"predictions\" in v:\n # Replace the annotation.\n v[\"predictions\"][0] = {\"user\": \"googler\"}\n annotations.append({\"annotation\" : v})\n else:\n annotations = 'Failure'\n return jsonify(annotations=annotations)"]]