Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

feat: Add shared_session parameter for aiohttp ClientSession reuse

Dharamendra Kumar77a39e7ca926
diff --git a/docs/my-website/docs/completion/shared_session.md b/docs/my-website/docs/completion/shared_session.md
new file mode 100644
index 00000000000..ff3da37f34f
--- /dev/null
+++ b/docs/my-website/docs/completion/shared_session.md
@@ -0,0 +1,213 @@
+# Shared Session Support
+
+## Overview
+
+LiteLLM now supports sharing `aiohttp.ClientSession` instances across multiple API calls to avoid creating unnecessary new sessions. This improves performance and resource utilization.
+
+## Usage
+
+### Basic Usage
+
+```python
+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-4o",
+ messages=[{"role": "user", "content": "Hello"}],
+ shared_session=shared_session
+ )
+
+ response2 = await acompletion(
+ model="gpt-4o",
+ messages=[{"role": "user", "content": "How are you?"}],
+ shared_session=shared_session
+ )
+
+ # Both calls reuse the same session!
+
+asyncio.run(main())
+```
+
+### Without Shared Session (Default)
+
+```python
+import asyncio
+from litellm import acompletion
+
+async def main():
+ # Each call creates a new session
+ response1 = await acompletion(
+ model="gpt-4o",
+ messages=[{"role": "user", "content": "Hello"}]
+ )
+
+ response2 = await acompletion(
+ model="gpt-4o",
+ messages=[{"role": "user", "content": "How are you?"}]
+ )
+ # Two separate sessions created
+
+asyncio.run(main())
+```
+
+## Benefits
+
+- **Performance**: Reuse HTTP connections across multiple calls
+- **Resource Efficiency**: Reduce memory and connection overhead
+- **Better Control**: Manage session lifecycle explicitly
+- **Debugging**: Easy to trace which calls use which sessions
+
+## Debug Logging
+
+Enable debug logging to see session reuse in action:
+
+```python
+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)
+```
+
+## Common Patterns
+
+### FastAPI Integration
+
+```python
+from fastapi import FastAPI
+import aiohttp
+import litellm
+
+app = FastAPI()
+
+async def chat(messages: list[dict]):
+ # Create session per request
+ async with aiohttp.ClientSession() as session:
+ return await litellm.acompletion(
+ model="gpt-4o",
+ messages=messages,
+ shared_session=session
+ )
+```
+
+### Batch Processing
+
+```python
+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-4o",
+ messages=messages,
+ shared_session=shared_session
+ )
+ tasks.append(task)
+
+ # All tasks use the same session
+ results = await asyncio.gather(*tasks)
+ return results
+```
+
+### Custom Session Configuration
+
+```python
+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-4o",
+ messages=[{"role": "user", "content": "Hello"}],
+ shared_session=shared_session
+ )
+```
+
+## Implementation Details
+
+The `shared_session` parameter is threaded through the entire LiteLLM call chain:
+
+1. **`acompletion()`** - Accepts `shared_session` parameter
+2. **`BaseLLMHTTPHandler`** - Passes session to HTTP client creation
+3. **`AsyncHTTPHandler`** - Uses existing session if provided
+4. **`LiteLLMAiohttpTransport`** - Reuses the session for HTTP requests
+
+## Backward Compatibility
+
+- **100% backward compatible** - Existing code works unchanged
+- **Optional parameter** - `shared_session=None` by default
+- **No breaking changes** - All existing functionality preserved
+
+## Testing
+
+Test the shared session functionality:
+
+```python
+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-4o",
+ 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())
+```
+
+## Files Modified
+
+The shared session functionality was added to these files:
+
+- `litellm/main.py` - Added `shared_session` parameter to `acompletion()` and `completion()`
+- `litellm/llms/custom_httpx/http_handler.py` - Core session reuse logic
+- `litellm/llms/custom_httpx/llm_http_handler.py` - HTTP handler integration
+- `litellm/llms/openai/openai.py` - OpenAI provider integration
+- `litellm/llms/openai/common_utils.py` - OpenAI client creation
+- `litellm/llms/azure/chat/o_series_handler.py` - Azure O Series handler
+
+## Troubleshooting
+
+### Session Not Being Reused
+
+1. **Check debug logs**: Enable `LITELLM_LOG=DEBUG` to see session reuse messages
+2. **Verify session is not closed**: Ensure the session is still active when making calls
+3. **Check parameter passing**: Make sure `shared_session` is passed to all `acompletion()` calls
+
+### Performance Issues
+
+1. **Session configuration**: Tune `aiohttp.ClientSession` parameters for your use case
+2. **Connection limits**: Adjust `limit` and `limit_per_host` in `TCPConnector`
+3. **Timeout settings**: Configure appropriate timeouts for your environment
diff --git a/litellm/llms/azure/chat/o_series_handler.py b/litellm/llms/azure/chat/o_series_handler.py
index 2f3e9e63996..d0f5153b0eb 100644
--- a/litellm/llms/azure/chat/o_series_handler.py
+++ b/litellm/llms/azure/chat/o_series_handler.py
@@ -4,7 +4,7 @@ Handler file for calls to Azure OpenAI's o1/o3 family of models
Written separately to handle faking streaming for o1 and o3 models.
"""
-from typing import Any, Callable, Optional, Union
+from typing import TYPE_CHECKING, Any, Callable, Optional, Union
import httpx
@@ -13,6 +13,9 @@ from litellm.types.utils import ModelResponse
from ...openai.openai import OpenAIChatCompletion
from ..common_utils import BaseAzureLLM
+if TYPE_CHECKING:
+ from aiohttp import ClientSession
+
class AzureOpenAIO1ChatCompletion(BaseAzureLLM, OpenAIChatCompletion):
def completion(
@@ -38,6 +41,7 @@ class AzureOpenAIO1ChatCompletion(BaseAzureLLM, OpenAIChatCompletion):
organization: Optional[str] = None,
custom_llm_provider: Optional[str] = None,
drop_params: Optional[bool] = None,
+ shared_session: Optional["ClientSession"] = None,
):
client = self.get_azure_openai_client(
litellm_params=litellm_params,
@@ -69,4 +73,5 @@ class AzureOpenAIO1ChatCompletion(BaseAzureLLM, OpenAIChatCompletion):
organization=organization,
custom_llm_provider=custom_llm_provider,
drop_params=drop_params,
+ shared_session=shared_session,
)
diff --git a/litellm/llms/custom_httpx/http_handler.py b/litellm/llms/custom_httpx/http_handler.py
index 36b543086f5..18b0cbd594f 100644
--- a/litellm/llms/custom_httpx/http_handler.py
+++ b/litellm/llms/custom_httpx/http_handler.py
@@ -167,6 +167,7 @@ class AsyncHTTPHandler:
concurrent_limit=1000,
client_alias: Optional[str] = None, # name for client in logs
ssl_verify: Optional[VerifyTypes] = None,
+ existing_session: Optional["ClientSession"] = None,
):
self.timeout = timeout
self.event_hooks = event_hooks
@@ -175,6 +176,7 @@ class AsyncHTTPHandler:
concurrent_limit=concurrent_limit,
event_hooks=event_hooks,
ssl_verify=ssl_verify,
+ existing_session=existing_session,
)
self.client_alias = client_alias
@@ -184,6 +186,7 @@ class AsyncHTTPHandler:
concurrent_limit: int,
event_hooks: Optional[Mapping[str, List[Callable[..., Any]]]],
ssl_verify: Optional[VerifyTypes] = None,
+ existing_session: Optional["ClientSession"] = None,
) -> httpx.AsyncClient:
# Get unified SSL configuration
ssl_config = get_ssl_configuration(ssl_verify)
@@ -199,6 +202,7 @@ class AsyncHTTPHandler:
transport = AsyncHTTPHandler._create_async_transport(
ssl_context=ssl_config if isinstance(ssl_config, ssl.SSLContext) else None,
ssl_verify=ssl_config if isinstance(ssl_config, bool) else None,
+ existing_session=existing_session,
)
return httpx.AsyncClient(
@@ -260,7 +264,6 @@ class AsyncHTTPHandler:
files: Optional[RequestFiles] = None,
content: Any = None,
):
-
start_time = time.time()
try:
if timeout is None:
@@ -523,7 +526,9 @@ class AsyncHTTPHandler:
@staticmethod
def _create_async_transport(
- ssl_context: Optional[ssl.SSLContext] = None, ssl_verify: Optional[bool] = None
+ ssl_context: Optional[ssl.SSLContext] = None,
+ ssl_verify: Optional[bool] = None,
+ existing_session: Optional["ClientSession"] = None,
) -> Optional[Union[LiteLLMAiohttpTransport, AsyncHTTPTransport]]:
"""
- Creates a transport for httpx.AsyncClient
@@ -544,7 +549,9 @@ class AsyncHTTPHandler:
#########################################################
if AsyncHTTPHandler._should_use_aiohttp_transport():
return AsyncHTTPHandler._create_aiohttp_transport(
- ssl_context=ssl_context, ssl_verify=ssl_verify
+ ssl_context=ssl_context,
+ ssl_verify=ssl_verify,
+ existing_session=existing_session,
)
#########################################################
@@ -612,6 +619,7 @@ class AsyncHTTPHandler:
def _create_aiohttp_transport(
ssl_verify: Optional[bool] = None,
ssl_context: Optional[ssl.SSLContext] = None,
+ existing_session: Optional["ClientSession"] = None,
) -> LiteLLMAiohttpTransport:
"""
Creates an AiohttpTransport with RequestNotRead error handling
@@ -635,6 +643,18 @@ class AsyncHTTPHandler:
trust_env = True
verbose_logger.debug("Creating AiohttpTransport...")
+
+ # Use existing session if provided and valid
+ if existing_session is not None and not existing_session.closed:
+ verbose_logger.debug(
+ f"SHARED SESSION: Reusing existing ClientSession (ID: {id(existing_session)})"
+ )
+ return LiteLLMAiohttpTransport(client=existing_session)
+
+ # Create new session only if none provided or existing one is invalid
+ verbose_logger.debug(
+ "NEW SESSION: Creating new ClientSession (no shared session provided)"
+ )
return LiteLLMAiohttpTransport(
client=lambda: ClientSession(
connector=TCPConnector(**connector_kwargs),
@@ -921,6 +941,7 @@ class HTTPHandler:
def get_async_httpx_client(
llm_provider: Union[LlmProviders, httpxSpecialProvider],
params: Optional[dict] = None,
+ existing_session: Optional["ClientSession"] = None,
) -> AsyncHTTPHandler:
"""
Retrieves the async HTTP client from the cache
@@ -942,10 +963,12 @@ def get_async_httpx_client(
return _cached_client
if params is not None:
+ params["existing_session"] = existing_session
_new_client = AsyncHTTPHandler(**params)
else:
_new_client = AsyncHTTPHandler(
- timeout=httpx.Timeout(timeout=600.0, connect=5.0)
+ timeout=httpx.Timeout(timeout=600.0, connect=5.0),
+ existing_session=existing_session,
)
litellm.in_memory_llm_clients_cache.set_cache(
diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.py
index dc64fea1a33..74d438db110 100644
--- a/litellm/llms/custom_httpx/llm_http_handler.py
+++ b/litellm/llms/custom_httpx/llm_http_handler.py
@@ -88,6 +88,7 @@ from litellm.utils import (
)
if TYPE_CHECKING:
+ from aiohttp import ClientSession
from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj
from litellm.llms.base_llm.passthrough.transformation import BasePassthroughConfig
@@ -236,11 +237,16 @@ class BaseLLMHTTPHandler:
client: Optional[AsyncHTTPHandler] = None,
json_mode: bool = False,
signed_json_body: Optional[bytes] = None,
+ shared_session: Optional["ClientSession"] = None,
):
if client is None:
+ verbose_logger.debug(
+ f"Creating HTTP client with shared_session: {id(shared_session) if shared_session else None}"
+ )
async_httpx_client = get_async_httpx_client(
llm_provider=litellm.LlmProviders(custom_llm_provider),
params={"ssl_verify": litellm_params.get("ssl_verify", None)},
+ existing_session=shared_session,
)
else:
async_httpx_client = client
@@ -290,6 +296,7 @@ class BaseLLMHTTPHandler:
headers: Optional[Dict[str, Any]] = None,
client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None,
provider_config: Optional[BaseConfig] = None,
+ shared_session: Optional["ClientSession"] = None,
):
json_mode: bool = optional_params.pop("json_mode", False)
extra_body: Optional[dict] = optional_params.pop("extra_body", None)
@@ -469,7 +476,7 @@ class BaseLLMHTTPHandler:
if client is None or not isinstance(client, HTTPHandler):
sync_httpx_client = _get_httpx_client(
- params={"ssl_verify": litellm_params.get("ssl_verify", None)}
+ params={"ssl_verify": litellm_params.get("ssl_verify", None)},
)
else:
sync_httpx_client = client
@@ -2283,7 +2290,7 @@ class BaseLLMHTTPHandler:
e=e,
provider_config=provider_config,
)
-
+
# Store the upload URL in litellm_params for the transformation method
litellm_params_with_url = dict(litellm_params)
litellm_params_with_url["upload_url"] = api_base
@@ -2574,11 +2581,11 @@ class BaseLLMHTTPHandler:
"url": transformed_request["url"],
"headers": transformed_request["headers"],
}
-
+
# Only add data for non-GET requests
if method != "get" and transformed_request.get("data") is not None:
request_kwargs["data"] = transformed_request["data"]
-
+
batch_response = getattr(sync_httpx_client, method)(**request_kwargs)
elif isinstance(transformed_request, dict) and api_base:
# For other providers that use JSON requests
@@ -2743,12 +2750,14 @@ class BaseLLMHTTPHandler:
"url": transformed_request["url"],
"headers": transformed_request["headers"],
}
-
+
# Only add data for non-GET requests
if method != "get" and transformed_request.get("data") is not None:
request_kwargs["data"] = transformed_request["data"]
-
- batch_response = await getattr(async_httpx_client, method)(**request_kwargs)
+
+ batch_response = await getattr(async_httpx_client, method)(
+ **request_kwargs
+ )
elif isinstance(transformed_request, dict) and api_base:
# For other providers that use JSON requests
batch_response = await async_httpx_client.get(
diff --git a/litellm/llms/openai/common_utils.py b/litellm/llms/openai/common_utils.py
index aa670df0531..0b2daa1446c 100644
--- a/litellm/llms/openai/common_utils.py
+++ b/litellm/llms/openai/common_utils.py
@@ -5,12 +5,15 @@ Common helpers / utils across al OpenAI endpoints
import hashlib
import json
import ssl
-from typing import Any, Dict, List, Literal, Optional, Union
+from typing import Any, Dict, List, Literal, Optional, TYPE_CHECKING, Union
import httpx
import openai
from openai import AsyncAzureOpenAI, AsyncOpenAI, AzureOpenAI, OpenAI
+if TYPE_CHECKING:
+ from aiohttp import ClientSession
+
import litellm
from litellm.llms.base_llm.chat.transformation import BaseLLMException
from litellm.llms.custom_httpx.http_handler import (
@@ -194,7 +197,9 @@ class BaseOpenAILLM:
return param_names
@staticmethod
- def _get_async_http_client() -> Optional[httpx.AsyncClient]:
+ def _get_async_http_client(
+ shared_session: Optional["ClientSession"] = None,
+ ) -> Optional[httpx.AsyncClient]:
if litellm.aclient_session is not None:
return litellm.aclient_session
@@ -205,8 +210,11 @@ class BaseOpenAILLM:
limits=httpx.Limits(max_connections=1000, max_keepalive_connections=100),
verify=ssl_config,
transport=AsyncHTTPHandler._create_async_transport(
- ssl_context=ssl_config if isinstance(ssl_config, ssl.SSLContext) else None,
+ ssl_context=ssl_config
+ if isinstance(ssl_config, ssl.SSLContext)
+ else None,
ssl_verify=ssl_config if isinstance(ssl_config, bool) else None,
+ existing_session=shared_session,
),
follow_redirects=True,
)
@@ -215,10 +223,10 @@ class BaseOpenAILLM:
def _get_sync_http_client() -> Optional[httpx.Client]:
if litellm.client_session is not None:
return litellm.client_session
-
+
# Get unified SSL configuration
ssl_config = get_ssl_configuration()
-
+
return httpx.Client(
limits=httpx.Limits(max_connections=1000, max_keepalive_connections=100),
verify=ssl_config,
diff --git a/litellm/llms/openai/openai.py b/litellm/llms/openai/openai.py
index 1f3cf24457d..3347e533242 100644
--- a/litellm/llms/openai/openai.py
+++ b/litellm/llms/openai/openai.py
@@ -10,12 +10,16 @@ from typing import (
List,
Literal,
Optional,
+ TYPE_CHECKING,
Union,
cast,
)
from urllib.parse import urlparse
import httpx
+
+if TYPE_CHECKING:
+ from aiohttp import ClientSession
import openai
from openai import AsyncOpenAI, OpenAI
from openai.types.beta.assistant_deleted import AssistantDeleted
@@ -355,6 +359,7 @@ class OpenAIChatCompletion(BaseLLM, BaseOpenAILLM):
max_retries: Optional[int] = DEFAULT_MAX_RETRIES,
organization: Optional[str] = None,
client: Optional[Union[OpenAI, AsyncOpenAI]] = None,
+ shared_session: Optional["ClientSession"] = None,
) -> Optional[Union[OpenAI, AsyncOpenAI]]:
client_initialization_params: Dict = locals()
if client is None:
@@ -379,7 +384,9 @@ class OpenAIChatCompletion(BaseLLM, BaseOpenAILLM):
_new_client: Union[OpenAI, AsyncOpenAI] = AsyncOpenAI(
api_key=api_key,
base_url=api_base,
- http_client=OpenAIChatCompletion._get_async_http_client(),
+ http_client=OpenAIChatCompletion._get_async_http_client(
+ shared_session=shared_session
+ ),
timeout=timeout,
max_retries=max_retries,
organization=organization,
@@ -522,8 +529,9 @@ class OpenAIChatCompletion(BaseLLM, BaseOpenAILLM):
organization: Optional[str] = None,
custom_llm_provider: Optional[str] = None,
drop_params: Optional[bool] = None,
+ shared_session: Optional["ClientSession"] = None,
):
- super().completion()
+ super().completion(shared_session=shared_session)
try:
fake_stream: bool = False
inference_params = optional_params.copy()
@@ -606,6 +614,7 @@ class OpenAIChatCompletion(BaseLLM, BaseOpenAILLM):
organization=organization,
drop_params=drop_params,
fake_stream=fake_stream,
+ shared_session=shared_session,
)
data = provider_config.transform_request(
@@ -771,6 +780,7 @@ class OpenAIChatCompletion(BaseLLM, BaseOpenAILLM):
drop_params: Optional[bool] = None,
stream_options: Optional[dict] = None,
fake_stream: bool = False,
+ shared_session: Optional["ClientSession"] = None,
):
response = None
data = await provider_config.async_transform_request(
@@ -793,6 +803,7 @@ class OpenAIChatCompletion(BaseLLM, BaseOpenAILLM):
max_retries=max_retries,
organization=organization,
client=client,
+ shared_session=shared_session,
)
## LOGGING
diff --git a/litellm/main.py b/litellm/main.py
index 44f591d49ae..6b2e13b8798 100644
--- a/litellm/main.py
+++ b/litellm/main.py
@@ -36,8 +36,12 @@ from typing import (
Union,
cast,
get_args,
+ TYPE_CHECKING,
)
+if TYPE_CHECKING:
+ from aiohttp import ClientSession
+
import dotenv
import httpx
import openai
@@ -374,6 +378,8 @@ async def acompletion(
# Optional liteLLM function params
thinking: Optional[AnthropicThinkingParam] = None,
web_search_options: Optional[OpenAIWebSearchOptions] = None,
+ # Session management
+ shared_session: Optional["ClientSession"] = None,
**kwargs,
) -> Union[ModelResponse, CustomStreamWrapper]:
"""
@@ -466,6 +472,16 @@ async def acompletion(
#########################################################
#########################################################
+ # Log shared session usage
+ if shared_session is not None:
+ verbose_logger.debug(
+ f"🔄 SHARED SESSION: acompletion called with shared_session (ID: {id(shared_session)})"
+ )
+ else:
+ verbose_logger.debug(
+ "🔄 NO SHARED SESSION: acompletion called without shared_session"
+ )
+
# Adjusted to use explicit arguments instead of *args and **kwargs
completion_kwargs = {
"model": model,
@@ -506,6 +522,7 @@ async def acompletion(
"acompletion": True, # assuming this is a required parameter
"thinking": thinking,
"web_search_options": web_search_options,
+ "shared_session": shared_session,
}
if custom_llm_provider is None:
_, custom_llm_provider, _, _ = get_llm_provider(
@@ -930,6 +947,8 @@ def completion( # type: ignore # noqa: PLR0915
model_list: Optional[list] = None, # pass in a list of api_base,keys, etc.
# Optional liteLLM function params
thinking: Optional[AnthropicThinkingParam] = None,
+ # Session management
+ shared_session: Optional["ClientSession"] = None,
**kwargs,
) -> Union[ModelResponse, CustomStreamWrapper]:
"""
@@ -1075,7 +1094,6 @@ def completion( # type: ignore # noqa: PLR0915
prompt_id=prompt_id, non_default_params=non_default_params
)
):
-
(
model,
messages,
@@ -1596,6 +1614,7 @@ def completion( # type: ignore # noqa: PLR0915
logging_obj=logging,
optional_params=optional_params,
litellm_params=litellm_params,
+ shared_session=shared_session,
timeout=timeout, # type: ignore
client=client,
custom_llm_provider=custom_llm_provider,
@@ -1642,6 +1661,7 @@ def completion( # type: ignore # noqa: PLR0915
logging_obj=logging,
optional_params=optional_params,
litellm_params=litellm_params,
+ shared_session=shared_session,
timeout=timeout, # type: ignore
client=client, # pass AsyncOpenAI, OpenAI client
custom_llm_provider=custom_llm_provider,
@@ -1771,6 +1791,7 @@ def completion( # type: ignore # noqa: PLR0915
logging_obj=logging,
optional_params=optional_params,
litellm_params=litellm_params,
+ shared_session=shared_session,
timeout=timeout, # type: ignore
client=client,
custom_llm_provider=custom_llm_provider,
@@ -1800,6 +1821,7 @@ def completion( # type: ignore # noqa: PLR0915
logging_obj=logging,
optional_params=optional_params,
litellm_params=litellm_params,
+ shared_session=shared_session,
timeout=timeout,
client=client,
custom_llm_provider=custom_llm_provider,
@@ -1830,6 +1852,7 @@ def completion( # type: ignore # noqa: PLR0915
logging_obj=logging,
optional_params=optional_params,
litellm_params=litellm_params,
+ shared_session=shared_session,
timeout=timeout, # type: ignore
client=client,
custom_llm_provider=custom_llm_provider,
@@ -1881,6 +1904,7 @@ def completion( # type: ignore # noqa: PLR0915
model_response=model_response,
optional_params=optional_params,
litellm_params=litellm_params,
+ shared_session=shared_session,
custom_llm_provider=custom_llm_provider,
timeout=timeout,
headers=headers,
@@ -1954,6 +1978,7 @@ def completion( # type: ignore # noqa: PLR0915
logging_obj=logging,
optional_params=optional_params,
litellm_params=litellm_params,
+ shared_session=shared_session,
timeout=timeout,
client=client,
custom_llm_provider=custom_llm_provider,
@@ -2032,7 +2057,6 @@ def completion( # type: ignore # noqa: PLR0915
try:
if use_base_llm_http_handler:
-
response = base_llm_http_handler.completion(
model=model,
messages=messages,
@@ -2044,6 +2068,7 @@ def completion( # type: ignore # noqa: PLR0915
optional_params=optional_params,
timeout=timeout,
litellm_params=litellm_params,
+ shared_session=shared_session,
acompletion=acompletion,
stream=stream,
api_key=api_key,
@@ -2070,6 +2095,7 @@ def completion( # type: ignore # noqa: PLR0915
client=client, # pass AsyncOpenAI, OpenAI client
organization=organization,
custom_llm_provider=custom_llm_provider,
+ shared_session=shared_session,
)
except Exception as e:
## LOGGING - log the original exception returned
@@ -2110,6 +2136,7 @@ def completion( # type: ignore # noqa: PLR0915
optional_params=optional_params,
timeout=timeout,
litellm_params=litellm_params,
+ shared_session=shared_session,
acompletion=acompletion,
stream=stream,
api_key=api_key,
@@ -2197,6 +2224,7 @@ def completion( # type: ignore # noqa: PLR0915
model_response=model_response,
optional_params=optional_params,
litellm_params=litellm_params,
+ shared_session=shared_session,
custom_llm_provider="clarifai",
timeout=timeout,
headers=headers,
@@ -2242,6 +2270,7 @@ def completion( # type: ignore # noqa: PLR0915
model_response=model_response,
optional_params=optional_params,
litellm_params=litellm_params,
+ shared_session=shared_session,
custom_llm_provider="anthropic_text",
timeout=timeout,
headers=headers,
@@ -2427,6 +2456,7 @@ def completion( # type: ignore # noqa: PLR0915
model_response=model_response,
optional_params=optional_params,
litellm_params=litellm_params,
+ shared_session=shared_session,
custom_llm_provider="cohere_chat",
timeout=timeout,
headers=headers,
@@ -2512,15 +2542,10 @@ def completion( # type: ignore # noqa: PLR0915
)
elif custom_llm_provider == "compactifai":
api_key = (
- api_key
- or get_secret_str("COMPACTIFAI_API_KEY")
- or litellm.api_key
+ api_key or get_secret_str("COMPACTIFAI_API_KEY") or litellm.api_key
)
- api_base = (
- api_base
- or "https://api.compactif.ai/v1"
- )
+ api_base = api_base or "https://api.compactif.ai/v1"
## COMPLETION CALL
response = base_llm_http_handler.completion(
@@ -2694,6 +2719,7 @@ def completion( # type: ignore # noqa: PLR0915
model_response=model_response,
optional_params=optional_params,
litellm_params=litellm_params,
+ shared_session=shared_session,
custom_llm_provider="openrouter",
timeout=timeout,
headers=headers,
@@ -2756,6 +2782,7 @@ def completion( # type: ignore # noqa: PLR0915
model_response=model_response,
optional_params=optional_params,
litellm_params=litellm_params,
+ shared_session=shared_session,
custom_llm_provider="vercel_ai_gateway",
timeout=timeout,
headers=headers,
@@ -3106,9 +3133,9 @@ def completion( # type: ignore # noqa: PLR0915
"aws_region_name" not in optional_params
or optional_params["aws_region_name"] is None
):
- optional_params["aws_region_name"] = (
- aws_bedrock_client.meta.region_name
- )
+ optional_params[
+ "aws_region_name"
+ ] = aws_bedrock_client.meta.region_name
bedrock_route = BedrockModelInfo.get_bedrock_route(model)
if bedrock_route == "converse":
@@ -3242,6 +3269,7 @@ def completion( # type: ignore # noqa: PLR0915
model_response=model_response,
optional_params=optional_params,
litellm_params=litellm_params,
+ shared_session=shared_session,
custom_llm_provider="watsonx_text",
timeout=timeout,
headers=headers,
@@ -3295,6 +3323,7 @@ def completion( # type: ignore # noqa: PLR0915
model_response=model_response,
optional_params=optional_params,
litellm_params=litellm_params,
+ shared_session=shared_session,
custom_llm_provider="ollama",
timeout=timeout,
headers=headers,
@@ -3328,6 +3357,7 @@ def completion( # type: ignore # noqa: PLR0915
model_response=model_response,
optional_params=optional_params,
litellm_params=litellm_params,
+ shared_session=shared_session,
custom_llm_provider="ollama_chat",
timeout=timeout,
headers=headers,
@@ -3348,6 +3378,7 @@ def completion( # type: ignore # noqa: PLR0915
model_response=model_response,
optional_params=optional_params,
litellm_params=litellm_params,
+ shared_session=shared_session,
custom_llm_provider=custom_llm_provider,
timeout=timeout,
headers=headers,
@@ -3380,6 +3411,7 @@ def completion( # type: ignore # noqa: PLR0915
model_response=model_response,
optional_params=optional_params,
litellm_params=litellm_params,
+ shared_session=shared_session,
custom_llm_provider="cloudflare",
timeout=timeout,
headers=headers,
@@ -3433,6 +3465,7 @@ def completion( # type: ignore # noqa: PLR0915
logging_obj=logging,
optional_params=optional_params,
litellm_params=litellm_params,
+ shared_session=shared_session,
timeout=timeout, # type: ignore
client=client,
custom_llm_provider=custom_llm_provider,
@@ -3450,7 +3483,6 @@ def completion( # type: ignore # noqa: PLR0915
)
raise e
elif custom_llm_provider == "gradient_ai":
-
api_base = litellm.api_base or api_base
response = base_llm_http_handler.completion(
model=model,
@@ -3461,6 +3493,7 @@ def completion( # type: ignore # noqa: PLR0915
model_response=model_response,
optional_params=optional_params,
litellm_params=litellm_params,
+ shared_session=shared_session,
custom_llm_provider="gradient_ai",
timeout=timeout,
headers=headers,
@@ -5089,9 +5122,9 @@ def adapter_completion(
new_kwargs = translation_obj.translate_completion_input_params(kwargs=kwargs)
response: Union[ModelResponse, CustomStreamWrapper] = completion(**new_kwargs) # type: ignore
- translated_response: Optional[Union[BaseModel, AdapterCompletionStreamWrapper]] = (
- None
- )
+ translated_response: Optional[
+ Union[BaseModel, AdapterCompletionStreamWrapper]
+ ] = None
if isinstance(response, ModelResponse):
translated_response = translation_obj.translate_completion_output_params(
response=response
@@ -6079,9 +6112,9 @@ def stream_chunk_builder( # noqa: PLR0915
]
if len(content_chunks) > 0:
- response["choices"][0]["message"]["content"] = (
- processor.get_combined_content(content_chunks)
- )
+ response["choices"][0]["message"][
+ "content"
+ ] = processor.get_combined_content(content_chunks)
thinking_blocks = [
chunk
@@ -6092,9 +6125,9 @@ def stream_chunk_builder( # noqa: PLR0915
]
if len(thinking_blocks) > 0:
- response["choices"][0]["message"]["thinking_blocks"] = (
- processor.get_combined_thinking_content(thinking_blocks)
- )
+ response["choices"][0]["message"][
+ "thinking_blocks"
+ ] = processor.get_combined_thinking_content(thinking_blocks)
reasoning_chunks = [
chunk
@@ -6105,9 +6138,9 @@ def stream_chunk_builder( # noqa: PLR0915
]
if len(reasoning_chunks) > 0:
- response["choices"][0]["message"]["reasoning_content"] = (
- processor.get_combined_reasoning_content(reasoning_chunks)
- )
+ response["choices"][0]["message"][
+ "reasoning_content"
+ ] = processor.get_combined_reasoning_content(reasoning_chunks)
audio_chunks = [
chunk
diff --git a/tests/test_litellm/llms/custom_httpx/test_http_handler.py b/tests/test_litellm/llms/custom_httpx/test_http_handler.py
index a649e9b6b9c..d33a3d0918b 100644
--- a/tests/test_litellm/llms/custom_httpx/test_http_handler.py
+++ b/tests/test_litellm/llms/custom_httpx/test_http_handler.py
@@ -29,16 +29,17 @@ async def test_ssl_security_level(monkeypatch):
# Get the transport (should be LiteLLMAiohttpTransport)
transport = client.client._transport
+ assert isinstance(transport, LiteLLMAiohttpTransport)
# Get the aiohttp ClientSession
client_session = transport._get_valid_client_session()
# Get the connector from the session
connector = client_session.connector
+ assert isinstance(connector, TCPConnector)
# Get the SSL context from the connector
ssl_context = connector._ssl
- print("ssl_context", ssl_context)
# Verify that the SSL context exists and has the correct cipher string
assert isinstance(ssl_context, ssl.SSLContext)
@@ -108,20 +109,19 @@ async def test_ssl_verification_with_aiohttp_transport():
# Create a test SSL context
litellm_async_client = AsyncHTTPHandler(ssl_verify=False)
- transport_connector = (
- litellm_async_client.client._transport._get_valid_client_session().connector
- )
- print("transport_connector", transport_connector)
- print("transport_connector._ssl", transport_connector._ssl)
+ transport = litellm_async_client.client._transport
+ assert isinstance(transport, LiteLLMAiohttpTransport)
+ transport_connector = transport._get_valid_client_session().connector
+ assert isinstance(transport_connector, TCPConnector)
aiohttp_session = aiohttp.ClientSession(
connector=aiohttp.TCPConnector(verify_ssl=False)
)
- print("aiohttp_session", aiohttp_session)
- print("aiohttp_session._ssl", aiohttp_session.connector._ssl)
+ aiohttp_connector = aiohttp_session.connector
+ assert isinstance(aiohttp_connector, aiohttp.TCPConnector)
# assert both litellm transport and aiohttp session have ssl_verify=False
- assert transport_connector._ssl == aiohttp_session.connector._ssl
+ assert transport_connector._ssl == aiohttp_connector._ssl
@pytest.mark.asyncio
@@ -183,3 +183,219 @@ def test_get_ssl_configuration_integration():
# Verify it has basic SSL context properties
assert ssl_context.protocol is not None
assert ssl_context.verify_mode is not None
+
+
+# Session Reuse Tests
+class MockClientSession:
+ """Mock ClientSession that is not callable"""
+ def __init__(self):
+ self.closed = False
+
+async def test_create_aiohttp_transport_with_existing_session():
+ """Test that _create_aiohttp_transport reuses existing session when provided"""
+ from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
+
+ # Create a mock existing session that's not callable
+ mock_session = MockClientSession()
+
+ # Test with existing session
+ transport = AsyncHTTPHandler._create_aiohttp_transport(
+ existing_session=mock_session # type: ignore
+ )
+
+ # Verify the transport uses the existing session directly
+ assert transport.client is mock_session
+ assert not callable(transport.client) # Should not be callable
+
+
+async def test_create_aiohttp_transport_without_existing_session():
+ """Test that _create_aiohttp_transport creates new session when none provided"""
+ from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
+
+ # Test without existing session
+ transport = AsyncHTTPHandler._create_aiohttp_transport(existing_session=None)
+
+ # Verify the transport uses a lambda function (for backward compatibility)
+ assert callable(transport.client) # Should be a lambda function
+
+
+async def test_create_aiohttp_transport_with_closed_session():
+ """Test that _create_aiohttp_transport creates new session when existing session is closed"""
+ from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
+
+ # Create a mock closed session
+ mock_session = MockClientSession()
+ mock_session.closed = True
+
+ # Test with closed session
+ transport = AsyncHTTPHandler._create_aiohttp_transport(
+ existing_session=mock_session # type: ignore
+ )
+
+ # Verify the transport creates a new session (lambda function)
+ assert callable(transport.client) # Should be a lambda function
+
+
+async def test_async_handler_with_existing_session():
+ """Test AsyncHTTPHandler initialization with existing session"""
+ from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
+
+ # Create a mock existing session
+ mock_session = MockClientSession()
+
+ # Create handler with existing session
+ handler = AsyncHTTPHandler(existing_session=mock_session) # type: ignore
+
+ # Verify the handler was created successfully
+ assert handler is not None
+ assert handler.client is not None
+
+
+async def test_get_async_httpx_client_with_existing_session():
+ """Test get_async_httpx_client with existing session"""
+ from litellm.llms.custom_httpx.http_handler import get_async_httpx_client
+ from litellm.types.utils import LlmProviders
+
+ # Create a mock existing session
+ mock_session = MockClientSession()
+
+ # Test with existing session
+ client = get_async_httpx_client(
+ llm_provider=LlmProviders.ANTHROPIC,
+ existing_session=mock_session # type: ignore
+ )
+
+ # Verify the client was created successfully
+ assert client is not None
+ assert isinstance(client, AsyncHTTPHandler)
+
+
+async def test_get_async_httpx_client_without_existing_session():
+ """Test get_async_httpx_client without existing session (backward compatibility)"""
+ from litellm.llms.custom_httpx.http_handler import get_async_httpx_client
+ from litellm.types.utils import LlmProviders
+
+ # Test without existing session
+ client = get_async_httpx_client(
+ llm_provider=LlmProviders.ANTHROPIC,
+ existing_session=None
+ )
+
+ # Verify the client was created successfully
+ assert client is not None
+ assert isinstance(client, AsyncHTTPHandler)
+
+
+async def test_session_reuse_chain():
+ """Test that session is properly passed through the entire call chain"""
+ from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
+
+ # Create a mock existing session
+ mock_session = MockClientSession()
+
+ # Test the entire chain
+ transport = AsyncHTTPHandler._create_async_transport(
+ existing_session=mock_session # type: ignore
+ )
+
+ # Verify the transport was created
+ assert transport is not None
+
+ # Test AsyncHTTPHandler creation
+ handler = AsyncHTTPHandler(existing_session=mock_session) # type: ignore
+ assert handler is not None
+
+
+def test_shared_session_parameter_in_acompletion():
+ """Test that acompletion function accepts shared_session parameter"""
+ import inspect
+ from litellm.main import acompletion
+
+ # Get the function signature
+ sig = inspect.signature(acompletion)
+ params = list(sig.parameters.keys())
+
+ # Verify shared_session parameter exists
+ assert 'shared_session' in params
+
+ # Verify the parameter type annotation
+ shared_session_param = sig.parameters['shared_session']
+ assert 'ClientSession' in str(shared_session_param.annotation)
+
+
+def test_shared_session_parameter_in_completion():
+ """Test that completion function accepts shared_session parameter"""
+ import inspect
+ from litellm.main import completion
+
+ # Get the function signature
+ sig = inspect.signature(completion)
+ params = list(sig.parameters.keys())
+
+ # Verify shared_session parameter exists
+ assert 'shared_session' in params
+
+ # Verify the parameter type annotation
+ shared_session_param = sig.parameters['shared_session']
+ assert 'ClientSession' in str(shared_session_param.annotation)
+
+
+async def test_session_reuse_integration():
+ """Integration test for session reuse functionality"""
+ from litellm.llms.custom_httpx.http_handler import get_async_httpx_client
+ from litellm.types.utils import LlmProviders
+
+ # Create a mock session
+ mock_session = MockClientSession()
+
+ # Create two clients with the same session
+ client1 = get_async_httpx_client(
+ llm_provider=LlmProviders.ANTHROPIC,
+ existing_session=mock_session # type: ignore
+ )
+
+ client2 = get_async_httpx_client(
+ llm_provider=LlmProviders.OPENAI,
+ existing_session=mock_session # type: ignore
+ )
+
+ # Both clients should be created successfully
+ assert client1 is not None
+ assert client2 is not None
+
+ # Both should be AsyncHTTPHandler instances
+ assert isinstance(client1, AsyncHTTPHandler)
+ assert isinstance(client2, AsyncHTTPHandler)
+
+ # Clean up
+ await client1.close()
+ await client2.close()
+
+
+async def test_session_validation():
+ """Test that session validation works correctly"""
+ from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
+
+ # Test with None session
+ transport1 = AsyncHTTPHandler._create_aiohttp_transport(existing_session=None)
+ assert callable(transport1.client) # Should create lambda
+
+ # Test with closed session
+ mock_closed_session = MockClientSession()
+ mock_closed_session.closed = True
+ transport2 = AsyncHTTPHandler._create_aiohttp_transport(existing_session=mock_closed_session) # type: ignore
+ assert callable(transport2.client) # Should create lambda
+
+ # Test with valid session
+ mock_valid_session = MockClientSession()
+ transport3 = AsyncHTTPHandler._create_aiohttp_transport(existing_session=mock_valid_session) # type: ignore
+ assert transport3.client is mock_valid_session # Should reuse session
diff --git a/tests/test_litellm/test_shared_session_integration.py b/tests/test_litellm/test_shared_session_integration.py
new file mode 100644
index 00000000000..94ec12b4e56
--- /dev/null
+++ b/tests/test_litellm/test_shared_session_integration.py
@@ -0,0 +1,190 @@
+"""
+Integration tests for shared session functionality in main.py
+"""
+import os
+import sys
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+# Add the litellm directory to the path
+sys.path.insert(0, os.path.abspath("../../.."))
+
+import litellm
+
+
+class TestSharedSessionIntegration:
+ """Test cases for shared session integration in main.py"""
+
+ def test_acompletion_shared_session_parameter(self):
+ """Test that acompletion accepts shared_session parameter"""
+ import inspect
+
+ # Get the function signature
+ sig = inspect.signature(litellm.acompletion)
+ params = list(sig.parameters.keys())
+
+ # Verify shared_session parameter exists
+ assert 'shared_session' in params
+
+ # Verify the parameter type annotation
+ shared_session_param = sig.parameters['shared_session']
+ assert 'ClientSession' in str(shared_session_param.annotation)
+
+ # Verify default value is None
+ assert shared_session_param.default is None
+
+ def test_completion_shared_session_parameter(self):
+ """Test that completion accepts shared_session parameter"""
+ import inspect
+
+ # Get the function signature
+ sig = inspect.signature(litellm.completion)
+ params = list(sig.parameters.keys())
+
+ # Verify shared_session parameter exists
+ assert 'shared_session' in params
+
+ # Verify the parameter type annotation
+ shared_session_param = sig.parameters['shared_session']
+ assert 'ClientSession' in str(shared_session_param.annotation)
+
+ # Verify default value is None
+ assert shared_session_param.default is None
+
+ @pytest.mark.asyncio
+ async def test_acompletion_with_shared_session_mock(self):
+ """Test acompletion with mocked shared session (no actual API call)"""
+ import inspect
+
+ # Create a mock session
+ mock_session = MagicMock()
+ mock_session.closed = False
+
+ # Mock the completion function to avoid actual API calls
+ with patch('litellm.completion') as mock_completion:
+ mock_completion.return_value = {"choices": [{"message": {"content": "test"}}]}
+
+ # This should not raise an error even though we can't make actual API calls
+ try:
+ # We can't actually call acompletion without proper setup,
+ # but we can verify the parameter is accepted
+ sig = inspect.signature(litellm.acompletion)
+ assert 'shared_session' in sig.parameters
+ except Exception as e:
+ # Expected to fail due to missing API keys, but parameter should be valid
+ sig = inspect.signature(litellm.acompletion)
+ assert 'shared_session' in sig.parameters
+
+ def test_shared_session_passed_to_completion_kwargs(self):
+ """Test that shared_session is passed through completion_kwargs"""
+ # This test verifies that the shared_session parameter
+ # is properly included in the completion_kwargs dictionary
+
+ # We can't easily test the internal logic without mocking,
+ # but we can verify the parameter exists in the function signature
+ import inspect
+
+ sig = inspect.signature(litellm.acompletion)
+ shared_session_param = sig.parameters['shared_session']
+
+ # Verify the parameter is properly typed
+ assert 'ClientSession' in str(shared_session_param.annotation)
+ assert shared_session_param.default is None
+
+ def test_backward_compatibility(self):
+ """Test that existing code without shared_session still works"""
+ import inspect
+
+ # Verify that shared_session has a default value of None
+ sig = inspect.signature(litellm.acompletion)
+ shared_session_param = sig.parameters['shared_session']
+
+ # This ensures backward compatibility
+ assert shared_session_param.default is None
+
+ def test_type_annotations_consistency(self):
+ """Test that type annotations are consistent between acompletion and completion"""
+ import inspect
+
+ # Get signatures for both functions
+ acompletion_sig = inspect.signature(litellm.acompletion)
+ completion_sig = inspect.signature(litellm.completion)
+
+ # Get the shared_session parameters
+ acompletion_param = acompletion_sig.parameters['shared_session']
+ completion_param = completion_sig.parameters['shared_session']
+
+ # Verify they have the same type annotation
+ assert str(acompletion_param.annotation) == str(completion_param.annotation)
+
+ # Verify they have the same default value
+ assert acompletion_param.default == completion_param.default
+
+ def test_shared_session_parameter_position(self):
+ """Test that shared_session parameter is in the correct position"""
+ import inspect
+
+ sig = inspect.signature(litellm.acompletion)
+ params = list(sig.parameters.keys())
+
+ # Find the position of shared_session
+ shared_session_index = params.index('shared_session')
+
+ # It should be near the end, before **kwargs
+ assert shared_session_index > 0
+ assert shared_session_index < len(params) - 1 # Should be before **kwargs
+
+ # Verify it's after the main parameters
+ assert 'model' in params[:shared_session_index]
+ assert 'messages' in params[:shared_session_index]
+
+
+class TestSharedSessionUsage:
+ """Test cases demonstrating proper usage of shared sessions"""
+
+ def test_shared_session_usage_example(self):
+ """Test example usage pattern for shared sessions"""
+ # This test demonstrates the expected usage pattern
+ # without actually making API calls
+
+ import inspect
+
+ # Verify the function signature allows for the expected usage
+ sig = inspect.signature(litellm.acompletion)
+ params = sig.parameters
+
+ # Verify all expected parameters exist
+ expected_params = [
+ 'model', 'messages', 'shared_session'
+ ]
+
+ for param in expected_params:
+ assert param in params, f"Parameter {param} not found in acompletion signature"
+
+ # Verify shared_session is optional
+ assert params['shared_session'].default is None
+
+ def test_shared_session_with_other_parameters(self):
+ """Test that shared_session works with other parameters"""
+ import inspect
+
+ sig = inspect.signature(litellm.acompletion)
+ params = sig.parameters
+
+ # Verify shared_session doesn't conflict with other parameters
+ assert 'shared_session' in params
+ assert 'model' in params
+ assert 'messages' in params
+ assert 'timeout' in params
+
+ # Verify the parameter order makes sense
+ param_list = list(params.keys())
+ shared_session_index = param_list.index('shared_session')
+
+ # shared_session should be after the main parameters but before **kwargs
+ assert shared_session_index > param_list.index('model')
+ assert shared_session_index > param_list.index('messages')
+
+ # Should be before **kwargs (last parameter)
+ assert shared_session_index < len(param_list) - 1