콘텐츠로 이동

예제 & 마이그레이션

다중 백엔드 설정

# 엔터프라이즈 다중 백엔드 설정
server:
  bind_address: "0.0.0.0:8080"
  workers: 8
  connection_pool_size: 400

backends:
  # 기본 OpenAI GPT 모델
  - name: "openai-primary"
    url: "https://api.openai.com"
    weight: 5
    models: ["gpt-4", "gpt-3.5-turbo"]
    retry_override:
      max_attempts: 3
      base_delay: "500ms"

  # 보조 Azure OpenAI
  - name: "azure-openai"
    url: "https://your-resource.openai.azure.com"
    weight: 3
    models: ["gpt-4", "gpt-35-turbo"]

  # 오픈 모델을 위한 로컬 Ollama
  - name: "local-ollama"
    url: "http://ollama:11434"
    weight: 2
    models: ["llama2", "mistral", "codellama"]

  # vLLM 배포
  - name: "vllm-cluster"
    url: "http://vllm-service:8000"
    weight: 4
    models: ["meta-llama/Llama-2-7b-chat-hf"]

health_checks:
  enabled: true
  interval: "45s"
  timeout: "15s"
  unhealthy_threshold: 3
  healthy_threshold: 2

request:
  timeout: "180s"
  max_retries: 4

cache:
  model_cache_ttl: "600s"        # 10분 캐시
  deduplication_ttl: "120s"      # 2분 중복 제거
  enable_deduplication: true

logging:
  level: "info"
  format: "json"

고성능 설정

# 높은 처리량 시나리오에 최적화
server:
  bind_address: "0.0.0.0:8080"
  workers: 16                     # 높은 워커 수
  connection_pool_size: 1000      # 큰 연결 풀

backends:
  - name: "fast-backend-1"
    url: "http://backend1:8000"
    weight: 1
  - name: "fast-backend-2"
    url: "http://backend2:8000"
    weight: 1
  - name: "fast-backend-3"
    url: "http://backend3:8000"
    weight: 1

health_checks:
  enabled: true
  interval: "30s"
  timeout: "5s"                   # 빠른 타임아웃
  unhealthy_threshold: 2          # 빠른 실패
  healthy_threshold: 1            # 빠른 복구

request:
  timeout: "60s"                  # 높은 처리량을 위한 짧은 타임아웃
  max_retries: 2                  # 적은 재시도

retry:
  max_attempts: 2
  base_delay: "50ms"              # 빠른 재시도
  max_delay: "5s"
  exponential_backoff: true
  jitter: true

cache:
  model_cache_ttl: "300s"
  deduplication_ttl: "30s"        # 짧은 중복 제거 윈도우
  enable_deduplication: true

logging:
  level: "warn"                   # 성능을 위한 최소 로깅
  format: "json"

개발 설정

# 개발자 친화적 설정
server:
  bind_address: "127.0.0.1:8080"  # localhost만
  workers: 2                      # 개발용 적은 워커
  connection_pool_size: 20        # 작은 풀

backends:
  - name: "local-ollama"
    url: "http://localhost:11434"
    weight: 1

health_checks:
  enabled: true
  interval: "10s"                 # 빠른 피드백을 위한 잦은 확인
  timeout: "3s"
  unhealthy_threshold: 2
  healthy_threshold: 1

request:
  timeout: "300s"                 # 디버깅을 위한 긴 타임아웃
  max_retries: 1                  # 디버깅을 위한 최소 재시도

logging:
  level: "debug"                  # 상세 로깅
  format: "pretty"                # 사람이 읽기 쉬운 형식
  enable_colors: true             # 컬러 출력

cache:
  model_cache_ttl: "60s"          # 빠른 테스트를 위한 짧은 캐시
  deduplication_ttl: "10s"        # 짧은 중복 제거
  enable_deduplication: false     # 테스트를 위해 비활성화

마이그레이션 가이드

명령줄 인수에서 마이그레이션

현재 명령줄 인수를 사용하고 있다면 설정 파일로 마이그레이션하세요:

이전:

continuum-router --backends "http://localhost:11434,http://localhost:1234" --bind "0.0.0.0:9000"

이후: 1. 설정 파일 생성:

continuum-router --generate-config > config.yaml

  1. 설정 편집:

    server:
      bind_address: "0.0.0.0:9000"
    
    backends:
      - name: "ollama"
        url: "http://localhost:11434"
      - name: "lm-studio"
        url: "http://localhost:1234"
    

  2. 설정 파일 사용:

    continuum-router --config config.yaml
    

환경 변수에서 마이그레이션

설정 파일과 함께 환경 변수를 오버라이드로 계속 사용할 수 있습니다:

설정 파일 (config.yaml):

server:
  bind_address: "0.0.0.0:8080"

backends:
  - name: "default"
    url: "http://localhost:11434"

환경 오버라이드:

export CONTINUUM_BIND_ADDRESS="0.0.0.0:9000"
export CONTINUUM_BACKEND_URLS="http://localhost:11434,http://localhost:1234"
continuum-router --config config.yaml

설정 유효성 검사

서버를 시작하지 않고 설정을 검증하려면:

# 설정 로딩 테스트
continuum-router --config config.yaml --help

# dry-run으로 설정 확인 (향후 기능)
continuum-router --config config.yaml --dry-run

Rust Builder API

Continuum Router를 Rust 라이브러리 크레이트로 임베딩할 때, 타입 안전 빌더 API를 사용하여 프로그래밍 방식으로 설정을 구성할 수 있습니다. YAML 파일 없이 빌드 시점에 모든 설정을 검증합니다.

BackendConfigBuilder

BackendConfigBuilder는 올바른 백엔드 타입을 설정하고 필요한 최소 인수만 요구하는 프로바이더별 생성자를 제공합니다.

프로바이더 생성자

생성자 API 키 필요 설명
BackendConfigBuilder::openai(url, api_key) Yes OpenAI API
BackendConfigBuilder::anthropic(url, api_key) Yes Anthropic Claude API
BackendConfigBuilder::gemini(url, api_key) Yes Google Gemini API
BackendConfigBuilder::vllm(url, api_key) Yes vLLM 추론 서버
BackendConfigBuilder::ollama(url) No Ollama 로컬 서버
BackendConfigBuilder::llamacpp(url) No llama.cpp 서버
BackendConfigBuilder::lm_studio(url) No LM Studio
BackendConfigBuilder::custom(backend_type, url) No 모든 백엔드 타입

선택적 빌더 메서드

프로바이더 생성자 호출 후, .build() 호출 전에 다음 메서드를 체이닝할 수 있습니다:

  • .name(name) - 백엔드 이름 오버라이드 (생략 시 "{provider}-{host}"로 자동 생성)
  • .models(vec![...]) - 이 백엔드에서 사용 가능한 모델 ID 지정
  • .weight(n) - 로드 밸런싱 가중치, 1~1000 (기본값: 1)
  • .timeout(duration) - 백엔드별 타임아웃 문자열, 예: "30s" 또는 "2m"
  • .max_retries(n) - 이 백엔드의 최대 재시도 횟수
  • .api_key(key) - API 키 설정 또는 오버라이드 (custom()과 함께 사용 시 유용)

예제

use continuum_router::config::builder::BackendConfigBuilder;

// 명시적 이름과 모델을 가진 OpenAI 백엔드
let openai = BackendConfigBuilder::openai("https://api.openai.com/v1", "sk-...")
    .name("primary-openai")
    .models(vec!["gpt-4o", "gpt-4o-mini"])
    .weight(3)
    .timeout("60s")
    .build()
    .unwrap();

// 자동 생성된 이름 "ollama-localhost"를 가진 Ollama 백엔드
let ollama = BackendConfigBuilder::ollama("http://localhost:11434")
    .models(vec!["llama3.2", "qwen3"])
    .build()
    .unwrap();

ConfigBuilder

ConfigBuilder는 합리적인 기본값으로 최상위 라우터 설정을 구성합니다.

빌더 메서드

  • .add_backend(backend) - BackendConfig 추가 (최소 하나 필요)
  • .selection_strategy(strategy) - 로드 밸런싱 전략 (기본값: RoundRobin)
  • .bind_address(addr) - TCP 주소 또는 Unix 소켓 경로 (기본값: "0.0.0.0:8080")
  • .enable_health_checks(bool) - 백그라운드 헬스 모니터링 토글 (기본값: true)
  • .health_check_interval(duration) - 헬스 체크 주기 (기본값: "30s")
  • .enable_rate_limiting(config) - RateLimitConfig 연결
  • .enable_circuit_breaker(config) - CircuitBreakerConfig 연결
  • .cors(config) - CORS 설정
  • .api_keys(config) - API 키 인증 설정
  • .logging_level(level) - 로깅 레벨: "error", "warn", "info", "debug", "trace" (기본값: "info")

예제

use continuum_router::config::builder::{BackendConfigBuilder, ConfigBuilder};
use continuum_router::core::models::backend::SelectionStrategy;

let backend = BackendConfigBuilder::ollama("http://localhost:11434")
    .name("local")
    .build()
    .unwrap();

let config = ConfigBuilder::new()
    .add_backend(backend)
    .selection_strategy(SelectionStrategy::LeastLatency)
    .bind_address("127.0.0.1:8080")
    .enable_health_checks(true)
    .health_check_interval("60s")
    .logging_level("debug")
    .build()
    .unwrap();

ConfigBuilderError

두 빌더 모두 .build()에서 Result<_, ConfigBuilderError>를 반환합니다. 오류 변형은 다음과 같습니다:

변형 원인
InvalidUrl URL을 파싱할 수 없음
MissingApiKey 필수 API 키가 비어 있거나 누락됨
NoBackends 백엔드를 추가하지 않고 ConfigBuilder::build() 호출
DuplicateBackendName 두 백엔드가 동일한 이름을 공유
InvalidBindAddress 바인드 주소가 유효한 TCP 또는 Unix 소켓 주소가 아님
ValidationError 필드 값이 범위를 벗어남 (예: weight가 1..=1000 범위 밖)

모든 변형은 편리한 오류 처리를 위해 std::error::ErrorDisplay를 구현합니다.

빌더 타입 임포트

// 최상위 크레이트 re-export에서 빌더 임포트
use continuum_router::{BackendConfigBuilder, ConfigBuilder, ConfigBuilderError};

// 또는 config 모듈에서 임포트
use continuum_router::config::builder::{BackendConfigBuilder, ConfigBuilder, ConfigBuilderError};

이 설정 가이드는 Continuum Router에서 사용할 수 있는 모든 설정 옵션에 대한 포괄적인 내용을 제공합니다. 유연한 설정 시스템을 통해 명확한 우선순위 규칙과 유효성 검사를 유지하면서 모든 배포 시나리오에 라우터를 적용할 수 있습니다.