|
| 1 | +""" |
| 2 | +FastAPI backend for Market Trends Agent React UI. |
| 3 | +Proxies chat requests to the deployed AgentCore Runtime agent. |
| 4 | +""" |
| 5 | + |
| 6 | +import json |
| 7 | +import os |
| 8 | +import logging |
| 9 | +from pathlib import Path |
| 10 | +from fastapi import FastAPI |
| 11 | +from fastapi.middleware.cors import CORSMiddleware |
| 12 | +from pydantic import BaseModel, Field |
| 13 | +import boto3 |
| 14 | +from botocore.config import Config |
| 15 | + |
| 16 | +logging.basicConfig(level=logging.INFO) |
| 17 | +logger = logging.getLogger(__name__) |
| 18 | + |
| 19 | +app = FastAPI(title="Market Trends Agent API") |
| 20 | + |
| 21 | +# Allow React dev server to connect |
| 22 | +app.add_middleware( |
| 23 | + CORSMiddleware, |
| 24 | + allow_origins=["http://localhost:3000"], |
| 25 | + allow_methods=["*"], |
| 26 | + allow_headers=["*"], |
| 27 | +) |
| 28 | + |
| 29 | +# AWS region for AgentCore Runtime |
| 30 | +REGION = os.getenv("AWS_REGION", "us-east-1") |
| 31 | + |
| 32 | +# Boto3 client with extended timeout for agent responses (browser + LLM calls can be slow) |
| 33 | +boto_config = Config(read_timeout=300, retries={"max_attempts": 2}) |
| 34 | +agentcore_client = boto3.client("bedrock-agentcore", region_name=REGION, config=boto_config) |
| 35 | + |
| 36 | + |
| 37 | +def load_agent_arn() -> str | None: |
| 38 | + """Load deployed agent ARN from the .agent_arn file created by deploy.py""" |
| 39 | + arn_file = Path(__file__).parent / ".agent_arn" |
| 40 | + if arn_file.exists(): |
| 41 | + return arn_file.read_text().strip() |
| 42 | + return None |
| 43 | + |
| 44 | + |
| 45 | +class ChatRequest(BaseModel): |
| 46 | + message: str = Field(..., max_length=4000) |
| 47 | + session_id: str = Field(default="", max_length=100) |
| 48 | + |
| 49 | + |
| 50 | +@app.get("/api/health") |
| 51 | +def health(): |
| 52 | + """Health check — also reports whether the agent is deployed""" |
| 53 | + arn = load_agent_arn() |
| 54 | + return {"status": "ok", "agent_deployed": arn is not None, "region": REGION} |
| 55 | + |
| 56 | + |
| 57 | +@app.post("/api/chat") |
| 58 | +def chat(req: ChatRequest): |
| 59 | + """Send a message to the deployed AgentCore agent and return the response""" |
| 60 | + arn = load_agent_arn() |
| 61 | + if not arn: |
| 62 | + return {"error": "Agent not deployed. Run 'uv run python deploy.py' first."} |
| 63 | + |
| 64 | + try: |
| 65 | + # Build invocation payload matching the agent's expected format |
| 66 | + payload = json.dumps({"prompt": req.message, "session_id": req.session_id}).encode("utf-8") |
| 67 | + params: dict = {"agentRuntimeArn": arn, "payload": payload} |
| 68 | + |
| 69 | + # Pass session ID for memory continuity across messages |
| 70 | + if req.session_id: |
| 71 | + params["runtimeSessionId"] = req.session_id |
| 72 | + |
| 73 | + logger.info(f"Invoking agent | session={req.session_id[:24]}...") |
| 74 | + response = agentcore_client.invoke_agent_runtime(**params) |
| 75 | + |
| 76 | + # Read the response body (handles both streaming and standard responses) |
| 77 | + if "response" in response: |
| 78 | + body = response["response"].read().decode("utf-8") |
| 79 | + else: |
| 80 | + body = str(response) |
| 81 | + |
| 82 | + # AgentCore often returns a JSON-encoded string (e.g. "\"hello\\nworld\"") |
| 83 | + # Unwrap it so the frontend receives clean text with real newlines |
| 84 | + try: |
| 85 | + parsed = json.loads(body) |
| 86 | + if isinstance(parsed, str): |
| 87 | + body = parsed |
| 88 | + except (json.JSONDecodeError, TypeError): |
| 89 | + pass |
| 90 | + |
| 91 | + # Final safety: replace any remaining literal \n sequences with real newlines |
| 92 | + body = body.replace("\\n", "\n") |
| 93 | + |
| 94 | + return {"response": body, "session_id": req.session_id} |
| 95 | + |
| 96 | + except Exception as e: |
| 97 | + logger.error(f"Agent invocation error: {e}") |
| 98 | + return {"error": "Agent request failed. Check server logs for details."} |
| 99 | + |
| 100 | + |
| 101 | +if __name__ == "__main__": |
| 102 | + import uvicorn |
| 103 | + uvicorn.run(app, host="0.0.0.0", port=8001) |
0 commit comments