Skip to content

Commit 3c3041f

Browse files
authored
add UA to requests (#61)
1 parent 6b1a111 commit 3c3041f

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

pydantic_ai/models/__init__.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -261,4 +261,15 @@ def cached_async_http_client(timeout: int = 600, connect: int = 5) -> httpx.Asyn
261261
The default timeouts match those of OpenAI,
262262
see <https://github.com/openai/openai-python/blob/v1.54.4/src/openai/_constants.py#L9>.
263263
"""
264-
return httpx.AsyncClient(timeout=httpx.Timeout(timeout=timeout, connect=connect))
264+
return httpx.AsyncClient(
265+
timeout=httpx.Timeout(timeout=timeout, connect=connect),
266+
headers={'User-Agent': get_user_agent()},
267+
)
268+
269+
270+
@cache
271+
def get_user_agent() -> str:
272+
"""Get the user agent string for the HTTP client."""
273+
from .. import __version__
274+
275+
return f'pydantic-ai/{__version__}'

pydantic_ai/models/gemini.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@
5656
StreamTextResponse,
5757
cached_async_http_client,
5858
check_allow_model_requests,
59+
get_user_agent,
5960
)
6061

6162
GeminiModelName = Literal['gemini-1.5-flash', 'gemini-1.5-flash-8b', 'gemini-1.5-pro', 'gemini-1.0-pro']
@@ -182,6 +183,7 @@ async def _make_request(self, messages: list[Message], streamed: bool) -> AsyncI
182183
headers = {
183184
'X-Goog-Api-Key': self.api_key,
184185
'Content-Type': 'application/json',
186+
'User-Agent': get_user_agent(),
185187
}
186188
url = self.url_template.format(
187189
model=self.model_name, function='streamGenerateContent' if streamed else 'generateContent'

tests/models/test_gemini.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -344,9 +344,12 @@ async def get_gemini_client(
344344
def create_client(response_or_list: ResOrList) -> httpx.AsyncClient:
345345
index = 0
346346

347-
def handler(_request: httpx.Request) -> httpx.Response:
347+
def handler(request: httpx.Request) -> httpx.Response:
348348
nonlocal index
349349

350+
ua = request.headers.get('User-Agent')
351+
assert isinstance(ua, str) and ua.startswith('pydantic-ai')
352+
350353
if isinstance(response_or_list, Sequence):
351354
response = response_or_list[index]
352355
index += 1

0 commit comments

Comments
 (0)