راهنمای استفاده امن از خودکارسازی و API دسته‌ای

روش‌های ایمنی خودکارسازی در سطح سازمان: محدودیت نرخ، اجتناب از تشخیص سوءاستفاده، توازن بار چندحسابی و ثبت ممیزی انطباق.

بر اساس گزارش‌های جامعه و مهندسی معکوس عمومی. موردبه‌مورد با مستندات Anthropic سنجیده نشده؛ جزئیات مهم را در مرکز راهنمای رسمی تأیید کنید.

محتوای آموزشی و تشخیصی: توضیح می‌دهد سیگنال‌های ریسک چگونه کار می‌کنند تا بتوانید پیکربندی خود را بفهمید و عیب‌یابی کنید. توصیه به نقض قوانین نیست. سیاست استفاده و شرایط خدمات Anthropic و قوانین محل زندگی‌تان را رعایت کنید؛ اگر منطقهٔ شما پشتیبانی نمی‌شود، از جایگزین رسمی در دسترس استفاده کنید.

در این صفحه

1. کنترل فرکانس فراخوانی دسته‌ای و محدودیت نرخ

Anthropic محدودیت‌های نرخ در سطح سازمان اعمال می‌کند. سیستم‌های خودکارسازی را طوری طراحی کنید که این محدودیت‌ها رعایت شود و طبقه‌بندی‌کننده‌های ضدسوءاستفاده تحریک نشوند:

سطوح محدودیت نرخ (تا 2026-08)

سطح حساب RPM (درخواست/دقیقه) TPM (توکن/دقیقه) سقف توکن روزانه
لایهٔ رایگان 5 40,000 50,000
لایهٔ Pro 50 200,000 5,000,000
لایهٔ Team 100 400,000 10,000,000
Enterprise سفارشی سفارشی توافقی

پیاده‌سازی محدودکنندهٔ نرخ تطبیقی

class AdaptiveRateLimiter {
  private requestQueue: Array<() => Promise> = [];
  private activeRequests = 0;
  private maxConcurrency: number;
  private minDelay: number; // ms between requests
  
  constructor(rpm: number, maxConcurrency = 5) {
    this.maxConcurrency = maxConcurrency;
    this.minDelay = (60 / rpm) * 1000;
  }
  
  async execute(fn: () => Promise): Promise {
    while (this.activeRequests >= this.maxConcurrency) {
      await new Promise(resolve => setTimeout(resolve, 100));
    }
    
    this.activeRequests++;
    try {
      const result = await fn();
      await new Promise(resolve => setTimeout(resolve, this.minDelay));
      return result;
    } catch (error: any) {
      if (error.status === 429) {
        // Rate limit hit, exponential backoff
        const retryAfter = error.headers?.['retry-after'] || 60;
        await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
        return this.execute(fn); // Retry
      }
      throw error;
    } finally {
      this.activeRequests--;
    }
  }
}

// Usage
const limiter = new AdaptiveRateLimiter(50); // 50 RPM for Pro tier
const results = await Promise.all(
  prompts.map(prompt => limiter.execute(() => callClaude(prompt)))
);

2. پرهیز از تشخیص ضدسوءاستفاده

طبقه‌بندی‌کننده‌های پشتی Anthropic الگوهایی را که نشان‌دهندهٔ تقطیر مدل یا scraping غیرمجاز هستند تشخیص می‌دهند. رفتار شبیه انسان تقلید کنید تا پرچم‌گذاری نشود:

فنون شبیه‌سازی رفتار انسانی

  • تنوع prompt: تنوع زبان طبیعی به promptها اضافه کنید. از ارسال 1000 درخواست تقریباً یکسان پرهیز کنید.
  • تزریق jitter: تأخیر بین درخواست‌ها را تصادفی کنید (مثلاً توزیع یکنواخت 100-3000ms).
  • مرزهای نشست: کار را در نشست‌های 20-50 درخواستی دسته‌بندی کنید و بین آن‌ها 5-10 دقیقه وقفه بگذارید.
  • تنوع طول خروجی: max_tokens را بین درخواست‌ها متنوع کنید تا الگوی خروجی با طول ثابت پیش نیاید.

نمونهٔ تنوع prompt

const templates = [
  "Refactor this code:
{code}",
  "Can you improve this function?
{code}",
  "Please optimize:
{code}",
  "How would you rewrite this?
{code}",
];

function varyPrompt(code: string): string {
  const template = templates[Math.floor(Math.random() * templates.length)];
  const prefix = Math.random() > 0.5 ? "Here's my code: " : "";
  return prefix + template.replace("{code}", code);
}

3. polling چندحسابی و توازن بار

بارهای حجیم را بین چند حساب Claude پخش کنید تا از محدودیت نرخ هر سازمان عبور نکنید و ریسک تقطیر کم شود:

توازن‌گر بار round-robin

class MultiAccountBalancer {
  private accounts: Array<{ apiKey: string; weight: number }>;
  private currentIndex = 0;
  private requestCounts: Map = new Map();
  
  constructor(accounts: Array<{ apiKey: string; weight?: number }>) {
    this.accounts = accounts.map(acc => ({ 
      apiKey: acc.apiKey, 
      weight: acc.weight || 1 
    }));
  }
  
  getNextAccount(): string {
    // Weighted round-robin selection
    const totalWeight = this.accounts.reduce((sum, acc) => sum + acc.weight, 0);
    let random = Math.random() * totalWeight;
    
    for (const account of this.accounts) {
      random -= account.weight;
      if (random <= 0) {
        this.requestCounts.set(account.apiKey, 
          (this.requestCounts.get(account.apiKey) || 0) + 1);
        return account.apiKey;
      }
    }
    
    return this.accounts[0].apiKey;
  }
  
  getStats(): Record {
    return Object.fromEntries(this.requestCounts);
  }
}

// Usage
const balancer = new MultiAccountBalancer([
  { apiKey: "sk-ant-api03-...", weight: 2 }, // Pro account, higher weight
  { apiKey: "sk-ant-api04-...", weight: 1 }, // Free account, lower weight
]);

async function callWithBalancing(prompt: string) {
  const apiKey = balancer.getNextAccount();
  return await anthropic.messages.create({
    apiKey,
    model: "claude-sonnet-4.5-high",
    messages: [{ role: "user", content: prompt }],
  });
}

4. لاگ ممیزی و چک‌لیست انطباق

لاگ جامع فعالیت خودکارسازی را برای ممیزی انطباق و دیباگ نگه دارید:

طرح لاگ ممیزی

interface AuditLog {
  timestamp: string;
  accountId: string;
  requestId: string;
  model: string;
  inputTokens: number;
  outputTokens: number;
  cacheHit: boolean;
  latencyMs: number;
  statusCode: number;
  errorMessage?: string;
  sourceIP: string;
  userAgent: string;
}

// Log every API call
async function auditedCall(prompt: string): Promise {
  const start = Date.now();
  try {
    const response = await anthropic.messages.create({...});
    
    await logAudit({
      timestamp: new Date().toISOString(),
      accountId: "org-123",
      requestId: response.id,
      model: response.model,
      inputTokens: response.usage.input_tokens,
      outputTokens: response.usage.output_tokens,
      cacheHit: response.usage.cache_read_input_tokens > 0,
      latencyMs: Date.now() - start,
      statusCode: 200,
      sourceIP: await getPublicIP(),
      userAgent: "my-automation/1.0",
    });
    
    return response;
  } catch (error: any) {
    await logAudit({
      timestamp: new Date().toISOString(),
      statusCode: error.status || 500,
      errorMessage: error.message,
      latencyMs: Date.now() - start,
      ...
    });
    throw error;
  }
}

چک‌لیست خودممیزی انطباق

  • همهٔ درخواست‌های خودکار از API key استفاده می‌کنند، نه توکن نشست سرقت‌شده
  • خودکارسازی محدودیت‌های نرخ Anthropic را رعایت می‌کند (بدون تلاش تهاجمی برای دور زدن)
  • خروجی برای ابزار داخلی استفاده می‌شود، نه فروش مجدد یا آموزش عمومی مدل
  • لاگ‌ها 90 روز برای مسیر ممیزی نگه داشته می‌شوند
  • برای ترافیک API از IP مسکونی استفاده می‌شود (بدون IP دیتاسنتر برای خودکارسازی پرحجم)
  • در جریان‌های خودکار حملهٔ prompt injection یا تلاش jailbreak نیست