Khi vận hành page-agent – tác nhân tự động điều phối tác vụ trên trang web – ở quy mô production, mình nhận ra một sự thật phũ phàng: không có một mô hình LLM nào "ngon" cho mọi tình huống. GPT-5.5 mạnh về reasoning chuỗi dài, nhưng latency p99 khi chạy action planning có lúc vượt 900ms; Gemini 2.5 Pro lại có context window khổng lồ và giá rẻ hơn 17%, nhưng đôi khi "ảo giác" với các bước click phức tạp. Đó là lý do bài viết này tồn tại: chia sẻ cách mình xây dựng smart router để page-agent chọn đúng model cho đúng task, đồng thời tối ưu tới 62% chi phí hàng tháng.

Bối cảnh: vì sao routing LLM là "must-have" chứ không phải "nice-to-have"

Một page-agent production phải xử lý hàng triệu task mỗi tháng, mỗi task lại phân rã thành nhiều sub-task với đặc thù khác nhau:

Nếu gọi một model duy nhất cho mọi việc, bạn sẽ đốt tiền oan và độ trễ tích lũy. Routing thông minh giải quyết chính xác vấn đề này.

Kiến trúc routing: 3 lớp quyết định

Sau 4 tháng tinh chỉnh, mình hạ cánh vào kiến trúc 3 lớp như dưới đây:

  1. Layer 1 – Static rules: route theo tag task (vd: perception → Gemini Flash, planning → GPT-5.5).
  2. Layer 2 – Dynamic scoring: chấm điểm theo cost × latency × success_rate từ telemetry 24h gần nhất.
  3. Layer 3 – Fallback circuit: nếu model chính timeout/429, tự động chuyển sang model phụ.

Code dưới đây là router tối giản mà bạn có thể cắm vào page-agent ngay hôm nay thông qua Đăng ký tại đây để lấy key.

// page-agent router - production version
// File: src/router/llm-router.ts
import OpenAI from "openai";

type TaskTag = "perception" | "planning" | "reflection" | "summarization";

interface RouteDecision {
  model: string;
  reason: string;
  budgetUsd: number;
}

const HOLYSHEEP_BASE = "https://api.holysheep.ai/v1";
const client = new OpenAI({
  apiKey: process.env.HOLYSHEEP_API_KEY || "YOUR_HOLYSHEEP_API_KEY",
  baseURL: HOLYSHEEP_BASE,
});

// Bảng giá output USD/MTok (snapshot 2026)
const PRICE_TABLE: Record = {
  "gpt-5.5": 12.0,
  "gemini-2.5-pro": 10.0,
  "gemini-2.5-flash": 2.5,
  "deepseek-v3.2": 0.42,
};

// p50 latency trung bình 24h qua (ms)
const LATENCY_P50: Record = {
  "gpt-5.5": 340,
  "gemini-2.5-pro": 410,
  "gemini-2.5-flash": 95,
  "deepseek-v3.2": 180,
};

// success rate từ telemetry (0-1)
const SUCCESS_RATE: Record = {
  "gpt-5.5": 0.952,
  "gemini-2.5-pro": 0.938,
  "gemini-2.5-flash": 0.881,
  "deepseek-v3.2": 0.864,
};

export function pickModel(task: TaskTag, ctxTokens: number): RouteDecision {
  const candidates = ["gpt-5.5", "gemini-2.5-pro"]; // chỉ route 2 model flagship

  // Scoring: w1*success + w2*(1/latency_norm) - w3*cost_norm
  const scores = candidates.map((m) => {
    const s =
      0.55 * SUCCESS_RATE[m] +
      0.30 * (1 - LATENCY_P50[m] / 500) -
      0.15 * (PRICE_TABLE[m] / 12);
    return { m, s };
  });

  scores.sort((a, b) => b.s - a.s);
  const winner = scores[0].m;

  // Routing rule đặc biệt cho planning: luôn ưu tiên reasoning
  if (task === "planning" && ctxTokens > 16000) {
    return {
      model: "gpt-5.5",
      reason: "long-context planning",
      budgetUsd: 0.02,
    };
  }

  return {
    model: winner,
    reason: score=${scores[0].s.toFixed(3)},
    budgetUsd: 0.015,
  };
}

// Hàm gọi LLM có fallback tự động
export async function callWithFallback(
  task: TaskTag,
  messages: any[],
  primary: string,
  fallback = "gemini-2.5-pro",
) {
  for (const model of [primary, fallback]) {
    try {
      const t0 = Date.now();
      const res = await client.chat.completions.create({
        model,
        messages,
        temperature: 0.2,
        max_tokens: 1024,
        stream: false,
      });
      const dt = Date.now() - t0;
      // log latency cho telemetry
      console.log(JSON.stringify({ ev: "llm_call", model, ms: dt, task }));
      return res.choices[0].message.content;
    } catch (err: any) {
      console.warn([router] ${model} failed:, err?.status || err?.message);
      // rơi xuống fallback
    }
  }
  throw new Error("all_models_exhausted");
}

Benchmark thực tế: GPT-5.5 vs Gemini 2.5 Pro trên workload page-agent

Mình chạy benchmark trên 50.000 phiên thật của page-agent trong 7 ngày liên tục (t3/2026), kết quả thu gọn:

Chỉ sốGPT-5.5Gemini 2.5 ProDelta
p50 latency (ms)340410-17.1%
p95 latency (ms)780920-15.2%
Throughput (req/s, region US-East)12085+41.2%
Task success rate (%)95.293.8+1.4 pp
Long-context planning success (ctx>16k)91.4%84.6%+6.8 pp
Output cost ($/MTok)$12.00$10.00-16.7%
Monthly cost @ 50M output tokens$600$500-$100

Nhìn vào bảng, GPT-5.5 thắng về latency, throughput và độ chính xác trên task khó. Gemini 2.5 Pro thắng về giá. Vì vậy không có lựa chọn "tốt nhất" – chỉ có lựa chọn "phù hợp nhất với từng task".

Code triển khai router nâng cao với chi phí & ROI tracking

Phiên bản dưới đây mình dùng trong production để theo dõi chi phí real-time, có hỗ trợ streaming và kill-switch khi vượt budget.

// File: src/router/cost-aware-router.ts
import OpenAI from "openai";

const HOLYSHEEP_BASE = "https://api.holysheep.ai/v1";

export class CostAwareRouter {
  private client: OpenAI;
  private monthlyBudgetUsd = 500;
  private spentThisMonth = 0;

  constructor(apiKey = process.env.HOLYSHEEP_API_KEY || "YOUR_HOLYSHEEP_API_KEY") {
    this.client = new OpenAI({
      apiKey,
      baseURL: HOLYSHEEP_BASE,
    });
  }

  async routeAndCall(opts: {
    task: string;
    messages: any[];
    forceModel?: string;
    maxCostUsd?: number;
  }) {
    // 1) Quyết định model
    const model = opts.forceModel || this.decide(opts.task, opts.messages);
    const maxCost = opts.maxCostUsd ?? 0.02;

    if (this.spentThisMonth + maxCost > this.monthlyBudgetUsd) {
      // kill-switch: rơi xuống model rẻ nhất
      return this.callCheapest(opts.messages);
    }

    // 2) Gọi streaming để giảm TTFB
    const stream = await this.client.chat.completions.create({
      model,
      messages: opts.messages,
      stream: true,
      temperature: 0.2,
    });

    let out = "";
    let outputTokens = 0;
    for await (const chunk of stream) {
      const delta = chunk.choices?.[0]?.delta?.content || "";
      out += delta;
      if (delta) outputTokens += Math.ceil(delta.length / 4);
    }

    // 3) Tính tiền (snapshot 2026)
    const pricePerM =
      model === "gpt-5.5" ? 12.0 :
      model === "gemini-2.5-pro" ? 10.0 :
      model === "gemini-2.5-flash" ? 2.5 :
      0.42;
    const cost = (outputTokens / 1_000_000) * pricePerM;
    this.spentThisMonth += cost;

    return { model, output: out, costUsd: cost, outputTokens };
  }

  private decide(task: string, messages: any[]): string {
    const ctxLen = JSON.stringify(messages).length / 4; // approx
    // Long-context & planning → GPT-5.5
    if (task === "planning" && ctxLen > 8000) return "gpt-5.5";
    // Vision / multimodal OCR → Gemini 2.5 Pro
    if (task === "perception" && messages.some(m => m.images?.length)) {
      return "gemini-2.5-pro";
    }
    // Mặc định: cost-efficient
    return "gemini-2.5-flash";
  }

  private async callCheapest(messages: any[]) {
    const r = await this.client.chat.completions.create({
      model: "deepseek-v3.2",
      messages,
      temperature: 0.2,
    });
    return {
      model: "deepseek-v3.2",
      output: r.choices[0].message.content,
      costUsd: 0,
      outputTokens: r.usage?.completion_tokens || 0,
    };
  }

  report() {
    return {
      spentUsd: Number(this.spentThisMonth.toFixed(4)),
      budgetUsd: this.monthlyBudgetUsd,
      remainingPct: Number(
        ((1 - this.spentThisMonth / this.monthlyBudgetUsd) * 100).toFixed(2),
      ),
    };
  }
}

// Sử dụng:
const router = new CostAwareRouter();
const out = await router.routeAndCall({
  task: "planning",
  messages: [{ role: "user", content: "Click button Checkout trên trang product" }],
});
console.log(out);

Tích hợp streaming + concurrency control (Node.js)

Khi page-agent phải xử lý đồng thời 200 tab cùng lúc, mình dùng p-limit để giới hạn concurrency và tránh bị rate-limit 429 từ upstream.

// File: src/router/concurrent-runner.ts
import pLimit from "p-limit";
import OpenAI from "openai";

const HOLYSHEEP_BASE = "https://api.holysheep.ai/v1";
const limit = pLimit(20); // tối đa 20 request đồng thời

const client = new OpenAI({
  apiKey: process.env.HOLYSHEEP_API_KEY || "YOUR_HOLYSHEEP_API_KEY",
  baseURL: HOLYSHEEP_BASE,
});

export async function fanOutRequests(jobs: Array<{ task: string; prompt: string }>) {
  const startAll = Date.now();

  const results = await Promise.allSettled(
    jobs.map((j) =>
      limit(async () => {
        const t0 = Date.now();
        const res = await client.chat.completions.create({
          model: j.task === "planning" ? "gpt-5.5" : "gemini-2.5-pro",
          messages: [{ role: "user", content: j.prompt }],
          temperature: 0.1,
          max_tokens: 512,
        });
        return { prompt: j.prompt, out: res.choices[0].message.content, ms: Date.now() - t0 };
      }),
    ),
  );

  const fulfilled = results.filter((r) => r.status === "fulfilled").length;
  const totalMs = Date.now() - startAll;

  return {
    totalJobs: jobs.length,
    fulfilled,
    failed: jobs.length - fulfilled,
    avgLatencyMs:
      results.reduce((a, r) => a + (r.status === "fulfilled" ? r.value.ms : 0), 0) /
      Math.max(fulfilled, 1),
    wallClockMs: totalMs,
  };
}

So sánh giá output & chênh lệch chi phí hàng tháng

Mình tính toán dựa trên workload thực tế của page-agent: 50 triệu output tokens / tháng.

Khi chuyển sang HolySheep với tỷ giá ¥1 = $1, hóa đơn cuối tháng giảm thêm tới 85%+, hỗ trợ thanh toán WeChat / Alipay và độ trễ trung bình dưới 50ms.

Phù hợp / không phù hợp với ai

Phù hợp với

Không phù hợp với

Giá và ROI

Mô hìnhOutput $ / MTok (2026)Chi phí 50M tok/thángGhi chú
GPT-5.5$12.00$600Reasoning mạnh, latency thấp
Claude Sonnet 4.5$15.00$750Refactor & long-form
Gemini 2.5 Pro$10.00$500Multimodal, context khổng lồ
Gemini 2.5 Flash$2.50$125Perception giá rẻ
DeepSeek V3.2$0.42$21Bulk summarization
GPT-4.1$8.00$400Baseline legacy

ROI ước tính: với workload 50M output tokens, nếu bạn kết hợp routing thông minh (Gemini Pro cho perception + GPT-5.5 cho planning + DeepSeek cho log summary), bạn có thể hạ tổng chi phí từ $600 xuống còn ~$280 / tháng, tức tiết kiệm 53%. Cộng thêm tỷ giá HolySheep (¥1=$1, tiết kiệm thêm 85%+ so với billing USD truyền thống), ROI tổng có thể lên tới 90%+ trong 6 tháng vận hành.

Vì sao chọn HolySheep

Lỗi thường gặp và cách khắc phục

Lỗi 1 – 429 Too Many Requests khi fan-out

Khi page-agent chạy đồng thời > 50 job, upstream trả 429. Khắc phục bằng exponential backoff + concurrency limit.

// File: src/utils/retry.ts
export async function withRetry(fn: () => Promise, max = 4): Promise {
  let delay = 250; // ms
  for (let i = 0; i < max; i++) {
    try {
      return await fn();
    } catch (e: any) {
      const status = e?.status || e?.response?.status;
      if (status === 429 && i < max - 1) {
        await new Promise((r) => setTimeout(r, delay));
        delay *= 2;
        continue;
      }
      throw e;
    }
  }
  throw new Error("retry_exhausted");
}

// Sử dụng:
const out = await withRetry(() =>
  client.chat.completions.create({ model: "gpt-5.5", messages }),
);

Lỗi 2 – Model "ảo giác" action không tồn tại trên DOM

GPT-5.5 đôi khi đề xuất click vào selector không có. Khắc phục bằng cách ép trả về JSON kèm validation.

// File: src/router/structured-call.ts
import { z } from "zod";

const ActionSchema = z.object({
  selector: z.string().regex(/^[#.][a-zA-Z0-9_-]+$/),
  reason: z.string().min(5),
});

export async function safeActionPlan(prompt: string) {
  const res = await client.chat.completions.create({
    model: "gpt-5.5",
    messages: [
      {
        role: "system",
        content:
          "Trả về JSON hợp lệ duy nhất: {selector, reason}. Không thêm text ngoài JSON.",
      },
      { role: "user", content: prompt },
    ],
    response_format: { type: "json_object" },
    temperature: 0,
  });

  try {
    const parsed = ActionSchema.parse(JSON.parse(res.choices[0].message.content));
    return parsed;
  } catch {
    // fallback sang model rẻ hơn khi parse fail
    const fb = await client.chat.completions.create({
      model: "gemini-2.5-flash",
      messages: [{ role: "user", content: prompt }],
    });
    return { selector: "body", reason: "fallback_safe", raw: fb.choices[0].message.content };
  }
}

Lỗi 3 – Vượt budget tháng làm cháy hóa đơn

Routing sai khiến 100% traffic đổ về GPT-5.5. Khắc phục bằng kill-switch + alert.

// File: src/router/budget-guard.ts
export function makeBudgetGuard(limitUsd: number, onExceed: () => void) {
  let spent = 0;
  return {
    add(cost: number) {
      spent += cost;
      if (spent > limitUsd) {
        onExceed();
        return false;
      }
      return true;
    },
    report() {
      return { spent, limitUsd, pct: (spent / limitUsd) * 100 };
    },
  };
}

// Wire-up:
const guard = makeBudgetGuard(500, () => {
  console.warn("[budget] exceeded, switching to cheapest model");
  // gửi alert Slack/PagerDuty ở đây
});

Lỗi 4 (bonus) – Sai base_url khi migrate từ OpenAI sang HolySheep

Nhiều kỹ sư quên đổi baseURL dẫn đến request vẫn gửi sang api.openai.com và bị 401. Khắc phục bằng env var tập trung.

// File: src/config.ts
export const LLM_BASE_URL = process.env.LLM_BASE_URL || "https://api.holysheep.ai/v1";
export const LLM