Initialize shared aiohttp session for connection reuse with connection limits.
()
| 1525 | |
| 1526 | |
| 1527 | async def initialize_shared_aiohttp_session() -> "ClientSession | None": |
| 1528 | """Initialize shared aiohttp session for connection reuse with connection limits.""" |
| 1529 | try: |
| 1530 | from aiohttp import ClientSession, DummyCookieJar, TCPConnector |
| 1531 | |
| 1532 | from litellm.llms.custom_httpx.http_handler import ( |
| 1533 | build_aiohttp_keepalive_socket_factory, |
| 1534 | ) |
| 1535 | |
| 1536 | connector_kwargs: Final[_AiohttpConnectorKwargs] = { |
| 1537 | "keepalive_timeout": AIOHTTP_KEEPALIVE_TIMEOUT, |
| 1538 | "ttl_dns_cache": AIOHTTP_TTL_DNS_CACHE, |
| 1539 | } |
| 1540 | if AIOHTTP_NEEDS_CLEANUP_CLOSED: |
| 1541 | connector_kwargs["enable_cleanup_closed"] = True |
| 1542 | if AIOHTTP_CONNECTOR_LIMIT > 0: |
| 1543 | connector_kwargs["limit"] = AIOHTTP_CONNECTOR_LIMIT |
| 1544 | if AIOHTTP_CONNECTOR_LIMIT_PER_HOST > 0: |
| 1545 | connector_kwargs["limit_per_host"] = AIOHTTP_CONNECTOR_LIMIT_PER_HOST |
| 1546 | socket_factory: Final = build_aiohttp_keepalive_socket_factory() |
| 1547 | if socket_factory is not None: |
| 1548 | connector_kwargs["socket_factory"] = socket_factory |
| 1549 | |
| 1550 | connector: Final = TCPConnector(**connector_kwargs) |
| 1551 | session: Final = ClientSession( |
| 1552 | connector=connector, |
| 1553 | cookie_jar=DummyCookieJar(), |
| 1554 | trace_configs=[build_pool_wait_trace_config()], |
| 1555 | ) |
| 1556 | |
| 1557 | verbose_proxy_logger.info( |
| 1558 | "SESSION REUSE: Created shared aiohttp session for connection pooling (ID: %s, limit=%s, limit_per_host=%s)", |
| 1559 | id(session), |
| 1560 | AIOHTTP_CONNECTOR_LIMIT, |
| 1561 | AIOHTTP_CONNECTOR_LIMIT_PER_HOST, |
| 1562 | ) |
| 1563 | return session |
| 1564 | except Exception as e: |
| 1565 | verbose_proxy_logger.warning( |
| 1566 | "Failed to create shared aiohttp session: %s. Continuing without session reuse.", e |
| 1567 | ) |
| 1568 | return None |
| 1569 | |
| 1570 | |
| 1571 | _initialize_shared_aiohttp_session: Final = initialize_shared_aiohttp_session |