-
Notifications
You must be signed in to change notification settings - Fork 84
Add HTTP Connection Pooling for Improved Performance #697
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
fede-kamel
wants to merge
4
commits into
cohere-ai:main
Choose a base branch
from
fede-kamel:feature/add-connection-pooling
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+178
−4
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
564d064
Add HTTP connection pooling for improved performance
7dfa761
Add comprehensive test suite for connection pooling
57fbdf5
fix: Address review feedback for connection pooling
fede-kamel 6d30241
fix: Remove unused setUpClass with dead api_key_available attribute
fede-kamel File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,152 @@ | ||
| import os | ||
| import time | ||
| import unittest | ||
|
|
||
| import httpx | ||
|
|
||
| import cohere | ||
|
|
||
|
|
||
| class TestConnectionPooling(unittest.TestCase): | ||
| """Test suite for HTTP connection pooling functionality.""" | ||
|
|
||
| def test_httpx_client_creation_with_limits(self): | ||
| """Test that httpx clients can be created with our connection pooling limits.""" | ||
| # Test creating httpx client with limits (our implementation) | ||
| client_with_limits = httpx.Client( | ||
| timeout=300, | ||
| limits=httpx.Limits( | ||
| max_keepalive_connections=20, | ||
| max_connections=100, | ||
| keepalive_expiry=30.0, | ||
| ), | ||
| ) | ||
|
|
||
| # Verify the client was created successfully | ||
| self.assertIsNotNone(client_with_limits) | ||
| self.assertIsInstance(client_with_limits, httpx.Client) | ||
|
|
||
| # The limits are applied internally - we can't directly access them | ||
| # but we verify the client works correctly with our configuration | ||
|
|
||
| client_with_limits.close() | ||
|
|
||
| def test_cohere_client_initialization(self): | ||
| """Test that Cohere clients can be initialized with connection pooling.""" | ||
| # Test with dummy API key - just verifies initialization works | ||
| sync_client = cohere.Client(api_key="dummy-key") | ||
| v2_client = cohere.ClientV2(api_key="dummy-key") | ||
|
|
||
| # Verify clients were created | ||
| self.assertIsNotNone(sync_client) | ||
| self.assertIsNotNone(v2_client) | ||
|
|
||
| def test_custom_httpx_client_with_pooling(self): | ||
| """Test that custom httpx clients with connection pooling work correctly.""" | ||
| # Create custom httpx client with explicit pooling configuration | ||
| custom_client = httpx.Client( | ||
| timeout=30, | ||
| limits=httpx.Limits( | ||
| max_keepalive_connections=10, | ||
| max_connections=50, | ||
| keepalive_expiry=20.0, | ||
| ), | ||
| ) | ||
|
|
||
| # Create Cohere client with custom httpx client | ||
| try: | ||
| client = cohere.ClientV2(api_key="dummy-key", httpx_client=custom_client) | ||
| self.assertIsNotNone(client) | ||
| finally: | ||
| custom_client.close() | ||
|
|
||
| def test_connection_pooling_vs_no_pooling_setup(self): | ||
| """Test creating clients with and without connection pooling.""" | ||
| # Create httpx client without pooling | ||
| no_pool_httpx = httpx.Client( | ||
| timeout=30, | ||
| limits=httpx.Limits( | ||
| max_keepalive_connections=0, | ||
| max_connections=1, | ||
| keepalive_expiry=0, | ||
| ), | ||
| ) | ||
|
|
||
| # Verify both configurations work | ||
| try: | ||
| pooled_client = cohere.ClientV2(api_key="dummy-key") | ||
| no_pool_client = cohere.ClientV2(api_key="dummy-key", httpx_client=no_pool_httpx) | ||
|
|
||
| self.assertIsNotNone(pooled_client) | ||
| self.assertIsNotNone(no_pool_client) | ||
|
|
||
| finally: | ||
| no_pool_httpx.close() | ||
|
|
||
| @unittest.skipIf(not os.environ.get("CO_API_KEY"), "API key not available") | ||
| def test_multiple_requests_performance(self): | ||
| """Test that multiple requests benefit from connection pooling.""" | ||
| client = cohere.ClientV2() | ||
|
|
||
| response_times = [] | ||
|
|
||
| # Make multiple requests | ||
| for i in range(3): | ||
| start_time = time.time() | ||
| try: | ||
| response = client.chat( | ||
| model="command-r-plus-08-2024", | ||
| messages=[{"role": "user", "content": f"Say the number {i+1}"}], | ||
| ) | ||
| elapsed = time.time() - start_time | ||
| response_times.append(elapsed) | ||
|
|
||
| # Verify response | ||
| self.assertIsNotNone(response) | ||
| self.assertIsNotNone(response.message) | ||
|
|
||
| # Rate limit protection | ||
| if i < 2: | ||
| time.sleep(2) | ||
|
|
||
| except Exception as e: | ||
| if "429" in str(e) or "rate" in str(e).lower(): | ||
| self.skipTest("Rate limited") | ||
| raise | ||
|
|
||
| # Verify all requests completed | ||
| self.assertEqual(len(response_times), 3) | ||
|
|
||
| # Generally, subsequent requests should be faster due to connection reuse | ||
| # First request establishes connection, subsequent ones reuse it | ||
| print(f"Response times: {response_times}") | ||
|
|
||
| @unittest.skipIf(not os.environ.get("CO_API_KEY"), "API key not available") | ||
| def test_streaming_with_pooling(self): | ||
| """Test that streaming works correctly with connection pooling.""" | ||
| client = cohere.ClientV2() | ||
|
|
||
| try: | ||
| response = client.chat_stream( | ||
| model="command-r-plus-08-2024", | ||
| messages=[{"role": "user", "content": "Count to 3"}], | ||
| ) | ||
|
|
||
| chunks = [] | ||
| for event in response: | ||
| if event.type == "content-delta": | ||
| chunks.append(event.delta.message.content.text) | ||
|
|
||
| # Verify streaming worked | ||
| self.assertGreater(len(chunks), 0) | ||
| full_response = "".join(chunks) | ||
| self.assertGreater(len(full_response), 0) | ||
|
|
||
| except Exception as e: | ||
| if "429" in str(e) or "rate" in str(e).lower(): | ||
| self.skipTest("Rate limited") | ||
| raise | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Changes to auto-generated file will be lost on regeneration
High Severity
base_client.pyis marked "auto-generated by Fern" and is not listed in.fernignore. The.fernignorefile protects manually-modified files likesrc/cohere/client.pyfrom being overwritten during code generation, butbase_client.pyis absent. The next Fern regeneration will silently discard all connection pooling changes. Either the file needs to be added to.fernignoreor the change needs to be applied through the Fern configuration itself.Additional Locations (2)
src/cohere/base_client.py#L136-L146src/cohere/base_client.py#L1648-L1658