Skip to content

AI Inference Layer: AI Model Providers

Hệ thống Hanoi Agents hỗ trợ hai phương thức triển khai suy luận AI chính, phục vụ cho các mục tiêu tối ưu hóa chi phí và chất lượng chấm điểm.


1. Workers AI (Serverless Inference)

Workers AI chạy trực tiếp các mô hình AI mã nguồn mở (như Llama 3, Mistral) trên hạ tầng GPU toàn cầu của Cloudflare. Đây là giải pháp hoàn hảo để tối ưu chi phí, không có phí duy trì (no idle infrastructure costs).

typescript
import { Ai } from '@cloudflare/ai';

export class WorkersAIProvider implements ModelProvider {
  private ai: Ai;
  private modelName: string;

  constructor(envAi: any, modelName = '@cf/meta/llama-3-8b-instruct') {
    this.ai = new Ai(envAi);
    this.modelName = modelName;
  }

  async generate(input: ModelInput): Promise<ModelOutput> {
    const response = await this.ai.run(this.modelName, {
      messages: [
        { role: 'system', content: input.systemPrompt },
        { role: 'user', content: input.userPrompt }
      ],
      temperature: input.temperature || 0.7
    });

    return {
      text: response.response,
      usage: { promptTokens: 0, completionTokens: 0 } // Workers AI hiện chưa tính toán trực tiếp token qua api
    };
  }
}

2. AI Gateway & External API Providers

Đối với các tác vụ chấm điểm tự luận phức tạp hoặc đánh giá Rubric khắt khe, chúng tôi gọi các mô hình thương mại cao cấp (như Claude 3.5 Sonnet hoặc GPT-4o) thông qua Cloudflare AI Gateway để tự động caching (giảm 80% chi phí gọi lặp lại) và theo dõi độ trễ.

typescript
export class AIProxyProvider implements ModelProvider {
  private gatewayUrl: string;
  private apiKey: string;

  constructor(env: { AI_GATEWAY_URL: string; PROVIDER_API_KEY: string }) {
    this.gatewayUrl = env.AI_GATEWAY_URL; // Ví dụ: https://gateway.ai.cloudflare.com/v1/account_id/gateway_name/anthropic
    this.apiKey = env.PROVIDER_API_KEY;
  }

  async generate(input: ModelInput): Promise<ModelOutput> {
    const response = await fetch(`${this.gatewayUrl}/messages`, {
      method: "POST",
      headers: {
        "x-api-key": this.apiKey,
        "content-type": "application/json",
        "anthropic-version": "2023-06-01"
      },
      body: JSON.stringify({
        model: "claude-3-5-sonnet-20240620",
        max_tokens: 1000,
        messages: [{ role: "user", content: input.userPrompt }],
        system: input.systemPrompt,
        temperature: input.temperature || 0.5
      })
    });

    const data = await response.json();
    return {
      text: data.content[0].text,
      usage: {
        promptTokens: data.usage.input_tokens,
        completionTokens: data.usage.output_tokens
      }
    };
  }
}

Tài liệu được phân phối nội bộ phục vụ Hackathon 2026.