@tanstack/ai-mistral 0.2.4 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/adapters/embedding.d.ts +76 -0
- package/dist/esm/adapters/embedding.js +122 -0
- package/dist/esm/adapters/embedding.js.map +1 -0
- package/dist/esm/adapters/text.js +18 -4
- package/dist/esm/adapters/text.js.map +1 -1
- package/dist/esm/embedding/embedding-provider-options.d.ts +29 -0
- package/dist/esm/index.d.ts +4 -2
- package/dist/esm/index.js +3 -2
- package/dist/esm/model-meta.d.ts +31 -4
- package/dist/esm/model-meta.js +25 -5
- package/dist/esm/model-meta.js.map +1 -1
- package/package.json +7 -3
- package/src/adapters/embedding.ts +177 -0
- package/src/adapters/text.ts +18 -1
- package/src/embedding/embedding-provider-options.ts +32 -0
- package/src/index.ts +17 -1
- package/src/model-meta.ts +42 -5
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { BaseEmbeddingAdapter } from '@tanstack/ai/adapters';
|
|
2
|
+
import { EmbeddingOptions, EmbeddingResult } from '@tanstack/ai';
|
|
3
|
+
import { Mistral } from '@mistralai/mistralai';
|
|
4
|
+
import { MistralEmbeddingModel, MistralEmbeddingModelInputModalitiesByName, MistralEmbeddingModelProviderOptionsByName } from '../model-meta.js';
|
|
5
|
+
import { MistralEmbeddingProviderOptions } from '../embedding/embedding-provider-options.js';
|
|
6
|
+
import { MistralClientConfig } from '../utils/client.js';
|
|
7
|
+
/**
|
|
8
|
+
* Configuration for Mistral embedding adapter.
|
|
9
|
+
*/
|
|
10
|
+
export type MistralEmbeddingConfig = MistralClientConfig;
|
|
11
|
+
/**
|
|
12
|
+
* Mistral Embedding Adapter
|
|
13
|
+
*
|
|
14
|
+
* Tree-shakeable adapter for Mistral text embeddings.
|
|
15
|
+
* Supports mistral-embed and codestral-embed.
|
|
16
|
+
*
|
|
17
|
+
* Features:
|
|
18
|
+
* - Batch embedding (one request for the whole input array)
|
|
19
|
+
* - Dimension reduction for codestral-embed via the top-level `dimensions`
|
|
20
|
+
* option (mapped to Mistral's `outputDimension`); mistral-embed has a fixed
|
|
21
|
+
* 1024-dimension output and rejects `dimensions`.
|
|
22
|
+
*/
|
|
23
|
+
export declare class MistralEmbeddingAdapter<TModel extends MistralEmbeddingModel> extends BaseEmbeddingAdapter<TModel, MistralEmbeddingProviderOptions, MistralEmbeddingModelProviderOptionsByName, MistralEmbeddingModelInputModalitiesByName> {
|
|
24
|
+
readonly name: "mistral";
|
|
25
|
+
protected client: Mistral;
|
|
26
|
+
constructor(config: MistralEmbeddingConfig, model: TModel);
|
|
27
|
+
createEmbeddings(options: EmbeddingOptions<MistralEmbeddingProviderOptions>): Promise<EmbeddingResult>;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Creates a Mistral embedding adapter with explicit API key.
|
|
31
|
+
* Type resolution happens here at the call site.
|
|
32
|
+
*
|
|
33
|
+
* @param model - The model name (e.g., 'mistral-embed')
|
|
34
|
+
* @param apiKey - Your Mistral API key
|
|
35
|
+
* @param config - Optional additional configuration
|
|
36
|
+
* @returns Configured Mistral embedding adapter instance with resolved types
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* ```typescript
|
|
40
|
+
* const adapter = createMistralEmbedding('mistral-embed', 'api_key');
|
|
41
|
+
*
|
|
42
|
+
* const result = await embed({
|
|
43
|
+
* adapter,
|
|
44
|
+
* input: 'a red guitar'
|
|
45
|
+
* });
|
|
46
|
+
* ```
|
|
47
|
+
*/
|
|
48
|
+
export declare function createMistralEmbedding<TModel extends MistralEmbeddingModel>(model: TModel, apiKey: string, config?: Omit<MistralEmbeddingConfig, 'apiKey'>): MistralEmbeddingAdapter<TModel>;
|
|
49
|
+
/**
|
|
50
|
+
* Creates a Mistral embedding adapter using the `MISTRAL_API_KEY` environment variable.
|
|
51
|
+
* Type resolution happens here at the call site.
|
|
52
|
+
*
|
|
53
|
+
* Looks for `MISTRAL_API_KEY` in:
|
|
54
|
+
* - `process.env` (Node.js)
|
|
55
|
+
* - `window.env` (Browser with injected env)
|
|
56
|
+
*
|
|
57
|
+
* @param model - The model name (e.g., 'codestral-embed')
|
|
58
|
+
* @param config - Optional configuration (excluding apiKey which is auto-detected)
|
|
59
|
+
* @returns Configured Mistral embedding adapter instance with resolved types
|
|
60
|
+
* @throws Error if MISTRAL_API_KEY is not found in environment
|
|
61
|
+
*
|
|
62
|
+
* @example
|
|
63
|
+
* ```typescript
|
|
64
|
+
* // Automatically uses MISTRAL_API_KEY from environment
|
|
65
|
+
* const adapter = mistralEmbedding('codestral-embed');
|
|
66
|
+
*
|
|
67
|
+
* const result = await embed({
|
|
68
|
+
* adapter,
|
|
69
|
+
* input: ['a red guitar', 'a blue drum kit'],
|
|
70
|
+
* dimensions: 256
|
|
71
|
+
* });
|
|
72
|
+
*
|
|
73
|
+
* console.log(result.embeddings[0].vector)
|
|
74
|
+
* ```
|
|
75
|
+
*/
|
|
76
|
+
export declare function mistralEmbedding<TModel extends MistralEmbeddingModel>(model: TModel, config?: Omit<MistralEmbeddingConfig, 'apiKey'>): MistralEmbeddingAdapter<TModel>;
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { createMistralClient, generateId, getMistralApiKeyFromEnv } from "../utils/client.js";
|
|
2
|
+
import { BaseEmbeddingAdapter } from "@tanstack/ai/adapters";
|
|
3
|
+
import { toRunErrorPayload } from "@tanstack/ai/adapter-internals";
|
|
4
|
+
import { requireTextOnlyEmbeddingInput } from "@tanstack/ai";
|
|
5
|
+
//#region src/adapters/embedding.ts
|
|
6
|
+
/**
|
|
7
|
+
* Mistral Embedding Adapter
|
|
8
|
+
*
|
|
9
|
+
* Tree-shakeable adapter for Mistral text embeddings.
|
|
10
|
+
* Supports mistral-embed and codestral-embed.
|
|
11
|
+
*
|
|
12
|
+
* Features:
|
|
13
|
+
* - Batch embedding (one request for the whole input array)
|
|
14
|
+
* - Dimension reduction for codestral-embed via the top-level `dimensions`
|
|
15
|
+
* option (mapped to Mistral's `outputDimension`); mistral-embed has a fixed
|
|
16
|
+
* 1024-dimension output and rejects `dimensions`.
|
|
17
|
+
*/
|
|
18
|
+
var MistralEmbeddingAdapter = class extends BaseEmbeddingAdapter {
|
|
19
|
+
name = "mistral";
|
|
20
|
+
client;
|
|
21
|
+
constructor(config, model) {
|
|
22
|
+
super(model, {});
|
|
23
|
+
this.client = createMistralClient(config);
|
|
24
|
+
}
|
|
25
|
+
async createEmbeddings(options) {
|
|
26
|
+
const { model, logger, modelOptions } = options;
|
|
27
|
+
const texts = requireTextOnlyEmbeddingInput(options.input, this.name, model);
|
|
28
|
+
if (options.dimensions !== void 0 && model === "mistral-embed") throw new Error("mistral-embed does not support requesting dimensions (output is a fixed 1024-dimension vector). Use codestral-embed for dimension reduction, or omit `dimensions`.");
|
|
29
|
+
try {
|
|
30
|
+
const request = {
|
|
31
|
+
...modelOptions,
|
|
32
|
+
model,
|
|
33
|
+
inputs: texts
|
|
34
|
+
};
|
|
35
|
+
if (options.dimensions !== void 0) request.outputDimension = options.dimensions;
|
|
36
|
+
logger.request(`activity=embed provider=${this.name} model=${model} inputs=${texts.length}`, {
|
|
37
|
+
provider: this.name,
|
|
38
|
+
model
|
|
39
|
+
});
|
|
40
|
+
const response = await this.client.embeddings.create(request);
|
|
41
|
+
const usage = {
|
|
42
|
+
promptTokens: response.usage.promptTokens ?? 0,
|
|
43
|
+
completionTokens: 0,
|
|
44
|
+
totalTokens: response.usage.totalTokens ?? 0
|
|
45
|
+
};
|
|
46
|
+
return {
|
|
47
|
+
id: generateId(this.name),
|
|
48
|
+
model,
|
|
49
|
+
embeddings: response.data.map((item, arrayIndex) => ({
|
|
50
|
+
vector: item.embedding ?? [],
|
|
51
|
+
index: item.index ?? arrayIndex
|
|
52
|
+
})),
|
|
53
|
+
usage
|
|
54
|
+
};
|
|
55
|
+
} catch (error) {
|
|
56
|
+
logger.errors(`${this.name}.createEmbeddings fatal`, {
|
|
57
|
+
error: toRunErrorPayload(error, `${this.name}.createEmbeddings failed`),
|
|
58
|
+
source: `${this.name}.createEmbeddings`
|
|
59
|
+
});
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
/**
|
|
65
|
+
* Creates a Mistral embedding adapter with explicit API key.
|
|
66
|
+
* Type resolution happens here at the call site.
|
|
67
|
+
*
|
|
68
|
+
* @param model - The model name (e.g., 'mistral-embed')
|
|
69
|
+
* @param apiKey - Your Mistral API key
|
|
70
|
+
* @param config - Optional additional configuration
|
|
71
|
+
* @returns Configured Mistral embedding adapter instance with resolved types
|
|
72
|
+
*
|
|
73
|
+
* @example
|
|
74
|
+
* ```typescript
|
|
75
|
+
* const adapter = createMistralEmbedding('mistral-embed', 'api_key');
|
|
76
|
+
*
|
|
77
|
+
* const result = await embed({
|
|
78
|
+
* adapter,
|
|
79
|
+
* input: 'a red guitar'
|
|
80
|
+
* });
|
|
81
|
+
* ```
|
|
82
|
+
*/
|
|
83
|
+
function createMistralEmbedding(model, apiKey, config) {
|
|
84
|
+
return new MistralEmbeddingAdapter({
|
|
85
|
+
apiKey,
|
|
86
|
+
...config
|
|
87
|
+
}, model);
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Creates a Mistral embedding adapter using the `MISTRAL_API_KEY` environment variable.
|
|
91
|
+
* Type resolution happens here at the call site.
|
|
92
|
+
*
|
|
93
|
+
* Looks for `MISTRAL_API_KEY` in:
|
|
94
|
+
* - `process.env` (Node.js)
|
|
95
|
+
* - `window.env` (Browser with injected env)
|
|
96
|
+
*
|
|
97
|
+
* @param model - The model name (e.g., 'codestral-embed')
|
|
98
|
+
* @param config - Optional configuration (excluding apiKey which is auto-detected)
|
|
99
|
+
* @returns Configured Mistral embedding adapter instance with resolved types
|
|
100
|
+
* @throws Error if MISTRAL_API_KEY is not found in environment
|
|
101
|
+
*
|
|
102
|
+
* @example
|
|
103
|
+
* ```typescript
|
|
104
|
+
* // Automatically uses MISTRAL_API_KEY from environment
|
|
105
|
+
* const adapter = mistralEmbedding('codestral-embed');
|
|
106
|
+
*
|
|
107
|
+
* const result = await embed({
|
|
108
|
+
* adapter,
|
|
109
|
+
* input: ['a red guitar', 'a blue drum kit'],
|
|
110
|
+
* dimensions: 256
|
|
111
|
+
* });
|
|
112
|
+
*
|
|
113
|
+
* console.log(result.embeddings[0].vector)
|
|
114
|
+
* ```
|
|
115
|
+
*/
|
|
116
|
+
function mistralEmbedding(model, config) {
|
|
117
|
+
return createMistralEmbedding(model, getMistralApiKeyFromEnv(), config);
|
|
118
|
+
}
|
|
119
|
+
//#endregion
|
|
120
|
+
export { MistralEmbeddingAdapter, createMistralEmbedding, mistralEmbedding };
|
|
121
|
+
|
|
122
|
+
//# sourceMappingURL=embedding.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"embedding.js","names":[],"sources":["../../../src/adapters/embedding.ts"],"sourcesContent":["import { BaseEmbeddingAdapter } from '@tanstack/ai/adapters'\nimport { toRunErrorPayload } from '@tanstack/ai/adapter-internals'\nimport { requireTextOnlyEmbeddingInput } from '@tanstack/ai'\nimport {\n createMistralClient,\n generateId,\n getMistralApiKeyFromEnv,\n} from '../utils/client'\nimport type {\n EmbeddingOptions,\n EmbeddingResult,\n TokenUsage,\n} from '@tanstack/ai'\nimport type { Mistral } from '@mistralai/mistralai'\nimport type { EmbeddingRequest } from '@mistralai/mistralai/models/components'\nimport type {\n MistralEmbeddingModel,\n MistralEmbeddingModelInputModalitiesByName,\n MistralEmbeddingModelProviderOptionsByName,\n} from '../model-meta'\nimport type { MistralEmbeddingProviderOptions } from '../embedding/embedding-provider-options'\nimport type { MistralClientConfig } from '../utils/client'\n\n/**\n * Configuration for Mistral embedding adapter.\n */\nexport type MistralEmbeddingConfig = MistralClientConfig\n\n/**\n * Mistral Embedding Adapter\n *\n * Tree-shakeable adapter for Mistral text embeddings.\n * Supports mistral-embed and codestral-embed.\n *\n * Features:\n * - Batch embedding (one request for the whole input array)\n * - Dimension reduction for codestral-embed via the top-level `dimensions`\n * option (mapped to Mistral's `outputDimension`); mistral-embed has a fixed\n * 1024-dimension output and rejects `dimensions`.\n */\nexport class MistralEmbeddingAdapter<\n TModel extends MistralEmbeddingModel,\n> extends BaseEmbeddingAdapter<\n TModel,\n MistralEmbeddingProviderOptions,\n MistralEmbeddingModelProviderOptionsByName,\n MistralEmbeddingModelInputModalitiesByName\n> {\n readonly name = 'mistral' as const\n\n protected client: Mistral\n\n constructor(config: MistralEmbeddingConfig, model: TModel) {\n super(model, {})\n this.client = createMistralClient(config)\n }\n\n async createEmbeddings(\n options: EmbeddingOptions<MistralEmbeddingProviderOptions>,\n ): Promise<EmbeddingResult> {\n const { model, logger, modelOptions } = options\n const texts = requireTextOnlyEmbeddingInput(options.input, this.name, model)\n\n if (options.dimensions !== undefined && model === 'mistral-embed') {\n throw new Error(\n 'mistral-embed does not support requesting dimensions (output is a fixed 1024-dimension vector). Use codestral-embed for dimension reduction, or omit `dimensions`.',\n )\n }\n\n try {\n // Spread modelOptions first so it can never override the validated\n // fields (server routes often pass modelOptions through from untyped\n // client input).\n const request: EmbeddingRequest = {\n ...modelOptions,\n model,\n inputs: texts,\n }\n if (options.dimensions !== undefined) {\n request.outputDimension = options.dimensions\n }\n\n logger.request(\n `activity=embed provider=${this.name} model=${model} inputs=${texts.length}`,\n { provider: this.name, model },\n )\n\n const response = await this.client.embeddings.create(request)\n\n const usage: TokenUsage = {\n promptTokens: response.usage.promptTokens ?? 0,\n completionTokens: 0,\n totalTokens: response.usage.totalTokens ?? 0,\n }\n\n return {\n id: generateId(this.name),\n model,\n // Mistral returns one entry per input; `index` is optional in the SDK\n // types, so fall back to array order when it's absent.\n embeddings: response.data.map((item, arrayIndex) => ({\n vector: item.embedding ?? [],\n index: item.index ?? arrayIndex,\n })),\n usage,\n }\n } catch (error: unknown) {\n logger.errors(`${this.name}.createEmbeddings fatal`, {\n error: toRunErrorPayload(error, `${this.name}.createEmbeddings failed`),\n source: `${this.name}.createEmbeddings`,\n })\n throw error\n }\n }\n}\n\n/**\n * Creates a Mistral embedding adapter with explicit API key.\n * Type resolution happens here at the call site.\n *\n * @param model - The model name (e.g., 'mistral-embed')\n * @param apiKey - Your Mistral API key\n * @param config - Optional additional configuration\n * @returns Configured Mistral embedding adapter instance with resolved types\n *\n * @example\n * ```typescript\n * const adapter = createMistralEmbedding('mistral-embed', 'api_key');\n *\n * const result = await embed({\n * adapter,\n * input: 'a red guitar'\n * });\n * ```\n */\nexport function createMistralEmbedding<TModel extends MistralEmbeddingModel>(\n model: TModel,\n apiKey: string,\n config?: Omit<MistralEmbeddingConfig, 'apiKey'>,\n): MistralEmbeddingAdapter<TModel> {\n return new MistralEmbeddingAdapter({ apiKey, ...config }, model)\n}\n\n/**\n * Creates a Mistral embedding adapter using the `MISTRAL_API_KEY` environment variable.\n * Type resolution happens here at the call site.\n *\n * Looks for `MISTRAL_API_KEY` in:\n * - `process.env` (Node.js)\n * - `window.env` (Browser with injected env)\n *\n * @param model - The model name (e.g., 'codestral-embed')\n * @param config - Optional configuration (excluding apiKey which is auto-detected)\n * @returns Configured Mistral embedding adapter instance with resolved types\n * @throws Error if MISTRAL_API_KEY is not found in environment\n *\n * @example\n * ```typescript\n * // Automatically uses MISTRAL_API_KEY from environment\n * const adapter = mistralEmbedding('codestral-embed');\n *\n * const result = await embed({\n * adapter,\n * input: ['a red guitar', 'a blue drum kit'],\n * dimensions: 256\n * });\n *\n * console.log(result.embeddings[0].vector)\n * ```\n */\nexport function mistralEmbedding<TModel extends MistralEmbeddingModel>(\n model: TModel,\n config?: Omit<MistralEmbeddingConfig, 'apiKey'>,\n): MistralEmbeddingAdapter<TModel> {\n const apiKey = getMistralApiKeyFromEnv()\n return createMistralEmbedding(model, apiKey, config)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwCA,IAAa,0BAAb,cAEU,qBAKR;CACA,OAAgB;CAEhB;CAEA,YAAY,QAAgC,OAAe;EACzD,MAAM,OAAO,CAAC,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D"}
|
|
@@ -82,7 +82,7 @@ var MistralTextAdapter = class extends BaseTextAdapter {
|
|
|
82
82
|
const { chatOptions, outputSchema } = options;
|
|
83
83
|
const { stream: _stream, ...nonStreamParams } = this.mapTextOptionsToMistral(chatOptions);
|
|
84
84
|
const jsonSchema = makeMistralStructuredOutputCompatible(outputSchema, outputSchema.required || []);
|
|
85
|
-
const
|
|
85
|
+
const response = await this.client.chat.complete({
|
|
86
86
|
...nonStreamParams,
|
|
87
87
|
responseFormat: {
|
|
88
88
|
type: "json_schema",
|
|
@@ -92,7 +92,8 @@ var MistralTextAdapter = class extends BaseTextAdapter {
|
|
|
92
92
|
strict: true
|
|
93
93
|
}
|
|
94
94
|
}
|
|
95
|
-
})
|
|
95
|
+
});
|
|
96
|
+
const rawText = response.choices[0]?.message?.content;
|
|
96
97
|
const textContent = typeof rawText === "string" ? rawText : "";
|
|
97
98
|
let parsed;
|
|
98
99
|
try {
|
|
@@ -100,9 +101,15 @@ var MistralTextAdapter = class extends BaseTextAdapter {
|
|
|
100
101
|
} catch {
|
|
101
102
|
throw new Error(`Failed to parse structured output as JSON. Content: ${textContent.slice(0, 200)}${textContent.length > 200 ? "..." : ""}`);
|
|
102
103
|
}
|
|
104
|
+
const usage = response.usage;
|
|
103
105
|
return {
|
|
104
106
|
data: transformNullsToUndefined(parsed),
|
|
105
|
-
rawText: textContent
|
|
107
|
+
rawText: textContent,
|
|
108
|
+
...usage && { usage: {
|
|
109
|
+
promptTokens: usage.promptTokens ?? 0,
|
|
110
|
+
completionTokens: usage.completionTokens ?? 0,
|
|
111
|
+
totalTokens: usage.totalTokens ?? 0
|
|
112
|
+
} }
|
|
106
113
|
};
|
|
107
114
|
}
|
|
108
115
|
/**
|
|
@@ -603,7 +610,14 @@ var MistralTextAdapter = class extends BaseTextAdapter {
|
|
|
603
610
|
} : imageUrl
|
|
604
611
|
};
|
|
605
612
|
}
|
|
606
|
-
|
|
613
|
+
if (part.type === "document") {
|
|
614
|
+
const documentValue = part.source.value;
|
|
615
|
+
return {
|
|
616
|
+
type: "document_url",
|
|
617
|
+
documentUrl: part.source.type === "data" && !documentValue.startsWith("data:") ? `data:${part.source.mimeType};base64,${documentValue}` : documentValue
|
|
618
|
+
};
|
|
619
|
+
}
|
|
620
|
+
throw new Error(`Mistral text adapter does not support content part of type '${part.type}'. Supported types: text, image, document. Use a vision-capable model (mistral-medium-latest or mistral-small-latest) for images and documents.`);
|
|
607
621
|
}
|
|
608
622
|
/**
|
|
609
623
|
* Normalizes message content to an array of ContentPart.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"text.js","names":[],"sources":["../../../src/adapters/text.ts"],"sourcesContent":["import { BaseTextAdapter } from '@tanstack/ai/adapters'\nimport { convertToolsToProviderFormat } from '../tools/tool-converter'\nimport {\n createMistralClient,\n generateId,\n getMistralApiKeyFromEnv,\n} from '../utils/client'\nimport {\n makeMistralStructuredOutputCompatible,\n transformNullsToUndefined,\n} from '../utils/schema-converter'\nimport type {\n ContentPart,\n Modality,\n ModelMessage,\n StreamChunk,\n TextOptions,\n} from '@tanstack/ai'\nimport type {\n MISTRAL_CHAT_MODELS,\n MistralChatModelProviderOptionsByName,\n MistralModelInputModalitiesByName,\n} from '../model-meta'\nimport type {\n StructuredOutputOptions,\n StructuredOutputResult,\n} from '@tanstack/ai/adapters'\nimport type { Mistral } from '@mistralai/mistralai'\nimport type { ChatCompletionStreamRequest } from '@mistralai/mistralai/models/components'\nimport type {\n ExternalTextProviderOptions,\n InternalTextProviderOptions,\n} from '../text/text-provider-options'\nimport type {\n ChatCompletionContentPart,\n ChatCompletionMessageParam,\n MistralImageMetadata,\n MistralMessageMetadataByModality,\n} from '../message-types'\nimport type { MistralClientConfig } from '../utils/client'\n\n/** Cast an event object to StreamChunk. Adapters construct events with string\n * literal types which are structurally compatible with the EventType enum. */\nconst asChunk = (chunk: Record<string, unknown>) =>\n // oxlint-disable-next-line eslint-js/no-restricted-syntax -- Record<string, unknown> doesn't structurally overlap the StreamChunk discriminated union; events are built with literal `type` fields the union accepts at runtime\n chunk as unknown as StreamChunk\n\n/**\n * Parse the accumulated streaming arguments for a tool call. Throws a clear\n * error if the JSON is malformed — silently substituting `{}` would let a\n * tool fire with empty inputs, masking truncated streams or mis-shaped output.\n */\nfunction parseToolCallInput(toolCall: {\n id: string\n name: string\n arguments: string\n}): unknown {\n if (!toolCall.arguments) return {}\n try {\n return transformNullsToUndefined(JSON.parse(toolCall.arguments))\n } catch (cause) {\n const preview = toolCall.arguments.slice(0, 200)\n const ellipsis = toolCall.arguments.length > 200 ? '...' : ''\n throw new Error(\n `Failed to parse tool call arguments for tool '${toolCall.name}' (id: ${toolCall.id}). Arguments: ${preview}${ellipsis}`,\n { cause },\n )\n }\n}\n\n/**\n * Configuration for Mistral text adapter.\n */\nexport type MistralTextConfig = MistralClientConfig\n\n/**\n * Alias for TextProviderOptions for external use.\n */\nexport type MistralTextProviderOptions = ExternalTextProviderOptions\n\n// ===========================\n// Type Resolution Helpers\n// ===========================\n\ntype ResolveProviderOptions<TModel extends string> =\n TModel extends keyof MistralChatModelProviderOptionsByName\n ? MistralChatModelProviderOptionsByName[TModel]\n : MistralTextProviderOptions\n\ntype ResolveInputModalities<TModel extends string> =\n TModel extends keyof MistralModelInputModalitiesByName\n ? MistralModelInputModalitiesByName[TModel]\n : readonly ['text']\n\n// ===========================\n// Wire-format chunk types\n// ===========================\n\n/**\n * Snake-case shape of a Mistral chat completion stream chunk as returned on the\n * wire. We bypass the SDK's `chat.stream` because its Zod validation rejects\n * tool-call argument deltas that omit `function.name` (only the first chunk in\n * a tool call carries the name).\n */\ninterface MistralRawToolCall {\n id?: string\n type?: string\n index?: number\n function?: {\n name?: string\n arguments?: string | Record<string, unknown>\n }\n}\n\ninterface MistralRawChoice {\n index?: number\n delta?: {\n role?: string | null\n content?:\n | string\n | Array<{\n type: string\n text?: string\n // Mistral magistral models stream reasoning as content parts of\n // type 'thinking' whose `thinking` field is itself an array of\n // text/reference chunks. See Mistral SDK ThinkChunk type.\n thinking?: Array<{ type: string; text?: string }>\n }>\n | null\n // Some OpenAI-compatible deployments (DeepSeek, Groq for reasoning\n // models, and aimock-based test environments) emit reasoning via a\n // separate `reasoning_content` delta field rather than as a content\n // part. Accept both shapes — they cannot collide because real Mistral\n // never sets the OpenAI-compat field, and aimock never sets the\n // thinking content part.\n reasoning_content?: string | null\n tool_calls?: Array<MistralRawToolCall>\n }\n finish_reason?: string | null\n}\n\ninterface MistralRawChunk {\n id?: string\n model?: string\n choices?: Array<MistralRawChoice>\n usage?: {\n prompt_tokens?: number\n completion_tokens?: number\n total_tokens?: number\n }\n}\n\n// ===========================\n// Adapter Implementation\n// ===========================\n\n/**\n * Mistral Text (Chat) Adapter.\n *\n * Tree-shakeable adapter for Mistral chat/text completion functionality.\n */\nexport class MistralTextAdapter<\n TModel extends (typeof MISTRAL_CHAT_MODELS)[number],\n TProviderOptions extends Record<string, any> = ResolveProviderOptions<TModel>,\n TInputModalities extends ReadonlyArray<Modality> =\n ResolveInputModalities<TModel>,\n> extends BaseTextAdapter<\n TModel,\n TProviderOptions,\n TInputModalities,\n MistralMessageMetadataByModality\n> {\n readonly name = 'mistral' as const\n\n private readonly client: Mistral\n private readonly rawConfig: MistralClientConfig\n\n constructor(config: MistralTextConfig, model: TModel) {\n super(config, model)\n // The SDK client is retained for `structuredOutput` (non-streaming). The\n // streaming path bypasses the SDK and uses `fetchRawMistralStream` because\n // the SDK's Zod schemas reject partial tool-call argument deltas.\n this.client = createMistralClient(config)\n this.rawConfig = config\n }\n\n async *chatStream(\n options: TextOptions<TProviderOptions>,\n ): AsyncIterable<StreamChunk> {\n const requestParams = this.mapTextOptionsToMistral(options)\n const timestamp = Date.now()\n\n const aguiState = {\n runId: options.runId ?? generateId(this.name),\n threadId: options.threadId ?? generateId(this.name),\n messageId: generateId(this.name),\n timestamp,\n hasEmittedRunStarted: false,\n }\n\n try {\n const stream = this.fetchRawMistralStream(requestParams, this.rawConfig)\n yield* this.processMistralStreamChunks(stream, options, aguiState)\n } catch (error: unknown) {\n const err = error as Error & { code?: string }\n\n if (!aguiState.hasEmittedRunStarted) {\n aguiState.hasEmittedRunStarted = true\n yield asChunk({\n type: 'RUN_STARTED',\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model: options.model,\n timestamp,\n })\n }\n\n yield asChunk({\n type: 'RUN_ERROR',\n runId: aguiState.runId,\n model: options.model,\n timestamp,\n message: err.message || 'Unknown error',\n code: err.code,\n error: {\n message: err.message || 'Unknown error',\n code: err.code,\n },\n })\n\n throw err\n }\n }\n\n /**\n * Generate structured output using Mistral's JSON Schema response format.\n */\n async structuredOutput(\n options: StructuredOutputOptions<TProviderOptions>,\n ): Promise<StructuredOutputResult<unknown>> {\n const { chatOptions, outputSchema } = options\n const { stream: _stream, ...nonStreamParams } =\n this.mapTextOptionsToMistral(chatOptions)\n\n const jsonSchema = makeMistralStructuredOutputCompatible(\n outputSchema,\n outputSchema.required || [],\n )\n\n const response = await this.client.chat.complete({\n ...nonStreamParams,\n responseFormat: {\n type: 'json_schema',\n jsonSchema: {\n name: 'structured_output',\n schemaDefinition: jsonSchema,\n strict: true,\n },\n },\n })\n\n const rawText = response.choices[0]?.message?.content\n const textContent = typeof rawText === 'string' ? rawText : ''\n\n let parsed: unknown\n try {\n parsed = JSON.parse(textContent)\n } catch {\n throw new Error(\n `Failed to parse structured output as JSON. Content: ${textContent.slice(0, 200)}${textContent.length > 200 ? '...' : ''}`,\n )\n }\n\n return {\n data: transformNullsToUndefined(parsed),\n rawText: textContent,\n }\n }\n\n /**\n * Processes streaming chunks from the Mistral API and yields AG-UI stream events.\n */\n private async *processMistralStreamChunks(\n stream: AsyncIterable<MistralRawChunk>,\n options: TextOptions,\n aguiState: {\n runId: string\n threadId: string\n messageId: string\n timestamp: number\n hasEmittedRunStarted: boolean\n },\n ): AsyncIterable<StreamChunk> {\n let accumulatedContent = ''\n const timestamp = aguiState.timestamp\n let hasEmittedTextMessageStart = false\n let hasEmittedTextMessageEnd = false\n let hasEmittedToolCall = false\n let hasEmittedRunFinished = false\n let lastChunkModel = options.model\n\n // Reasoning lifecycle (magistral-* models stream `thinking` content\n // parts before any text). Mirrors the anthropic adapter's pattern:\n // open REASONING_* events on the first thinking delta, close them when\n // text/tool content begins or the run finishes.\n let reasoningMessageId: string | null = null\n let hasClosedReasoning = false\n\n const toolCallsInProgress = new Map<\n number,\n {\n id: string\n name: string\n arguments: string\n started: boolean\n ended: boolean\n }\n >()\n\n try {\n for await (const chunk of stream) {\n lastChunkModel = chunk.model || options.model\n const choice = chunk.choices?.[0]\n if (!choice) continue\n\n const chunkModel = chunk.model || options.model\n\n if (!aguiState.hasEmittedRunStarted) {\n aguiState.hasEmittedRunStarted = true\n yield asChunk({\n type: 'RUN_STARTED',\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model: chunkModel,\n timestamp,\n })\n }\n\n const delta = choice.delta\n const { text: deltaContent, thinking: deltaThinkingFromContent } =\n this.extractDeltaParts(delta?.content)\n // Reasoning may also arrive as a separate top-level field\n // (`delta.reasoning_content`) on OpenAI-compatible deployments.\n const deltaThinking =\n deltaThinkingFromContent +\n (typeof delta?.reasoning_content === 'string'\n ? delta.reasoning_content\n : '')\n const deltaToolCalls = delta?.tool_calls\n\n // Emit reasoning events FIRST so they always precede the matching\n // text or tool deltas in the same chunk.\n if (deltaThinking) {\n if (reasoningMessageId === null) {\n reasoningMessageId = generateId(this.name)\n yield asChunk({\n type: 'REASONING_START',\n messageId: reasoningMessageId,\n model: chunkModel,\n timestamp,\n })\n yield asChunk({\n type: 'REASONING_MESSAGE_START',\n messageId: reasoningMessageId,\n role: 'reasoning',\n model: chunkModel,\n timestamp,\n })\n }\n yield asChunk({\n type: 'REASONING_MESSAGE_CONTENT',\n messageId: reasoningMessageId,\n model: chunkModel,\n timestamp,\n delta: deltaThinking,\n })\n }\n\n // Close reasoning before any text/tool output starts in this chunk.\n const aboutToEmitOutput =\n !!deltaContent || (!!deltaToolCalls && deltaToolCalls.length > 0)\n if (\n reasoningMessageId !== null &&\n !hasClosedReasoning &&\n aboutToEmitOutput\n ) {\n hasClosedReasoning = true\n yield asChunk({\n type: 'REASONING_MESSAGE_END',\n messageId: reasoningMessageId,\n model: chunkModel,\n timestamp,\n })\n yield asChunk({\n type: 'REASONING_END',\n messageId: reasoningMessageId,\n model: chunkModel,\n timestamp,\n })\n }\n\n if (deltaContent) {\n if (!hasEmittedTextMessageStart) {\n hasEmittedTextMessageStart = true\n yield asChunk({\n type: 'TEXT_MESSAGE_START',\n messageId: aguiState.messageId,\n model: chunkModel,\n timestamp,\n role: 'assistant',\n })\n }\n\n accumulatedContent += deltaContent\n\n yield asChunk({\n type: 'TEXT_MESSAGE_CONTENT',\n messageId: aguiState.messageId,\n model: chunkModel,\n timestamp,\n delta: deltaContent,\n content: accumulatedContent,\n })\n }\n\n if (deltaToolCalls) {\n for (const [i, toolCallDelta] of deltaToolCalls.entries()) {\n const index = toolCallDelta.index ?? i\n\n let toolCall = toolCallsInProgress.get(index)\n if (!toolCall) {\n toolCall = {\n id: toolCallDelta.id || '',\n name: toolCallDelta.function?.name || '',\n arguments: '',\n started: false,\n ended: false,\n }\n toolCallsInProgress.set(index, toolCall)\n }\n\n if (toolCallDelta.id) toolCall.id = toolCallDelta.id\n if (toolCallDelta.function?.name) {\n toolCall.name = toolCallDelta.function.name\n }\n\n const rawArgs = toolCallDelta.function?.arguments\n const argsDelta =\n rawArgs === undefined\n ? undefined\n : typeof rawArgs === 'string'\n ? rawArgs\n : JSON.stringify(rawArgs)\n\n if (argsDelta !== undefined) {\n toolCall.arguments += argsDelta\n }\n\n const justStarted =\n !!toolCall.id && !!toolCall.name && !toolCall.started\n if (justStarted) {\n toolCall.started = true\n yield asChunk({\n type: 'TOOL_CALL_START',\n toolCallId: toolCall.id,\n toolCallName: toolCall.name,\n toolName: toolCall.name,\n model: chunkModel,\n timestamp,\n index,\n })\n // Replay any args buffered before id+name arrived (including\n // this chunk's argsDelta, if any).\n if (toolCall.arguments.length > 0) {\n yield asChunk({\n type: 'TOOL_CALL_ARGS',\n toolCallId: toolCall.id,\n model: chunkModel,\n timestamp,\n delta: toolCall.arguments,\n })\n }\n } else if (argsDelta !== undefined && toolCall.started) {\n yield asChunk({\n type: 'TOOL_CALL_ARGS',\n toolCallId: toolCall.id,\n model: chunkModel,\n timestamp,\n delta: argsDelta,\n })\n }\n }\n }\n\n const finishReason = choice.finish_reason\n if (finishReason) {\n if (finishReason === 'tool_calls' || toolCallsInProgress.size > 0) {\n for (const [, toolCall] of toolCallsInProgress) {\n if (\n !toolCall.started ||\n !toolCall.id ||\n !toolCall.name ||\n toolCall.ended\n ) {\n continue\n }\n\n const parsedInput = parseToolCallInput(toolCall)\n\n toolCall.ended = true\n hasEmittedToolCall = true\n yield asChunk({\n type: 'TOOL_CALL_END',\n toolCallId: toolCall.id,\n toolCallName: toolCall.name,\n toolName: toolCall.name,\n model: chunkModel,\n timestamp,\n input: parsedInput,\n })\n }\n }\n\n const computedFinishReason =\n finishReason === 'tool_calls' || hasEmittedToolCall\n ? 'tool_calls'\n : finishReason === 'length'\n ? 'length'\n : 'stop'\n\n // If the run finished while reasoning was still open (no text or\n // tool output ever followed), close reasoning before TEXT/RUN\n // finalization events.\n if (reasoningMessageId !== null && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield asChunk({\n type: 'REASONING_MESSAGE_END',\n messageId: reasoningMessageId,\n model: chunkModel,\n timestamp,\n })\n yield asChunk({\n type: 'REASONING_END',\n messageId: reasoningMessageId,\n model: chunkModel,\n timestamp,\n })\n }\n\n if (hasEmittedTextMessageStart && !hasEmittedTextMessageEnd) {\n hasEmittedTextMessageEnd = true\n yield asChunk({\n type: 'TEXT_MESSAGE_END',\n messageId: aguiState.messageId,\n model: chunkModel,\n timestamp,\n })\n }\n\n const usage = chunk.usage\n hasEmittedRunFinished = true\n yield asChunk({\n type: 'RUN_FINISHED',\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model: chunkModel,\n timestamp,\n usage: usage\n ? {\n promptTokens: usage.prompt_tokens || 0,\n completionTokens: usage.completion_tokens || 0,\n totalTokens: usage.total_tokens || 0,\n }\n : undefined,\n finishReason: computedFinishReason,\n })\n }\n }\n\n // Stream ended cleanly without finish_reason — flush any open\n // lifecycle events so consumers don't see orphaned starts. This\n // happens for abrupt `[DONE]` or upstream cuts.\n if (!hasEmittedRunFinished) {\n if (reasoningMessageId !== null && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield asChunk({\n type: 'REASONING_MESSAGE_END',\n messageId: reasoningMessageId,\n model: lastChunkModel,\n timestamp,\n })\n yield asChunk({\n type: 'REASONING_END',\n messageId: reasoningMessageId,\n model: lastChunkModel,\n timestamp,\n })\n }\n for (const [, toolCall] of toolCallsInProgress) {\n if (toolCall.started && !toolCall.ended) {\n toolCall.ended = true\n hasEmittedToolCall = true\n yield asChunk({\n type: 'TOOL_CALL_END',\n toolCallId: toolCall.id,\n toolCallName: toolCall.name,\n toolName: toolCall.name,\n model: lastChunkModel,\n timestamp,\n input: parseToolCallInput(toolCall),\n })\n }\n }\n if (hasEmittedTextMessageStart && !hasEmittedTextMessageEnd) {\n hasEmittedTextMessageEnd = true\n yield asChunk({\n type: 'TEXT_MESSAGE_END',\n messageId: aguiState.messageId,\n model: lastChunkModel,\n timestamp,\n })\n }\n hasEmittedRunFinished = true\n yield asChunk({\n type: 'RUN_FINISHED',\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model: lastChunkModel,\n timestamp,\n usage: undefined,\n finishReason: hasEmittedToolCall ? 'tool_calls' : 'stop',\n })\n }\n } catch (error: unknown) {\n // Lifecycle cleanup (TEXT_MESSAGE_END / TOOL_CALL_END / REASONING_END)\n // on error path so consumers don't see orphaned starts. RUN_ERROR is\n // emitted by the outer chatStream catch — emitting it here would\n // duplicate the event.\n if (reasoningMessageId !== null && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield asChunk({\n type: 'REASONING_MESSAGE_END',\n messageId: reasoningMessageId,\n model: lastChunkModel,\n timestamp,\n })\n yield asChunk({\n type: 'REASONING_END',\n messageId: reasoningMessageId,\n model: lastChunkModel,\n timestamp,\n })\n }\n if (hasEmittedTextMessageStart && !hasEmittedTextMessageEnd) {\n hasEmittedTextMessageEnd = true\n yield asChunk({\n type: 'TEXT_MESSAGE_END',\n messageId: aguiState.messageId,\n model: lastChunkModel,\n timestamp,\n })\n }\n for (const [, toolCall] of toolCallsInProgress) {\n if (toolCall.started && !toolCall.ended) {\n toolCall.ended = true\n // Best-effort parse for the partial args; if invalid, surface\n // empty input rather than throwing inside the cleanup path.\n let partialInput: unknown = {}\n try {\n partialInput = toolCall.arguments\n ? transformNullsToUndefined(JSON.parse(toolCall.arguments))\n : {}\n } catch {\n partialInput = {}\n }\n yield asChunk({\n type: 'TOOL_CALL_END',\n toolCallId: toolCall.id,\n toolCallName: toolCall.name,\n toolName: toolCall.name,\n model: lastChunkModel,\n timestamp,\n input: partialInput,\n })\n }\n }\n throw error\n }\n }\n\n /**\n * Makes a raw fetch request to the Mistral chat completions endpoint and\n * parses the SSE stream manually, bypassing the SDK's Zod validation which\n * rejects streaming tool call chunks that omit `name` in argument deltas.\n */\n private async *fetchRawMistralStream(\n params: ChatCompletionStreamRequest,\n config: MistralClientConfig,\n ): AsyncGenerator<MistralRawChunk> {\n const serverURL = (config.serverURL ?? 'https://api.mistral.ai')\n .replace(/\\/+$/, '')\n .replace(/\\/v1$/, '')\n const url = `${serverURL}/v1/chat/completions`\n\n const body = this.toWireBody(params)\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n ...config.defaultHeaders,\n }\n\n const response = await fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Mistral API error ${response.status}: ${errorText}`)\n }\n\n if (!response.body) {\n throw new Error(\n 'Mistral API returned a response with no body. This may indicate a proxy or runtime that does not support streaming.',\n )\n }\n\n const reader = response.body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n\n buffer += decoder.decode(value, { stream: true })\n const lines = buffer.split('\\n')\n // split('\\n') always yields at least one element, so pop() is a\n // string here; `?? ''` only satisfies the type narrowing.\n buffer = lines.pop() ?? ''\n\n for (const line of lines) {\n const trimmed = line.trim()\n if (!trimmed.startsWith('data:')) continue\n const data = trimmed.slice(5).trimStart()\n if (data === '[DONE]') return\n\n let parsed: unknown\n try {\n parsed = JSON.parse(data)\n } catch (e) {\n if (e instanceof SyntaxError) {\n console.warn(\n `[mistral] skipped unparseable SSE chunk: ${data.slice(0, 200)}`,\n )\n continue\n }\n throw e\n }\n\n // Mistral signals mid-stream errors via an `error` field. Surface\n // them as RUN_ERROR rather than swallowing them as empty chunks.\n if (\n parsed &&\n typeof parsed === 'object' &&\n 'error' in parsed &&\n !('choices' in parsed)\n ) {\n const errPayload = parsed.error\n const message =\n typeof errPayload === 'string'\n ? errPayload\n : errPayload &&\n typeof errPayload === 'object' &&\n 'message' in errPayload\n ? String(errPayload.message)\n : JSON.stringify(errPayload)\n throw new Error(`Mistral stream error: ${message}`)\n }\n\n yield parsed as MistralRawChunk\n }\n }\n } finally {\n await reader.cancel().catch(() => {})\n reader.releaseLock()\n }\n }\n\n /**\n * Converts the SDK's camelCase `ChatCompletionStreamRequest` into the\n * snake_case wire body, including converting messages.\n */\n private toWireBody(\n params: ChatCompletionStreamRequest,\n ): Record<string, unknown> {\n const {\n messages,\n maxTokens,\n topP,\n randomSeed,\n responseFormat,\n toolChoice,\n parallelToolCalls,\n frequencyPenalty,\n presencePenalty,\n safePrompt,\n stream: _stream,\n ...rest\n } = params\n\n return {\n ...rest,\n messages: messages.map(messageToWire),\n stream: true,\n // Opt in to usage on the final streaming chunk.\n stream_options: { include_usage: true },\n ...(maxTokens != null && { max_tokens: maxTokens }),\n ...(topP != null && { top_p: topP }),\n ...(randomSeed != null && { random_seed: randomSeed }),\n ...(responseFormat != null && { response_format: responseFormat }),\n ...(toolChoice != null && { tool_choice: toolChoice }),\n ...(parallelToolCalls != null && {\n parallel_tool_calls: parallelToolCalls,\n }),\n ...(frequencyPenalty != null && { frequency_penalty: frequencyPenalty }),\n ...(presencePenalty != null && { presence_penalty: presencePenalty }),\n ...(safePrompt != null && { safe_prompt: safePrompt }),\n }\n }\n\n /**\n * Splits a Mistral delta content payload into text and reasoning deltas.\n * Mistral reasoning models (magistral-*) stream reasoning content as\n * `{ type: 'thinking', thinking: [{ type: 'text', text }, ...] }` content\n * parts. A single delta may contain text only, thinking only, or — rarely —\n * both (when a step transitions); both fields are returned so the caller\n * can sequence REASONING and TEXT lifecycle events in order.\n */\n private extractDeltaParts(\n content:\n | string\n | Array<{\n type: string\n text?: string\n thinking?: Array<{ type: string; text?: string }>\n }>\n | null\n | undefined,\n ): { text: string; thinking: string } {\n if (!content) return { text: '', thinking: '' }\n if (typeof content === 'string') return { text: content, thinking: '' }\n\n let text = ''\n let thinking = ''\n for (const part of content) {\n if (part.type === 'text' && typeof part.text === 'string') {\n text += part.text\n } else if (part.type === 'thinking' && Array.isArray(part.thinking)) {\n for (const inner of part.thinking) {\n if (inner.type === 'text' && typeof inner.text === 'string') {\n thinking += inner.text\n }\n }\n }\n }\n return { text, thinking }\n }\n\n /**\n * Maps common TextOptions to Mistral Chat Completions request parameters.\n */\n private mapTextOptionsToMistral(\n options: TextOptions<TProviderOptions>,\n ): ChatCompletionStreamRequest {\n const modelOptions = options.modelOptions as\n | Omit<InternalTextProviderOptions, 'tools'>\n | undefined\n\n const tools = options.tools\n ? convertToolsToProviderFormat(options.tools)\n : undefined\n\n const messages: Array<ChatCompletionMessageParam> = []\n\n if (options.systemPrompts && options.systemPrompts.length > 0) {\n messages.push({\n role: 'system',\n content: options.systemPrompts.join('\\n'),\n })\n }\n\n for (const message of options.messages) {\n messages.push(this.convertMessageToMistral(message))\n }\n\n return {\n model: options.model,\n messages: messages,\n temperature: modelOptions?.temperature ?? undefined,\n maxTokens: modelOptions?.max_tokens ?? undefined,\n topP: modelOptions?.top_p ?? undefined,\n tools: tools as ChatCompletionStreamRequest['tools'],\n stream: true,\n ...(modelOptions && {\n ...(modelOptions.stop != null && { stop: modelOptions.stop }),\n ...(modelOptions.random_seed != null && {\n randomSeed: modelOptions.random_seed,\n }),\n ...(modelOptions.response_format != null && {\n responseFormat: modelOptions.response_format,\n }),\n ...(modelOptions.tool_choice != null && {\n toolChoice: modelOptions.tool_choice,\n }),\n ...(modelOptions.parallel_tool_calls != null && {\n parallelToolCalls: modelOptions.parallel_tool_calls,\n }),\n ...(modelOptions.frequency_penalty != null && {\n frequencyPenalty: modelOptions.frequency_penalty,\n }),\n ...(modelOptions.presence_penalty != null && {\n presencePenalty: modelOptions.presence_penalty,\n }),\n ...(modelOptions.n != null && { n: modelOptions.n }),\n ...(modelOptions.prediction != null && {\n prediction: modelOptions.prediction,\n }),\n ...(modelOptions.safe_prompt != null && {\n safePrompt: modelOptions.safe_prompt,\n }),\n }),\n }\n }\n\n /**\n * Converts a TanStack AI ModelMessage to a Mistral ChatCompletionMessageParam.\n */\n private convertMessageToMistral(\n message: ModelMessage,\n ): ChatCompletionMessageParam {\n if (message.role === 'tool') {\n if (!message.toolCallId) {\n throw new Error('Missing toolCallId for tool message')\n }\n return {\n role: 'tool',\n toolCallId: message.toolCallId,\n content:\n typeof message.content === 'string'\n ? message.content\n : JSON.stringify(message.content),\n }\n }\n\n if (message.role === 'assistant') {\n const toolCalls = message.toolCalls?.map((tc) => ({\n id: tc.id,\n type: 'function' as const,\n function: {\n name: tc.function.name,\n arguments:\n typeof tc.function.arguments === 'string'\n ? tc.function.arguments\n : JSON.stringify(tc.function.arguments),\n },\n }))\n\n return {\n role: 'assistant',\n content: this.extractTextContent(message.content),\n ...(toolCalls && toolCalls.length > 0 ? { toolCalls } : {}),\n }\n }\n\n const contentParts = this.normalizeContent(message.content)\n\n if (contentParts.length === 1 && contentParts[0]?.type === 'text') {\n return {\n role: 'user',\n content: contentParts[0].content,\n }\n }\n\n const parts = contentParts.map((part) =>\n this.convertContentPartToMistral(part),\n )\n\n return {\n role: 'user',\n content: parts.length > 0 ? parts : '',\n }\n }\n\n /**\n * Converts a ContentPart to a Mistral content part. Returns undefined for\n * unsupported part types.\n */\n private convertContentPartToMistral(\n part: ContentPart,\n ): ChatCompletionContentPart {\n if (part.type === 'text') {\n return { type: 'text', text: part.content }\n }\n\n if (part.type === 'image') {\n const imageMetadata = part.metadata as MistralImageMetadata | undefined\n const imageValue = part.source.value\n const imageUrl =\n part.source.type === 'data' && !imageValue.startsWith('data:')\n ? `data:${part.source.mimeType};base64,${imageValue}`\n : imageValue\n return {\n type: 'image_url',\n imageUrl: imageMetadata?.detail\n ? { url: imageUrl, detail: imageMetadata.detail }\n : imageUrl,\n }\n }\n\n throw new Error(\n `Mistral text adapter does not support content part of type '${(part as ContentPart).type}'. Supported types: text, image. Use a vision-capable model (pixtral-large-latest, pixtral-12b-2409, mistral-medium-latest, or mistral-small-latest) for images.`,\n )\n }\n\n /**\n * Normalizes message content to an array of ContentPart.\n */\n private normalizeContent(\n content: string | null | Array<ContentPart>,\n ): Array<ContentPart> {\n if (content === null) return []\n if (typeof content === 'string') return [{ type: 'text', content }]\n return content\n }\n\n /**\n * Extracts text content from a content value that may be string, null, or ContentPart array.\n */\n private extractTextContent(\n content: string | null | Array<ContentPart>,\n ): string {\n if (content === null) return ''\n if (typeof content === 'string') return content\n return content\n .filter((p) => p.type === 'text')\n .map((p) => p.content)\n .join('')\n }\n}\n\n/**\n * Snake-cases a Mistral SDK message into the wire format expected by the API.\n */\nfunction messageToWire(msg: ChatCompletionStreamRequest['messages'][number]) {\n if (msg.role === 'tool') {\n return {\n role: 'tool',\n tool_call_id: msg.toolCallId,\n content: msg.content,\n ...(msg.name !== undefined ? { name: msg.name } : {}),\n }\n }\n if (msg.role === 'assistant') {\n const base: Record<string, unknown> = {\n role: 'assistant',\n content: msg.content ?? null,\n }\n if (msg.toolCalls && msg.toolCalls.length > 0) {\n base.tool_calls = msg.toolCalls.map((tc) => ({\n id: tc.id,\n type: tc.type ?? 'function',\n function: tc.function,\n }))\n }\n if (msg.prefix !== undefined) base.prefix = msg.prefix\n return base\n }\n if (msg.role === 'user' && Array.isArray(msg.content)) {\n return {\n role: 'user',\n content: msg.content.map((part) => {\n if (part.type === 'image_url') {\n return { type: 'image_url', image_url: part.imageUrl }\n }\n if (part.type === 'document_url') {\n return { type: 'document_url', document_url: part.documentUrl }\n }\n return part\n }),\n }\n }\n return msg\n}\n\n/**\n * Creates a Mistral text adapter with explicit API key.\n *\n * @param model - The model name (e.g., 'mistral-large-latest')\n * @param apiKey - Your Mistral API key\n * @param config - Optional additional configuration\n * @returns Configured Mistral text adapter instance\n *\n * @example\n * ```typescript\n * const adapter = createMistralText('mistral-large-latest', 'api_key');\n * ```\n */\nexport function createMistralText<\n TModel extends (typeof MISTRAL_CHAT_MODELS)[number],\n>(\n model: TModel,\n apiKey: string,\n config?: Omit<MistralTextConfig, 'apiKey'>,\n): MistralTextAdapter<TModel> {\n return new MistralTextAdapter({ apiKey, ...config }, model)\n}\n\n/**\n * Creates a Mistral text adapter using the `MISTRAL_API_KEY` environment variable.\n *\n * @param model - The model name (e.g., 'mistral-large-latest')\n * @param config - Optional configuration (excluding apiKey)\n * @returns Configured Mistral text adapter instance\n * @throws Error if MISTRAL_API_KEY is not found in environment\n *\n * @example\n * ```typescript\n * const adapter = mistralText('mistral-large-latest');\n * ```\n */\nexport function mistralText<\n TModel extends (typeof MISTRAL_CHAT_MODELS)[number],\n>(\n model: TModel,\n config?: Omit<MistralTextConfig, 'apiKey'>,\n): MistralTextAdapter<TModel> {\n const apiKey = getMistralApiKeyFromEnv()\n return createMistralText(model, apiKey, config)\n}\n"],"mappings":";;;;;;;AA2CA,IAAM,WAAW,UAEf;;;;;;AAOF,SAAS,mBAAmB,UAIhB;CACV,IAAI,CAAC,SAAS,WAAW,OAAO,CAAC;CACjC,IAAI;EACF,OAAO,0BAA0B,KAAK,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A,SAAgB,YAGd,OACA,QAC4B;CAE5B,OAAO,kBAAkB,OADV,wBACiB,GAAQ,MAAM;AAChD"}
|
|
1
|
+
{"version":3,"file":"text.js","names":[],"sources":["../../../src/adapters/text.ts"],"sourcesContent":["import { BaseTextAdapter } from '@tanstack/ai/adapters'\nimport { convertToolsToProviderFormat } from '../tools/tool-converter'\nimport {\n createMistralClient,\n generateId,\n getMistralApiKeyFromEnv,\n} from '../utils/client'\nimport {\n makeMistralStructuredOutputCompatible,\n transformNullsToUndefined,\n} from '../utils/schema-converter'\nimport type {\n ContentPart,\n Modality,\n ModelMessage,\n StreamChunk,\n TextOptions,\n} from '@tanstack/ai'\nimport type {\n MISTRAL_CHAT_MODELS,\n MistralChatModelProviderOptionsByName,\n MistralModelInputModalitiesByName,\n} from '../model-meta'\nimport type {\n StructuredOutputOptions,\n StructuredOutputResult,\n} from '@tanstack/ai/adapters'\nimport type { Mistral } from '@mistralai/mistralai'\nimport type { ChatCompletionStreamRequest } from '@mistralai/mistralai/models/components'\nimport type {\n ExternalTextProviderOptions,\n InternalTextProviderOptions,\n} from '../text/text-provider-options'\nimport type {\n ChatCompletionContentPart,\n ChatCompletionMessageParam,\n MistralImageMetadata,\n MistralMessageMetadataByModality,\n} from '../message-types'\nimport type { MistralClientConfig } from '../utils/client'\n\n/** Cast an event object to StreamChunk. Adapters construct events with string\n * literal types which are structurally compatible with the EventType enum. */\nconst asChunk = (chunk: Record<string, unknown>) =>\n // oxlint-disable-next-line eslint-js/no-restricted-syntax -- Record<string, unknown> doesn't structurally overlap the StreamChunk discriminated union; events are built with literal `type` fields the union accepts at runtime\n chunk as unknown as StreamChunk\n\n/**\n * Parse the accumulated streaming arguments for a tool call. Throws a clear\n * error if the JSON is malformed — silently substituting `{}` would let a\n * tool fire with empty inputs, masking truncated streams or mis-shaped output.\n */\nfunction parseToolCallInput(toolCall: {\n id: string\n name: string\n arguments: string\n}): unknown {\n if (!toolCall.arguments) return {}\n try {\n return transformNullsToUndefined(JSON.parse(toolCall.arguments))\n } catch (cause) {\n const preview = toolCall.arguments.slice(0, 200)\n const ellipsis = toolCall.arguments.length > 200 ? '...' : ''\n throw new Error(\n `Failed to parse tool call arguments for tool '${toolCall.name}' (id: ${toolCall.id}). Arguments: ${preview}${ellipsis}`,\n { cause },\n )\n }\n}\n\n/**\n * Configuration for Mistral text adapter.\n */\nexport type MistralTextConfig = MistralClientConfig\n\n/**\n * Alias for TextProviderOptions for external use.\n */\nexport type MistralTextProviderOptions = ExternalTextProviderOptions\n\n// ===========================\n// Type Resolution Helpers\n// ===========================\n\ntype ResolveProviderOptions<TModel extends string> =\n TModel extends keyof MistralChatModelProviderOptionsByName\n ? MistralChatModelProviderOptionsByName[TModel]\n : MistralTextProviderOptions\n\ntype ResolveInputModalities<TModel extends string> =\n TModel extends keyof MistralModelInputModalitiesByName\n ? MistralModelInputModalitiesByName[TModel]\n : readonly ['text']\n\n// ===========================\n// Wire-format chunk types\n// ===========================\n\n/**\n * Snake-case shape of a Mistral chat completion stream chunk as returned on the\n * wire. We bypass the SDK's `chat.stream` because its Zod validation rejects\n * tool-call argument deltas that omit `function.name` (only the first chunk in\n * a tool call carries the name).\n */\ninterface MistralRawToolCall {\n id?: string\n type?: string\n index?: number\n function?: {\n name?: string\n arguments?: string | Record<string, unknown>\n }\n}\n\ninterface MistralRawChoice {\n index?: number\n delta?: {\n role?: string | null\n content?:\n | string\n | Array<{\n type: string\n text?: string\n // Mistral magistral models stream reasoning as content parts of\n // type 'thinking' whose `thinking` field is itself an array of\n // text/reference chunks. See Mistral SDK ThinkChunk type.\n thinking?: Array<{ type: string; text?: string }>\n }>\n | null\n // Some OpenAI-compatible deployments (DeepSeek, Groq for reasoning\n // models, and aimock-based test environments) emit reasoning via a\n // separate `reasoning_content` delta field rather than as a content\n // part. Accept both shapes — they cannot collide because real Mistral\n // never sets the OpenAI-compat field, and aimock never sets the\n // thinking content part.\n reasoning_content?: string | null\n tool_calls?: Array<MistralRawToolCall>\n }\n finish_reason?: string | null\n}\n\ninterface MistralRawChunk {\n id?: string\n model?: string\n choices?: Array<MistralRawChoice>\n usage?: {\n prompt_tokens?: number\n completion_tokens?: number\n total_tokens?: number\n }\n}\n\n// ===========================\n// Adapter Implementation\n// ===========================\n\n/**\n * Mistral Text (Chat) Adapter.\n *\n * Tree-shakeable adapter for Mistral chat/text completion functionality.\n */\nexport class MistralTextAdapter<\n TModel extends (typeof MISTRAL_CHAT_MODELS)[number],\n TProviderOptions extends Record<string, any> = ResolveProviderOptions<TModel>,\n TInputModalities extends ReadonlyArray<Modality> =\n ResolveInputModalities<TModel>,\n> extends BaseTextAdapter<\n TModel,\n TProviderOptions,\n TInputModalities,\n MistralMessageMetadataByModality\n> {\n readonly name = 'mistral' as const\n\n private readonly client: Mistral\n private readonly rawConfig: MistralClientConfig\n\n constructor(config: MistralTextConfig, model: TModel) {\n super(config, model)\n // The SDK client is retained for `structuredOutput` (non-streaming). The\n // streaming path bypasses the SDK and uses `fetchRawMistralStream` because\n // the SDK's Zod schemas reject partial tool-call argument deltas.\n this.client = createMistralClient(config)\n this.rawConfig = config\n }\n\n async *chatStream(\n options: TextOptions<TProviderOptions>,\n ): AsyncIterable<StreamChunk> {\n const requestParams = this.mapTextOptionsToMistral(options)\n const timestamp = Date.now()\n\n const aguiState = {\n runId: options.runId ?? generateId(this.name),\n threadId: options.threadId ?? generateId(this.name),\n messageId: generateId(this.name),\n timestamp,\n hasEmittedRunStarted: false,\n }\n\n try {\n const stream = this.fetchRawMistralStream(requestParams, this.rawConfig)\n yield* this.processMistralStreamChunks(stream, options, aguiState)\n } catch (error: unknown) {\n const err = error as Error & { code?: string }\n\n if (!aguiState.hasEmittedRunStarted) {\n aguiState.hasEmittedRunStarted = true\n yield asChunk({\n type: 'RUN_STARTED',\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model: options.model,\n timestamp,\n })\n }\n\n yield asChunk({\n type: 'RUN_ERROR',\n runId: aguiState.runId,\n model: options.model,\n timestamp,\n message: err.message || 'Unknown error',\n code: err.code,\n error: {\n message: err.message || 'Unknown error',\n code: err.code,\n },\n })\n\n throw err\n }\n }\n\n /**\n * Generate structured output using Mistral's JSON Schema response format.\n */\n async structuredOutput(\n options: StructuredOutputOptions<TProviderOptions>,\n ): Promise<StructuredOutputResult<unknown>> {\n const { chatOptions, outputSchema } = options\n const { stream: _stream, ...nonStreamParams } =\n this.mapTextOptionsToMistral(chatOptions)\n\n const jsonSchema = makeMistralStructuredOutputCompatible(\n outputSchema,\n outputSchema.required || [],\n )\n\n const response = await this.client.chat.complete({\n ...nonStreamParams,\n responseFormat: {\n type: 'json_schema',\n jsonSchema: {\n name: 'structured_output',\n schemaDefinition: jsonSchema,\n strict: true,\n },\n },\n })\n\n const rawText = response.choices[0]?.message?.content\n const textContent = typeof rawText === 'string' ? rawText : ''\n\n let parsed: unknown\n try {\n parsed = JSON.parse(textContent)\n } catch {\n throw new Error(\n `Failed to parse structured output as JSON. Content: ${textContent.slice(0, 200)}${textContent.length > 200 ? '...' : ''}`,\n )\n }\n\n const usage = response.usage\n return {\n data: transformNullsToUndefined(parsed),\n rawText: textContent,\n ...(usage && {\n usage: {\n promptTokens: usage.promptTokens ?? 0,\n completionTokens: usage.completionTokens ?? 0,\n totalTokens: usage.totalTokens ?? 0,\n },\n }),\n }\n }\n\n /**\n * Processes streaming chunks from the Mistral API and yields AG-UI stream events.\n */\n private async *processMistralStreamChunks(\n stream: AsyncIterable<MistralRawChunk>,\n options: TextOptions,\n aguiState: {\n runId: string\n threadId: string\n messageId: string\n timestamp: number\n hasEmittedRunStarted: boolean\n },\n ): AsyncIterable<StreamChunk> {\n let accumulatedContent = ''\n const timestamp = aguiState.timestamp\n let hasEmittedTextMessageStart = false\n let hasEmittedTextMessageEnd = false\n let hasEmittedToolCall = false\n let hasEmittedRunFinished = false\n let lastChunkModel = options.model\n\n // Reasoning lifecycle (magistral-* models stream `thinking` content\n // parts before any text). Mirrors the anthropic adapter's pattern:\n // open REASONING_* events on the first thinking delta, close them when\n // text/tool content begins or the run finishes.\n let reasoningMessageId: string | null = null\n let hasClosedReasoning = false\n\n const toolCallsInProgress = new Map<\n number,\n {\n id: string\n name: string\n arguments: string\n started: boolean\n ended: boolean\n }\n >()\n\n try {\n for await (const chunk of stream) {\n lastChunkModel = chunk.model || options.model\n const choice = chunk.choices?.[0]\n if (!choice) continue\n\n const chunkModel = chunk.model || options.model\n\n if (!aguiState.hasEmittedRunStarted) {\n aguiState.hasEmittedRunStarted = true\n yield asChunk({\n type: 'RUN_STARTED',\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model: chunkModel,\n timestamp,\n })\n }\n\n const delta = choice.delta\n const { text: deltaContent, thinking: deltaThinkingFromContent } =\n this.extractDeltaParts(delta?.content)\n // Reasoning may also arrive as a separate top-level field\n // (`delta.reasoning_content`) on OpenAI-compatible deployments.\n const deltaThinking =\n deltaThinkingFromContent +\n (typeof delta?.reasoning_content === 'string'\n ? delta.reasoning_content\n : '')\n const deltaToolCalls = delta?.tool_calls\n\n // Emit reasoning events FIRST so they always precede the matching\n // text or tool deltas in the same chunk.\n if (deltaThinking) {\n if (reasoningMessageId === null) {\n reasoningMessageId = generateId(this.name)\n yield asChunk({\n type: 'REASONING_START',\n messageId: reasoningMessageId,\n model: chunkModel,\n timestamp,\n })\n yield asChunk({\n type: 'REASONING_MESSAGE_START',\n messageId: reasoningMessageId,\n role: 'reasoning',\n model: chunkModel,\n timestamp,\n })\n }\n yield asChunk({\n type: 'REASONING_MESSAGE_CONTENT',\n messageId: reasoningMessageId,\n model: chunkModel,\n timestamp,\n delta: deltaThinking,\n })\n }\n\n // Close reasoning before any text/tool output starts in this chunk.\n const aboutToEmitOutput =\n !!deltaContent || (!!deltaToolCalls && deltaToolCalls.length > 0)\n if (\n reasoningMessageId !== null &&\n !hasClosedReasoning &&\n aboutToEmitOutput\n ) {\n hasClosedReasoning = true\n yield asChunk({\n type: 'REASONING_MESSAGE_END',\n messageId: reasoningMessageId,\n model: chunkModel,\n timestamp,\n })\n yield asChunk({\n type: 'REASONING_END',\n messageId: reasoningMessageId,\n model: chunkModel,\n timestamp,\n })\n }\n\n if (deltaContent) {\n if (!hasEmittedTextMessageStart) {\n hasEmittedTextMessageStart = true\n yield asChunk({\n type: 'TEXT_MESSAGE_START',\n messageId: aguiState.messageId,\n model: chunkModel,\n timestamp,\n role: 'assistant',\n })\n }\n\n accumulatedContent += deltaContent\n\n yield asChunk({\n type: 'TEXT_MESSAGE_CONTENT',\n messageId: aguiState.messageId,\n model: chunkModel,\n timestamp,\n delta: deltaContent,\n content: accumulatedContent,\n })\n }\n\n if (deltaToolCalls) {\n for (const [i, toolCallDelta] of deltaToolCalls.entries()) {\n const index = toolCallDelta.index ?? i\n\n let toolCall = toolCallsInProgress.get(index)\n if (!toolCall) {\n toolCall = {\n id: toolCallDelta.id || '',\n name: toolCallDelta.function?.name || '',\n arguments: '',\n started: false,\n ended: false,\n }\n toolCallsInProgress.set(index, toolCall)\n }\n\n if (toolCallDelta.id) toolCall.id = toolCallDelta.id\n if (toolCallDelta.function?.name) {\n toolCall.name = toolCallDelta.function.name\n }\n\n const rawArgs = toolCallDelta.function?.arguments\n const argsDelta =\n rawArgs === undefined\n ? undefined\n : typeof rawArgs === 'string'\n ? rawArgs\n : JSON.stringify(rawArgs)\n\n if (argsDelta !== undefined) {\n toolCall.arguments += argsDelta\n }\n\n const justStarted =\n !!toolCall.id && !!toolCall.name && !toolCall.started\n if (justStarted) {\n toolCall.started = true\n yield asChunk({\n type: 'TOOL_CALL_START',\n toolCallId: toolCall.id,\n toolCallName: toolCall.name,\n toolName: toolCall.name,\n model: chunkModel,\n timestamp,\n index,\n })\n // Replay any args buffered before id+name arrived (including\n // this chunk's argsDelta, if any).\n if (toolCall.arguments.length > 0) {\n yield asChunk({\n type: 'TOOL_CALL_ARGS',\n toolCallId: toolCall.id,\n model: chunkModel,\n timestamp,\n delta: toolCall.arguments,\n })\n }\n } else if (argsDelta !== undefined && toolCall.started) {\n yield asChunk({\n type: 'TOOL_CALL_ARGS',\n toolCallId: toolCall.id,\n model: chunkModel,\n timestamp,\n delta: argsDelta,\n })\n }\n }\n }\n\n const finishReason = choice.finish_reason\n if (finishReason) {\n if (finishReason === 'tool_calls' || toolCallsInProgress.size > 0) {\n for (const [, toolCall] of toolCallsInProgress) {\n if (\n !toolCall.started ||\n !toolCall.id ||\n !toolCall.name ||\n toolCall.ended\n ) {\n continue\n }\n\n const parsedInput = parseToolCallInput(toolCall)\n\n toolCall.ended = true\n hasEmittedToolCall = true\n yield asChunk({\n type: 'TOOL_CALL_END',\n toolCallId: toolCall.id,\n toolCallName: toolCall.name,\n toolName: toolCall.name,\n model: chunkModel,\n timestamp,\n input: parsedInput,\n })\n }\n }\n\n const computedFinishReason =\n finishReason === 'tool_calls' || hasEmittedToolCall\n ? 'tool_calls'\n : finishReason === 'length'\n ? 'length'\n : 'stop'\n\n // If the run finished while reasoning was still open (no text or\n // tool output ever followed), close reasoning before TEXT/RUN\n // finalization events.\n if (reasoningMessageId !== null && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield asChunk({\n type: 'REASONING_MESSAGE_END',\n messageId: reasoningMessageId,\n model: chunkModel,\n timestamp,\n })\n yield asChunk({\n type: 'REASONING_END',\n messageId: reasoningMessageId,\n model: chunkModel,\n timestamp,\n })\n }\n\n if (hasEmittedTextMessageStart && !hasEmittedTextMessageEnd) {\n hasEmittedTextMessageEnd = true\n yield asChunk({\n type: 'TEXT_MESSAGE_END',\n messageId: aguiState.messageId,\n model: chunkModel,\n timestamp,\n })\n }\n\n const usage = chunk.usage\n hasEmittedRunFinished = true\n yield asChunk({\n type: 'RUN_FINISHED',\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model: chunkModel,\n timestamp,\n usage: usage\n ? {\n promptTokens: usage.prompt_tokens || 0,\n completionTokens: usage.completion_tokens || 0,\n totalTokens: usage.total_tokens || 0,\n }\n : undefined,\n finishReason: computedFinishReason,\n })\n }\n }\n\n // Stream ended cleanly without finish_reason — flush any open\n // lifecycle events so consumers don't see orphaned starts. This\n // happens for abrupt `[DONE]` or upstream cuts.\n if (!hasEmittedRunFinished) {\n if (reasoningMessageId !== null && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield asChunk({\n type: 'REASONING_MESSAGE_END',\n messageId: reasoningMessageId,\n model: lastChunkModel,\n timestamp,\n })\n yield asChunk({\n type: 'REASONING_END',\n messageId: reasoningMessageId,\n model: lastChunkModel,\n timestamp,\n })\n }\n for (const [, toolCall] of toolCallsInProgress) {\n if (toolCall.started && !toolCall.ended) {\n toolCall.ended = true\n hasEmittedToolCall = true\n yield asChunk({\n type: 'TOOL_CALL_END',\n toolCallId: toolCall.id,\n toolCallName: toolCall.name,\n toolName: toolCall.name,\n model: lastChunkModel,\n timestamp,\n input: parseToolCallInput(toolCall),\n })\n }\n }\n if (hasEmittedTextMessageStart && !hasEmittedTextMessageEnd) {\n hasEmittedTextMessageEnd = true\n yield asChunk({\n type: 'TEXT_MESSAGE_END',\n messageId: aguiState.messageId,\n model: lastChunkModel,\n timestamp,\n })\n }\n hasEmittedRunFinished = true\n yield asChunk({\n type: 'RUN_FINISHED',\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model: lastChunkModel,\n timestamp,\n usage: undefined,\n finishReason: hasEmittedToolCall ? 'tool_calls' : 'stop',\n })\n }\n } catch (error: unknown) {\n // Lifecycle cleanup (TEXT_MESSAGE_END / TOOL_CALL_END / REASONING_END)\n // on error path so consumers don't see orphaned starts. RUN_ERROR is\n // emitted by the outer chatStream catch — emitting it here would\n // duplicate the event.\n if (reasoningMessageId !== null && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield asChunk({\n type: 'REASONING_MESSAGE_END',\n messageId: reasoningMessageId,\n model: lastChunkModel,\n timestamp,\n })\n yield asChunk({\n type: 'REASONING_END',\n messageId: reasoningMessageId,\n model: lastChunkModel,\n timestamp,\n })\n }\n if (hasEmittedTextMessageStart && !hasEmittedTextMessageEnd) {\n hasEmittedTextMessageEnd = true\n yield asChunk({\n type: 'TEXT_MESSAGE_END',\n messageId: aguiState.messageId,\n model: lastChunkModel,\n timestamp,\n })\n }\n for (const [, toolCall] of toolCallsInProgress) {\n if (toolCall.started && !toolCall.ended) {\n toolCall.ended = true\n // Best-effort parse for the partial args; if invalid, surface\n // empty input rather than throwing inside the cleanup path.\n let partialInput: unknown = {}\n try {\n partialInput = toolCall.arguments\n ? transformNullsToUndefined(JSON.parse(toolCall.arguments))\n : {}\n } catch {\n partialInput = {}\n }\n yield asChunk({\n type: 'TOOL_CALL_END',\n toolCallId: toolCall.id,\n toolCallName: toolCall.name,\n toolName: toolCall.name,\n model: lastChunkModel,\n timestamp,\n input: partialInput,\n })\n }\n }\n throw error\n }\n }\n\n /**\n * Makes a raw fetch request to the Mistral chat completions endpoint and\n * parses the SSE stream manually, bypassing the SDK's Zod validation which\n * rejects streaming tool call chunks that omit `name` in argument deltas.\n */\n private async *fetchRawMistralStream(\n params: ChatCompletionStreamRequest,\n config: MistralClientConfig,\n ): AsyncGenerator<MistralRawChunk> {\n const serverURL = (config.serverURL ?? 'https://api.mistral.ai')\n .replace(/\\/+$/, '')\n .replace(/\\/v1$/, '')\n const url = `${serverURL}/v1/chat/completions`\n\n const body = this.toWireBody(params)\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${config.apiKey}`,\n ...config.defaultHeaders,\n }\n\n const response = await fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Mistral API error ${response.status}: ${errorText}`)\n }\n\n if (!response.body) {\n throw new Error(\n 'Mistral API returned a response with no body. This may indicate a proxy or runtime that does not support streaming.',\n )\n }\n\n const reader = response.body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n\n buffer += decoder.decode(value, { stream: true })\n const lines = buffer.split('\\n')\n // split('\\n') always yields at least one element, so pop() is a\n // string here; `?? ''` only satisfies the type narrowing.\n buffer = lines.pop() ?? ''\n\n for (const line of lines) {\n const trimmed = line.trim()\n if (!trimmed.startsWith('data:')) continue\n const data = trimmed.slice(5).trimStart()\n if (data === '[DONE]') return\n\n let parsed: unknown\n try {\n parsed = JSON.parse(data)\n } catch (e) {\n if (e instanceof SyntaxError) {\n console.warn(\n `[mistral] skipped unparseable SSE chunk: ${data.slice(0, 200)}`,\n )\n continue\n }\n throw e\n }\n\n // Mistral signals mid-stream errors via an `error` field. Surface\n // them as RUN_ERROR rather than swallowing them as empty chunks.\n if (\n parsed &&\n typeof parsed === 'object' &&\n 'error' in parsed &&\n !('choices' in parsed)\n ) {\n const errPayload = parsed.error\n const message =\n typeof errPayload === 'string'\n ? errPayload\n : errPayload &&\n typeof errPayload === 'object' &&\n 'message' in errPayload\n ? String(errPayload.message)\n : JSON.stringify(errPayload)\n throw new Error(`Mistral stream error: ${message}`)\n }\n\n yield parsed as MistralRawChunk\n }\n }\n } finally {\n await reader.cancel().catch(() => {})\n reader.releaseLock()\n }\n }\n\n /**\n * Converts the SDK's camelCase `ChatCompletionStreamRequest` into the\n * snake_case wire body, including converting messages.\n */\n private toWireBody(\n params: ChatCompletionStreamRequest,\n ): Record<string, unknown> {\n const {\n messages,\n maxTokens,\n topP,\n randomSeed,\n responseFormat,\n toolChoice,\n parallelToolCalls,\n frequencyPenalty,\n presencePenalty,\n safePrompt,\n stream: _stream,\n ...rest\n } = params\n\n return {\n ...rest,\n messages: messages.map(messageToWire),\n stream: true,\n // Opt in to usage on the final streaming chunk.\n stream_options: { include_usage: true },\n ...(maxTokens != null && { max_tokens: maxTokens }),\n ...(topP != null && { top_p: topP }),\n ...(randomSeed != null && { random_seed: randomSeed }),\n ...(responseFormat != null && { response_format: responseFormat }),\n ...(toolChoice != null && { tool_choice: toolChoice }),\n ...(parallelToolCalls != null && {\n parallel_tool_calls: parallelToolCalls,\n }),\n ...(frequencyPenalty != null && { frequency_penalty: frequencyPenalty }),\n ...(presencePenalty != null && { presence_penalty: presencePenalty }),\n ...(safePrompt != null && { safe_prompt: safePrompt }),\n }\n }\n\n /**\n * Splits a Mistral delta content payload into text and reasoning deltas.\n * Mistral reasoning models (magistral-*) stream reasoning content as\n * `{ type: 'thinking', thinking: [{ type: 'text', text }, ...] }` content\n * parts. A single delta may contain text only, thinking only, or — rarely —\n * both (when a step transitions); both fields are returned so the caller\n * can sequence REASONING and TEXT lifecycle events in order.\n */\n private extractDeltaParts(\n content:\n | string\n | Array<{\n type: string\n text?: string\n thinking?: Array<{ type: string; text?: string }>\n }>\n | null\n | undefined,\n ): { text: string; thinking: string } {\n if (!content) return { text: '', thinking: '' }\n if (typeof content === 'string') return { text: content, thinking: '' }\n\n let text = ''\n let thinking = ''\n for (const part of content) {\n if (part.type === 'text' && typeof part.text === 'string') {\n text += part.text\n } else if (part.type === 'thinking' && Array.isArray(part.thinking)) {\n for (const inner of part.thinking) {\n if (inner.type === 'text' && typeof inner.text === 'string') {\n thinking += inner.text\n }\n }\n }\n }\n return { text, thinking }\n }\n\n /**\n * Maps common TextOptions to Mistral Chat Completions request parameters.\n */\n private mapTextOptionsToMistral(\n options: TextOptions<TProviderOptions>,\n ): ChatCompletionStreamRequest {\n const modelOptions = options.modelOptions as\n | Omit<InternalTextProviderOptions, 'tools'>\n | undefined\n\n const tools = options.tools\n ? convertToolsToProviderFormat(options.tools)\n : undefined\n\n const messages: Array<ChatCompletionMessageParam> = []\n\n if (options.systemPrompts && options.systemPrompts.length > 0) {\n messages.push({\n role: 'system',\n content: options.systemPrompts.join('\\n'),\n })\n }\n\n for (const message of options.messages) {\n messages.push(this.convertMessageToMistral(message))\n }\n\n return {\n model: options.model,\n messages: messages,\n temperature: modelOptions?.temperature ?? undefined,\n maxTokens: modelOptions?.max_tokens ?? undefined,\n topP: modelOptions?.top_p ?? undefined,\n tools: tools as ChatCompletionStreamRequest['tools'],\n stream: true,\n ...(modelOptions && {\n ...(modelOptions.stop != null && { stop: modelOptions.stop }),\n ...(modelOptions.random_seed != null && {\n randomSeed: modelOptions.random_seed,\n }),\n ...(modelOptions.response_format != null && {\n responseFormat: modelOptions.response_format,\n }),\n ...(modelOptions.tool_choice != null && {\n toolChoice: modelOptions.tool_choice,\n }),\n ...(modelOptions.parallel_tool_calls != null && {\n parallelToolCalls: modelOptions.parallel_tool_calls,\n }),\n ...(modelOptions.frequency_penalty != null && {\n frequencyPenalty: modelOptions.frequency_penalty,\n }),\n ...(modelOptions.presence_penalty != null && {\n presencePenalty: modelOptions.presence_penalty,\n }),\n ...(modelOptions.n != null && { n: modelOptions.n }),\n ...(modelOptions.prediction != null && {\n prediction: modelOptions.prediction,\n }),\n ...(modelOptions.safe_prompt != null && {\n safePrompt: modelOptions.safe_prompt,\n }),\n }),\n }\n }\n\n /**\n * Converts a TanStack AI ModelMessage to a Mistral ChatCompletionMessageParam.\n */\n private convertMessageToMistral(\n message: ModelMessage,\n ): ChatCompletionMessageParam {\n if (message.role === 'tool') {\n if (!message.toolCallId) {\n throw new Error('Missing toolCallId for tool message')\n }\n return {\n role: 'tool',\n toolCallId: message.toolCallId,\n content:\n typeof message.content === 'string'\n ? message.content\n : JSON.stringify(message.content),\n }\n }\n\n if (message.role === 'assistant') {\n const toolCalls = message.toolCalls?.map((tc) => ({\n id: tc.id,\n type: 'function' as const,\n function: {\n name: tc.function.name,\n arguments:\n typeof tc.function.arguments === 'string'\n ? tc.function.arguments\n : JSON.stringify(tc.function.arguments),\n },\n }))\n\n return {\n role: 'assistant',\n content: this.extractTextContent(message.content),\n ...(toolCalls && toolCalls.length > 0 ? { toolCalls } : {}),\n }\n }\n\n const contentParts = this.normalizeContent(message.content)\n\n if (contentParts.length === 1 && contentParts[0]?.type === 'text') {\n return {\n role: 'user',\n content: contentParts[0].content,\n }\n }\n\n const parts = contentParts.map((part) =>\n this.convertContentPartToMistral(part),\n )\n\n return {\n role: 'user',\n content: parts.length > 0 ? parts : '',\n }\n }\n\n /**\n * Converts a ContentPart to a Mistral content part. Returns undefined for\n * unsupported part types.\n */\n private convertContentPartToMistral(\n part: ContentPart,\n ): ChatCompletionContentPart {\n if (part.type === 'text') {\n return { type: 'text', text: part.content }\n }\n\n if (part.type === 'image') {\n const imageMetadata = part.metadata as MistralImageMetadata | undefined\n const imageValue = part.source.value\n const imageUrl =\n part.source.type === 'data' && !imageValue.startsWith('data:')\n ? `data:${part.source.mimeType};base64,${imageValue}`\n : imageValue\n return {\n type: 'image_url',\n imageUrl: imageMetadata?.detail\n ? { url: imageUrl, detail: imageMetadata.detail }\n : imageUrl,\n }\n }\n\n if (part.type === 'document') {\n const documentValue = part.source.value\n const documentUrl =\n part.source.type === 'data' && !documentValue.startsWith('data:')\n ? `data:${part.source.mimeType};base64,${documentValue}`\n : documentValue\n return { type: 'document_url', documentUrl }\n }\n\n throw new Error(\n `Mistral text adapter does not support content part of type '${(part as ContentPart).type}'. Supported types: text, image, document. Use a vision-capable model (mistral-medium-latest or mistral-small-latest) for images and documents.`,\n )\n }\n\n /**\n * Normalizes message content to an array of ContentPart.\n */\n private normalizeContent(\n content: string | null | Array<ContentPart>,\n ): Array<ContentPart> {\n if (content === null) return []\n if (typeof content === 'string') return [{ type: 'text', content }]\n return content\n }\n\n /**\n * Extracts text content from a content value that may be string, null, or ContentPart array.\n */\n private extractTextContent(\n content: string | null | Array<ContentPart>,\n ): string {\n if (content === null) return ''\n if (typeof content === 'string') return content\n return content\n .filter((p) => p.type === 'text')\n .map((p) => p.content)\n .join('')\n }\n}\n\n/**\n * Snake-cases a Mistral SDK message into the wire format expected by the API.\n */\nfunction messageToWire(msg: ChatCompletionStreamRequest['messages'][number]) {\n if (msg.role === 'tool') {\n return {\n role: 'tool',\n tool_call_id: msg.toolCallId,\n content: msg.content,\n ...(msg.name !== undefined ? { name: msg.name } : {}),\n }\n }\n if (msg.role === 'assistant') {\n const base: Record<string, unknown> = {\n role: 'assistant',\n content: msg.content ?? null,\n }\n if (msg.toolCalls && msg.toolCalls.length > 0) {\n base.tool_calls = msg.toolCalls.map((tc) => ({\n id: tc.id,\n type: tc.type ?? 'function',\n function: tc.function,\n }))\n }\n if (msg.prefix !== undefined) base.prefix = msg.prefix\n return base\n }\n if (msg.role === 'user' && Array.isArray(msg.content)) {\n return {\n role: 'user',\n content: msg.content.map((part) => {\n if (part.type === 'image_url') {\n return { type: 'image_url', image_url: part.imageUrl }\n }\n if (part.type === 'document_url') {\n return { type: 'document_url', document_url: part.documentUrl }\n }\n return part\n }),\n }\n }\n return msg\n}\n\n/**\n * Creates a Mistral text adapter with explicit API key.\n *\n * @param model - The model name (e.g., 'mistral-large-latest')\n * @param apiKey - Your Mistral API key\n * @param config - Optional additional configuration\n * @returns Configured Mistral text adapter instance\n *\n * @example\n * ```typescript\n * const adapter = createMistralText('mistral-large-latest', 'api_key');\n * ```\n */\nexport function createMistralText<\n TModel extends (typeof MISTRAL_CHAT_MODELS)[number],\n>(\n model: TModel,\n apiKey: string,\n config?: Omit<MistralTextConfig, 'apiKey'>,\n): MistralTextAdapter<TModel> {\n return new MistralTextAdapter({ apiKey, ...config }, model)\n}\n\n/**\n * Creates a Mistral text adapter using the `MISTRAL_API_KEY` environment variable.\n *\n * @param model - The model name (e.g., 'mistral-large-latest')\n * @param config - Optional configuration (excluding apiKey)\n * @returns Configured Mistral text adapter instance\n * @throws Error if MISTRAL_API_KEY is not found in environment\n *\n * @example\n * ```typescript\n * const adapter = mistralText('mistral-large-latest');\n * ```\n */\nexport function mistralText<\n TModel extends (typeof MISTRAL_CHAT_MODELS)[number],\n>(\n model: TModel,\n config?: Omit<MistralTextConfig, 'apiKey'>,\n): MistralTextAdapter<TModel> {\n const apiKey = getMistralApiKeyFromEnv()\n return createMistralText(model, apiKey, config)\n}\n"],"mappings":";;;;;;;AA2CA,IAAM,WAAW,UAEf;;;;;;AAOF,SAAS,mBAAmB,UAIhB;CACV,IAAI,CAAC,SAAS,WAAW,OAAO,CAAC;CACjC,IAAI;EACF,OAAO,0BAA0B,KAAK,MAAM,SAAS,SAAS,CAAC;CAC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ACjC,IAAI,KAAK,SAAS,aAChB,OAAO;IAAE,MAAM;IAAa,WAAW,KAAK;GAAS;GAEvD,IAAI,KAAK,SAAS,gBAChB,OAAO;IAAE,MAAM;IAAgB,cAAc,KAAK;GAAY;GAEhE,OAAO;EACT,CAAC;CACH;CAEF,OAAO;AACT;;;;;;;;;;;;;;AAeA,SAAgB,kBAGd,OACA,QACA,QAC4B;CAC5B,OAAO,IAAI,mBAAmB;EAAE;EAAQ,GAAG;CAAO,GAAG,KAAK;AAC5D;;;;;;;;;;;;;;AAeA,SAAgB,YAGd,OACA,QAC4B;CAE5B,OAAO,kBAAkB,OADV,wBACiB,GAAQ,MAAM;AAChD"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Provider options for Mistral embedding models.
|
|
3
|
+
*
|
|
4
|
+
* `dimensions` is deliberately absent: it's a first-class top-level option on
|
|
5
|
+
* `embed()` and is mapped to Mistral's `outputDimension` request field by the
|
|
6
|
+
* adapter (codestral-embed only — mistral-embed has a fixed 1024-dim output).
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Provider options for `mistral-embed`.
|
|
10
|
+
*
|
|
11
|
+
* mistral-embed accepts no provider-specific options: its output is a fixed
|
|
12
|
+
* 1024-dimension float vector.
|
|
13
|
+
*/
|
|
14
|
+
export type MistralEmbedProviderOptions = Record<string, never>;
|
|
15
|
+
/**
|
|
16
|
+
* Provider options for `codestral-embed`.
|
|
17
|
+
*/
|
|
18
|
+
export interface CodestralEmbedProviderOptions {
|
|
19
|
+
/**
|
|
20
|
+
* The data type of the output embedding values. Mirrors the Mistral SDK's
|
|
21
|
+
* `EmbeddingDtype` enum. Defaults to `float`.
|
|
22
|
+
*/
|
|
23
|
+
outputDtype?: 'float' | 'int8' | 'uint8' | 'binary' | 'ubinary';
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Widest provider options shape accepted by the Mistral embedding adapter.
|
|
27
|
+
* Per-model narrowing happens via `MistralEmbeddingModelProviderOptionsByName`.
|
|
28
|
+
*/
|
|
29
|
+
export type MistralEmbeddingProviderOptions = CodestralEmbedProviderOptions;
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -5,6 +5,8 @@
|
|
|
5
5
|
* Provides tree-shakeable adapters for Mistral's Chat Completions API.
|
|
6
6
|
*/
|
|
7
7
|
export { MistralTextAdapter, createMistralText, mistralText, type MistralTextConfig, type MistralTextProviderOptions, } from './adapters/text.js';
|
|
8
|
-
export
|
|
9
|
-
export {
|
|
8
|
+
export { MistralEmbeddingAdapter, createMistralEmbedding, mistralEmbedding, type MistralEmbeddingConfig, } from './adapters/embedding.js';
|
|
9
|
+
export type { MistralEmbeddingProviderOptions, MistralEmbedProviderOptions, CodestralEmbedProviderOptions, } from './embedding/embedding-provider-options.js';
|
|
10
|
+
export type { MistralChatModelProviderOptionsByName, MistralModelInputModalitiesByName, ResolveProviderOptions, ResolveInputModalities, MistralChatModels, MistralEmbeddingModel, MistralEmbeddingModelProviderOptionsByName, MistralEmbeddingModelInputModalitiesByName, } from './model-meta.js';
|
|
11
|
+
export { MISTRAL_CHAT_MODELS, MISTRAL_EMBEDDING_MODELS } from './model-meta.js';
|
|
10
12
|
export type { MistralTextMetadata, MistralImageMetadata, MistralAudioMetadata, MistralVideoMetadata, MistralDocumentMetadata, MistralMessageMetadataByModality, } from './message-types.js';
|
package/dist/esm/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
import { MistralTextAdapter, createMistralText, mistralText } from "./adapters/text.js";
|
|
2
|
-
import {
|
|
3
|
-
|
|
2
|
+
import { MistralEmbeddingAdapter, createMistralEmbedding, mistralEmbedding } from "./adapters/embedding.js";
|
|
3
|
+
import { MISTRAL_CHAT_MODELS, MISTRAL_EMBEDDING_MODELS } from "./model-meta.js";
|
|
4
|
+
export { MISTRAL_CHAT_MODELS, MISTRAL_EMBEDDING_MODELS, MistralEmbeddingAdapter, MistralTextAdapter, createMistralEmbedding, createMistralText, mistralEmbedding, mistralText };
|
package/dist/esm/model-meta.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { MistralTextProviderOptions } from './text/text-provider-options.js';
|
|
2
|
+
import { CodestralEmbedProviderOptions, MistralEmbedProviderOptions } from './embedding/embedding-provider-options.js';
|
|
2
3
|
/** Provider options for vision-capable Mistral models (pixtral-*). */
|
|
3
4
|
export type MistralVisionProviderOptions = MistralTextProviderOptions;
|
|
4
5
|
/** Provider options for reasoning-capable Mistral models (magistral-*). */
|
|
@@ -35,7 +36,7 @@ declare const MISTRAL_MEDIUM_LATEST: {
|
|
|
35
36
|
};
|
|
36
37
|
};
|
|
37
38
|
readonly supports: {
|
|
38
|
-
readonly input: ["text", "image"];
|
|
39
|
+
readonly input: ["text", "image", "document"];
|
|
39
40
|
readonly output: ["text"];
|
|
40
41
|
readonly endpoints: ["chat"];
|
|
41
42
|
readonly features: ["streaming", "tools", "json_object", "json_schema", "vision"];
|
|
@@ -54,7 +55,7 @@ declare const MISTRAL_SMALL_LATEST: {
|
|
|
54
55
|
};
|
|
55
56
|
};
|
|
56
57
|
readonly supports: {
|
|
57
|
-
readonly input: ["text", "image"];
|
|
58
|
+
readonly input: ["text", "image", "document"];
|
|
58
59
|
readonly output: ["text"];
|
|
59
60
|
readonly endpoints: ["chat"];
|
|
60
61
|
readonly features: ["streaming", "tools", "json_object", "json_schema", "vision"];
|
|
@@ -130,7 +131,7 @@ declare const PIXTRAL_LARGE_LATEST: {
|
|
|
130
131
|
};
|
|
131
132
|
};
|
|
132
133
|
readonly supports: {
|
|
133
|
-
readonly input: ["text", "image"];
|
|
134
|
+
readonly input: ["text", "image", "document"];
|
|
134
135
|
readonly output: ["text"];
|
|
135
136
|
readonly endpoints: ["chat"];
|
|
136
137
|
readonly features: ["streaming", "tools", "json_object", "json_schema", "vision"];
|
|
@@ -149,7 +150,7 @@ declare const PIXTRAL_12B_2409: {
|
|
|
149
150
|
};
|
|
150
151
|
};
|
|
151
152
|
readonly supports: {
|
|
152
|
-
readonly input: ["text", "image"];
|
|
153
|
+
readonly input: ["text", "image", "document"];
|
|
153
154
|
readonly output: ["text"];
|
|
154
155
|
readonly endpoints: ["chat"];
|
|
155
156
|
readonly features: ["streaming", "tools", "json_object", "vision"];
|
|
@@ -252,6 +253,32 @@ export type MistralChatModelProviderOptionsByName = {
|
|
|
252
253
|
[MAGISTRAL_SMALL_LATEST.name]: MistralReasoningProviderOptions;
|
|
253
254
|
[OPEN_MISTRAL_NEMO.name]: MistralTextProviderOptions;
|
|
254
255
|
};
|
|
256
|
+
/**
|
|
257
|
+
* Embedding models (based on endpoints: "embeddings")
|
|
258
|
+
*/
|
|
259
|
+
export declare const MISTRAL_EMBEDDING_MODELS: readonly ["mistral-embed", "codestral-embed"];
|
|
260
|
+
/**
|
|
261
|
+
* Union type of all supported Mistral embedding model names.
|
|
262
|
+
*/
|
|
263
|
+
export type MistralEmbeddingModel = (typeof MISTRAL_EMBEDDING_MODELS)[number];
|
|
264
|
+
/**
|
|
265
|
+
* Type-only map from embedding model name to its provider options type.
|
|
266
|
+
*
|
|
267
|
+
* `mistral-embed` accepts no provider options (fixed 1024-dim output);
|
|
268
|
+
* `codestral-embed` additionally supports `outputDtype`.
|
|
269
|
+
*/
|
|
270
|
+
export type MistralEmbeddingModelProviderOptionsByName = {
|
|
271
|
+
'mistral-embed': MistralEmbedProviderOptions;
|
|
272
|
+
'codestral-embed': CodestralEmbedProviderOptions;
|
|
273
|
+
};
|
|
274
|
+
/**
|
|
275
|
+
* Per-model input modalities for embedding models. Mistral embedding models
|
|
276
|
+
* are text-only, so image inputs fail at compile time.
|
|
277
|
+
*/
|
|
278
|
+
export type MistralEmbeddingModelInputModalitiesByName = {
|
|
279
|
+
'mistral-embed': readonly ['text'];
|
|
280
|
+
'codestral-embed': readonly ['text'];
|
|
281
|
+
};
|
|
255
282
|
/**
|
|
256
283
|
* Resolves the provider options type for a specific Mistral model.
|
|
257
284
|
*/
|
package/dist/esm/model-meta.js
CHANGED
|
@@ -31,7 +31,11 @@ var MISTRAL_CHAT_MODELS = [
|
|
|
31
31
|
output: { normal: 2 }
|
|
32
32
|
},
|
|
33
33
|
supports: {
|
|
34
|
-
input: [
|
|
34
|
+
input: [
|
|
35
|
+
"text",
|
|
36
|
+
"image",
|
|
37
|
+
"document"
|
|
38
|
+
],
|
|
35
39
|
output: ["text"],
|
|
36
40
|
endpoints: ["chat"],
|
|
37
41
|
features: [
|
|
@@ -52,7 +56,11 @@ var MISTRAL_CHAT_MODELS = [
|
|
|
52
56
|
output: { normal: .3 }
|
|
53
57
|
},
|
|
54
58
|
supports: {
|
|
55
|
-
input: [
|
|
59
|
+
input: [
|
|
60
|
+
"text",
|
|
61
|
+
"image",
|
|
62
|
+
"document"
|
|
63
|
+
],
|
|
56
64
|
output: ["text"],
|
|
57
65
|
endpoints: ["chat"],
|
|
58
66
|
features: [
|
|
@@ -134,7 +142,11 @@ var MISTRAL_CHAT_MODELS = [
|
|
|
134
142
|
output: { normal: 6 }
|
|
135
143
|
},
|
|
136
144
|
supports: {
|
|
137
|
-
input: [
|
|
145
|
+
input: [
|
|
146
|
+
"text",
|
|
147
|
+
"image",
|
|
148
|
+
"document"
|
|
149
|
+
],
|
|
138
150
|
output: ["text"],
|
|
139
151
|
endpoints: ["chat"],
|
|
140
152
|
features: [
|
|
@@ -155,7 +167,11 @@ var MISTRAL_CHAT_MODELS = [
|
|
|
155
167
|
output: { normal: .15 }
|
|
156
168
|
},
|
|
157
169
|
supports: {
|
|
158
|
-
input: [
|
|
170
|
+
input: [
|
|
171
|
+
"text",
|
|
172
|
+
"image",
|
|
173
|
+
"document"
|
|
174
|
+
],
|
|
159
175
|
output: ["text"],
|
|
160
176
|
endpoints: ["chat"],
|
|
161
177
|
features: [
|
|
@@ -228,7 +244,11 @@ var MISTRAL_CHAT_MODELS = [
|
|
|
228
244
|
}
|
|
229
245
|
}.name
|
|
230
246
|
];
|
|
247
|
+
/**
|
|
248
|
+
* Embedding models (based on endpoints: "embeddings")
|
|
249
|
+
*/
|
|
250
|
+
var MISTRAL_EMBEDDING_MODELS = ["mistral-embed", "codestral-embed"];
|
|
231
251
|
//#endregion
|
|
232
|
-
export { MISTRAL_CHAT_MODELS };
|
|
252
|
+
export { MISTRAL_CHAT_MODELS, MISTRAL_EMBEDDING_MODELS };
|
|
233
253
|
|
|
234
254
|
//# sourceMappingURL=model-meta.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model-meta.js","names":[],"sources":["../../src/model-meta.ts"],"sourcesContent":["import type { MistralTextProviderOptions } from './text/text-provider-options'\n\n/** Provider options for vision-capable Mistral models (pixtral-*). */\nexport type MistralVisionProviderOptions = MistralTextProviderOptions\n\n/** Provider options for reasoning-capable Mistral models (magistral-*). */\nexport type MistralReasoningProviderOptions = MistralTextProviderOptions\n\n/**\n * Internal metadata structure describing a Mistral model's capabilities\n * and approximate pricing (USD per million tokens).\n */\ninterface ModelMeta<TProviderOptions = unknown> {\n name: string\n context_window?: number\n max_completion_tokens?: number\n pricing: {\n input?: { normal: number; cached?: number }\n output?: { normal: number }\n }\n supports: {\n input: Array<'text' | 'image' | 'audio'>\n output: Array<'text'>\n endpoints: Array<'chat' | 'embeddings'>\n\n features: Array<\n | 'streaming'\n | 'tools'\n | 'json_object'\n | 'json_schema'\n | 'reasoning'\n | 'vision'\n | 'code'\n >\n }\n providerOptions?: TProviderOptions\n}\n\nconst MISTRAL_LARGE_LATEST = {\n name: 'mistral-large-latest',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.5 },\n output: { normal: 1.5 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst MISTRAL_MEDIUM_LATEST = {\n name: 'mistral-medium-latest',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.4 },\n output: { normal: 2 },\n },\n supports: {\n input: ['text', 'image'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema', 'vision'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst MISTRAL_SMALL_LATEST = {\n name: 'mistral-small-latest',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.1 },\n output: { normal: 0.3 },\n },\n supports: {\n input: ['text', 'image'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema', 'vision'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst MINISTRAL_8B_LATEST = {\n name: 'ministral-8b-latest',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.1 },\n output: { normal: 0.1 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst MINISTRAL_3B_LATEST = {\n name: 'ministral-3b-latest',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.04 },\n output: { normal: 0.04 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst CODESTRAL_LATEST = {\n name: 'codestral-latest',\n context_window: 256_000,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.3 },\n output: { normal: 0.9 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema', 'code'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst PIXTRAL_LARGE_LATEST = {\n name: 'pixtral-large-latest',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 2 },\n output: { normal: 6 },\n },\n supports: {\n input: ['text', 'image'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema', 'vision'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst PIXTRAL_12B_2409 = {\n name: 'pixtral-12b-2409',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.15 },\n output: { normal: 0.15 },\n },\n supports: {\n input: ['text', 'image'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'vision'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst MAGISTRAL_MEDIUM_LATEST = {\n name: 'magistral-medium-latest',\n context_window: 40_000,\n max_completion_tokens: 40_000,\n pricing: {\n input: { normal: 2 },\n output: { normal: 5 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'reasoning', 'json_object', 'json_schema'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst MAGISTRAL_SMALL_LATEST = {\n name: 'magistral-small-latest',\n context_window: 40_000,\n max_completion_tokens: 40_000,\n pricing: {\n input: { normal: 0.5 },\n output: { normal: 1.5 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'reasoning', 'json_object', 'json_schema'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst OPEN_MISTRAL_NEMO = {\n name: 'open-mistral-nemo',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.15 },\n output: { normal: 0.15 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\n/**\n * All supported Mistral chat model identifiers.\n */\nexport const MISTRAL_CHAT_MODELS = [\n MISTRAL_LARGE_LATEST.name,\n MISTRAL_MEDIUM_LATEST.name,\n MISTRAL_SMALL_LATEST.name,\n MINISTRAL_8B_LATEST.name,\n MINISTRAL_3B_LATEST.name,\n CODESTRAL_LATEST.name,\n PIXTRAL_LARGE_LATEST.name,\n PIXTRAL_12B_2409.name,\n MAGISTRAL_MEDIUM_LATEST.name,\n MAGISTRAL_SMALL_LATEST.name,\n OPEN_MISTRAL_NEMO.name,\n] as const\n\n/**\n * Union type of all supported Mistral chat model names.\n */\nexport type MistralChatModels = (typeof MISTRAL_CHAT_MODELS)[number]\n\n/**\n * Type-only map from Mistral chat model name to its supported input modalities.\n */\nexport type MistralModelInputModalitiesByName = {\n [MISTRAL_LARGE_LATEST.name]: typeof MISTRAL_LARGE_LATEST.supports.input\n [MISTRAL_MEDIUM_LATEST.name]: typeof MISTRAL_MEDIUM_LATEST.supports.input\n [MISTRAL_SMALL_LATEST.name]: typeof MISTRAL_SMALL_LATEST.supports.input\n [MINISTRAL_8B_LATEST.name]: typeof MINISTRAL_8B_LATEST.supports.input\n [MINISTRAL_3B_LATEST.name]: typeof MINISTRAL_3B_LATEST.supports.input\n [CODESTRAL_LATEST.name]: typeof CODESTRAL_LATEST.supports.input\n [PIXTRAL_LARGE_LATEST.name]: typeof PIXTRAL_LARGE_LATEST.supports.input\n [PIXTRAL_12B_2409.name]: typeof PIXTRAL_12B_2409.supports.input\n [MAGISTRAL_MEDIUM_LATEST.name]: typeof MAGISTRAL_MEDIUM_LATEST.supports.input\n [MAGISTRAL_SMALL_LATEST.name]: typeof MAGISTRAL_SMALL_LATEST.supports.input\n [OPEN_MISTRAL_NEMO.name]: typeof OPEN_MISTRAL_NEMO.supports.input\n}\n\n/**\n * Type-only map from Mistral chat model name to its provider options type.\n */\nexport type MistralChatModelProviderOptionsByName = {\n [MISTRAL_LARGE_LATEST.name]: MistralTextProviderOptions\n [MISTRAL_MEDIUM_LATEST.name]: MistralVisionProviderOptions\n [MISTRAL_SMALL_LATEST.name]: MistralVisionProviderOptions\n [MINISTRAL_8B_LATEST.name]: MistralTextProviderOptions\n [MINISTRAL_3B_LATEST.name]: MistralTextProviderOptions\n [CODESTRAL_LATEST.name]: MistralTextProviderOptions\n [PIXTRAL_LARGE_LATEST.name]: MistralVisionProviderOptions\n [PIXTRAL_12B_2409.name]: MistralVisionProviderOptions\n [MAGISTRAL_MEDIUM_LATEST.name]: MistralReasoningProviderOptions\n [MAGISTRAL_SMALL_LATEST.name]: MistralReasoningProviderOptions\n [OPEN_MISTRAL_NEMO.name]: MistralTextProviderOptions\n}\n\n/**\n * Resolves the provider options type for a specific Mistral model.\n */\nexport type ResolveProviderOptions<TModel extends string> =\n TModel extends keyof MistralChatModelProviderOptionsByName\n ? MistralChatModelProviderOptionsByName[TModel]\n : MistralTextProviderOptions\n\n/**\n * Resolve input modalities for a specific model.\n */\nexport type ResolveInputModalities<TModel extends string> =\n TModel extends keyof MistralModelInputModalitiesByName\n ? MistralModelInputModalitiesByName[TModel]\n : readonly ['text']\n"],"mappings":";;;AAyNA,IAAa,sBAAsB;CACjC;EAnLA,MAAM;EACN,gBAAgB;EAChB,uBAAuB;EACvB,SAAS;GACP,OAAO,EAAE,QAAQ,GAAI;GACrB,QAAQ,EAAE,QAAQ,IAAI;EACxB;EACA,UAAU;GACR,OAAO,CAAC,MAAM;GACd,QAAQ,CAAC,MAAM;GACf,WAAW,CAAC,MAAM;GAClB,UAAU;IAAC;IAAa;IAAS;IAAe;GAAa;EAC/D;CAuKA,EAAqB;CACrB;EApKA,MAAM;EACN,gBAAgB;EAChB,uBAAuB;EACvB,SAAS;GACP,OAAO,EAAE,QAAQ,GAAI;GACrB,QAAQ,EAAE,QAAQ,EAAE;EACtB;EACA,UAAU;GACR,OAAO,CAAC,QAAQ,OAAO;GACvB,QAAQ,CAAC,MAAM;GACf,WAAW,CAAC,MAAM;GAClB,UAAU;IAAC;IAAa;IAAS;IAAe;IAAe;GAAQ;EACzE;CAwJA,EAAsB;CACtB;EArJA,MAAM;EACN,gBAAgB;EAChB,uBAAuB;EACvB,SAAS;GACP,OAAO,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js","names":[],"sources":["../../src/model-meta.ts"],"sourcesContent":["import type { MistralTextProviderOptions } from './text/text-provider-options'\nimport type {\n CodestralEmbedProviderOptions,\n MistralEmbedProviderOptions,\n} from './embedding/embedding-provider-options'\n\n/** Provider options for vision-capable Mistral models (pixtral-*). */\nexport type MistralVisionProviderOptions = MistralTextProviderOptions\n\n/** Provider options for reasoning-capable Mistral models (magistral-*). */\nexport type MistralReasoningProviderOptions = MistralTextProviderOptions\n\n/**\n * Internal metadata structure describing a Mistral model's capabilities\n * and approximate pricing (USD per million tokens).\n */\ninterface ModelMeta<TProviderOptions = unknown> {\n name: string\n context_window?: number\n max_completion_tokens?: number\n pricing: {\n input?: { normal: number; cached?: number }\n output?: { normal: number }\n }\n supports: {\n input: Array<'text' | 'image' | 'audio' | 'document'>\n output: Array<'text'>\n endpoints: Array<'chat' | 'embeddings'>\n\n features: Array<\n | 'streaming'\n | 'tools'\n | 'json_object'\n | 'json_schema'\n | 'reasoning'\n | 'vision'\n | 'code'\n >\n }\n providerOptions?: TProviderOptions\n}\n\nconst MISTRAL_LARGE_LATEST = {\n name: 'mistral-large-latest',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.5 },\n output: { normal: 1.5 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst MISTRAL_MEDIUM_LATEST = {\n name: 'mistral-medium-latest',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.4 },\n output: { normal: 2 },\n },\n supports: {\n input: ['text', 'image', 'document'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema', 'vision'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst MISTRAL_SMALL_LATEST = {\n name: 'mistral-small-latest',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.1 },\n output: { normal: 0.3 },\n },\n supports: {\n input: ['text', 'image', 'document'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema', 'vision'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst MINISTRAL_8B_LATEST = {\n name: 'ministral-8b-latest',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.1 },\n output: { normal: 0.1 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst MINISTRAL_3B_LATEST = {\n name: 'ministral-3b-latest',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.04 },\n output: { normal: 0.04 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst CODESTRAL_LATEST = {\n name: 'codestral-latest',\n context_window: 256_000,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.3 },\n output: { normal: 0.9 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema', 'code'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst PIXTRAL_LARGE_LATEST = {\n name: 'pixtral-large-latest',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 2 },\n output: { normal: 6 },\n },\n supports: {\n input: ['text', 'image', 'document'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema', 'vision'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst PIXTRAL_12B_2409 = {\n name: 'pixtral-12b-2409',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.15 },\n output: { normal: 0.15 },\n },\n supports: {\n input: ['text', 'image', 'document'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'vision'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst MAGISTRAL_MEDIUM_LATEST = {\n name: 'magistral-medium-latest',\n context_window: 40_000,\n max_completion_tokens: 40_000,\n pricing: {\n input: { normal: 2 },\n output: { normal: 5 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'reasoning', 'json_object', 'json_schema'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst MAGISTRAL_SMALL_LATEST = {\n name: 'magistral-small-latest',\n context_window: 40_000,\n max_completion_tokens: 40_000,\n pricing: {\n input: { normal: 0.5 },\n output: { normal: 1.5 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'reasoning', 'json_object', 'json_schema'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst OPEN_MISTRAL_NEMO = {\n name: 'open-mistral-nemo',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.15 },\n output: { normal: 0.15 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\n/**\n * All supported Mistral chat model identifiers.\n */\nexport const MISTRAL_CHAT_MODELS = [\n MISTRAL_LARGE_LATEST.name,\n MISTRAL_MEDIUM_LATEST.name,\n MISTRAL_SMALL_LATEST.name,\n MINISTRAL_8B_LATEST.name,\n MINISTRAL_3B_LATEST.name,\n CODESTRAL_LATEST.name,\n PIXTRAL_LARGE_LATEST.name,\n PIXTRAL_12B_2409.name,\n MAGISTRAL_MEDIUM_LATEST.name,\n MAGISTRAL_SMALL_LATEST.name,\n OPEN_MISTRAL_NEMO.name,\n] as const\n\n/**\n * Union type of all supported Mistral chat model names.\n */\nexport type MistralChatModels = (typeof MISTRAL_CHAT_MODELS)[number]\n\n/**\n * Type-only map from Mistral chat model name to its supported input modalities.\n */\nexport type MistralModelInputModalitiesByName = {\n [MISTRAL_LARGE_LATEST.name]: typeof MISTRAL_LARGE_LATEST.supports.input\n [MISTRAL_MEDIUM_LATEST.name]: typeof MISTRAL_MEDIUM_LATEST.supports.input\n [MISTRAL_SMALL_LATEST.name]: typeof MISTRAL_SMALL_LATEST.supports.input\n [MINISTRAL_8B_LATEST.name]: typeof MINISTRAL_8B_LATEST.supports.input\n [MINISTRAL_3B_LATEST.name]: typeof MINISTRAL_3B_LATEST.supports.input\n [CODESTRAL_LATEST.name]: typeof CODESTRAL_LATEST.supports.input\n [PIXTRAL_LARGE_LATEST.name]: typeof PIXTRAL_LARGE_LATEST.supports.input\n [PIXTRAL_12B_2409.name]: typeof PIXTRAL_12B_2409.supports.input\n [MAGISTRAL_MEDIUM_LATEST.name]: typeof MAGISTRAL_MEDIUM_LATEST.supports.input\n [MAGISTRAL_SMALL_LATEST.name]: typeof MAGISTRAL_SMALL_LATEST.supports.input\n [OPEN_MISTRAL_NEMO.name]: typeof OPEN_MISTRAL_NEMO.supports.input\n}\n\n/**\n * Type-only map from Mistral chat model name to its provider options type.\n */\nexport type MistralChatModelProviderOptionsByName = {\n [MISTRAL_LARGE_LATEST.name]: MistralTextProviderOptions\n [MISTRAL_MEDIUM_LATEST.name]: MistralVisionProviderOptions\n [MISTRAL_SMALL_LATEST.name]: MistralVisionProviderOptions\n [MINISTRAL_8B_LATEST.name]: MistralTextProviderOptions\n [MINISTRAL_3B_LATEST.name]: MistralTextProviderOptions\n [CODESTRAL_LATEST.name]: MistralTextProviderOptions\n [PIXTRAL_LARGE_LATEST.name]: MistralVisionProviderOptions\n [PIXTRAL_12B_2409.name]: MistralVisionProviderOptions\n [MAGISTRAL_MEDIUM_LATEST.name]: MistralReasoningProviderOptions\n [MAGISTRAL_SMALL_LATEST.name]: MistralReasoningProviderOptions\n [OPEN_MISTRAL_NEMO.name]: MistralTextProviderOptions\n}\n\n/**\n * Embedding models (based on endpoints: \"embeddings\")\n */\nexport const MISTRAL_EMBEDDING_MODELS = [\n 'mistral-embed',\n 'codestral-embed',\n] as const\n\n/**\n * Union type of all supported Mistral embedding model names.\n */\nexport type MistralEmbeddingModel = (typeof MISTRAL_EMBEDDING_MODELS)[number]\n\n/**\n * Type-only map from embedding model name to its provider options type.\n *\n * `mistral-embed` accepts no provider options (fixed 1024-dim output);\n * `codestral-embed` additionally supports `outputDtype`.\n */\nexport type MistralEmbeddingModelProviderOptionsByName = {\n 'mistral-embed': MistralEmbedProviderOptions\n 'codestral-embed': CodestralEmbedProviderOptions\n}\n\n/**\n * Per-model input modalities for embedding models. Mistral embedding models\n * are text-only, so image inputs fail at compile time.\n */\nexport type MistralEmbeddingModelInputModalitiesByName = {\n 'mistral-embed': readonly ['text']\n 'codestral-embed': readonly ['text']\n}\n\n/**\n * Resolves the provider options type for a specific Mistral model.\n */\nexport type ResolveProviderOptions<TModel extends string> =\n TModel extends keyof MistralChatModelProviderOptionsByName\n ? MistralChatModelProviderOptionsByName[TModel]\n : MistralTextProviderOptions\n\n/**\n * Resolve input modalities for a specific model.\n */\nexport type ResolveInputModalities<TModel extends string> =\n TModel extends keyof MistralModelInputModalitiesByName\n ? MistralModelInputModalitiesByName[TModel]\n : readonly ['text']\n"],"mappings":";;;AA6NA,IAAa,sBAAsB;CACjC;EAnLA,MAAM;EACN,gBAAgB;EAChB,uBAAuB;EACvB,SAAS;GACP,OAAO,EAAE,QAAQ,GAAI;GACrB,QAAQ,EAAE,QAAQ,IAAI;EACxB;EACA,UAAU;GACR,OAAO,CAAC,MAAM;GACd,QAAQ,CAAC,MAAM;GACf,WAAW,CAAC,MAAM;GAClB,UAAU;IAAC;IAAa;IAAS;IAAe;GAAa;EAC/D;CAuKA,EAAqB;CACrB;EApKA,MAAM;EACN,gBA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a;IAAS;IAAa;IAAe;GAAa;EAC5E;CAgCA,EAAuB;CACvB;EA7BA,MAAM;EACN,gBAAgB;EAChB,uBAAuB;EACvB,SAAS;GACP,OAAO,EAAE,QAAQ,IAAK;GACtB,QAAQ,EAAE,QAAQ,IAAK;EACzB;EACA,UAAU;GACR,OAAO,CAAC,MAAM;GACd,QAAQ,CAAC,MAAM;GACf,WAAW,CAAC,MAAM;GAClB,UAAU;IAAC;IAAa;IAAS;GAAa;EAChD;CAiBA,EAAkB;AACpB;;;;AA4CA,IAAa,2BAA2B,CACtC,iBACA,iBACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/ai-mistral",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Mistral adapter for TanStack AI",
|
|
6
6
|
"author": "",
|
|
@@ -20,6 +20,10 @@
|
|
|
20
20
|
"./adapters/text": {
|
|
21
21
|
"types": "./dist/esm/adapters/text.d.ts",
|
|
22
22
|
"import": "./dist/esm/adapters/text.js"
|
|
23
|
+
},
|
|
24
|
+
"./adapters/embedding": {
|
|
25
|
+
"types": "./dist/esm/adapters/embedding.d.ts",
|
|
26
|
+
"import": "./dist/esm/adapters/embedding.js"
|
|
23
27
|
}
|
|
24
28
|
},
|
|
25
29
|
"files": [
|
|
@@ -35,11 +39,11 @@
|
|
|
35
39
|
"devDependencies": {
|
|
36
40
|
"@vitest/coverage-v8": "4.0.14",
|
|
37
41
|
"vite": "^8.1.4",
|
|
38
|
-
"@tanstack/ai": "0.
|
|
42
|
+
"@tanstack/ai": "0.44.0"
|
|
39
43
|
},
|
|
40
44
|
"peerDependencies": {
|
|
41
45
|
"zod": "^4.0.0",
|
|
42
|
-
"@tanstack/ai": "^0.
|
|
46
|
+
"@tanstack/ai": "^0.44.0"
|
|
43
47
|
},
|
|
44
48
|
"dependencies": {
|
|
45
49
|
"@mistralai/mistralai": "2.2.0"
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { BaseEmbeddingAdapter } from '@tanstack/ai/adapters'
|
|
2
|
+
import { toRunErrorPayload } from '@tanstack/ai/adapter-internals'
|
|
3
|
+
import { requireTextOnlyEmbeddingInput } from '@tanstack/ai'
|
|
4
|
+
import {
|
|
5
|
+
createMistralClient,
|
|
6
|
+
generateId,
|
|
7
|
+
getMistralApiKeyFromEnv,
|
|
8
|
+
} from '../utils/client'
|
|
9
|
+
import type {
|
|
10
|
+
EmbeddingOptions,
|
|
11
|
+
EmbeddingResult,
|
|
12
|
+
TokenUsage,
|
|
13
|
+
} from '@tanstack/ai'
|
|
14
|
+
import type { Mistral } from '@mistralai/mistralai'
|
|
15
|
+
import type { EmbeddingRequest } from '@mistralai/mistralai/models/components'
|
|
16
|
+
import type {
|
|
17
|
+
MistralEmbeddingModel,
|
|
18
|
+
MistralEmbeddingModelInputModalitiesByName,
|
|
19
|
+
MistralEmbeddingModelProviderOptionsByName,
|
|
20
|
+
} from '../model-meta'
|
|
21
|
+
import type { MistralEmbeddingProviderOptions } from '../embedding/embedding-provider-options'
|
|
22
|
+
import type { MistralClientConfig } from '../utils/client'
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Configuration for Mistral embedding adapter.
|
|
26
|
+
*/
|
|
27
|
+
export type MistralEmbeddingConfig = MistralClientConfig
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Mistral Embedding Adapter
|
|
31
|
+
*
|
|
32
|
+
* Tree-shakeable adapter for Mistral text embeddings.
|
|
33
|
+
* Supports mistral-embed and codestral-embed.
|
|
34
|
+
*
|
|
35
|
+
* Features:
|
|
36
|
+
* - Batch embedding (one request for the whole input array)
|
|
37
|
+
* - Dimension reduction for codestral-embed via the top-level `dimensions`
|
|
38
|
+
* option (mapped to Mistral's `outputDimension`); mistral-embed has a fixed
|
|
39
|
+
* 1024-dimension output and rejects `dimensions`.
|
|
40
|
+
*/
|
|
41
|
+
export class MistralEmbeddingAdapter<
|
|
42
|
+
TModel extends MistralEmbeddingModel,
|
|
43
|
+
> extends BaseEmbeddingAdapter<
|
|
44
|
+
TModel,
|
|
45
|
+
MistralEmbeddingProviderOptions,
|
|
46
|
+
MistralEmbeddingModelProviderOptionsByName,
|
|
47
|
+
MistralEmbeddingModelInputModalitiesByName
|
|
48
|
+
> {
|
|
49
|
+
readonly name = 'mistral' as const
|
|
50
|
+
|
|
51
|
+
protected client: Mistral
|
|
52
|
+
|
|
53
|
+
constructor(config: MistralEmbeddingConfig, model: TModel) {
|
|
54
|
+
super(model, {})
|
|
55
|
+
this.client = createMistralClient(config)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async createEmbeddings(
|
|
59
|
+
options: EmbeddingOptions<MistralEmbeddingProviderOptions>,
|
|
60
|
+
): Promise<EmbeddingResult> {
|
|
61
|
+
const { model, logger, modelOptions } = options
|
|
62
|
+
const texts = requireTextOnlyEmbeddingInput(options.input, this.name, model)
|
|
63
|
+
|
|
64
|
+
if (options.dimensions !== undefined && model === 'mistral-embed') {
|
|
65
|
+
throw new Error(
|
|
66
|
+
'mistral-embed does not support requesting dimensions (output is a fixed 1024-dimension vector). Use codestral-embed for dimension reduction, or omit `dimensions`.',
|
|
67
|
+
)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
try {
|
|
71
|
+
// Spread modelOptions first so it can never override the validated
|
|
72
|
+
// fields (server routes often pass modelOptions through from untyped
|
|
73
|
+
// client input).
|
|
74
|
+
const request: EmbeddingRequest = {
|
|
75
|
+
...modelOptions,
|
|
76
|
+
model,
|
|
77
|
+
inputs: texts,
|
|
78
|
+
}
|
|
79
|
+
if (options.dimensions !== undefined) {
|
|
80
|
+
request.outputDimension = options.dimensions
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
logger.request(
|
|
84
|
+
`activity=embed provider=${this.name} model=${model} inputs=${texts.length}`,
|
|
85
|
+
{ provider: this.name, model },
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
const response = await this.client.embeddings.create(request)
|
|
89
|
+
|
|
90
|
+
const usage: TokenUsage = {
|
|
91
|
+
promptTokens: response.usage.promptTokens ?? 0,
|
|
92
|
+
completionTokens: 0,
|
|
93
|
+
totalTokens: response.usage.totalTokens ?? 0,
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return {
|
|
97
|
+
id: generateId(this.name),
|
|
98
|
+
model,
|
|
99
|
+
// Mistral returns one entry per input; `index` is optional in the SDK
|
|
100
|
+
// types, so fall back to array order when it's absent.
|
|
101
|
+
embeddings: response.data.map((item, arrayIndex) => ({
|
|
102
|
+
vector: item.embedding ?? [],
|
|
103
|
+
index: item.index ?? arrayIndex,
|
|
104
|
+
})),
|
|
105
|
+
usage,
|
|
106
|
+
}
|
|
107
|
+
} catch (error: unknown) {
|
|
108
|
+
logger.errors(`${this.name}.createEmbeddings fatal`, {
|
|
109
|
+
error: toRunErrorPayload(error, `${this.name}.createEmbeddings failed`),
|
|
110
|
+
source: `${this.name}.createEmbeddings`,
|
|
111
|
+
})
|
|
112
|
+
throw error
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Creates a Mistral embedding adapter with explicit API key.
|
|
119
|
+
* Type resolution happens here at the call site.
|
|
120
|
+
*
|
|
121
|
+
* @param model - The model name (e.g., 'mistral-embed')
|
|
122
|
+
* @param apiKey - Your Mistral API key
|
|
123
|
+
* @param config - Optional additional configuration
|
|
124
|
+
* @returns Configured Mistral embedding adapter instance with resolved types
|
|
125
|
+
*
|
|
126
|
+
* @example
|
|
127
|
+
* ```typescript
|
|
128
|
+
* const adapter = createMistralEmbedding('mistral-embed', 'api_key');
|
|
129
|
+
*
|
|
130
|
+
* const result = await embed({
|
|
131
|
+
* adapter,
|
|
132
|
+
* input: 'a red guitar'
|
|
133
|
+
* });
|
|
134
|
+
* ```
|
|
135
|
+
*/
|
|
136
|
+
export function createMistralEmbedding<TModel extends MistralEmbeddingModel>(
|
|
137
|
+
model: TModel,
|
|
138
|
+
apiKey: string,
|
|
139
|
+
config?: Omit<MistralEmbeddingConfig, 'apiKey'>,
|
|
140
|
+
): MistralEmbeddingAdapter<TModel> {
|
|
141
|
+
return new MistralEmbeddingAdapter({ apiKey, ...config }, model)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Creates a Mistral embedding adapter using the `MISTRAL_API_KEY` environment variable.
|
|
146
|
+
* Type resolution happens here at the call site.
|
|
147
|
+
*
|
|
148
|
+
* Looks for `MISTRAL_API_KEY` in:
|
|
149
|
+
* - `process.env` (Node.js)
|
|
150
|
+
* - `window.env` (Browser with injected env)
|
|
151
|
+
*
|
|
152
|
+
* @param model - The model name (e.g., 'codestral-embed')
|
|
153
|
+
* @param config - Optional configuration (excluding apiKey which is auto-detected)
|
|
154
|
+
* @returns Configured Mistral embedding adapter instance with resolved types
|
|
155
|
+
* @throws Error if MISTRAL_API_KEY is not found in environment
|
|
156
|
+
*
|
|
157
|
+
* @example
|
|
158
|
+
* ```typescript
|
|
159
|
+
* // Automatically uses MISTRAL_API_KEY from environment
|
|
160
|
+
* const adapter = mistralEmbedding('codestral-embed');
|
|
161
|
+
*
|
|
162
|
+
* const result = await embed({
|
|
163
|
+
* adapter,
|
|
164
|
+
* input: ['a red guitar', 'a blue drum kit'],
|
|
165
|
+
* dimensions: 256
|
|
166
|
+
* });
|
|
167
|
+
*
|
|
168
|
+
* console.log(result.embeddings[0].vector)
|
|
169
|
+
* ```
|
|
170
|
+
*/
|
|
171
|
+
export function mistralEmbedding<TModel extends MistralEmbeddingModel>(
|
|
172
|
+
model: TModel,
|
|
173
|
+
config?: Omit<MistralEmbeddingConfig, 'apiKey'>,
|
|
174
|
+
): MistralEmbeddingAdapter<TModel> {
|
|
175
|
+
const apiKey = getMistralApiKeyFromEnv()
|
|
176
|
+
return createMistralEmbedding(model, apiKey, config)
|
|
177
|
+
}
|
package/src/adapters/text.ts
CHANGED
|
@@ -271,9 +271,17 @@ export class MistralTextAdapter<
|
|
|
271
271
|
)
|
|
272
272
|
}
|
|
273
273
|
|
|
274
|
+
const usage = response.usage
|
|
274
275
|
return {
|
|
275
276
|
data: transformNullsToUndefined(parsed),
|
|
276
277
|
rawText: textContent,
|
|
278
|
+
...(usage && {
|
|
279
|
+
usage: {
|
|
280
|
+
promptTokens: usage.promptTokens ?? 0,
|
|
281
|
+
completionTokens: usage.completionTokens ?? 0,
|
|
282
|
+
totalTokens: usage.totalTokens ?? 0,
|
|
283
|
+
},
|
|
284
|
+
}),
|
|
277
285
|
}
|
|
278
286
|
}
|
|
279
287
|
|
|
@@ -1021,8 +1029,17 @@ export class MistralTextAdapter<
|
|
|
1021
1029
|
}
|
|
1022
1030
|
}
|
|
1023
1031
|
|
|
1032
|
+
if (part.type === 'document') {
|
|
1033
|
+
const documentValue = part.source.value
|
|
1034
|
+
const documentUrl =
|
|
1035
|
+
part.source.type === 'data' && !documentValue.startsWith('data:')
|
|
1036
|
+
? `data:${part.source.mimeType};base64,${documentValue}`
|
|
1037
|
+
: documentValue
|
|
1038
|
+
return { type: 'document_url', documentUrl }
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1024
1041
|
throw new Error(
|
|
1025
|
-
`Mistral text adapter does not support content part of type '${(part as ContentPart).type}'. Supported types: text, image. Use a vision-capable model (
|
|
1042
|
+
`Mistral text adapter does not support content part of type '${(part as ContentPart).type}'. Supported types: text, image, document. Use a vision-capable model (mistral-medium-latest or mistral-small-latest) for images and documents.`,
|
|
1026
1043
|
)
|
|
1027
1044
|
}
|
|
1028
1045
|
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Provider options for Mistral embedding models.
|
|
3
|
+
*
|
|
4
|
+
* `dimensions` is deliberately absent: it's a first-class top-level option on
|
|
5
|
+
* `embed()` and is mapped to Mistral's `outputDimension` request field by the
|
|
6
|
+
* adapter (codestral-embed only — mistral-embed has a fixed 1024-dim output).
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Provider options for `mistral-embed`.
|
|
11
|
+
*
|
|
12
|
+
* mistral-embed accepts no provider-specific options: its output is a fixed
|
|
13
|
+
* 1024-dimension float vector.
|
|
14
|
+
*/
|
|
15
|
+
export type MistralEmbedProviderOptions = Record<string, never>
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Provider options for `codestral-embed`.
|
|
19
|
+
*/
|
|
20
|
+
export interface CodestralEmbedProviderOptions {
|
|
21
|
+
/**
|
|
22
|
+
* The data type of the output embedding values. Mirrors the Mistral SDK's
|
|
23
|
+
* `EmbeddingDtype` enum. Defaults to `float`.
|
|
24
|
+
*/
|
|
25
|
+
outputDtype?: 'float' | 'int8' | 'uint8' | 'binary' | 'ubinary'
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Widest provider options shape accepted by the Mistral embedding adapter.
|
|
30
|
+
* Per-model narrowing happens via `MistralEmbeddingModelProviderOptionsByName`.
|
|
31
|
+
*/
|
|
32
|
+
export type MistralEmbeddingProviderOptions = CodestralEmbedProviderOptions
|
package/src/index.ts
CHANGED
|
@@ -14,6 +14,19 @@ export {
|
|
|
14
14
|
type MistralTextProviderOptions,
|
|
15
15
|
} from './adapters/text'
|
|
16
16
|
|
|
17
|
+
// Embedding adapter - for embedding vectors
|
|
18
|
+
export {
|
|
19
|
+
MistralEmbeddingAdapter,
|
|
20
|
+
createMistralEmbedding,
|
|
21
|
+
mistralEmbedding,
|
|
22
|
+
type MistralEmbeddingConfig,
|
|
23
|
+
} from './adapters/embedding'
|
|
24
|
+
export type {
|
|
25
|
+
MistralEmbeddingProviderOptions,
|
|
26
|
+
MistralEmbedProviderOptions,
|
|
27
|
+
CodestralEmbedProviderOptions,
|
|
28
|
+
} from './embedding/embedding-provider-options'
|
|
29
|
+
|
|
17
30
|
// Types
|
|
18
31
|
export type {
|
|
19
32
|
MistralChatModelProviderOptionsByName,
|
|
@@ -21,8 +34,11 @@ export type {
|
|
|
21
34
|
ResolveProviderOptions,
|
|
22
35
|
ResolveInputModalities,
|
|
23
36
|
MistralChatModels,
|
|
37
|
+
MistralEmbeddingModel,
|
|
38
|
+
MistralEmbeddingModelProviderOptionsByName,
|
|
39
|
+
MistralEmbeddingModelInputModalitiesByName,
|
|
24
40
|
} from './model-meta'
|
|
25
|
-
export { MISTRAL_CHAT_MODELS } from './model-meta'
|
|
41
|
+
export { MISTRAL_CHAT_MODELS, MISTRAL_EMBEDDING_MODELS } from './model-meta'
|
|
26
42
|
export type {
|
|
27
43
|
MistralTextMetadata,
|
|
28
44
|
MistralImageMetadata,
|
package/src/model-meta.ts
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
import type { MistralTextProviderOptions } from './text/text-provider-options'
|
|
2
|
+
import type {
|
|
3
|
+
CodestralEmbedProviderOptions,
|
|
4
|
+
MistralEmbedProviderOptions,
|
|
5
|
+
} from './embedding/embedding-provider-options'
|
|
2
6
|
|
|
3
7
|
/** Provider options for vision-capable Mistral models (pixtral-*). */
|
|
4
8
|
export type MistralVisionProviderOptions = MistralTextProviderOptions
|
|
@@ -19,7 +23,7 @@ interface ModelMeta<TProviderOptions = unknown> {
|
|
|
19
23
|
output?: { normal: number }
|
|
20
24
|
}
|
|
21
25
|
supports: {
|
|
22
|
-
input: Array<'text' | 'image' | 'audio'>
|
|
26
|
+
input: Array<'text' | 'image' | 'audio' | 'document'>
|
|
23
27
|
output: Array<'text'>
|
|
24
28
|
endpoints: Array<'chat' | 'embeddings'>
|
|
25
29
|
|
|
@@ -61,7 +65,7 @@ const MISTRAL_MEDIUM_LATEST = {
|
|
|
61
65
|
output: { normal: 2 },
|
|
62
66
|
},
|
|
63
67
|
supports: {
|
|
64
|
-
input: ['text', 'image'],
|
|
68
|
+
input: ['text', 'image', 'document'],
|
|
65
69
|
output: ['text'],
|
|
66
70
|
endpoints: ['chat'],
|
|
67
71
|
features: ['streaming', 'tools', 'json_object', 'json_schema', 'vision'],
|
|
@@ -77,7 +81,7 @@ const MISTRAL_SMALL_LATEST = {
|
|
|
77
81
|
output: { normal: 0.3 },
|
|
78
82
|
},
|
|
79
83
|
supports: {
|
|
80
|
-
input: ['text', 'image'],
|
|
84
|
+
input: ['text', 'image', 'document'],
|
|
81
85
|
output: ['text'],
|
|
82
86
|
endpoints: ['chat'],
|
|
83
87
|
features: ['streaming', 'tools', 'json_object', 'json_schema', 'vision'],
|
|
@@ -141,7 +145,7 @@ const PIXTRAL_LARGE_LATEST = {
|
|
|
141
145
|
output: { normal: 6 },
|
|
142
146
|
},
|
|
143
147
|
supports: {
|
|
144
|
-
input: ['text', 'image'],
|
|
148
|
+
input: ['text', 'image', 'document'],
|
|
145
149
|
output: ['text'],
|
|
146
150
|
endpoints: ['chat'],
|
|
147
151
|
features: ['streaming', 'tools', 'json_object', 'json_schema', 'vision'],
|
|
@@ -157,7 +161,7 @@ const PIXTRAL_12B_2409 = {
|
|
|
157
161
|
output: { normal: 0.15 },
|
|
158
162
|
},
|
|
159
163
|
supports: {
|
|
160
|
-
input: ['text', 'image'],
|
|
164
|
+
input: ['text', 'image', 'document'],
|
|
161
165
|
output: ['text'],
|
|
162
166
|
endpoints: ['chat'],
|
|
163
167
|
features: ['streaming', 'tools', 'json_object', 'vision'],
|
|
@@ -268,6 +272,39 @@ export type MistralChatModelProviderOptionsByName = {
|
|
|
268
272
|
[OPEN_MISTRAL_NEMO.name]: MistralTextProviderOptions
|
|
269
273
|
}
|
|
270
274
|
|
|
275
|
+
/**
|
|
276
|
+
* Embedding models (based on endpoints: "embeddings")
|
|
277
|
+
*/
|
|
278
|
+
export const MISTRAL_EMBEDDING_MODELS = [
|
|
279
|
+
'mistral-embed',
|
|
280
|
+
'codestral-embed',
|
|
281
|
+
] as const
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* Union type of all supported Mistral embedding model names.
|
|
285
|
+
*/
|
|
286
|
+
export type MistralEmbeddingModel = (typeof MISTRAL_EMBEDDING_MODELS)[number]
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* Type-only map from embedding model name to its provider options type.
|
|
290
|
+
*
|
|
291
|
+
* `mistral-embed` accepts no provider options (fixed 1024-dim output);
|
|
292
|
+
* `codestral-embed` additionally supports `outputDtype`.
|
|
293
|
+
*/
|
|
294
|
+
export type MistralEmbeddingModelProviderOptionsByName = {
|
|
295
|
+
'mistral-embed': MistralEmbedProviderOptions
|
|
296
|
+
'codestral-embed': CodestralEmbedProviderOptions
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Per-model input modalities for embedding models. Mistral embedding models
|
|
301
|
+
* are text-only, so image inputs fail at compile time.
|
|
302
|
+
*/
|
|
303
|
+
export type MistralEmbeddingModelInputModalitiesByName = {
|
|
304
|
+
'mistral-embed': readonly ['text']
|
|
305
|
+
'codestral-embed': readonly ['text']
|
|
306
|
+
}
|
|
307
|
+
|
|
271
308
|
/**
|
|
272
309
|
* Resolves the provider options type for a specific Mistral model.
|
|
273
310
|
*/
|