Implementar o Tracing com AWS X-Ray e o AWS X-Ray SDK em uma infraestrutura serverless da AWS pode parecer complicado, mas é essencial para monitorar e otimizar o desempenho das suas aplicações. Este artigo detalha como integrar o tracing em vários serviços da AWS, incluindo API Gateway (REST API), funções Lambda, Systems Manager Parameter Store e o modelo Amazon Bedrock. Vamos mostrar como configurar tudo isso de forma clara e direta.
Este guia é uma extensão de um artigo anterior sobre como interagir com modelos Amazon Bedrock usando API Gateway e funções Lambda. A infraestrutura existente foi aprimorada com configurações para Tracing com AWS X-Ray. Inicialmente, a configuração utilizava uma HTTP API, que não possui suporte nativo para X-Ray. Por isso, foi adotada uma REST API para habilitar o tracing.
Para mais informações sobre o API Gateway tracing com X-Ray, consulte a documentação oficial. A documentação do AWS X-Ray SDK pode ser encontrada aqui.
A função Main Lambda e a configuração da função IAM no template CloudFormation infrastructure/tracing-rest-api.yaml são cruciais para o processo.
“`
Parameters:
BedrockModelId:
Type: String
Default: ‘amazon.titan-text-express-v1’
LambdaLayerVersionArn:
Type: String
Default: ‘arn:aws:lambda:
Resources:
MainLambdaFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: MainLambdaFunction
Description: Make requests to Bedrock models
Runtime: python3.12
Handler: index.lambda_handler
Role: !GetAtt MainLambdaExecutionRole.Arn
Timeout: 30
MemorySize: 512
TracingConfig:
Mode: Active
Layers:
– !Ref LambdaLayerVersionArn
Environment:
Variables:
BEDROCK_MODEL_ID: !Ref BedrockModelId
Code:
ZipFile: |
import json
import boto3
import os
import logging
from botocore.exceptions import ClientError
from aws_xray_sdk.core import patch_all, xray_recorder
# Initialize logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# Initialize the X-Ray SDK
patch_all()
# Initialize the Bedrock Runtime client
bedrock_runtime = boto3.client(‘bedrock-runtime’)
def lambda_handler(event, context):
try:
# Retrieve the model ID from environment variables
model_id = os.environ[‘BEDROCK_MODEL_ID’]
# Validate the input
input_text = event.get(“queryStringParameters”, {}).get(“inputText”)
if not input_text:
logger.error(‘Input text is missing in the request’)
raise ValueError(“Input text is required in the request query parameters.”)
# Prepare the payload for invoking the Bedrock model
payload = json.dumps({
“inputText”: input_text,
“textGenerationConfig”: {
“maxTokenCount”: 8192,
“stopSequences”: [],
“temperature”: 0,
“topP”: 1
}
})
logger.info(‘Payload for Bedrock model: %s’, payload)
# Create a subsegment for the Bedrock model invocation
with xray_recorder.in_subsegment(‘Bedrock InvokeModel’) as subsegment:
# Invoke the Bedrock model
response = bedrock_runtime.invoke_model(
modelId=model_id,
contentType=”application/json”,
accept=”application/json”,
body=payload
)
logger.info(‘Response from Bedrock model: %s’, response)
# Check if the ‘body’ exists in the response and handle it correctly
if ‘body’ not in response or not response[‘body’]:
logger.error(‘Response body is empty’)
raise ValueError(“Response body is empty.”)
# Read and process the response
response_body = json.loads(response[‘body’].read().decode(‘utf-8’))
logger.info(‘Processed response body: %s’, response_body)
return {
‘statusCode’: 200,
‘body’: json.dumps(response_body)
}
except ClientError as e:
logger.error(‘ClientError: %s’, e)
return {
‘statusCode’: 500,
‘body’: json.dumps({“error”: “Error interacting with the Bedrock API”})
}
except ValueError as e:
logger.error(‘ValueError: %s’, e)
return {
‘statusCode’: 400,
‘body’: json.dumps({“error”: str(e)})
}
except Exception as e:
logger.error(‘Exception: %s’, e)
return {
‘statusCode’: 500,
‘body’: json.dumps({“error”: “Internal Server Error”})
}
MainLambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
RoleName: MainLambdaExecutionRole
AssumeRolePolicyDocument:
Version: ‘2012-10-17’
Statement:
– Effect: Allow
Principal:
Service:
– lambda.amazonaws.com
Action:
– sts:AssumeRole
ManagedPolicyArns:
– arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
– PolicyName: BedrockAccessPolicy
PolicyDocument:
Version: ‘2012-10-17’
Statement:
– Effect: Allow
Action:
– bedrock:InvokeModel
– bedrock:ListFoundationModels
Resource: ‘*’
– PolicyName: XRayAccessPolicy
PolicyDocument:
Version: ‘2012-10-17’
Statement:
– Effect: Allow
Action:
– xray:PutTelemetryRecords
– xray:PutAnnotation
– xray:PutTraceSegments
Resource: ‘*’
“`
Para seguir este guia, você precisará de uma conta AWS com permissões para criar e gerenciar recursos, além do AWS CLI instalado na sua máquina local.
Implementando o Tracing com AWS X-Ray
Antes de começar, caso a infraestrutura do artigo anterior não tenha sido configurada, siga os passos de 1 a 4 deste artigo antes de prosseguir com os passos de deployment abaixo.
O primeiro passo é criar uma Lambda layer que inclua o AWS X-Ray SDK. Use o ARN da versão da layer no template CloudFormation tracing-rest-api.yaml. Veja o comando para criar a layer:
“`
aws lambda publish-layer-version –layer-name aws-xray-sdk-layer –zip-file fileb://infrastructure/aws-xray-sdk-layer-layer/aws-xray-sdk-layer-layer.zip –compatible-runtimes python3.12
“`
Em seguida, atualize a CloudFormation stack existente para habilitar o X-Ray tracing e fazer a transição de uma HTTP API para uma REST API. Use o seguinte comando:
“`
aws cloudformation update-stack \
–stack-name apigw-lambda-bedrock \
–template-body file://infrastructure/tracing-rest-api.yaml \
–capabilities CAPABILITY_NAMED_IAM \
–disable-rollback
“`
Para testar a API, recupere a Invoke URL para o API Gateway Stage utilizando o script retrieve_invoke_url_rest_api.sh. Em seguida, use o CURL para testar a API.
“`
./scripts/retrieve_invoke_url_rest_api.sh
export APIGW_TOKEN=’token_value’
curl -s -X GET -H “Authorization: Bearer $APIGW_TOKEN” “https://api_id.execute-api.eu-central-1.amazonaws.com/dev/invoke?inputText=your_question” | jq -r ‘.results[0].outputText’
“`
Para visualizar o X-Ray trace map e a segments timeline, navegue até o console da AWS: CloudWatch -> X-Ray traces -> Traces. Na seção Traces, uma lista de trace IDs será exibida. Ao clicar em um trace ID, você verá o Trace map, a Segments timeline e os Logs associados.
Para manter sua conta organizada, após os testes, limpe os recursos excluindo a versão da Lambda layer, o token do Parameter Store e a CloudFormation stack. Utilize os seguintes comandos:
“`
aws lambda delete-layer-version –layer-name aws-xray-sdk-layer –version-number
aws ssm delete-parameter –name “AuthorizationLambdaToken”
aws cloudformation delete-stack –stack-name apigw-lambda-bedrock
“`
A integração do AWS X-Ray em uma infraestrutura serverless oferece insights valiosos sobre o desempenho de APIs e funções Lambda. Além disso, facilita a análise das interações com outros serviços AWS, como Systems Manager e Bedrock. Essa visibilidade aprimorada simplifica a depuração, otimiza o desempenho e garante um monitoramento eficaz do sistema.
Este conteúdo foi auxiliado por Inteligência Artificial, mas escrito e revisado por um humano.
Via Dev.to