공유 세션 지원

공유 세션 지원 (Shared Session Support)

개요

LiteLLM은 이제 여러 API 호출에서 aiohttp.ClientSession 인스턴스를 공유해 불필요한 새 세션 생성 피하는 것을 지원해요. 이는 성능과 리소스 사용을 개선합니다.

사용법

기본 사용법

import asyncio
from aiohttp import ClientSession
from litellm import acompletion

async def main():
    # Create a shared session
    async with ClientSession() as shared_session:
        # Use the same session for multiple calls
        response1 = await acompletion(
            model="gpt-5.6-terra",
            messages=[{"role": "user", "content": "Hello"}],
            shared_session=shared_session
        )
        
        response2 = await acompletion(
            model="gpt-5.6-terra", 
            messages=[{"role": "user", "content": "How are you?"}],
            shared_session=shared_session
        )
        
        # Both calls reuse the same session!

asyncio.run(main())

공유 세션 없이 (기본)

import asyncio
from litellm import acompletion

async def main():
    # Each call creates a new session
    response1 = await acompletion(
        model="gpt-5.6-terra",
        messages=[{"role": "user", "content": "Hello"}]
    )
    
    response2 = await acompletion(
        model="gpt-5.6-terra",
        messages=[{"role": "user", "content": "How are you?"}]
    )
    # Two separate sessions created

asyncio.run(main())

출처: 문서

본문

이점

  • 성능: 여러 호출에서 HTTP 연결 재사용
  • 리소스 효율성: 메모리 및 연결 오버헤드 감소
  • 더 나은 제어: 세션 수명 주기를 명시적으로 관리
  • 디버깅: 어떤 호출이 어떤 세션을 쓰는지 추적 용이

디버그 로깅

디버그 로깅을 활성화해 세션 재사용을 확인할 수 있어요:

import os
import litellm

# Enable debug logging
os.environ['LITELLM_LOG'] = 'DEBUG'

# You'll see logs like:
# 🔄 SHARED SESSION: acompletion called with shared_session (ID: 12345)
# ✅ SHARED SESSION: Reusing existing ClientSession (ID: 12345)

일반적인 패턴

FastAPI 통합

from fastapi import FastAPI
import aiohttp
import litellm

app = FastAPI()

@app.post("/chat")
async def chat(messages: list[dict]):
    # Create session per request
    async with aiohttp.ClientSession() as session:
        return await litellm.acompletion(
            model="gpt-5.6-terra",
            messages=messages,
            shared_session=session
        )

배치 처리

import asyncio
from aiohttp import ClientSession
from litellm import acompletion

async def process_batch(messages_list):
    async with ClientSession() as shared_session:
        tasks = []
        for messages in messages_list:
            task = acompletion(
                model="gpt-5.6-terra",
                messages=messages,
                shared_session=shared_session
            )
            tasks.append(task)
        
        # All tasks use the same session
        results = await asyncio.gather(*tasks)
        return results

커스텀 세션 구성

import aiohttp
import litellm

# Create optimized session
async with aiohttp.ClientSession(
    timeout=aiohttp.ClientTimeout(total=180),
    connector=aiohttp.TCPConnector(limit=300, limit_per_host=75)
) as shared_session:
    
    response = await litellm.acompletion(
        model="gpt-5.6-terra",
        messages=[{"role": "user", "content": "Hello"}],
        shared_session=shared_session
    )

구현 세부 사항

shared_session 파라미터는 LiteLLM 호출 체인 전체에 이어집니다:

  1. acompletion() - shared_session 파라미터 수락
  2. BaseLLMHTTPHandler - HTTP 클라이언트 생성에 세션 전달
  3. AsyncHTTPHandler - 제공되면 기존 세션 사용
  4. LiteLLMAiohttpTransport - HTTP 요청에 세션 재사용

하위 호환성

  • 100% 하위 호환 - 기존 코드가 변경 없이 동작
  • 선택 파라미터 - shared_session=None 이 기본
  • Breaking 변경 없음 - 모든 기존 기능 보존

테스트

공유 세션 기능을 테스트해 보세요:

import asyncio
from aiohttp import ClientSession
from litellm import acompletion

async def test_shared_session():
    async with ClientSession() as session:
        print(f"✅ Created session: {id(session)}")
        
        try:
            response = await acompletion(
                model="gpt-5.6-terra",
                messages=[{"role": "user", "content": "Hello"}],
                shared_session=session,
                api_key="your-api-key"
            )
            print(f"Response: {response.choices[0].message.content}")
        except Exception as e:
            print(f"✅ Expected error: {type(e).__name__}")
        
        print("✅ Session control working!")

asyncio.run(test_shared_session())

수정된 파일

공유 세션 기능은 다음 파일에 추가되었습니다:

  • litellm/main.py - acompletion()completion()shared_session 파라미터 추가
  • litellm/llms/custom_httpx/http_handler.py - 핵심 세션 재사용 로직
  • litellm/llms/custom_httpx/llm_http_handler.py - HTTP 핸들러 통합
  • litellm/llms/openai/openai.py - OpenAI 프로바이더 통합
  • litellm/llms/openai/common_utils.py - OpenAI 클라이언트 생성
  • litellm/llms/azure/chat/o_series_handler.py - Azure O Series 핸들러

문제 해결

세션이 재사용되지 않음

  1. 디버그 로그 확인: LITELLM_LOG=DEBUG 를 활성화해 세션 재사용 메시지 확인
  2. 세션 닫힘 여부 확인: 호출 시 세션이 여전히 활성 상태인지 확인
  3. 파라미터 전달 확인: 모든 acompletion() 호출에 shared_session 을 전달했는지 확인

성능 문제

  1. 세션 구성: 사용 사례에 맞게 aiohttp.ClientSession 파라미터 튜닝
  2. 연결 한도: TCPConnectorlimitlimit_per_host 조정
  3. 타임아웃 설정: 환경에 적절한 타임아웃 구성

더 알아보기 (Learn more)