@@ -431,32 +431,41 @@ def infer_model(model: Model | KnownModelName) -> Model:
431
431
raise UserError (f'Unknown model: { model } ' )
432
432
433
433
434
- def cached_async_http_client (timeout : int = 600 , connect : int = 5 ) -> httpx .AsyncClient :
435
- """Cached HTTPX async client so multiple agents and calls can share the same client.
434
+ def cached_async_http_client (* , provider : str | None = None , timeout : int = 600 , connect : int = 5 ) -> httpx .AsyncClient :
435
+ """Cached HTTPX async client that creates a separate client for each provider.
436
+
437
+ The client is cached based on the provider parameter. If provider is None, it's used for non-provider specific
438
+ requests (like downloading images). Multiple agents and calls can share the same client when they use the same provider.
436
439
437
440
There are good reasons why in production you should use a `httpx.AsyncClient` as an async context manager as
438
441
described in [encode/httpx#2026](https://github.com/encode/httpx/pull/2026), but when experimenting or showing
439
- examples, it's very useful not to, this allows multiple Agents to use a single client .
442
+ examples, it's very useful not to.
440
443
441
444
The default timeouts match those of OpenAI,
442
445
see <https://github.com/openai/openai-python/blob/v1.54.4/src/openai/_constants.py#L9>.
443
446
"""
444
- client = _cached_async_http_client (timeout = timeout , connect = connect )
447
+ client = _cached_async_http_client (provider = provider , timeout = timeout , connect = connect )
445
448
if client .is_closed :
446
449
# This happens if the context manager is used, so we need to create a new client.
447
450
_cached_async_http_client .cache_clear ()
448
- client = _cached_async_http_client (timeout = timeout , connect = connect )
451
+ client = _cached_async_http_client (provider = provider , timeout = timeout , connect = connect )
449
452
return client
450
453
451
454
452
455
@cache
453
- def _cached_async_http_client (timeout : int = 600 , connect : int = 5 ) -> httpx .AsyncClient :
456
+ def _cached_async_http_client (provider : str | None , timeout : int = 600 , connect : int = 5 ) -> httpx .AsyncClient :
454
457
return httpx .AsyncClient (
458
+ transport = _cached_async_http_transport (),
455
459
timeout = httpx .Timeout (timeout = timeout , connect = connect ),
456
460
headers = {'User-Agent' : get_user_agent ()},
457
461
)
458
462
459
463
464
+ @cache
465
+ def _cached_async_http_transport () -> httpx .AsyncHTTPTransport :
466
+ return httpx .AsyncHTTPTransport ()
467
+
468
+
460
469
@cache
461
470
def get_user_agent () -> str :
462
471
"""Get the user agent string for the HTTP client."""
0 commit comments