Skip to content

Commit e1a38de

Browse files
authored
perf: trim unused Mistral APIs from standalone worker (#132368)
Use the public chat subclient while preserving SDK HTTP hooks, guarded fetch, cancellation, and streaming behavior. The matched worker build drops 912,851 bytes without changing versions, capabilities, or build budgets.
1 parent aa4e4be commit e1a38de

3 files changed

Lines changed: 42 additions & 36 deletions

File tree

‎packages/ai/src/providers/mistral-http-client.contract.test.ts‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,19 @@
1-
import { HTTPClient, Mistral } from "@mistralai/mistralai";
1+
import { Mistral } from "@mistralai/mistralai";
2+
import { HTTPClient } from "@mistralai/mistralai/lib/http";
3+
import { Chat } from "@mistralai/mistralai/sdk/chat";
24
import { describe, expect, it, vi } from "vitest";
35

46
describe("Mistral HTTPClient contract", () => {
5-
it("routes chat.stream responses through the injected HTTPClient hooks", async () => {
7+
it.each([
8+
{
9+
name: "root client",
10+
createChat: (options: ConstructorParameters<typeof Chat>[0]) => new Mistral(options).chat,
11+
},
12+
{
13+
name: "chat subclient",
14+
createChat: (options: ConstructorParameters<typeof Chat>[0]) => new Chat(options),
15+
},
16+
])("routes $name responses through the injected HTTPClient hooks", async ({ createChat }) => {
617
const response = new Response("data: [DONE]\n\n", {
718
status: 200,
819
headers: { "content-type": "text/event-stream" },
@@ -11,13 +22,13 @@ describe("Mistral HTTPClient contract", () => {
1122
const onResponse = vi.fn();
1223
const httpClient = new HTTPClient({ fetcher });
1324
httpClient.addHook("response", onResponse);
14-
const mistral = new Mistral({
25+
const chat = createChat({
1526
apiKey: "test-key",
1627
serverURL: "https://mistral.invalid",
1728
httpClient,
1829
});
1930

20-
const stream = await mistral.chat.stream({
31+
const stream = await chat.stream({
2132
model: "mistral-test",
2233
messages: [{ role: "user", content: "hello" }],
2334
});

‎packages/ai/src/providers/mistral.test.ts‎

Lines changed: 21 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -23,42 +23,37 @@ vi.mock("node:crypto", async () => {
2323
};
2424
});
2525

26-
vi.mock("@mistralai/mistralai", async () => {
27-
const actual =
28-
await vi.importActual<typeof import("@mistralai/mistralai")>("@mistralai/mistralai");
26+
vi.mock("@mistralai/mistralai/sdk/chat", () => {
2927
return {
30-
...actual,
31-
Mistral: class MockMistral {
28+
Chat: class MockMistralChat {
3229
private readonly config: unknown;
3330

3431
constructor(config: unknown) {
3532
this.config = config;
3633
mistralMockState.configs.push(config);
3734
}
3835

39-
chat = {
40-
stream: vi.fn(async (payload: unknown, requestOptions: unknown) => {
41-
mistralMockState.payloads.push(payload);
42-
mistralMockState.requestOptions.push(requestOptions);
43-
if (mistralMockState.requestThroughHttpClient) {
44-
const httpClient = (
45-
this.config as {
46-
httpClient?: { request(request: Request): Promise<Response> };
47-
}
48-
).httpClient;
49-
const response = await httpClient?.request(new Request("https://api.mistral.ai/chat"));
50-
if (response && !response.ok) {
51-
throw Object.assign(new Error(`Mistral HTTP ${response.status}`), {
52-
statusCode: response.status,
53-
});
36+
stream = vi.fn(async (payload: unknown, requestOptions: unknown) => {
37+
mistralMockState.payloads.push(payload);
38+
mistralMockState.requestOptions.push(requestOptions);
39+
if (mistralMockState.requestThroughHttpClient) {
40+
const httpClient = (
41+
this.config as {
42+
httpClient?: { request(request: Request): Promise<Response> };
5443
}
44+
).httpClient;
45+
const response = await httpClient?.request(new Request("https://api.mistral.ai/chat"));
46+
if (response && !response.ok) {
47+
throw Object.assign(new Error(`Mistral HTTP ${response.status}`), {
48+
statusCode: response.status,
49+
});
5550
}
56-
if (mistralMockState.streamResult !== undefined) {
57-
return mistralMockState.streamResult;
58-
}
59-
throw mistralMockState.streamError;
60-
}),
61-
};
51+
}
52+
if (mistralMockState.streamResult !== undefined) {
53+
return mistralMockState.streamResult;
54+
}
55+
throw mistralMockState.streamError;
56+
});
6257
},
6358
};
6459
});

‎packages/ai/src/providers/mistral.ts‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
// Mistral provider adapts Mistral streams and tool calls to the runtime.
22
import { randomUUID } from "node:crypto";
3-
import { HTTPClient, Mistral, type Fetcher } from "@mistralai/mistralai";
3+
import { HTTPClient, type Fetcher } from "@mistralai/mistralai/lib/http";
44
import type {
55
ChatCompletionStreamRequest,
66
ChatCompletionStreamRequestMessage,
77
CompletionEvent,
88
ContentChunk,
99
FunctionTool,
1010
} from "@mistralai/mistralai/models/components";
11+
import { Chat } from "@mistralai/mistralai/sdk/chat";
1112
import { getEnvApiKey } from "../env-api-keys.js";
1213
import { getAiTransportHost } from "../host.js";
1314
import { calculateCost, clampThinkingLevel } from "../model-utils.js";
@@ -160,13 +161,12 @@ export const streamMistral: StreamFunction<"mistral-conversations", MistralOptio
160161
reportedResponse = response;
161162
}
162163
});
164+
// Use the public chat subclient so standalone bundles omit unrelated Mistral APIs.
163165
// Intentionally per-request: avoids shared SDK mutable state across concurrent consumers.
164-
const mistral = new Mistral({
166+
const chat = new Chat({
165167
apiKey,
166168
serverURL: model.baseUrl,
167-
// Bound the streamed Mistral response body at 16 MiB so a hostile or
168-
// malfunctioning endpoint cannot exhaust memory. The HTTPClient is the
169-
// SDK's public fetch and response-hook boundary for every chat.stream attempt.
169+
// Keep bounded fetch and response hooks on every streaming attempt.
170170
httpClient,
171171
});
172172

@@ -186,7 +186,7 @@ export const streamMistral: StreamFunction<"mistral-conversations", MistralOptio
186186
if (resolveMistralPromptCacheKey(options) && options?.sessionId) {
187187
headers["x-affinity"] ||= options.sessionId;
188188
}
189-
const mistralStream = await mistral.chat.stream(payload, {
189+
const mistralStream = await chat.stream(payload, {
190190
headers,
191191
signal: options?.signal,
192192
});

0 commit comments

Comments
 (0)