Cloudflare AI Gateway 프로바이더

Cloudflare AI Gateway 프로바이더

Cloudflare AI Gateway 프로바이더는 Cloudflare의 AI Gateway를 Vercel AI SDK와 통합하는 라이브러리예요. 통합 인터페이스를 통해 다양한 제공업체의 여러 AI 모델에 원활하게 접근할 수 있고, 고가용성을 위한 자동 폴백(fallback)을 제공해요.

출처: 문서

본문

기능 (Features)

  • 런타임 무관 (Runtime Agnostic): Node.js, Edge Runtime, 그리고 Vercel AI SDK가 지원하는 기타 JavaScript 런타임과 호환돼요.
  • 자동 폴백 (Automatic Fallback): 한 모델이 실패하면 다음 사용 가능한 모델로 자동 전환해 복원력을 보장해요.
  • 멀티 프로바이더 지원 (Multi-Provider Support): OpenAI, Anthropic, DeepSeek, Google AI Studio, Grok, Mistral, Perplexity AI, Replicate, Groq의 모델을 지원해요.
  • Cloudflare AI Gateway 통합 (Integration): 요청 관리, 캐싱, 속도 제한에 Cloudflare의 AI Gateway를 활용해요.
  • 간편한 설정 (Simplified Configuration): API 키 인증 또는 Cloudflare AI 바인딩을 지원하는 쉬운 설정.

설정 (Setup)

Cloudflare AI Gateway 프로바이더는 ai-gateway-provider 모듈에서 사용할 수 있어요. 다음과 같이 설치하세요:

프로바이더 인스턴스 (Provider Instance)

createAiGateway 함수로 aigateway 프로바이더 인스턴스를 만들어요. API 키 또는 Cloudflare AI 바인딩으로 인증할 수 있어요.

API 키 인증 (API Key Authentication)

import { createAiGateway } from 'ai-gateway-provider';

const aigateway = createAiGateway({
  accountId: 'your-cloudflare-account-id',
  gateway: 'your-gateway-name',
  apiKey: 'your-...ey', // 게이트웨이에서 인증을 활성화한 경우에만 필요
  options: {
    skipCache: true, // 선택적 요청별 설정
  },
});

Cloudflare AI 바인딩 (Cloudflare AI Binding)

이 방법은 Cloudflare Workers 내부에서만 사용할 수 있어요.

wrangler.toml에서 AI 바인딩을 구성하세요:

[AI]
binding = "AI"

worker에서 바인딩을 사용해 새 인스턴스를 만드세요:

import { createAiGateway } from 'ai-gateway-provider';

const aigateway = createAiGateway({
  binding: env.AI.gateway('my-gateway'),
  options: {
    skipCache: true, // 선택적 요청별 설정
  },
});

언어 모델 (Language Models)

모델 배열을 aigateway 프로바이더에 전달해 모델 인스턴스를 만들어요. 프로바이더는 모델을 순서대로 사용하려 시도하고, 하나가 실패하면 다음 것으로 폴백해요.

import { createAiGateway } from 'ai-gateway-provider';
import { createOpenAI } from '@ai-sdk/openai';
import { createAnthropic } from '@ai-sdk/anthropic';

const aigateway = createAiGateway({
  accountId: 'your-cloudflare-account-id',
  gateway: 'your-gateway-name',
  apiKey: 'your-...ey',
});

const openai = createOpenAI({ apiKey: *** });
const anthropic = createAnthropic({ apiKey: 'anthr...key' });

const model = aigateway([
  anthropic('claude-haiku-4-5'), // 기본 모델
  openai('gpt-4o-mini'), // 폴백 모델
]);

요청 옵션 (Request Options)

Cloudflare AI Gateway 설정을 요청별로 커스터마이즈할 수 있어요:

  • cacheKey: 요청의 커스텀 캐시 키.
  • cacheTtl: 캐시의 유효 시간(초).
  • skipCache: 캐싱 우회.
  • metadata: 요청의 커스텀 메타데이터.
  • collectLog: 로그 수집 활성화/비활성화.
  • eventId: 커스텀 이벤트 식별자.
  • requestTimeoutMs: 요청 타임아웃(밀리초).
  • retries:
    • maxAttempts: 재시도 횟수 (1-5).
    • retryDelayMs: 재시도 사이의 지연.
    • backoff: 재시도 전략 (constant, linear, exponential).

예시:

const aigateway = createAiGateway({
  accountId: 'your-cloudflare-account-id',
  gateway: 'your-gateway-name',
  apiKey: 'your-...ey',
  options: {
    cacheTtl: 3600, // 1시간 동안 캐시
    metadata: { userId: 'user123' },
    retries: {
      maxAttempts: 3,
      retryDelayMs: 1000,
      backoff: 'exponential',
    },
  },
});

예시 (Examples)

generateText

Cloudflare AI Gateway 프로바이더로 비스트리밍 텍스트를 생성해요:

import { createAiGateway } from 'ai-gateway-provider';
import { createOpenAI } from '@ai-sdk/openai';
import { generateText } from 'ai';

const aigateway = createAiGateway({
  accountId: 'your-cloudflare-account-id',
  gateway: 'your-gateway-name',
  apiKey: 'your-...ey',
});

const openai = createOpenAI({ apiKey: *** });

const { text } = await generateText({
  model: aigateway([openai('gpt-4o-mini')]),
  prompt: 'Write a greeting.',
});

console.log(text); // 출력: "Hello"

streamText

Cloudflare AI Gateway 프로바이더로 텍스트 응답을 스트리밍해요:

import { createAiGateway } from 'ai-gateway-provider';
import { createOpenAI } from '@ai-sdk/openai';
import { streamText } from 'ai';

const aigateway = createAiGateway({
  accountId: 'your-cloudflare-account-id',
  gateway: 'your-gateway-name',
  apiKey: 'your-...ey',
});

const openai = createOpenAI({ apiKey: *** });

const result = await streamText({
  model: aigateway([openai('gpt-4o-mini')]),
  prompt: 'Write a multi-part greeting.',
});

let accumulatedText = '';
for await (const chunk of result.textStream) {
  accumulatedText += chunk;
}

console.log(accumulatedText); // 출력: "Hello world!"

지원 프로바이더 (Supported Providers)

  • OpenAI
  • Anthropic
  • DeepSeek
  • Google AI Studio
  • Grok
  • Mistral
  • Perplexity AI
  • Replicate
  • Groq

오류 처리 (Error Handling)

프로바이더는 다음 커스텀 오류를 발생시켜요:

  • AiGatewayUnauthorizedError: 인증이 활성화된 상태에서 API 키가 없거나 잘못된 경우.
  • AiGatewayDoesNotExist: 지정된 Cloudflare AI Gateway가 존재하지 않는 경우.

더 알아보기 (Learn more)

전체 사이트맵