Most tutorials for building an AI chat app start by spinning up a Node.js or Python backend server, configuring Docker, and babysitting an EC2 instance or container service.

You don't need any of that.

Combining a static HTML frontend with an Amazon API Gateway WebSocket API and AWS Lambda gives you real-time, bidirectional user interaction and token-by-token LLM streaming—with zero servers to manage, automatic scaling to zero when idle, and near-\$0 running costs.

In this step-by-step guide, you'll build and deploy a complete serverless streaming AI chat app on AWS using:

wss:// connections Before writing a single line of code, let's clear up a common misconception about AWS AI pricing:

amazon.nova-micro-v1:0), AWS's fastest and most economical text model, even uncredited testing costs Best of all, we'll use Bedrock's unified ConverseStream API—so if you ever want to switch to Meta Llama or Anthropic Claude, it's a one-line environment variable change.

Standard REST APIs force users to stare at a loading spinner until the LLM finishes generating its entire answer—and long responses easily hit gateway timeouts.

With API Gateway WebSockets, the browser keeps a persistent connection open. As Amazon Bedrock streams tokens to AWS Lambda, Lambda immediately pushes each chunk back through API Gateway to the browser in real time.

index.html from Amazon S3 (fronted by CloudFront).$connect Lambda saves the user's connectionId to DynamoDB."action": "sendMessage". API Gateway routes it to the ws-send-message Lambda.bedrock-runtime.converse_stream() using contentBlockDelta event from Bedrock, Lambda calls apigatewaymanagementapi.post_to_connection() to push the text chunk straight to the browser, finishing with a {"type": "done"} event.$disconnect deletes the | Service | Purpose | Cost Profile | |---|---|---| | Amazon S3 + CloudFront | Hosts static index.html over HTTPS | AWS Free Tier eligible | | API Gateway (WebSocket) | Manages persistent wss:// connections | 1M messages & 750K connection-mins/mo (Free Tier) | | AWS Lambda (Python 3.12) | Runs $connect ,$disconnect , and streaming logic | 1M requests/mo always free | | Amazon DynamoDB | Stores active connectionId records + TTL | 25 GB storage + generous on-demand Free Tier | | Amazon Bedrock | Serverless LLM inference ( amazon.nova-micro-v1:0 ) | Pay-per-token (covered by new-account AWS credits) | | IAM & CloudWatch Logs | Least-privilege security & execution logs | Free IAM / 5 GB CloudWatch Free Tier |

aws configure) us-east-1 Create a working folder on your machine so everything stays organized:

mkdir aws-serverless-llm-chat
cd aws-serverless-llm-chat

You can quickly verify access from your terminal:

aws bedrock list-foundation-models \
  --region us-east-1 \
  --by-provider Amazon \
  --query "modelSummaries[?contains(modelId, 'nova-micro')].modelId"

You should see "amazon.nova-micro-v1:0" in the output.

Create an on-demand DynamoDB table called WebSocketConnections to store each client's connectionId:

aws dynamodb create-table \
  --table-name WebSocketConnections \
  --attribute-definitions AttributeName=connectionId,AttributeType=S \
  --key-schema AttributeName=connectionId,KeyType=HASH \
  --billing-mode PAY_PER_REQUEST \
  --region us-east-1

Enable TTL (Time to Live) on the ttl attribute so abandoned connections clean themselves up automatically:

aws dynamodb update-time-to-live \
  --table-name WebSocketConnections \
  --time-to-live-specification "Enabled=true, AttributeName=ttl" \
  --region us-east-1

Our Lambda functions need permission to:

bedrock:InvokeModelWithResponseStream execute-api:ManageConnections First, grab your 12-digit AWS Account ID:

ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
echo $ACCOUNT_ID

Create trust-policy.json:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": { "Service": "lambda.amazonaws.com" },
      "Action": "sts:AssumeRole"
    }
  ]
}

Create the role and attach the basic CloudWatch logging policy:

aws iam create-role \
  --role-name ServerlessLLMWebSocketRole \
  --assume-role-policy-document file://trust-policy.json

aws iam attach-role-policy \
  --role-name ServerlessLLMWebSocketRole \
  --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

Now create lambda-permissions.json (replace <ACCOUNT_ID> with your Account ID):

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "DynamoDBConnectionsAccess",
      "Effect": "Allow",
      "Action": [
        "dynamodb:PutItem",
        "dynamodb:DeleteItem"
      ],
      "Resource": "arn:aws:dynamodb:us-east-1:<ACCOUNT_ID>:table/WebSocketConnections"
    },
    {
      "Sid": "BedrockNovaMicroStream",
      "Effect": "Allow",
      "Action": [
        "bedrock:InvokeModelWithResponseStream"
      ],
      "Resource": "arn:aws:bedrock:us-east-1::foundation-model/amazon.nova-micro-v1:0"
    },
    {
      "Sid": "ApiGatewayManageConnections",
      "Effect": "Allow",
      "Action": [
        "execute-api:ManageConnections"
      ],
      "Resource": "arn:aws:execute-api:us-east-1:<ACCOUNT_ID>:*/prod/POST/@connections/*"
    }
  ]
}

Security Tip: After Step 5 gives you your exact <API_ID>, tighten the ApiGatewayManageConnections resource ARN by replacing * with your <API_ID>.

Attach the inline policy:

aws iam put-role-policy \
  --role-name ServerlessLLMWebSocketRole \
  --policy-name ServerlessLLMInlinePolicy \
  --policy-document file://lambda-permissions.json

We'll create three small, focused Python 3.12 Lambda functions.

connect.py ( Runs whenever a user opens the chat page and establishes a WebSocket connection.

import os
import time
import boto3

dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table(os.environ["CONNECTIONS_TABLE"])

def lambda_handler(event, context):
    connection_id = event["requestContext"]["connectionId"]

    table.put_item(
        Item={
            "connectionId": connection_id,
            "ttl": int(time.time()) + 7200,  # Auto-expire after 2 hours
        }
    )

    return {"statusCode": 200, "body": "Connected"}

disconnect.py ( Runs when the browser closes or drops the connection.

import os
import boto3

dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table(os.environ["CONNECTIONS_TABLE"])

def lambda_handler(event, context):
    connection_id = event["requestContext"]["connectionId"]
    table.delete_item(Key={"connectionId": connection_id})
    return {"statusCode": 200, "body": "Disconnected"}

send_message.py (sendMessage route) This is the core of the application. It parses the incoming chat history, invokes Amazon Bedrock converse_stream, and streams every token delta back to the browser via post_to_connection.

import json
import os
import boto3
from botocore.exceptions import ClientError

REGION = os.environ.get("AWS_REGION", "us-east-1")
MODEL_ID = os.environ.get("MODEL_ID", "amazon.nova-micro-v1:0")

bedrock = boto3.client("bedrock-runtime", region_name=REGION)

def post_json(apigw_client, connection_id, payload):
    """Push a JSON frame back to the connected WebSocket client."""
    apigw_client.post_to_connection(
        ConnectionId=connection_id,
        Data=json.dumps(payload).encode("utf-8"),
    )

def lambda_handler(event, context):
    connection_id = event["requestContext"]["connectionId"]
    domain = event["requestContext"]["domainName"]
    stage = event["requestContext"]["stage"]

    # Build the Management API client dynamically from the WebSocket request context
    apigw = boto3.client(
        "apigatewaymanagementapi",
        endpoint_url=f"https://{domain}/{stage}",
    )

    try:
        body = json.loads(event.get("body") or "{}")
        messages = body.get("messages")

        # Support either a multi-turn "messages" array or a single "prompt" string
        if not messages:
            prompt = (body.get("prompt") or "").strip()
            if not prompt:
                post_json(apigw, connection_id, {"type": "error", "message": "Prompt cannot be empty."})
                return {"statusCode": 400, "body": "Empty prompt"}
            messages = [{"role": "user", "content": [{"text": prompt}]}]

        # Call Amazon Bedrock's unified ConverseStream API
        response = bedrock.converse_stream(
            modelId=MODEL_ID,
            system=[{"text": "You are a helpful, concise technical assistant."}],
            messages=messages,
            inferenceConfig={
                "maxTokens": 1024,
                "temperature": 0.7,
            },
        )

        # Forward every token chunk to the browser immediately as it arrives
        for event_chunk in response.get("stream", []):
            if "contentBlockDelta" in event_chunk:
                text = event_chunk["contentBlockDelta"]["delta"].get("text", "")
                if text:
                    post_json(apigw, connection_id, {"type": "chunk", "text": text})

        # Signal that the stream has finished
        post_json(apigw, connection_id, {"type": "done"})
        return {"statusCode": 200, "body": "Stream complete"}

    except apigw.exceptions.GoneException:
        # User closed their browser tab mid-stream — exit cleanly
        return {"statusCode": 410, "body": "Client disconnected"}
    except ClientError as exc:
        err_msg = exc.response["Error"]["Message"]
        post_json(apigw, connection_id, {"type": "error", "message": err_msg})
        return {"statusCode": 500, "body": err_msg}

Package and deploy all three functions with the AWS CLI (or paste the code directly into the AWS Lambda Console):

ROLE_ARN="arn:aws:iam::${ACCOUNT_ID}:role/ServerlessLLMWebSocketRole"

zip connect.zip connect.py
zip disconnect.zip disconnect.py
zip send_message.zip send_message.py

aws lambda create-function \
  --function-name ws-connect \
  --runtime python3.12 \
  --role "$ROLE_ARN" \
  --handler connect.lambda_handler \
  --zip-file fileb://connect.zip \
  --environment "Variables={CONNECTIONS_TABLE=WebSocketConnections}" \
  --region us-east-1

aws lambda create-function \
  --function-name ws-disconnect \
  --runtime python3.12 \
  --role "$ROLE_ARN" \
  --handler disconnect.lambda_handler \
  --zip-file fileb://disconnect.zip \
  --environment "Variables={CONNECTIONS_TABLE=WebSocketConnections}" \
  --region us-east-1

aws lambda create-function \
  --function-name ws-send-message \
  --runtime python3.12 \
  --role "$ROLE_ARN" \
  --handler send_message.lambda_handler \
  --zip-file fileb://send_message.zip \
  --timeout 30 \
  --memory-size 256 \
  --environment "Variables={MODEL_ID=amazon.nova-micro-v1:0}" \
  --region us-east-1

Important: Notice --timeout 30 on ws-send-message. Lambda's default 3-second timeout will cut off LLM responses mid-sentence!

The quickest way to wire up the routes (and automatically grant API Gateway permission to invoke your Lambdas) is in the AWS Console:

ServerlessLLMChatAPI $request.body.action ws-connect ws-disconnect prod

wss://<your-api-id>.execute-api.us-east-1.amazonaws.com/prod

Now let's build a sleek, dependency-free index.html file. No React, no bundler, no node_modules—just clean HTML, CSS, and the browser's built-in WebSocket API.

Replace YOUR_WEBSOCKET_URL with the wss://... URL from Step 5:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Serverless AWS Streaming LLM Chat</title>
  <style>
    :root {
      --bg: #0f172a;
      --panel: #1e293b;
      --text: #f8fafc;
      --muted: #94a3b8;
      --user: #2563eb;
      --bot: #334155;
      --border: #475569;
      --ok: #22c55e;
      --warn: #f59e0b;
    }
    * { box-sizing: border-box; }
    body {
      margin: 0;
      font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
      background: var(--bg);
      color: var(--text);
      display: flex;
      flex-direction: column;
      height: 100vh;
    }
    header {
      padding: 1rem 1.5rem;
      background: var(--panel);
      border-bottom: 1px solid var(--border);
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    header h1 { margin: 0; font-size: 1.05rem; }
    #status {
      font-size: 0.85rem;
      color: var(--muted);
      display: flex;
      align-items: center;
      gap: 0.45rem;
    }
    .dot {
      width: 9px;
      height: 9px;
      border-radius: 50%;
      background: var(--warn);
      display: inline-block;
    }
    .dot.connected { background: var(--ok); }
    #chat {
      flex: 1;
      overflow-y: auto;
      padding: 1.5rem;
      display: flex;
      flex-direction: column;
      gap: 1rem;
      max-width: 820px;
      width: 100%;
      margin: 0 auto;
    }
    .msg {
      padding: 0.85rem 1.05rem;
      border-radius: 0.8rem;
      max-width: 85%;
      white-space: pre-wrap;
      line-height: 1.55;
    }
    .user { align-self: flex-end; background: var(--user); }
    .assistant { align-self: flex-start; background: var(--bot); }
    .error { align-self: center; background: #7f1d1d; font-size: 0.9rem; }
    form {
      display: flex;
      gap: 0.75rem;
      padding: 1rem 1.5rem;
      background: var(--panel);
      border-top: 1px solid var(--border);
      justify-content: center;
    }
    input {
      flex: 1;
      max-width: 700px;
      padding: 0.75rem 1rem;
      border-radius: 0.5rem;
      border: 1px solid var(--border);
      background: var(--bg);
      color: var(--text);
      font-size: 1rem;
    }
    button {
      padding: 0.75rem 1.35rem;
      border: none;
      border-radius: 0.5rem;
      background: var(--user);
      color: #fff;
      font-weight: 600;
      cursor: pointer;
    }
    button:disabled { opacity: 0.5; cursor: not-allowed; }
  </style>
</head>
<body>
  <header>
    <h1>Serverless Streaming AI Chat (Amazon Nova Micro)</h1>
    <span id="status"><span class="dot" id="dot"></span><span id="status-text">Connecting...</span></span>
  </header>

  <main id="chat"></main>

  <form id="chat-form">
    <input id="prompt" type="text" placeholder="Ask anything..." autocomplete="off" required />
    <button id="send-btn" type="submit" disabled>Send</button>
  </form>

  <script>
    const WS_URL = "YOUR_WEBSOCKET_URL"; // e.g. wss://abc123.execute-api.us-east-1.amazonaws.com/prod
    const chatEl = document.getElementById("chat");
    const dotEl = document.getElementById("dot");
    const statusTextEl = document.getElementById("status-text");
    const formEl = document.getElementById("chat-form");
    const inputEl = document.getElementById("prompt");
    const sendBtn = document.getElementById("send-btn");

    let socket;
    let currentBotEl = null;
    let currentBotText = "";
    const history = [];

    function appendMessage(role, text = "") {
      const div = document.createElement("div");
      div.className = `msg ${role}`;
      div.textContent = text;
      chatEl.appendChild(div);
      chatEl.scrollTop = chatEl.scrollHeight;
      return div;
    }

    function connect() {
      socket = new WebSocket(WS_URL);

      socket.onopen = () => {
        dotEl.classList.add("connected");
        statusTextEl.textContent = "Connected";
        sendBtn.disabled = false;
      };

      socket.onclose = () => {
        dotEl.classList.remove("connected");
        statusTextEl.textContent = "Reconnecting...";
        sendBtn.disabled = true;
        setTimeout(connect, 2000);
      };

      socket.onerror = () => {
        statusTextEl.textContent = "Connection error";
      };

      socket.onmessage = (event) => {
        const data = JSON.parse(event.data);

        if (data.type === "chunk") {
          if (!currentBotEl) {
            currentBotEl = appendMessage("assistant", "");
            currentBotText = "";
          }
          currentBotText += data.text;
          currentBotEl.textContent = currentBotText;
          chatEl.scrollTop = chatEl.scrollHeight;
        } else if (data.type === "done") {
          if (currentBotText) {
            history.push({ role: "assistant", content: [{ text: currentBotText }] });
          }
          currentBotEl = null;
          currentBotText = "";
          sendBtn.disabled = false;
          inputEl.focus();
        } else if (data.type === "error") {
          appendMessage("error", `Error: ${data.message}`);
          currentBotEl = null;
          sendBtn.disabled = false;
        }
      };
    }

    formEl.addEventListener("submit", (e) => {
      e.preventDefault();
      const text = inputEl.value.trim();
      if (!text || socket.readyState !== WebSocket.OPEN) return;

      appendMessage("user", text);
      history.push({ role: "user", content: [{ text }] });

      // Send the last 10 turns to preserve context while keeping token usage low
      socket.send(
        JSON.stringify({
          action: "sendMessage",
          messages: history.slice(-10),
        })
      );

      inputEl.value = "";
      sendBtn.disabled = true;
    });

    connect();
  </script>
</body>
</html>
aws s3 mb s3://my-serverless-llm-chat-ui --region us-east-1
aws s3 cp index.html s3://my-serverless-llm-chat-ui/index.html

Open your CloudFront URL (or local index.html), wait for the green Connected indicator, and ask a question like "Explain AWS Lambda cold starts in 3 bullet points." You'll see tokens stream into the chat bubble in real time.

| Error | Likely Cause | Fix | |---|---|---| | AccessDeniedException (Bedrock) | Model not enabled or wrong IAM ARN | Confirm amazon.nova-micro-v1:0 inus-east-1 and verifybedrock:InvokeModelWithResponseStream in IAM. | | ForbiddenException onpost_to_connection | Missing execute-api:ManageConnections permission | Check the IAM resource ARN matches your region, account ID, API ID, and stage ( prod ). | | Endpoint request timed out | Lambda timeout too low or >29s generation | Increase Lambda timeout to 30s (or use the async worker pattern below for >29s responses). | | Connection closes immediately | $connect Lambda failed | Inspect /aws/lambda/ws-connect in CloudWatch Logs; verifyCONNECTIONS_TABLE env var. |

When you're done experimenting, delete your resources to ensure \$0 ongoing cost:

WebSocketConnections ServerlessLLMWebSocketRole What are you building with serverless AI? Drop a comment below

原文来源:dev.to