How to Integrate Anthropic for insurance with Cloudflare Workers for AI agents

By Cyprian AaronsUpdated 2026-04-21
anthropic-for-insurancecloudflare-workersai-agents

Why this integration matters

If you’re building AI agents for insurance, you need two things: a strong model for reasoning over policy, claims, and underwriting language, and an edge runtime that can sit close to users and systems. Anthropic gives you the model layer; Cloudflare Workers gives you the low-latency execution layer for routing requests, enforcing guardrails, and calling internal services.

The useful pattern here is not “chatbot plus serverless.” It’s an agent gateway: Cloudflare Workers receives the request, applies policy checks, forwards the right context to Anthropic, then returns a structured response your insurance workflow can trust.

Prerequisites

  • A Cloudflare account with Workers enabled
  • Python 3.10+
  • pip installed
  • Anthropic API key
  • Cloudflare API token with permission to deploy Workers
  • wrangler installed and authenticated
  • Basic familiarity with HTTP APIs and JSON payloads
  • An insurance use case ready to test:
    • claims triage
    • policy Q&A
    • underwriting document summarization

Integration Steps

  1. Install the SDKs and set environment variables

    You’ll use Anthropic from Python for local development and validation, then deploy the Worker as the edge entrypoint.

    pip install anthropic requests python-dotenv
    npm install -g wrangler
    wrangler login
    

    Set your secrets locally:

    export ANTHROPIC_API_KEY="your_anthropic_key"
    export CLOUDFLARE_ACCOUNT_ID="your_account_id"
    export CLOUDFLARE_API_TOKEN="your_cloudflare_token"
    
  2. Create a Python client for Anthropic

    This is your baseline integration test. For insurance workflows, keep prompts narrow and force structured output so downstream systems can parse it.

    import os
    from anthropic import Anthropic
    
    client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
    
    def summarize_claim(note: str) -> str:
        response = client.messages.create(
            model="claude-3-5-sonnet-latest",
            max_tokens=300,
            temperature=0,
            system=(
                "You are an insurance operations assistant. "
                "Return concise, factual output only."
            ),
            messages=[
                {
                    "role": "user",
                    "content": f"""
                    Summarize this claim note into:
                    - claim type
                    - severity
                    - recommended next action
    
                    Note:
                    {note}
                    """
                }
            ],
        )
        return response.content[0].text
    
    if __name__ == "__main__":
        print(summarize_claim("Rear-end collision. No injuries reported. Vehicle drivable."))
    
  3. Build a Cloudflare Worker that forwards requests to Anthropic

    In production, the Worker should act as the public agent endpoint. It can validate input, enrich context from KV/D1/Queues later, then call Anthropic through its API.

    Create worker.py logic conceptually in Python first so the request/response contract is clear:

    import json
    import os
    import requests
    
    ANTHROPIC_API_KEY = os.environ["ANTHROPIC_API_KEY"]
    
    def handler(request_body: dict) -> dict:
        prompt = request_body["prompt"]
    
        headers = {
            "x-api-key": ANTHROPIC_API_KEY,
            "anthropic-version": "2023-06-01",
            "content-type": "application/json",
        }
    
        payload = {
            "model": "claude-3-5-sonnet-latest",
            "max_tokens": 250,
            "temperature": 0,
            "system": "You are an insurance agent assistant.",
            "messages": [
                {"role": "user", "content": prompt}
            ],
        }
    
        resp = requests.post(
            "https://api.anthropic.com/v1/messages",
            headers=headers,
            data=json.dumps(payload),
            timeout=30,
        )
        resp.raise_for_status()
        return resp.json()
    
  4. Deploy the Worker using Wrangler and bind secrets

    Cloudflare Workers runs JavaScript/TypeScript at the edge, but deployment is still straightforward from your local machine. The important part is wiring secrets correctly so your worker can call Anthropic without hardcoding credentials.

    Example wrangler.toml:

    name = "insurance-agent-gateway"
    main = "src/index.ts"
    compatibility_date = "2024-11-01"
    
    [vars]
    MODEL_NAME = "claude-3-5-sonnet-latest"
    

    Set secrets:

    wrangler secret put ANTHROPIC_API_KEY
    
  5. Call the Worker from Python as your agent entrypoint

    Your app should talk to Cloudflare Workers, not directly to Anthropic. That gives you one place for auth, logging, rate limits, and routing across multiple agent tools.

     import os
     import requests
    
     WORKER_URL = os.environ["WORKER_URL"]
    
     def ask_agent(prompt: str) -> dict:
         response = requests.post(
             WORKER_URL,
             json={"prompt": prompt},
             timeout=30,
         )
         response.raise_for_status()
         return response.json()
    
     if __name__ == "__main__":
         result = ask_agent("Classify this as a first notice of loss or not: Water leak in kitchen overnight.")
         print(result)
    

Testing the Integration

Use a claim triage prompt that should produce deterministic output.

import json
import os
import requests

WORKER_URL = os.environ["WORKER_URL"]

payload = {
    "prompt": """
    Classify this insurance message:
    'Customer reports hail damage to roof after storm last night.
    Photos attached. No interior damage reported.'

    Return JSON with keys: claim_type, severity, action.
    """
}

resp = requests.post(WORKER_URL, json=payload, timeout=30)
resp.raise_for_status()

print(json.dumps(resp.json(), indent=2))

Expected output:

{
  "claim_type": "property_damage",
  "severity": "medium",
  "action": "route_to_adjuster_and_request_estimate"
}

If you get a valid JSON object back consistently, your request path is working end to end: Python client → Cloudflare Worker → Anthropic API → structured response.

Real-World Use Cases

  • Claims intake triage

    • Classify FNOL submissions at the edge.
    • Route urgent cases to human adjusters before they hit core systems.
  • Policy servicing assistant

    • Answer coverage questions from policyholders.
    • Pull supporting context from internal systems via Worker fetch calls.
  • Underwriting document review

    • Summarize PDFs or broker submissions.
    • Extract risk signals and generate review notes for underwriters.

Production Notes

Keep the Worker thin. Put orchestration at the edge, not business logic in prompts.

Use these controls early:

  • strict JSON schemas for outputs
  • request timeouts and retries with backoff
  • per-route rate limits in Workers
  • audit logs for every insurance decision path

Keep learning

By Cyprian Aarons, AI Consultant at Topiax.

Want the complete 8-step roadmap?

Grab the free AI Agent Starter Kit — architecture templates, compliance checklists, and a 7-email deep-dive course.

Get the Starter Kit

Related Guides