@tanstack/ai-mistral 1.0.0 → 1.1.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/README.md +4 -3
- package/dist/esm/adapters/embedding.d.ts +2 -2
- package/dist/esm/adapters/embedding.js +3 -2
- package/dist/esm/adapters/embedding.js.map +1 -1
- package/dist/esm/adapters/text.js +52 -32
- package/dist/esm/adapters/text.js.map +1 -1
- package/dist/esm/client/index.d.ts +181 -0
- package/dist/esm/client/index.js +385 -0
- package/dist/esm/client/index.js.map +1 -0
- package/dist/esm/utils/client.d.ts +0 -5
- package/dist/esm/utils/client.js +1 -33
- package/dist/esm/utils/client.js.map +1 -1
- package/package.json +5 -4
- package/src/adapters/embedding.ts +9 -8
- package/src/adapters/text.ts +102 -48
- package/src/client/index.ts +588 -0
- package/src/utils/client.ts +0 -67
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { MistralError } from '@mistralai/mistralai/models/errors/mistralerror.js';
|
|
2
|
+
import { AssistantMessage$Outbound, ChatCompletionChoice, ChatCompletionRequest, ChatCompletionResponse, ContentChunk$Outbound, EmbeddingRequest, EmbeddingResponse, EmbeddingResponseData, ImageURLChunk, ToolCall, UsageInfo$Outbound, ValidationError } from '@mistralai/mistralai/models/components';
|
|
3
|
+
import { MistralClientConfig } from '../utils/client.js';
|
|
4
|
+
/**
|
|
5
|
+
* The part of the Mistral SDK client that the adapters call. A real
|
|
6
|
+
* `Mistral` instance fits this type.
|
|
7
|
+
*/
|
|
8
|
+
export interface MistralClient {
|
|
9
|
+
chat: {
|
|
10
|
+
complete: (request: ChatCompletionRequest, options?: MistralRequestOptions) => Promise<ChatCompletionResponse>;
|
|
11
|
+
};
|
|
12
|
+
embeddings: {
|
|
13
|
+
create: (request: EmbeddingRequest, options?: MistralRequestOptions) => Promise<EmbeddingResponse>;
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* The part of the SDK `RequestOptions` that the adapters pass. Same as the
|
|
18
|
+
* SDK: a signal replaces the default timeout.
|
|
19
|
+
*/
|
|
20
|
+
export interface MistralRequestOptions {
|
|
21
|
+
signal?: AbortSignal | null;
|
|
22
|
+
fetchOptions?: {
|
|
23
|
+
signal?: AbortSignal | null;
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
type Fetcher = (url: string, init: RequestInit) => Promise<Response>;
|
|
27
|
+
/** The JSON body the SDK sends for `chat.complete`. */
|
|
28
|
+
export declare function chatCompletionRequestToWire(request: ChatCompletionRequest): {
|
|
29
|
+
model: string;
|
|
30
|
+
temperature: number | null | undefined;
|
|
31
|
+
top_p: number | undefined;
|
|
32
|
+
max_tokens: number | null | undefined;
|
|
33
|
+
stream: boolean;
|
|
34
|
+
stop: string | string[] | undefined;
|
|
35
|
+
random_seed: number | null | undefined;
|
|
36
|
+
metadata: {
|
|
37
|
+
[k: string]: any;
|
|
38
|
+
} | null | undefined;
|
|
39
|
+
messages: ({
|
|
40
|
+
role: "assistant";
|
|
41
|
+
content: string | unknown[] | null | undefined;
|
|
42
|
+
tool_calls: {
|
|
43
|
+
id: string;
|
|
44
|
+
type: string | undefined;
|
|
45
|
+
function: import('@mistralai/mistralai/models/components').FunctionCall;
|
|
46
|
+
index: number;
|
|
47
|
+
}[] | undefined;
|
|
48
|
+
prefix: boolean;
|
|
49
|
+
tool_call_id?: undefined;
|
|
50
|
+
name?: undefined;
|
|
51
|
+
} | {
|
|
52
|
+
role: "system";
|
|
53
|
+
content: string | unknown[] | null | undefined;
|
|
54
|
+
tool_calls?: undefined;
|
|
55
|
+
prefix?: undefined;
|
|
56
|
+
tool_call_id?: undefined;
|
|
57
|
+
name?: undefined;
|
|
58
|
+
} | {
|
|
59
|
+
role: "tool";
|
|
60
|
+
content: string | unknown[] | null | undefined;
|
|
61
|
+
tool_call_id: string | null | undefined;
|
|
62
|
+
name: string | null | undefined;
|
|
63
|
+
tool_calls?: undefined;
|
|
64
|
+
prefix?: undefined;
|
|
65
|
+
} | {
|
|
66
|
+
role: "user";
|
|
67
|
+
content: string | unknown[] | null | undefined;
|
|
68
|
+
tool_calls?: undefined;
|
|
69
|
+
prefix?: undefined;
|
|
70
|
+
tool_call_id?: undefined;
|
|
71
|
+
name?: undefined;
|
|
72
|
+
})[];
|
|
73
|
+
response_format: {
|
|
74
|
+
type: import('@mistralai/mistralai/models/components').ResponseFormats | undefined;
|
|
75
|
+
json_schema: {
|
|
76
|
+
name: string;
|
|
77
|
+
description: string | null | undefined;
|
|
78
|
+
schema: {
|
|
79
|
+
[k: string]: any;
|
|
80
|
+
};
|
|
81
|
+
strict: boolean | undefined;
|
|
82
|
+
} | null | undefined;
|
|
83
|
+
} | undefined;
|
|
84
|
+
tools: (import('@mistralai/mistralai/models/components').Tool | import('@mistralai/mistralai/models/components').WebSearchTool | import('@mistralai/mistralai/models/components').WebSearchPremiumTool | import('@mistralai/mistralai/models/components').CodeInterpreterTool | import('@mistralai/mistralai/models/components').ImageGenerationTool | import('@mistralai/mistralai/models/components').DocumentLibraryTool | import('@mistralai/mistralai/models/components').CustomConnector)[] | null | undefined;
|
|
85
|
+
tool_choice: import('@mistralai/mistralai/models/components').ToolChoice | import('@mistralai/mistralai/models/components').ToolChoiceEnum | undefined;
|
|
86
|
+
presence_penalty: number | undefined;
|
|
87
|
+
frequency_penalty: number | undefined;
|
|
88
|
+
n: number | null | undefined;
|
|
89
|
+
prediction: {
|
|
90
|
+
type: "content";
|
|
91
|
+
content: string;
|
|
92
|
+
} | undefined;
|
|
93
|
+
parallel_tool_calls: boolean | undefined;
|
|
94
|
+
reasoning_effort: import('@mistralai/mistralai/models/components').ReasoningEffort | null | undefined;
|
|
95
|
+
prompt_mode: import('@mistralai/mistralai/models/components').MistralPromptMode | null | undefined;
|
|
96
|
+
guardrails: import('@mistralai/mistralai/models/components').GuardrailConfig[] | null | undefined;
|
|
97
|
+
safe_prompt: boolean | undefined;
|
|
98
|
+
};
|
|
99
|
+
/** The JSON body the SDK sends for `embeddings.create`. */
|
|
100
|
+
export declare function embeddingRequestToWire(request: EmbeddingRequest): {
|
|
101
|
+
model: string;
|
|
102
|
+
metadata: {
|
|
103
|
+
[k: string]: any;
|
|
104
|
+
} | null | undefined;
|
|
105
|
+
input: string | string[];
|
|
106
|
+
output_dimension: number | null | undefined;
|
|
107
|
+
output_dtype: import('@mistralai/mistralai/models/components').EmbeddingDtype | undefined;
|
|
108
|
+
encoding_format: import('@mistralai/mistralai/models/components').EncodingFormat | undefined;
|
|
109
|
+
};
|
|
110
|
+
/** An assistant message on the wire. The SDK fills `role` and `prefix`. */
|
|
111
|
+
type WireAssistant = Omit<AssistantMessage$Outbound, 'role' | 'prefix' | 'tool_calls' | 'content'> & {
|
|
112
|
+
role?: 'assistant';
|
|
113
|
+
content?: string | Array<WireContentChunk> | null;
|
|
114
|
+
prefix?: boolean;
|
|
115
|
+
tool_calls?: Array<ToolCall> | null;
|
|
116
|
+
};
|
|
117
|
+
/** A content chunk on the wire. `image_url` keeps the SDK value as is. */
|
|
118
|
+
type WireContentChunk = Exclude<ContentChunk$Outbound, {
|
|
119
|
+
type: 'image_url';
|
|
120
|
+
}> | {
|
|
121
|
+
type: 'image_url';
|
|
122
|
+
image_url: ImageURLChunk['imageUrl'];
|
|
123
|
+
};
|
|
124
|
+
/** Usage on the wire. The SDK fills missing token counts with 0. */
|
|
125
|
+
type WireUsage = Partial<UsageInfo$Outbound>;
|
|
126
|
+
interface WireChoice {
|
|
127
|
+
index: number;
|
|
128
|
+
message?: WireAssistant;
|
|
129
|
+
messages?: Array<WireAssistant>;
|
|
130
|
+
finish_reason: ChatCompletionChoice['finishReason'];
|
|
131
|
+
}
|
|
132
|
+
interface WireChatCompletion {
|
|
133
|
+
id: string;
|
|
134
|
+
object: string;
|
|
135
|
+
model: string;
|
|
136
|
+
usage: WireUsage;
|
|
137
|
+
created: number;
|
|
138
|
+
choices: Array<WireChoice>;
|
|
139
|
+
}
|
|
140
|
+
interface WireEmbedding {
|
|
141
|
+
id: string;
|
|
142
|
+
object: string;
|
|
143
|
+
model: string;
|
|
144
|
+
usage: WireUsage;
|
|
145
|
+
data: Array<EmbeddingResponseData>;
|
|
146
|
+
}
|
|
147
|
+
/** The SDK `ChatCompletionResponse` for a wire response. */
|
|
148
|
+
export declare function chatCompletionResponseFromWire(wire: WireChatCompletion): ChatCompletionResponse;
|
|
149
|
+
/** The SDK `EmbeddingResponse` for a wire response. */
|
|
150
|
+
export declare function embeddingResponseFromWire(wire: WireEmbedding): EmbeddingResponse;
|
|
151
|
+
/**
|
|
152
|
+
* The SDK's `HTTPValidationError` (422), with the same name, message, and
|
|
153
|
+
* fields. The SDK class module loads zod, so this copy stands in for it.
|
|
154
|
+
* It extends the real `MistralError`.
|
|
155
|
+
*/
|
|
156
|
+
export declare class HTTPValidationError extends MistralError {
|
|
157
|
+
detail?: Array<ValidationError>;
|
|
158
|
+
data$: {
|
|
159
|
+
detail?: Array<ValidationError>;
|
|
160
|
+
request$: Request;
|
|
161
|
+
response$: Response;
|
|
162
|
+
body$: string;
|
|
163
|
+
};
|
|
164
|
+
constructor(err: HTTPValidationError['data$'], httpMeta: {
|
|
165
|
+
request: Request;
|
|
166
|
+
response: Response;
|
|
167
|
+
body: string;
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Creates the Mistral client the adapters use. It sends the same requests as
|
|
172
|
+
* the SDK `Mistral` client (no retries, 30 s default timeout) with `fetch`.
|
|
173
|
+
* A `fetcher` replaces `fetch`; it gets `(url, init)`.
|
|
174
|
+
*
|
|
175
|
+
* @throws The SDK error classes: `SDKError` for a 4xx/5xx or an unexpected
|
|
176
|
+
* response, `HTTPValidationError` for a 422 JSON body, and the HTTP client
|
|
177
|
+
* errors (`ConnectionError`, `RequestTimeoutError`, `RequestAbortedError`,
|
|
178
|
+
* `UnexpectedClientError`) when the request fails.
|
|
179
|
+
*/
|
|
180
|
+
export declare function createMistralClient(config: MistralClientConfig, fetcher?: Fetcher): MistralClient;
|
|
181
|
+
export {};
|
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
import { MistralError } from "@mistralai/mistralai/models/errors/mistralerror.js";
|
|
2
|
+
import { SDKError } from "@mistralai/mistralai/models/errors/sdkerror.js";
|
|
3
|
+
import { ConnectionError, RequestAbortedError, RequestTimeoutError, UnexpectedClientError } from "@mistralai/mistralai/models/errors/httpclienterrors.js";
|
|
4
|
+
//#region src/client/index.ts
|
|
5
|
+
function chunkToWire(chunk) {
|
|
6
|
+
switch (chunk.type) {
|
|
7
|
+
case "image_url": return {
|
|
8
|
+
type: chunk.type,
|
|
9
|
+
image_url: chunk.imageUrl
|
|
10
|
+
};
|
|
11
|
+
case "document_url": return {
|
|
12
|
+
type: chunk.type,
|
|
13
|
+
document_url: chunk.documentUrl,
|
|
14
|
+
document_name: chunk.documentName
|
|
15
|
+
};
|
|
16
|
+
case "text": return {
|
|
17
|
+
type: chunk.type,
|
|
18
|
+
text: chunk.text
|
|
19
|
+
};
|
|
20
|
+
case "reference": return {
|
|
21
|
+
type: chunk.type,
|
|
22
|
+
reference_ids: chunk.referenceIds
|
|
23
|
+
};
|
|
24
|
+
case "file": return {
|
|
25
|
+
type: chunk.type,
|
|
26
|
+
file_id: chunk.fileId
|
|
27
|
+
};
|
|
28
|
+
case "thinking": return thinkChunkToWire(chunk);
|
|
29
|
+
case "input_audio": return {
|
|
30
|
+
type: chunk.type,
|
|
31
|
+
input_audio: chunk.inputAudio
|
|
32
|
+
};
|
|
33
|
+
case "UNKNOWN": return chunk.raw;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
function thinkChunkToWire(chunk) {
|
|
37
|
+
return {
|
|
38
|
+
type: "thinking",
|
|
39
|
+
thinking: chunk.thinking.map((part) => {
|
|
40
|
+
if ("referenceIds" in part) return {
|
|
41
|
+
type: "reference",
|
|
42
|
+
reference_ids: part.referenceIds
|
|
43
|
+
};
|
|
44
|
+
if ("title" in part) {
|
|
45
|
+
const { tool, title, url, favicon, description } = part;
|
|
46
|
+
return {
|
|
47
|
+
type: "tool_reference",
|
|
48
|
+
tool,
|
|
49
|
+
title,
|
|
50
|
+
url,
|
|
51
|
+
favicon,
|
|
52
|
+
description
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
return {
|
|
56
|
+
type: "text",
|
|
57
|
+
text: part.text
|
|
58
|
+
};
|
|
59
|
+
}),
|
|
60
|
+
closed: chunk.closed
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
function contentToWire(content) {
|
|
64
|
+
return Array.isArray(content) ? content.map(chunkToWire) : content;
|
|
65
|
+
}
|
|
66
|
+
function messageToWire(message) {
|
|
67
|
+
switch (message.role) {
|
|
68
|
+
case "assistant": return {
|
|
69
|
+
role: message.role,
|
|
70
|
+
content: contentToWire(message.content),
|
|
71
|
+
tool_calls: message.toolCalls?.map((call) => ({
|
|
72
|
+
id: call.id ?? "null",
|
|
73
|
+
type: call.type,
|
|
74
|
+
function: call.function,
|
|
75
|
+
index: call.index ?? 0
|
|
76
|
+
})),
|
|
77
|
+
prefix: message.prefix ?? false
|
|
78
|
+
};
|
|
79
|
+
case "system": return {
|
|
80
|
+
role: message.role,
|
|
81
|
+
content: contentToWire(message.content)
|
|
82
|
+
};
|
|
83
|
+
case "tool": return {
|
|
84
|
+
role: message.role,
|
|
85
|
+
content: contentToWire(message.content),
|
|
86
|
+
tool_call_id: message.toolCallId,
|
|
87
|
+
name: message.name
|
|
88
|
+
};
|
|
89
|
+
case "user": return {
|
|
90
|
+
role: message.role,
|
|
91
|
+
content: contentToWire(message.content)
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
/** The JSON body the SDK sends for `chat.complete`. */
|
|
96
|
+
function chatCompletionRequestToWire(request) {
|
|
97
|
+
const { responseFormat, prediction } = request;
|
|
98
|
+
const jsonSchema = responseFormat?.jsonSchema;
|
|
99
|
+
return {
|
|
100
|
+
model: request.model,
|
|
101
|
+
temperature: request.temperature,
|
|
102
|
+
top_p: request.topP,
|
|
103
|
+
max_tokens: request.maxTokens,
|
|
104
|
+
stream: request.stream ?? false,
|
|
105
|
+
stop: request.stop,
|
|
106
|
+
random_seed: request.randomSeed,
|
|
107
|
+
metadata: request.metadata,
|
|
108
|
+
messages: request.messages.map(messageToWire),
|
|
109
|
+
response_format: responseFormat && {
|
|
110
|
+
type: responseFormat.type,
|
|
111
|
+
json_schema: jsonSchema && {
|
|
112
|
+
name: jsonSchema.name,
|
|
113
|
+
description: jsonSchema.description,
|
|
114
|
+
schema: jsonSchema.schemaDefinition,
|
|
115
|
+
strict: jsonSchema.strict
|
|
116
|
+
}
|
|
117
|
+
},
|
|
118
|
+
tools: request.tools,
|
|
119
|
+
tool_choice: request.toolChoice,
|
|
120
|
+
presence_penalty: request.presencePenalty,
|
|
121
|
+
frequency_penalty: request.frequencyPenalty,
|
|
122
|
+
n: request.n,
|
|
123
|
+
prediction: prediction && {
|
|
124
|
+
type: prediction.type ?? "content",
|
|
125
|
+
content: prediction.content ?? ""
|
|
126
|
+
},
|
|
127
|
+
parallel_tool_calls: request.parallelToolCalls,
|
|
128
|
+
reasoning_effort: request.reasoningEffort,
|
|
129
|
+
prompt_mode: request.promptMode,
|
|
130
|
+
guardrails: request.guardrails,
|
|
131
|
+
safe_prompt: request.safePrompt
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
/** The JSON body the SDK sends for `embeddings.create`. */
|
|
135
|
+
function embeddingRequestToWire(request) {
|
|
136
|
+
return {
|
|
137
|
+
model: request.model,
|
|
138
|
+
metadata: request.metadata,
|
|
139
|
+
input: request.inputs,
|
|
140
|
+
output_dimension: request.outputDimension,
|
|
141
|
+
output_dtype: request.outputDtype,
|
|
142
|
+
encoding_format: request.encodingFormat
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
function usageFromWire(usage) {
|
|
146
|
+
const { prompt_tokens = 0, completion_tokens = 0, total_tokens = 0, prompt_audio_seconds, ...rest } = usage;
|
|
147
|
+
return {
|
|
148
|
+
...rest,
|
|
149
|
+
promptTokens: prompt_tokens,
|
|
150
|
+
completionTokens: completion_tokens,
|
|
151
|
+
totalTokens: total_tokens,
|
|
152
|
+
..."prompt_audio_seconds" in usage && { promptAudioSeconds: prompt_audio_seconds }
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
function thinkingFromWire(part) {
|
|
156
|
+
switch (part.type) {
|
|
157
|
+
case "reference": return {
|
|
158
|
+
type: part.type,
|
|
159
|
+
referenceIds: part.reference_ids
|
|
160
|
+
};
|
|
161
|
+
case "tool_reference": return part;
|
|
162
|
+
case "text": return {
|
|
163
|
+
type: part.type,
|
|
164
|
+
text: part.text
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
function chunkFromWire(chunk) {
|
|
169
|
+
switch (chunk.type) {
|
|
170
|
+
case "image_url": return {
|
|
171
|
+
type: chunk.type,
|
|
172
|
+
imageUrl: chunk.image_url
|
|
173
|
+
};
|
|
174
|
+
case "document_url": return {
|
|
175
|
+
type: chunk.type,
|
|
176
|
+
documentUrl: chunk.document_url,
|
|
177
|
+
documentName: chunk.document_name
|
|
178
|
+
};
|
|
179
|
+
case "text": return {
|
|
180
|
+
type: chunk.type,
|
|
181
|
+
text: chunk.text
|
|
182
|
+
};
|
|
183
|
+
case "reference": return {
|
|
184
|
+
type: chunk.type,
|
|
185
|
+
referenceIds: chunk.reference_ids
|
|
186
|
+
};
|
|
187
|
+
case "file": return {
|
|
188
|
+
type: chunk.type,
|
|
189
|
+
fileId: chunk.file_id
|
|
190
|
+
};
|
|
191
|
+
case "thinking": return {
|
|
192
|
+
type: chunk.type,
|
|
193
|
+
thinking: chunk.thinking.map(thinkingFromWire),
|
|
194
|
+
closed: chunk.closed
|
|
195
|
+
};
|
|
196
|
+
case "input_audio": return {
|
|
197
|
+
type: chunk.type,
|
|
198
|
+
inputAudio: chunk.input_audio
|
|
199
|
+
};
|
|
200
|
+
default: return {
|
|
201
|
+
raw: chunk,
|
|
202
|
+
type: "UNKNOWN",
|
|
203
|
+
isUnknown: true
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
function toolCallFromWire(call) {
|
|
208
|
+
return {
|
|
209
|
+
id: call.id ?? "null",
|
|
210
|
+
type: call.type,
|
|
211
|
+
function: {
|
|
212
|
+
name: call.function.name,
|
|
213
|
+
arguments: call.function.arguments
|
|
214
|
+
},
|
|
215
|
+
index: call.index ?? 0
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
function assistantFromWire(message) {
|
|
219
|
+
const { content, tool_calls: toolCalls } = message;
|
|
220
|
+
return {
|
|
221
|
+
role: message.role ?? "assistant",
|
|
222
|
+
content: Array.isArray(content) ? content.map(chunkFromWire) : content,
|
|
223
|
+
toolCalls: toolCalls && toolCalls.map(toolCallFromWire),
|
|
224
|
+
prefix: message.prefix ?? false
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
/** The SDK `ChatCompletionResponse` for a wire response. */
|
|
228
|
+
function chatCompletionResponseFromWire(wire) {
|
|
229
|
+
return {
|
|
230
|
+
id: wire.id,
|
|
231
|
+
object: wire.object,
|
|
232
|
+
model: wire.model,
|
|
233
|
+
usage: usageFromWire(wire.usage),
|
|
234
|
+
created: wire.created,
|
|
235
|
+
choices: wire.choices.map((choice) => ({
|
|
236
|
+
index: choice.index,
|
|
237
|
+
message: choice.message && assistantFromWire(choice.message),
|
|
238
|
+
messages: choice.messages?.map(assistantFromWire),
|
|
239
|
+
finishReason: choice.finish_reason
|
|
240
|
+
}))
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
/** The SDK `EmbeddingResponse` for a wire response. */
|
|
244
|
+
function embeddingResponseFromWire(wire) {
|
|
245
|
+
return {
|
|
246
|
+
id: wire.id,
|
|
247
|
+
object: wire.object,
|
|
248
|
+
model: wire.model,
|
|
249
|
+
usage: usageFromWire(wire.usage),
|
|
250
|
+
data: wire.data.map((item) => ({
|
|
251
|
+
object: item.object,
|
|
252
|
+
embedding: item.embedding,
|
|
253
|
+
index: item.index
|
|
254
|
+
}))
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* The SDK's `HTTPValidationError` (422), with the same name, message, and
|
|
259
|
+
* fields. The SDK class module loads zod, so this copy stands in for it.
|
|
260
|
+
* It extends the real `MistralError`.
|
|
261
|
+
*/
|
|
262
|
+
var HTTPValidationError = class extends MistralError {
|
|
263
|
+
detail;
|
|
264
|
+
data$;
|
|
265
|
+
constructor(err, httpMeta) {
|
|
266
|
+
super(`API error occurred: ${JSON.stringify(err)}`, httpMeta);
|
|
267
|
+
this.data$ = err;
|
|
268
|
+
if (err.detail != null) this.detail = err.detail;
|
|
269
|
+
this.name = "HTTPValidationError";
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
var hasCode = (err, test) => "code" in err && test(err.code);
|
|
273
|
+
var isEconn = (suffix) => (code) => typeof code === "string" && code.toLowerCase() === `econn${suffix}`;
|
|
274
|
+
/** The SDK `_do` error mapping for a failed fetch. */
|
|
275
|
+
function toClientError(err) {
|
|
276
|
+
if (typeof err !== "object" || err === null) return new UnexpectedClientError("Unexpected HTTP client error", { cause: err });
|
|
277
|
+
const name = "name" in err ? err.name : void 0;
|
|
278
|
+
if (name === "AbortError" || hasCode(err, (code) => code === 20) || hasCode(err, isEconn("aborted"))) return new RequestAbortedError("Request aborted by client", { cause: err });
|
|
279
|
+
if (name === "TimeoutError" || hasCode(err, (code) => code === 23)) return new RequestTimeoutError("Request timed out", { cause: err });
|
|
280
|
+
const message = err instanceof TypeError ? err.message.toLowerCase() : "";
|
|
281
|
+
if (message.startsWith("failed to fetch") || message.startsWith("fetch failed") || name === "ConnectionError" || hasCode(err, isEconn("reset"))) return new ConnectionError("Unable to make request", { cause: err });
|
|
282
|
+
return new UnexpectedClientError("Unexpected HTTP client error", { cause: err });
|
|
283
|
+
}
|
|
284
|
+
var isJSONResponse = (response) => (response.headers.get("content-type")?.trim() || "").toLowerCase().split(/\s*;\s*/)[0] === "application/json";
|
|
285
|
+
var isStatusFamily = (response, family) => String(response.status).startsWith(family);
|
|
286
|
+
/**
|
|
287
|
+
* Creates the Mistral client the adapters use. It sends the same requests as
|
|
288
|
+
* the SDK `Mistral` client (no retries, 30 s default timeout) with `fetch`.
|
|
289
|
+
* A `fetcher` replaces `fetch`; it gets `(url, init)`.
|
|
290
|
+
*
|
|
291
|
+
* @throws The SDK error classes: `SDKError` for a 4xx/5xx or an unexpected
|
|
292
|
+
* response, `HTTPValidationError` for a 422 JSON body, and the HTTP client
|
|
293
|
+
* errors (`ConnectionError`, `RequestTimeoutError`, `RequestAbortedError`,
|
|
294
|
+
* `UnexpectedClientError`) when the request fails.
|
|
295
|
+
*/
|
|
296
|
+
function createMistralClient(config, fetcher) {
|
|
297
|
+
const { apiKey, defaultHeaders, getAccessToken, resolveRequestUrl } = config;
|
|
298
|
+
const baseURL = new URL(config.baseURL || config.serverURL || "https://api.mistral.ai");
|
|
299
|
+
baseURL.pathname = `${baseURL.pathname.replace(/\/+$/, "")}/`;
|
|
300
|
+
const timeoutMs = config.timeoutMs || 3e4;
|
|
301
|
+
async function post(path, body, requestOptions) {
|
|
302
|
+
const url = new URL(path, baseURL);
|
|
303
|
+
url.hash = "";
|
|
304
|
+
const headers = new Headers({
|
|
305
|
+
"Content-Type": "application/json",
|
|
306
|
+
Accept: "application/json"
|
|
307
|
+
});
|
|
308
|
+
if (apiKey) {
|
|
309
|
+
const isBearer = apiKey.slice(0, 7).toLowerCase() === "bearer ";
|
|
310
|
+
headers.set("Authorization", isBearer ? apiKey : `Bearer ${apiKey}`);
|
|
311
|
+
}
|
|
312
|
+
const init = {
|
|
313
|
+
method: "POST",
|
|
314
|
+
headers,
|
|
315
|
+
body: JSON.stringify(body),
|
|
316
|
+
signal: requestOptions?.signal ?? requestOptions?.fetchOptions?.signal ?? (timeoutMs > 0 ? AbortSignal.timeout(timeoutMs) : void 0)
|
|
317
|
+
};
|
|
318
|
+
const send = fetcher ?? ((input, options) => fetch(input, options));
|
|
319
|
+
let requestURL = url.href;
|
|
320
|
+
let response;
|
|
321
|
+
try {
|
|
322
|
+
if (resolveRequestUrl !== void 0) requestURL = resolveRequestUrl(false);
|
|
323
|
+
for (const [key, value] of Object.entries(defaultHeaders ?? {})) headers.set(key, value);
|
|
324
|
+
if (getAccessToken !== void 0) headers.set("Authorization", `Bearer ${await getAccessToken()}`);
|
|
325
|
+
response = await send(requestURL, init);
|
|
326
|
+
} catch (err) {
|
|
327
|
+
throw toClientError(err);
|
|
328
|
+
}
|
|
329
|
+
const isJSON = isJSONResponse(response);
|
|
330
|
+
if (response.status === 200 && isJSON) {
|
|
331
|
+
const wire = JSON.parse(await response.text());
|
|
332
|
+
const deprecation = response.headers.get("x-model-deprecation-timestamp");
|
|
333
|
+
if (deprecation !== null) console.warn(`WARNING: The model ${wire.model} is deprecated and will be removed on ${deprecation}. Please refer to https://docs.mistral.ai/getting-started/models/#api-versioning for more information.`);
|
|
334
|
+
return wire;
|
|
335
|
+
}
|
|
336
|
+
const request = new Request(requestURL, {
|
|
337
|
+
method: "POST",
|
|
338
|
+
headers,
|
|
339
|
+
body: init.body
|
|
340
|
+
});
|
|
341
|
+
const isAPIError = isStatusFamily(response, "4") || isStatusFamily(response, "5");
|
|
342
|
+
if (response.status === 422 && isJSON) {
|
|
343
|
+
const text = await response.text();
|
|
344
|
+
const detail = JSON.parse(text).detail?.map(({ loc, msg, type, input, ctx }) => ({
|
|
345
|
+
loc,
|
|
346
|
+
msg,
|
|
347
|
+
type,
|
|
348
|
+
input,
|
|
349
|
+
...ctx !== void 0 && { ctx: {} }
|
|
350
|
+
}));
|
|
351
|
+
throw new HTTPValidationError({
|
|
352
|
+
...detail !== void 0 && { detail },
|
|
353
|
+
request$: request,
|
|
354
|
+
response$: response,
|
|
355
|
+
body$: text
|
|
356
|
+
}, {
|
|
357
|
+
request,
|
|
358
|
+
response,
|
|
359
|
+
body: text
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
if (isAPIError) {
|
|
363
|
+
const text = await response.text();
|
|
364
|
+
throw new SDKError("API error occurred", {
|
|
365
|
+
request,
|
|
366
|
+
response,
|
|
367
|
+
body: text
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
const text = await response.text().catch(() => "");
|
|
371
|
+
throw new SDKError("Unexpected Status or Content-Type", {
|
|
372
|
+
request,
|
|
373
|
+
response,
|
|
374
|
+
body: text
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
return {
|
|
378
|
+
chat: { complete: async (request, options) => chatCompletionResponseFromWire(await post("v1/chat/completions", chatCompletionRequestToWire(request), options)) },
|
|
379
|
+
embeddings: { create: async (request, options) => embeddingResponseFromWire(await post("v1/embeddings", embeddingRequestToWire(request), options)) }
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
//#endregion
|
|
383
|
+
export { HTTPValidationError, chatCompletionRequestToWire, chatCompletionResponseFromWire, createMistralClient, embeddingRequestToWire, embeddingResponseFromWire };
|
|
384
|
+
|
|
385
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../src/client/index.ts"],"sourcesContent":["import { MistralError } from '@mistralai/mistralai/models/errors/mistralerror.js'\nimport { SDKError } from '@mistralai/mistralai/models/errors/sdkerror.js'\nimport {\n ConnectionError,\n RequestAbortedError,\n RequestTimeoutError,\n UnexpectedClientError,\n} from '@mistralai/mistralai/models/errors/httpclienterrors.js'\nimport type {\n AssistantMessage,\n AssistantMessage$Outbound,\n ChatCompletionChoice,\n ChatCompletionRequest,\n ChatCompletionResponse,\n ContentChunk,\n ContentChunk$Outbound,\n EmbeddingRequest,\n EmbeddingResponse,\n EmbeddingResponseData,\n ImageURLChunk,\n ThinkChunk,\n Thinking$Outbound,\n ToolCall,\n UsageInfo,\n UsageInfo$Outbound,\n ValidationError,\n} from '@mistralai/mistralai/models/components'\nimport type { MistralClientConfig } from '../utils/client'\n\n/**\n * The part of the Mistral SDK client that the adapters call. A real\n * `Mistral` instance fits this type.\n */\nexport interface MistralClient {\n chat: {\n complete: (\n request: ChatCompletionRequest,\n options?: MistralRequestOptions,\n ) => Promise<ChatCompletionResponse>\n }\n embeddings: {\n create: (\n request: EmbeddingRequest,\n options?: MistralRequestOptions,\n ) => Promise<EmbeddingResponse>\n }\n}\n\n/**\n * The part of the SDK `RequestOptions` that the adapters pass. Same as the\n * SDK: a signal replaces the default timeout.\n */\nexport interface MistralRequestOptions {\n signal?: AbortSignal | null\n fetchOptions?: { signal?: AbortSignal | null }\n}\n\ntype Fetcher = (url: string, init: RequestInit) => Promise<Response>\n\n// ===========================\n// Outbound: SDK camelCase -> wire snake_case (the SDK `$outboundSchema`s)\n// ===========================\n\nfunction chunkToWire(chunk: ContentChunk) {\n switch (chunk.type) {\n case 'image_url':\n return { type: chunk.type, image_url: chunk.imageUrl }\n case 'document_url':\n return {\n type: chunk.type,\n document_url: chunk.documentUrl,\n document_name: chunk.documentName,\n }\n case 'text':\n return { type: chunk.type, text: chunk.text }\n case 'reference':\n return { type: chunk.type, reference_ids: chunk.referenceIds }\n case 'file':\n return { type: chunk.type, file_id: chunk.fileId }\n case 'thinking':\n return thinkChunkToWire(chunk)\n case 'input_audio':\n return { type: chunk.type, input_audio: chunk.inputAudio }\n case 'UNKNOWN':\n // An unknown chunk read from a response. Send what came in.\n return chunk.raw\n }\n}\n\nfunction thinkChunkToWire(chunk: ThinkChunk) {\n return {\n type: 'thinking',\n thinking: chunk.thinking.map((part) => {\n if ('referenceIds' in part) {\n return { type: 'reference', reference_ids: part.referenceIds }\n }\n if ('title' in part) {\n const { tool, title, url, favicon, description } = part\n return {\n type: 'tool_reference',\n tool,\n title,\n url,\n favicon,\n description,\n }\n }\n return { type: 'text', text: part.text }\n }),\n closed: chunk.closed,\n }\n}\n\nfunction contentToWire(\n content: string | Array<ContentChunk> | null | undefined,\n) {\n return Array.isArray(content) ? content.map(chunkToWire) : content\n}\n\nfunction messageToWire(message: ChatCompletionRequest['messages'][number]) {\n switch (message.role) {\n case 'assistant':\n return {\n role: message.role,\n content: contentToWire(message.content),\n tool_calls: message.toolCalls?.map((call) => ({\n id: call.id ?? 'null',\n type: call.type,\n function: call.function,\n index: call.index ?? 0,\n })),\n prefix: message.prefix ?? false,\n }\n case 'system':\n return { role: message.role, content: contentToWire(message.content) }\n case 'tool':\n return {\n role: message.role,\n content: contentToWire(message.content),\n tool_call_id: message.toolCallId,\n name: message.name,\n }\n case 'user':\n return { role: message.role, content: contentToWire(message.content) }\n }\n}\n\n/** The JSON body the SDK sends for `chat.complete`. */\nexport function chatCompletionRequestToWire(request: ChatCompletionRequest) {\n const { responseFormat, prediction } = request\n const jsonSchema = responseFormat?.jsonSchema\n return {\n model: request.model,\n temperature: request.temperature,\n top_p: request.topP,\n max_tokens: request.maxTokens,\n stream: request.stream ?? false,\n stop: request.stop,\n random_seed: request.randomSeed,\n metadata: request.metadata,\n messages: request.messages.map(messageToWire),\n response_format: responseFormat && {\n type: responseFormat.type,\n json_schema: jsonSchema && {\n name: jsonSchema.name,\n description: jsonSchema.description,\n schema: jsonSchema.schemaDefinition,\n strict: jsonSchema.strict,\n },\n },\n // ponytail: function tools and tool choice need no renames. Built-in\n // connector tools and `guardrails` go out as given; the adapters never\n // send them. Port their rename tables when an adapter does.\n tools: request.tools,\n tool_choice: request.toolChoice,\n presence_penalty: request.presencePenalty,\n frequency_penalty: request.frequencyPenalty,\n n: request.n,\n prediction: prediction && {\n type: prediction.type ?? 'content',\n content: prediction.content ?? '',\n },\n parallel_tool_calls: request.parallelToolCalls,\n reasoning_effort: request.reasoningEffort,\n prompt_mode: request.promptMode,\n guardrails: request.guardrails,\n safe_prompt: request.safePrompt,\n }\n}\n\n/** The JSON body the SDK sends for `embeddings.create`. */\nexport function embeddingRequestToWire(request: EmbeddingRequest) {\n return {\n model: request.model,\n metadata: request.metadata,\n input: request.inputs,\n output_dimension: request.outputDimension,\n output_dtype: request.outputDtype,\n encoding_format: request.encodingFormat,\n }\n}\n\n// ===========================\n// Inbound: wire snake_case -> SDK camelCase (the SDK `$inboundSchema`s)\n// ===========================\n\n/** An assistant message on the wire. The SDK fills `role` and `prefix`. */\ntype WireAssistant = Omit<\n AssistantMessage$Outbound,\n 'role' | 'prefix' | 'tool_calls' | 'content'\n> & {\n role?: 'assistant'\n content?: string | Array<WireContentChunk> | null\n prefix?: boolean\n tool_calls?: Array<ToolCall> | null\n}\n\n/** A content chunk on the wire. `image_url` keeps the SDK value as is. */\ntype WireContentChunk =\n | Exclude<ContentChunk$Outbound, { type: 'image_url' }>\n | { type: 'image_url'; image_url: ImageURLChunk['imageUrl'] }\n\n/** Usage on the wire. The SDK fills missing token counts with 0. */\ntype WireUsage = Partial<UsageInfo$Outbound>\n\ninterface WireChoice {\n index: number\n message?: WireAssistant\n messages?: Array<WireAssistant>\n finish_reason: ChatCompletionChoice['finishReason']\n}\n\ninterface WireChatCompletion {\n id: string\n object: string\n model: string\n usage: WireUsage\n created: number\n choices: Array<WireChoice>\n}\n\ninterface WireEmbedding {\n id: string\n object: string\n model: string\n usage: WireUsage\n data: Array<EmbeddingResponseData>\n}\n\nfunction usageFromWire(usage: WireUsage): UsageInfo {\n // Unknown keys (`prompt_tokens_details`, `num_cached_tokens`) stay as they\n // are, like the SDK's catchall.\n const {\n prompt_tokens = 0,\n completion_tokens = 0,\n total_tokens = 0,\n prompt_audio_seconds,\n ...rest\n } = usage\n return {\n ...rest,\n promptTokens: prompt_tokens,\n completionTokens: completion_tokens,\n totalTokens: total_tokens,\n ...('prompt_audio_seconds' in usage && {\n promptAudioSeconds: prompt_audio_seconds,\n }),\n }\n}\n\nfunction thinkingFromWire(\n part: Thinking$Outbound,\n): ThinkChunk['thinking'][number] {\n switch (part.type) {\n case 'reference':\n return { type: part.type, referenceIds: part.reference_ids }\n case 'tool_reference':\n return part\n case 'text':\n return { type: part.type, text: part.text }\n }\n}\n\nfunction chunkFromWire(chunk: WireContentChunk): ContentChunk {\n switch (chunk.type) {\n case 'image_url':\n return { type: chunk.type, imageUrl: chunk.image_url }\n case 'document_url':\n return {\n type: chunk.type,\n documentUrl: chunk.document_url,\n documentName: chunk.document_name,\n }\n case 'text':\n return { type: chunk.type, text: chunk.text }\n case 'reference':\n return { type: chunk.type, referenceIds: chunk.reference_ids }\n case 'file':\n return { type: chunk.type, fileId: chunk.file_id }\n case 'thinking':\n return {\n type: chunk.type,\n thinking: chunk.thinking.map(thinkingFromWire),\n closed: chunk.closed,\n }\n case 'input_audio':\n return { type: chunk.type, inputAudio: chunk.input_audio }\n default:\n return { raw: chunk, type: 'UNKNOWN', isUnknown: true }\n }\n}\n\nfunction toolCallFromWire(call: ToolCall): ToolCall {\n return {\n id: call.id ?? 'null',\n type: call.type,\n function: { name: call.function.name, arguments: call.function.arguments },\n index: call.index ?? 0,\n }\n}\n\nfunction assistantFromWire(message: WireAssistant): AssistantMessage {\n const { content, tool_calls: toolCalls } = message\n return {\n role: message.role ?? 'assistant',\n content: Array.isArray(content) ? content.map(chunkFromWire) : content,\n toolCalls: toolCalls && toolCalls.map(toolCallFromWire),\n prefix: message.prefix ?? false,\n }\n}\n\n/** The SDK `ChatCompletionResponse` for a wire response. */\nexport function chatCompletionResponseFromWire(\n wire: WireChatCompletion,\n): ChatCompletionResponse {\n return {\n id: wire.id,\n object: wire.object,\n model: wire.model,\n usage: usageFromWire(wire.usage),\n created: wire.created,\n choices: wire.choices.map((choice) => ({\n index: choice.index,\n message: choice.message && assistantFromWire(choice.message),\n messages: choice.messages?.map(assistantFromWire),\n finishReason: choice.finish_reason,\n })),\n }\n}\n\n/** The SDK `EmbeddingResponse` for a wire response. */\nexport function embeddingResponseFromWire(\n wire: WireEmbedding,\n): EmbeddingResponse {\n return {\n id: wire.id,\n object: wire.object,\n model: wire.model,\n usage: usageFromWire(wire.usage),\n data: wire.data.map((item) => ({\n object: item.object,\n embedding: item.embedding,\n index: item.index,\n })),\n }\n}\n\n// ===========================\n// Errors\n// ===========================\n\n/**\n * The SDK's `HTTPValidationError` (422), with the same name, message, and\n * fields. The SDK class module loads zod, so this copy stands in for it.\n * It extends the real `MistralError`.\n */\nexport class HTTPValidationError extends MistralError {\n detail?: Array<ValidationError>\n data$: {\n detail?: Array<ValidationError>\n request$: Request\n response$: Response\n body$: string\n }\n\n constructor(\n err: HTTPValidationError['data$'],\n httpMeta: { request: Request; response: Response; body: string },\n ) {\n // The SDK schema strips `message`, so the SDK always builds this text.\n super(`API error occurred: ${JSON.stringify(err)}`, httpMeta)\n this.data$ = err\n if (err.detail != null) this.detail = err.detail\n this.name = 'HTTPValidationError'\n }\n}\n\nconst hasCode = (err: object, test: (code: unknown) => boolean) =>\n 'code' in err && test(err.code)\n\nconst isEconn = (suffix: string) => (code: unknown) =>\n typeof code === 'string' && code.toLowerCase() === `econn${suffix}`\n\n/** The SDK `_do` error mapping for a failed fetch. */\nfunction toClientError(err: unknown) {\n if (typeof err !== 'object' || err === null) {\n return new UnexpectedClientError('Unexpected HTTP client error', {\n cause: err,\n })\n }\n const name = 'name' in err ? err.name : undefined\n const isAbort =\n name === 'AbortError' ||\n hasCode(err, (code) => code === 20) ||\n hasCode(err, isEconn('aborted'))\n if (isAbort) {\n return new RequestAbortedError('Request aborted by client', { cause: err })\n }\n const isTimeout =\n name === 'TimeoutError' || hasCode(err, (code) => code === 23)\n if (isTimeout) {\n return new RequestTimeoutError('Request timed out', { cause: err })\n }\n const message = err instanceof TypeError ? err.message.toLowerCase() : ''\n const isConnection =\n message.startsWith('failed to fetch') ||\n message.startsWith('fetch failed') ||\n name === 'ConnectionError' ||\n hasCode(err, isEconn('reset'))\n if (isConnection) {\n return new ConnectionError('Unable to make request', { cause: err })\n }\n return new UnexpectedClientError('Unexpected HTTP client error', {\n cause: err,\n })\n}\n\nconst isJSONResponse = (response: Response) =>\n (response.headers.get('content-type')?.trim() || '')\n .toLowerCase()\n .split(/\\s*;\\s*/)[0] === 'application/json'\n\nconst isStatusFamily = (response: Response, family: string) =>\n String(response.status).startsWith(family)\n\n// ===========================\n// Client\n// ===========================\n\n/**\n * Creates the Mistral client the adapters use. It sends the same requests as\n * the SDK `Mistral` client (no retries, 30 s default timeout) with `fetch`.\n * A `fetcher` replaces `fetch`; it gets `(url, init)`.\n *\n * @throws The SDK error classes: `SDKError` for a 4xx/5xx or an unexpected\n * response, `HTTPValidationError` for a 422 JSON body, and the HTTP client\n * errors (`ConnectionError`, `RequestTimeoutError`, `RequestAbortedError`,\n * `UnexpectedClientError`) when the request fails.\n */\nexport function createMistralClient(\n config: MistralClientConfig,\n fetcher?: Fetcher,\n): MistralClient {\n const { apiKey, defaultHeaders, getAccessToken, resolveRequestUrl } = config\n const baseURL = new URL(\n config.baseURL || config.serverURL || 'https://api.mistral.ai',\n )\n baseURL.pathname = `${baseURL.pathname.replace(/\\/+$/, '')}/`\n const timeoutMs = config.timeoutMs || 30000\n\n async function post(\n path: string,\n body: unknown,\n requestOptions?: MistralRequestOptions,\n ) {\n const url = new URL(path, baseURL)\n url.hash = ''\n const headers = new Headers({\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n })\n if (apiKey) {\n const isBearer = apiKey.slice(0, 7).toLowerCase() === 'bearer '\n headers.set('Authorization', isBearer ? apiKey : `Bearer ${apiKey}`)\n }\n const init: RequestInit = {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n signal:\n requestOptions?.signal ??\n requestOptions?.fetchOptions?.signal ??\n (timeoutMs > 0 ? AbortSignal.timeout(timeoutMs) : undefined),\n }\n const send =\n fetcher ??\n ((input: string, options: RequestInit) => fetch(input, options))\n\n let requestURL = url.href\n let response: Response\n try {\n // The SDK runs these in its request hook, so their errors map the same.\n if (resolveRequestUrl !== undefined) requestURL = resolveRequestUrl(false)\n for (const [key, value] of Object.entries(defaultHeaders ?? {})) {\n headers.set(key, value)\n }\n if (getAccessToken !== undefined) {\n headers.set('Authorization', `Bearer ${await getAccessToken()}`)\n }\n response = await send(requestURL, init)\n } catch (err) {\n throw toClientError(err)\n }\n\n const isJSON = isJSONResponse(response)\n if (response.status === 200 && isJSON) {\n const wire = JSON.parse(await response.text())\n const deprecation = response.headers.get('x-model-deprecation-timestamp')\n if (deprecation !== null) {\n console.warn(\n `WARNING: The model ${wire.model} is deprecated and will be removed on ${deprecation}. Please refer to https://docs.mistral.ai/getting-started/models/#api-versioning for more information.`,\n )\n }\n return wire\n }\n\n const request = new Request(requestURL, {\n method: 'POST',\n headers,\n body: init.body,\n })\n const isAPIError =\n isStatusFamily(response, '4') || isStatusFamily(response, '5')\n if (response.status === 422 && isJSON) {\n const text = await response.text()\n const raw: { detail?: Array<ValidationError> } = JSON.parse(text)\n const detail = raw.detail?.map(({ loc, msg, type, input, ctx }) => ({\n loc,\n msg,\n type,\n input,\n ...(ctx !== undefined && { ctx: {} }),\n }))\n throw new HTTPValidationError(\n {\n ...(detail !== undefined && { detail }),\n request$: request,\n response$: response,\n body$: text,\n },\n { request, response, body: text },\n )\n }\n if (isAPIError) {\n const text = await response.text()\n throw new SDKError('API error occurred', {\n request,\n response,\n body: text,\n })\n }\n const text = await response.text().catch(() => '')\n throw new SDKError('Unexpected Status or Content-Type', {\n request,\n response,\n body: text,\n })\n }\n\n return {\n chat: {\n complete: async (request, options) =>\n chatCompletionResponseFromWire(\n await post(\n 'v1/chat/completions',\n chatCompletionRequestToWire(request),\n options,\n ),\n ),\n },\n embeddings: {\n create: async (request, options) =>\n embeddingResponseFromWire(\n await post('v1/embeddings', embeddingRequestToWire(request), options),\n ),\n },\n }\n}\n"],"mappings":";;;;AA+DA,SAAS,YAAY,OAAqB;CACxC,QAAQ,MAAM,MAAd;EACE,KAAK,aACH,OAAO;GAAE,MAAM,MAAM;GAAM,WAAW,MAAM;EAAS;EACvD,KAAK,gBACH,OAAO;GACL,MAAM,MAAM;GACZ,cAAc,MAAM;GACpB,eAAe,MAAM;EACvB;EACF,KAAK,QACH,OAAO;GAAE,MAAM,MAAM;GAAM,MAAM,MAAM;EAAK;EAC9C,KAAK,aACH,OAAO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AA,KAAa,EAAE,OAAO;IACrC,UAAU;IACV,WAAW;IACX,OAAO;GACT,GACA;IAAE;IAAS;IAAU,MAAM;GAAK,CAClC;EACF;EACA,IAAI,YAAY;GACd,MAAM,OAAO,MAAM,SAAS,KAAK;GACjC,MAAM,IAAI,SAAS,sBAAsB;IACvC;IACA;IACA,MAAM;GACR,CAAC;EACH;EACA,MAAM,OAAO,MAAM,SAAS,KAAK,CAAC,CAAC,YAAY,EAAE;EACjD,MAAM,IAAI,SAAS,qCAAqC;GACtD;GACA;GACA,MAAM;EACR,CAAC;CACH;CAEA,OAAO;EACL,MAAM,EACJ,UAAU,OAAO,SAAS,YACxB,+BACE,MAAM,KACJ,uBACA,4BAA4B,OAAO,GACnC,OACF,CACF,EACJ;EACA,YAAY,EACV,QAAQ,OAAO,SAAS,YACtB,0BACE,MAAM,KAAK,iBAAiB,uBAAuB,OAAO,GAAG,OAAO,CACtE,EACJ;CACF;AACF"}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { Mistral } from '@mistralai/mistralai';
|
|
2
1
|
export interface MistralClientConfig {
|
|
3
2
|
/** Mistral API key. */
|
|
4
3
|
apiKey: string;
|
|
@@ -27,10 +26,6 @@ export interface MistralClientConfig {
|
|
|
27
26
|
/** Optional model id sent on the wire. Vertex uses publisher model ids. */
|
|
28
27
|
requestModel?: string;
|
|
29
28
|
}
|
|
30
|
-
/**
|
|
31
|
-
* Creates a Mistral SDK client instance. A `fetcher` replaces the SDK's fetch.
|
|
32
|
-
*/
|
|
33
|
-
export declare function createMistralClient(config: MistralClientConfig, fetcher?: typeof fetch): Mistral;
|
|
34
29
|
/**
|
|
35
30
|
* Gets Mistral API key from environment variables.
|
|
36
31
|
* @throws Error if MISTRAL_API_KEY is not found
|
package/dist/esm/utils/client.js
CHANGED
|
@@ -1,37 +1,5 @@
|
|
|
1
|
-
import { HTTPClient, Mistral } from "@mistralai/mistralai";
|
|
2
1
|
//#region src/utils/client.ts
|
|
3
2
|
/**
|
|
4
|
-
* Creates a Mistral SDK client instance. A `fetcher` replaces the SDK's fetch.
|
|
5
|
-
*/
|
|
6
|
-
function createMistralClient(config, fetcher) {
|
|
7
|
-
const { apiKey, baseURL, timeoutMs, defaultHeaders, getAccessToken, resolveRequestUrl } = config;
|
|
8
|
-
const serverURL = baseURL ?? config.serverURL;
|
|
9
|
-
const needsHook = defaultHeaders !== void 0 && Object.keys(defaultHeaders).length > 0 || getAccessToken !== void 0 || resolveRequestUrl !== void 0;
|
|
10
|
-
let httpClient;
|
|
11
|
-
if (needsHook || fetcher) httpClient = new HTTPClient({ fetcher: fetcher && (async (input) => {
|
|
12
|
-
const request = new Request(input);
|
|
13
|
-
return fetcher(request.url, {
|
|
14
|
-
method: request.method,
|
|
15
|
-
headers: request.headers,
|
|
16
|
-
body: request.body && await request.arrayBuffer(),
|
|
17
|
-
signal: request.signal
|
|
18
|
-
});
|
|
19
|
-
}) });
|
|
20
|
-
if (httpClient && needsHook) httpClient.addHook("beforeRequest", async (req) => {
|
|
21
|
-
const nextUrl = resolveRequestUrl === void 0 ? req.url : resolveRequestUrl(false);
|
|
22
|
-
const next = new Request(nextUrl, req);
|
|
23
|
-
if (defaultHeaders) for (const [key, value] of Object.entries(defaultHeaders)) next.headers.set(key, value);
|
|
24
|
-
if (getAccessToken !== void 0) next.headers.set("Authorization", `Bearer ${await getAccessToken()}`);
|
|
25
|
-
return next;
|
|
26
|
-
});
|
|
27
|
-
return new Mistral({
|
|
28
|
-
apiKey,
|
|
29
|
-
...serverURL !== void 0 ? { serverURL } : {},
|
|
30
|
-
...timeoutMs !== void 0 ? { timeoutMs } : {},
|
|
31
|
-
...httpClient !== void 0 ? { httpClient } : {}
|
|
32
|
-
});
|
|
33
|
-
}
|
|
34
|
-
/**
|
|
35
3
|
* Gets Mistral API key from environment variables.
|
|
36
4
|
* @throws Error if MISTRAL_API_KEY is not found
|
|
37
5
|
*/
|
|
@@ -49,6 +17,6 @@ function generateId(prefix) {
|
|
|
49
17
|
return `${prefix}-${crypto.randomUUID()}`;
|
|
50
18
|
}
|
|
51
19
|
//#endregion
|
|
52
|
-
export {
|
|
20
|
+
export { generateId, getMistralApiKeyFromEnv };
|
|
53
21
|
|
|
54
22
|
//# sourceMappingURL=client.js.map
|