Giới thiệu
Trong phần trước của loạt bài viết này, chúng ta đã triển khai Strands Agents SDK với bộ công cụ khởi động Amazon Bedrock AgentCore. Bài viết này sẽ hướng dẫn bạn cách sử dụng Custom Agent thay vì bộ công cụ khởi động AgentCore, giúp chúng ta có toàn quyền kiểm soát giao diện HTTP của agent và triển khai nó lên Amazon Bedrock AgentCore Runtime.
Điều kiện tiên quyết là bạn đã thiết lập theo hướng dẫn trong bài viết "Exposing existing Amazon API Gateway REST API via MCP and Gateway endpoint". Điều này bao gồm việc tạo Cognito User Pool, Cognito Resource Server và Cognito User Pool Client, và cuối cùng là có URL của AgentCore Gateway.
Phát triển Custom Agent
Mã nguồn đầy đủ đã được cung cấp trong kho GitHub amazon-agentcore-runtime-to-gateway-custom-agent-demo.
Phương pháp này cho thấy cách triển khai một custom agent bằng FastAPI và Docker, tuân theo các yêu cầu của AgentCore Runtime. Các yêu cầu bao gồm:
- Máy chủ FastAPI: Framework web để xử lý yêu cầu.
- /invocations Endpoint: POST endpoint để tương tác với agent.
- /ping Endpoint: GET endpoint để kiểm tra tình trạng.
- Docker Container: Gói triển khai container ARM64.
Cài đặt phụ thuộc
Đầu tiên, chúng ta định nghĩa các phụ thuộc cần thiết:
plaintext
fastapi
uvicorn[standard]
pydantic
httpx
strands-agents
requests
aws-opentelemetry-distro>=0.10.1
boto3
Tạo FastAPI Instance
Custom agent của chúng ta sẽ tương tự như cách triển khai với bộ công cụ khởi động AgentCore từ phần trước. Ta tạo một instance FastAPI và các mô hình yêu cầu và phản hồi:
python
app = FastAPI(title="Custom Strands Agent Server", version="1.0.0")
class InvocationRequest(BaseModel):
input: Dict[str, Any]
class InvocationResponse(BaseModel):
output: Dict[str, Any]
Xây dựng Logic Kinh Doanh
Logic kinh doanh trước đây nằm trong hàm invoke với bộ công cụ khởi động đã trở thành một phần của hàm invocations
, được định nghĩa như sau:
python
@app.post("/invocations", response_model=InvocationResponse)
async def invoke_agent(request: InvocationRequest):
...
Chúng ta cũng định nghĩa endpoint GET ping để kiểm tra tình trạng:
python
@app.get("/ping")
async def ping():
return {"status": "healthy"}
Và chạy máy chủ web FastAPI:
python
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8080)
Hãy nhớ thay thế giá trị của biến gateway_url
trong phần mã với URL của AgentCore Gateway.
Kiểm tra Agent Locally
Chúng ta có thể khởi động agent của mình cục bộ và kiểm tra bằng lệnh sau:
bash
curl -X POST http://localhost:8080/invocations \
-H "Content-Type: application/json" \
-d '{"input": {"prompt": "Cung cấp thông tin về đơn hàng với id 12345"}}
Người dùng Windows có thể dùng HTTPie để thử nghiệm:
bash
http POST http://localhost:8080/invocations input[prompt]="Cung cấp thông tin về đơn hàng với id 12345"
Docker hóa Custom Agent
Chúng ta cần xây dựng một hình ảnh Docker ARM64 cho ứng dụng của mình. Dưới đây là Dockerfile:
plaintext
# Sử dụng base image ARM64 Python
FROM --platform=linux/arm64 ghcr.io/astral-sh/uv:python3.13-bookworm-slim
WORKDIR /app
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
COPY agentcore_runtime_custom_agent_demo.py ./
COPY agent_core_utils.py ./
EXPOSE 8080
CMD ["opentelemetry-instrument", "uvicorn", "agentcore_runtime_custom_agent_demo:app", "--host", "0.0.0.0", "--port", "8080"]
Chúng ta cần xây dựng hình ảnh Docker và tải nó lên kho ECR. Dưới đây là các lệnh để thực hiện điều này:
bash
sudo docker build --no-cache -t agentcore-runtime-custom-agent-demo:v1 .
aws ecr get-login-password --region us-east-1 | sudo docker login --username AWS --password-stdin {account_id}.dkr.ecr.{region}.amazonaws.com
aws ecr create-repository --repository-name agentcore-runtime-custom-agent-demo --image-scanning-configuration scanOnPush=true --region {region}
sudo docker tag agentcore-runtime-custom-agent-demo:v1 {account_id}.dkr.ecr.{region}.amazonaws.com/agentcore-runtime-custom-agent-demo:v1
sudo docker push {account_id}.dkr.ecr.{region}.amazonaws.com/agentcore-runtime-custom-agent-demo:v1
Hãy thay thế {account_id}
và {region}
bằng giá trị của bạn.
Triển khai Custom Agent
Chúng ta triển khai custom agent lên AgentCore Runtime với đoạn mã sau:
python
import boto3
import os
os.environ['AWS_DEFAULT_REGION'] = 'us-east-1'
client = boto3.client('bedrock-agentcore-control')
response = client.create_agent_runtime(
agentRuntimeName='strands_custom_agent',
agentRuntimeArtifact={
'containerConfiguration': {
'containerUri': '{YOUR_ECR_REPO_URI}'
}
},
networkConfiguration={"networkMode": "PUBLIC"},
roleArn='{YOUR_IAM_ROLE_ARN}'
)
Hãy thay thế {YOUR_ECR_REPO_URI}
và {YOUR_IAM_ROLE_ARN}
với các giá trị tương ứng của bạn.
Gọi Custom Agent
Chúng ta gọi custom agent bằng AWS SDK cho Python:
python
import boto3
import json
import os
agent_core_client = boto3.client('bedrock-agentcore', region_name=os.environ['AWS_DEFAULT_REGION'])
payload = json.dumps({
"input": {"prompt": "Cung cấp thông tin về đơn hàng với id 1"}
})
response = agent_core_client.invoke_agent_runtime(
agentRuntimeArn="{YOUR_RUNTIME_ARN}",
qualifier="DEFAULT",
payload=payload
)
response_body = response['response'].read()
response_data = json.loads(response_body)
print("Phản hồi từ agent:", response_data)
Hãy thay thế giá trị của biến agentRuntimeArn
với ARN của AgentCore Runtime mà bạn đã triển khai.
Quan sát Custom Agent
Với việc sử dụng AWS Distro cho Open Telemetry (ADOT), các thông tin về Agents, Sessions và Traces sẽ được cung cấp ngay lập tức trong dịch vụ CloudWatch GenAI Observability cùng với logging và metrics cho việc gọi model.
Kết luận
Trong bài viết này, chúng ta đã viết lại triển khai để sử dụng Custom Agent thay cho bộ công cụ khởi động Bedrock AgentCore, cho phép chúng ta kiểm soát toàn bộ giao diện HTTP của agent và triển khai nó trên Amazon Bedrock AgentCore Runtime.
Trong bài viết tiếp theo, chúng ta sẽ tìm hiểu cách triển khai Custom Agent tương tự bằng ngôn ngữ lập trình Java với framework Spring AI. Hãy theo dõi để khám phá các dịch vụ AgentCore khác như Memory bắt đầu với bộ nhớ ngắn hạn.
Đừng quên kiểm tra loạt bài viết về Amazon Bedrock AgentCore Gateway của tôi!