Todos os produtos
Search
Central de documentação

Platform For AI:Chamar serviços de inferência do PAI-EAS via gRPC

Última atualização: Sep 10, 2026

O PAI-EAS oferece suporte à inferência de modelos via gRPC. Em comparação com HTTP/JSON, o gRPC proporciona serialização mais eficiente e melhor suporte a streaming, sendo ideal para cargas de trabalho de inferência sensíveis à latência ou baseadas em streaming.

Pré-requisitos

Antes de começar:

  1. Implante um service de inferência do PAI-EAS.

  2. Configure um ambiente de desenvolvimento Go (Go 1.18 ou posterior).

  3. Instale os pacotes de dependência necessários para gRPC.

Pontos principais

Formato do endpoint

Para chamar um service pelo gateway, obtenha o endpoint no console do PAI-EAS, extraia o nome de domínio e adicione a porta :80, conforme descrito em Obtain the access endpoint and token.

Importante

A porta é fixa em 80 porque o PAI-EAS expõe os serviços gRPC por meio de um gateway que escuta na porta 80.

Exemplos de endpoints:

Método de acesso

Endpoint no console

Endpoint gRPC (adicionar :80)

Rede pública

http://grpc-test.123456***.cn-hangzhou.pai-eas.aliyuncs.com/

grpc-test.123456***.cn-hangzhou.pai-eas.aliyuncs.com:80

VPC

http://grpc-test.123456***.vpc.cn-hangzhou.pai-eas.aliyuncs.com/

grpc-test.123456***.vpc.cn-hangzhou.pai-eas.aliyuncs.com:80

Nota: Um endpoint gRPC não inclui o prefixo http://.

Autenticação por token

O PAI-EAS utiliza autenticação Bearer Token. Passe o token nos metadados da requisição gRPC definindo o campo authorization da seguinte forma:

authorization: Bearer <Token>

Adicione o prefixo Bearer seguido de um espaço ao token. Obtenha seu token na página de detalhes do service no console do PAI-EAS.

Exemplos de código

Antes de programar, prepare o arquivo proto do seu service e compile o stub do cliente.

Estes exemplos demonstram o fluxo principal de chamada gRPC. O arquivo proto correspondente e o código do servidor estão disponíveis no apêndice gRPC service demo.

package main

import (
	"context"
	"log"
	"time"

	pb "your-project/proto"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/metadata"
)

func main() {
	// Replace with your gRPC endpoint. You can find it in the call info panel in the PAI-EAS console.
	// The public network endpoint format is: service-name.{uid}.{region}.pai-eas.aliyuncs.com:80 (the port is fixed at 80).
	host := "your-service-endpoint:your port"
	// Replace with your service token. You can find it on the service details page in the PAI-EAS console.
	token := "your-service-token"

	log.Printf("Connecting to the PAI-EAS gRPC service (%s)...", host)
        
        // 1. Establish a connection. Connections are thread-safe. We recommend that you create one connection and reuse it.
	conn, err := grpc.NewClient(
		host,
		grpc.WithTransportCredentials(insecure.NewCredentials()),
	)
	if err != nil {
		log.Fatalf("Failed to connect: %v", err)
	}
	defer conn.Close()

	// 2. Create a client.
	client := pb.NewGreeterServiceClient(conn)
	
	// 3. Inject the authentication token by using gRPC metadata.
	md := metadata.Pairs("authorization", "Bearer " + token)

	ctx := metadata.NewOutgoingContext(context.Background(), md)

	// 4. Set a timeout.
	ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()

	// 5. Construct the request.
	req := &pb.HelloRequest{Name: "World"}

	// 6. Make the call.
	resp, err := client.SayHello(ctx, req)
	if err != nil {
		log.Fatalf("Call failed: %v", err)
	}

	log.Printf("Received response: %s", resp.Message)
}
import grpc
import helloworld_pb2
import helloworld_pb2_grpc

# Replace with your gRPC endpoint. You can find it in the call info panel in the PAI-EAS console.
# The public network endpoint format is: service-name.{uid}.{region}.pai-eas.aliyuncs.com:80 (the port is fixed at 80).
host = "your-service-endpoint:your port"
# Replace with your service token. You can find it on the service details page in the PAI-EAS console.
token = "your-service-token"

# 1. Create a channel to connect to the server.
channel = grpc.insecure_channel(host)

# 2. Initialize the stub (client handle).
stub = helloworld_pb2_grpc.GreeterServiceStub(channel)

# 3. Construct the request.
request = helloworld_pb2.HelloRequest(name="World")

# 4. Construct the authentication metadata to pass the token to the PAI-EAS service.
metadata = (("authorization",  "Bearer " + token),)

print("Initiating gRPC call...")

try:
    # 5. Make a synchronous request. Pass the metadata for authentication.
    response = stub.SayHello(request, metadata=metadata, timeout=5.0)
    print(response.message)
except grpc.RpcError as e:
    print(f"Call failed: {e.code()} - {e.details()}")
finally:
    channel.close()

Melhores práticas

  • Reutilização de conexões: As conexões gRPC são seguras para threads. Crie uma única conexão na inicialização da aplicação e reutilize-a para todas as requisições.

    Importante

    Dispositivos intermediários podem encerrar conexões ociosas. Em produção, ative o keepalive: use KeepaliveParams em Go ou o parâmetro options em Python.

  • Timeout: Defina um timeout para cada chamada a fim de evitar que requisições fiquem pendentes devido a falhas de rede ou do service.

Perguntas frequentes

Falha na autenticação (UNAUTHENTICATED)

Verifique se o seu token é válido e não expirou. Confirme se o campo de metadados está nomeado exatamente como authorization e se o valor começa com Bearer seguido de um espaço.

Timeout de conexão (UNAVAILABLE)

Verifique se o endpoint gRPC está correto e se a rede está acessível.

Para endpoints de VPC, confirme se o cliente e o service PAI-EAS estão na mesma VPC e região. Verifique também se as regras do grupo de segurança permitem tráfego na porta relevante.

Apêndice

Demonstração de service gRPC

Definição da API

  1. No diretório raiz do seu projeto, crie um arquivo chamado helloworld.proto para definir um service GreeterService que inclui um método SayHello.

    • Requisição: HelloRequest, contendo um campo string chamado name.

    • Resposta: HelloResponse, contendo um campo string chamado message.

    Clique para visualizar helloworld.proto

    syntax = "proto3";
    
    package helloworld;
    
    option go_package = "your-project/proto;helloworld";
    
    message HelloRequest {
      string name = 1;
    }
    
    message HelloResponse {
      string message = 1;
    }
    
    service GreeterService {
      rpc SayHello (HelloRequest) returns (HelloResponse);
    }
  2. Compile o arquivo .proto para gerar os arquivos de código helloworld_pb2_grpc.py e helloworld_pb2.py. O comando abaixo usa Python como exemplo.

    python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. helloworld.proto

2. Implantação do servidor

Implante o service no PAI-EAS. A estrutura do projeto é a seguinte:

my-grpc-demo
├── helloworld_pb2_grpc.py
├── helloworld_pb2.py
└── server.py  

Clique para visualizar server.py

import grpc
from concurrent import futures
import helloworld_pb2
import helloworld_pb2_grpc

# Implement the service logic.
class GreeterServicer(helloworld_pb2_grpc.GreeterServiceServicer):
    def SayHello(self, request, context):
        # Business logic: Concatenate a string.
        response_msg = f"Hello, {request.name}!"
        return helloworld_pb2.HelloResponse(message=response_msg)

def serve():
    # 1. Create a server with a thread pool.
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
  
    # 2. Register the service implementation with the server.
    helloworld_pb2_grpc.add_GreeterServiceServicer_to_server(GreeterServicer(), server)
   
    # 3. Listen on a port. This is the deployment address.
    port = "[::]:50051"
    server.add_insecure_port(port)
   
    print(f"Server started, listening on {port} ...")
    server.start()
   
    # 4. Block the main thread to keep the service running.
    server.wait_for_termination()

if __name__ == "__main__":
    serve()

Clique para visualizar a configuração JSON do service PAI-EAS

{
    "cloud": {
        "computing": {
            "instances": [
                {
                    "type": "ecs.c7.large"
                }
            ]
        }
    },
    "containers": [
        {
            "image": "eas-registry-vpc.cn-hangzhou.cr.aliyuncs.com/pai-eas/python-inference:py39-ubuntu2004",
            "port": 50051,
            "prepare": {
                "pythonRequirements": [
                    "grpcio",
                    "grpcio-tools"
                ]
            },
            "script": "python /mnt/data/server.py"
        }
    ],
    "metadata": {
        "cpu": 2,
        "disk": "30Gi",
        "enable_grpc": true,
        "instance": 1,
        "memory": 4000,
        "name": "grpc_test",
        "rpc": {
            "keepalive": 5000
        },
        "workspace_id": "your-workspace-id"
    },
    "storage": [
        {
            "mount_path": "/mnt/data/",
            "oss": {
                "path": "oss://my-oss/eas/my-grpc-demo/",
                "readOnly": false
            }
        }
    ]
}