Skip to content

Commit 37e6ead

Browse files
authored
Add SDK/version as User-Agent in HTTPClients (#204)
* Add SDK+version as user-agent in HttpClients for C#/JS/Python/Rust Format and modify tests accordingly * Address comments Capitalize AssemblyVersion, use cs instead of C# * Lowercase SDK * Update version * Rm outdated
1 parent 3773169 commit 37e6ead

File tree

14 files changed

+166
-11
lines changed

14 files changed

+166
-11
lines changed

sdk/cs/samples/TestApp/Program.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ public class TestApp
1515
{
1616
public static async Task Main(string[] args)
1717
{
18-
var app = new TestApp(); // Create an instance of TestApp
18+
var app = new TestApp(); // Create an instance of TestApp
1919

2020
Console.WriteLine(new string('=', 80)); // Separator for clarity
2121
Console.WriteLine("Testing catalog integration...");
@@ -84,7 +84,7 @@ private async Task TestService()
8484
}
8585

8686
private async Task TestCatalog()
87-
// First test catalog listing
87+
// First test catalog listing
8888
{
8989
using var manager = new FoundryLocalManager();
9090
foreach (var m in await manager.ListCatalogModelsAsync())

sdk/cs/src/FoundryLocalManager.cs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ namespace Microsoft.AI.Foundry.Local;
1313
using System.Linq;
1414
using System.Net.Http.Json;
1515
using System.Net.Mime;
16+
using System.Reflection;
1617
using System.Runtime.InteropServices;
1718
using System.Text;
1819
using System.Text.Json;
@@ -47,6 +48,7 @@ public partial class FoundryLocalManager : IDisposable, IAsyncDisposable
4748
private List<ModelInfo>? _catalogModels;
4849
private Dictionary<string, ModelInfo>? _catalogDictionary;
4950
private readonly Dictionary<ExecutionProvider, int> _priorityMap;
51+
private static readonly string AssemblyVersion = typeof(FoundryLocalManager).Assembly.GetName().Version?.ToString() ?? "unknown";
5052

5153
// Gets the service URI
5254
public Uri ServiceUri => _serviceUri ?? throw new InvalidOperationException("Service URI is not set. Call StartServiceAsync() first.");
@@ -111,6 +113,8 @@ public async Task StartServiceAsync(CancellationToken ct = default)
111113
// set the timeout to 2 hours (for downloading large models)
112114
Timeout = TimeSpan.FromSeconds(7200)
113115
};
116+
117+
_serviceClient.DefaultRequestHeaders.UserAgent.ParseAdd($"foundry-local-cs-sdk/{AssemblyVersion}");
114118
}
115119
}
116120

sdk/js/package-lock.json

Lines changed: 127 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

sdk/js/package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
"types": "dist/index.d.ts",
1313
"license": "MIT",
1414
"scripts": {
15-
"build": "unbuild",
15+
"build": "npx genversion -e src/version.ts && unbuild",
1616
"format": "prettier --write .",
1717
"format:check": "prettier --check .",
1818
"lint": "eslint ./src/*",
@@ -42,6 +42,7 @@
4242
"eslint-plugin-header": "^3.1.1",
4343
"eslint-plugin-import": "^2.28.1",
4444
"eslint-plugin-jsdoc": "^46.8.2",
45+
"genversion": "^3.2.0",
4546
"prettier": "^3.2.4",
4647
"typescript": "^5.2.2",
4748
"unbuild": "^3.5.0",

sdk/js/src/client.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// Licensed under the MIT License.
33

44
import type { Fetch } from './types.js'
5+
import { version } from './version.js'
56

67
/**
78
* Handles fetch requests with error handling.
@@ -71,7 +72,7 @@ export const postWithProgress = async (
7172
// Sending a POST request and getting a streamable response
7273
const response = await fetchWithErrorHandling(fetch, host, {
7374
method: 'POST',
74-
headers: { 'Content-Type': 'application/json' },
75+
headers: { 'Content-Type': 'application/json', 'User-Agent': `foundry-local-js-sdk/${version}` },
7576
body: body ? JSON.stringify(body) : undefined,
7677
})
7778

sdk/js/src/version.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
// Generated by genversion.
2+
export const version = '0.4.0'

sdk/js/test/client.test.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import { describe, expect, it, vi, beforeEach } from 'vitest'
55
import * as client from '../src/client'
66
import type { Fetch } from '../src/types'
7+
import { version } from '../src/version'
78

89
describe('Client', () => {
910
const mockFetch = vi.fn() as unknown as Fetch
@@ -60,7 +61,10 @@ describe('Client', () => {
6061
expect(result).toEqual({ ok: true })
6162
expect(mockFetch).toHaveBeenCalledWith('http://example.com', {
6263
method: 'POST',
63-
headers: { 'Content-Type': 'application/json' },
64+
headers: {
65+
'Content-Type': 'application/json',
66+
'User-Agent': `foundry-local-js-sdk/${version}`,
67+
},
6468
body: JSON.stringify(body),
6569
})
6670
})

sdk/python/foundry_local/__init__.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,5 +19,3 @@
1919
_logger.propagate = False
2020

2121
__all__ = ["FoundryLocalManager"]
22-
23-
__version__ = "0.4.0"

sdk/python/foundry_local/client.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
import httpx
1212
from tqdm import tqdm
1313

14+
from foundry_local.version import __version__ as sdk_version
15+
1416
logger = logging.getLogger(__name__)
1517

1618

@@ -34,7 +36,8 @@ def __init__(self, host: str, timeout: float | httpx.Timeout | None = None) -> N
3436
host (str): Base URL of the host.
3537
timeout (float | httpx.Timeout | None): Timeout for the HTTP client.
3638
"""
37-
self._client = httpx.Client(base_url=host, timeout=timeout)
39+
headers = {"user-agent": f"foundry-local-python-sdk/{sdk_version}"}
40+
self._client = httpx.Client(base_url=host, timeout=timeout, headers=headers)
3841

3942
def _request(self, *args, **kwargs) -> httpx.Response:
4043
"""
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
__version__ = "0.4.0"

0 commit comments

Comments
 (0)