Open History to see the last commit
1import { BaseEmbeddingAdapter } from '@tanstack/ai/adapters'
2import { toRunErrorPayload } from '@tanstack/ai/adapter-internals'
3import { requireTextOnlyEmbeddingInput } from '@tanstack/ai'
4import {
5 createMistralClient,
6 generateId,
7 getMistralApiKeyFromEnv,
8} from '../utils/client'
9import type {
10 EmbeddingOptions,
11 EmbeddingResult,
12 TokenUsage,
13} from '@tanstack/ai'
14import type { Mistral } from '@mistralai/mistralai'
15import type { EmbeddingRequest } from '@mistralai/mistralai/models/components'
16import type {
17 MistralEmbeddingModel,
18 MistralEmbeddingModelInputModalitiesByName,
19 MistralEmbeddingModelProviderOptionsByName,
20} from '../model-meta'
21import type { MistralEmbeddingProviderOptions } from '../embedding/embedding-provider-options'
22import type { MistralClientConfig } from '../utils/client'
23
24/**
25 * Configuration for Mistral embedding adapter.
26 */
27export 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 */
41export 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 */
136export 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 */
171export 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}