|
| 1 | +# Shared Session Support |
| 2 | + |
| 3 | +## Overview |
| 4 | + |
| 5 | +LiteLLM now supports sharing `aiohttp.ClientSession` instances across multiple API calls to avoid creating unnecessary new sessions. This improves performance and resource utilization. |
| 6 | + |
| 7 | +## Usage |
| 8 | + |
| 9 | +### Basic Usage |
| 10 | + |
| 11 | +```python |
| 12 | +import asyncio |
| 13 | +from aiohttp import ClientSession |
| 14 | +from litellm import acompletion |
| 15 | + |
| 16 | +async def main(): |
| 17 | + # Create a shared session |
| 18 | + async with ClientSession() as shared_session: |
| 19 | + # Use the same session for multiple calls |
| 20 | + response1 = await acompletion( |
| 21 | + model="gpt-4o", |
| 22 | + messages=[{"role": "user", "content": "Hello"}], |
| 23 | + shared_session=shared_session |
| 24 | + ) |
| 25 | + |
| 26 | + response2 = await acompletion( |
| 27 | + model="gpt-4o", |
| 28 | + messages=[{"role": "user", "content": "How are you?"}], |
| 29 | + shared_session=shared_session |
| 30 | + ) |
| 31 | + |
| 32 | + # Both calls reuse the same session! |
| 33 | + |
| 34 | +asyncio.run(main()) |
| 35 | +``` |
| 36 | + |
| 37 | +### Without Shared Session (Default) |
| 38 | + |
| 39 | +```python |
| 40 | +import asyncio |
| 41 | +from litellm import acompletion |
| 42 | + |
| 43 | +async def main(): |
| 44 | + # Each call creates a new session |
| 45 | + response1 = await acompletion( |
| 46 | + model="gpt-4o", |
| 47 | + messages=[{"role": "user", "content": "Hello"}] |
| 48 | + ) |
| 49 | + |
| 50 | + response2 = await acompletion( |
| 51 | + model="gpt-4o", |
| 52 | + messages=[{"role": "user", "content": "How are you?"}] |
| 53 | + ) |
| 54 | + # Two separate sessions created |
| 55 | + |
| 56 | +asyncio.run(main()) |
| 57 | +``` |
| 58 | + |
| 59 | +## Benefits |
| 60 | + |
| 61 | +- **Performance**: Reuse HTTP connections across multiple calls |
| 62 | +- **Resource Efficiency**: Reduce memory and connection overhead |
| 63 | +- **Better Control**: Manage session lifecycle explicitly |
| 64 | +- **Debugging**: Easy to trace which calls use which sessions |
| 65 | + |
| 66 | +## Debug Logging |
| 67 | + |
| 68 | +Enable debug logging to see session reuse in action: |
| 69 | + |
| 70 | +```python |
| 71 | +import os |
| 72 | +import litellm |
| 73 | + |
| 74 | +# Enable debug logging |
| 75 | +os.environ['LITELLM_LOG'] = 'DEBUG' |
| 76 | + |
| 77 | +# You'll see logs like: |
| 78 | +# 🔄 SHARED SESSION: acompletion called with shared_session (ID: 12345) |
| 79 | +# ✅ SHARED SESSION: Reusing existing ClientSession (ID: 12345) |
| 80 | +``` |
| 81 | + |
| 82 | +## Common Patterns |
| 83 | + |
| 84 | +### FastAPI Integration |
| 85 | + |
| 86 | +```python |
| 87 | +from fastapi import FastAPI |
| 88 | +import aiohttp |
| 89 | +import litellm |
| 90 | + |
| 91 | +app = FastAPI() |
| 92 | + |
| 93 | +@app.post("/chat") |
| 94 | +async def chat(messages: list[dict]): |
| 95 | + # Create session per request |
| 96 | + async with aiohttp.ClientSession() as session: |
| 97 | + return await litellm.acompletion( |
| 98 | + model="gpt-4o", |
| 99 | + messages=messages, |
| 100 | + shared_session=session |
| 101 | + ) |
| 102 | +``` |
| 103 | + |
| 104 | +### Batch Processing |
| 105 | + |
| 106 | +```python |
| 107 | +import asyncio |
| 108 | +from aiohttp import ClientSession |
| 109 | +from litellm import acompletion |
| 110 | + |
| 111 | +async def process_batch(messages_list): |
| 112 | + async with ClientSession() as shared_session: |
| 113 | + tasks = [] |
| 114 | + for messages in messages_list: |
| 115 | + task = acompletion( |
| 116 | + model="gpt-4o", |
| 117 | + messages=messages, |
| 118 | + shared_session=shared_session |
| 119 | + ) |
| 120 | + tasks.append(task) |
| 121 | + |
| 122 | + # All tasks use the same session |
| 123 | + results = await asyncio.gather(*tasks) |
| 124 | + return results |
| 125 | +``` |
| 126 | + |
| 127 | +### Custom Session Configuration |
| 128 | + |
| 129 | +```python |
| 130 | +import aiohttp |
| 131 | +import litellm |
| 132 | + |
| 133 | +# Create optimized session |
| 134 | +async with aiohttp.ClientSession( |
| 135 | + timeout=aiohttp.ClientTimeout(total=180), |
| 136 | + connector=aiohttp.TCPConnector(limit=300, limit_per_host=75) |
| 137 | +) as shared_session: |
| 138 | + |
| 139 | + response = await litellm.acompletion( |
| 140 | + model="gpt-4o", |
| 141 | + messages=[{"role": "user", "content": "Hello"}], |
| 142 | + shared_session=shared_session |
| 143 | + ) |
| 144 | +``` |
| 145 | + |
| 146 | +## Implementation Details |
| 147 | + |
| 148 | +The `shared_session` parameter is threaded through the entire LiteLLM call chain: |
| 149 | + |
| 150 | +1. **`acompletion()`** - Accepts `shared_session` parameter |
| 151 | +2. **`BaseLLMHTTPHandler`** - Passes session to HTTP client creation |
| 152 | +3. **`AsyncHTTPHandler`** - Uses existing session if provided |
| 153 | +4. **`LiteLLMAiohttpTransport`** - Reuses the session for HTTP requests |
| 154 | + |
| 155 | +## Backward Compatibility |
| 156 | + |
| 157 | +- **100% backward compatible** - Existing code works unchanged |
| 158 | +- **Optional parameter** - `shared_session=None` by default |
| 159 | +- **No breaking changes** - All existing functionality preserved |
| 160 | + |
| 161 | +## Testing |
| 162 | + |
| 163 | +Test the shared session functionality: |
| 164 | + |
| 165 | +```python |
| 166 | +import asyncio |
| 167 | +from aiohttp import ClientSession |
| 168 | +from litellm import acompletion |
| 169 | + |
| 170 | +async def test_shared_session(): |
| 171 | + async with ClientSession() as session: |
| 172 | + print(f"✅ Created session: {id(session)}") |
| 173 | + |
| 174 | + try: |
| 175 | + response = await acompletion( |
| 176 | + model="gpt-4o", |
| 177 | + messages=[{"role": "user", "content": "Hello"}], |
| 178 | + shared_session=session, |
| 179 | + api_key="your-api-key" |
| 180 | + ) |
| 181 | + print(f"Response: {response.choices[0].message.content}") |
| 182 | + except Exception as e: |
| 183 | + print(f"✅ Expected error: {type(e).__name__}") |
| 184 | + |
| 185 | + print("✅ Session control working!") |
| 186 | + |
| 187 | +asyncio.run(test_shared_session()) |
| 188 | +``` |
| 189 | + |
| 190 | +## Files Modified |
| 191 | + |
| 192 | +The shared session functionality was added to these files: |
| 193 | + |
| 194 | +- `litellm/main.py` - Added `shared_session` parameter to `acompletion()` and `completion()` |
| 195 | +- `litellm/llms/custom_httpx/http_handler.py` - Core session reuse logic |
| 196 | +- `litellm/llms/custom_httpx/llm_http_handler.py` - HTTP handler integration |
| 197 | +- `litellm/llms/openai/openai.py` - OpenAI provider integration |
| 198 | +- `litellm/llms/openai/common_utils.py` - OpenAI client creation |
| 199 | +- `litellm/llms/azure/chat/o_series_handler.py` - Azure O Series handler |
| 200 | + |
| 201 | +## Troubleshooting |
| 202 | + |
| 203 | +### Session Not Being Reused |
| 204 | + |
| 205 | +1. **Check debug logs**: Enable `LITELLM_LOG=DEBUG` to see session reuse messages |
| 206 | +2. **Verify session is not closed**: Ensure the session is still active when making calls |
| 207 | +3. **Check parameter passing**: Make sure `shared_session` is passed to all `acompletion()` calls |
| 208 | + |
| 209 | +### Performance Issues |
| 210 | + |
| 211 | +1. **Session configuration**: Tune `aiohttp.ClientSession` parameters for your use case |
| 212 | +2. **Connection limits**: Adjust `limit` and `limit_per_host` in `TCPConnector` |
| 213 | +3. **Timeout settings**: Configure appropriate timeouts for your environment |
0 commit comments