본문으로 건너뛰기

Mistral

Mistral 어댑터는 Mistral Large, 멀티모달 Pixtral 제품군, Magistral 추론 모델, 코드 특화 모델인 Codestral을 비롯한 Mistral의 채팅 모델에 액세스할 수 있게 합니다.

설치

npm install @tanstack/ai-mistral

기본 사용법

import { chat } from "@tanstack/ai";
import { mistralText } from "@tanstack/ai-mistral";

const stream = chat({
adapter: mistralText("mistral-large-latest"),
messages: [{ role: "user", content: "Hello!" }],
});

기본 사용법 - 사용자 지정 API 키

import { chat } from "@tanstack/ai";
import { createMistralText } from "@tanstack/ai-mistral";

const adapter = createMistralText(
"mistral-large-latest",
process.env.MISTRAL_API_KEY!,
);

const stream = chat({
adapter,
messages: [{ role: "user", content: "Hello!" }],
});

구성

import {
createMistralText,
type MistralTextConfig,
} from "@tanstack/ai-mistral";

const config: Omit<MistralTextConfig, "apiKey"> = {
serverURL: "https://api.mistral.ai", // Optional, this is the default
defaultHeaders: {
"X-Custom-Header": "value",
},
};

const adapter = createMistralText(
"mistral-large-latest",
process.env.MISTRAL_API_KEY!,
config,
);

Vertex의 Mistral

Mistral을 Vertex AI에서 실행해야 할 때는 @tanstack/ai-mistral/vertex를 사용합니다. 이 경로는 Google Cloud 자격 증명과 publisher rawPredict 엔드포인트를 사용합니다.

Vertex의 Mistral은 리전에서만 사용할 수 있습니다. us-central1 또는 europe-west4를 사용합니다.

npm install @tanstack/ai-mistral google-auth-library
import { chat } from "@tanstack/ai";
import { mistralVertexText } from "@tanstack/ai-mistral/vertex";

const stream = chat({
adapter: mistralVertexText("mistral-medium-3", {
project: "my-project",
location: "europe-west4",
}),
messages: [{ role: "user", content: "Hello!" }],
});

projectlocation@tanstack/ai-vertex와 동일한 이름을 사용합니다. location은 필수입니다.

mistralVertexText는 Vertex에 나열된 Mistral 채팅 모델만 허용합니다.

  • mistral-medium-3
  • mistral-small-2503
  • codestral-2

mistral-large-latestmistral-medium-latest와 같은 Mistral API 별칭은 Vertex 모델 ID가 아닙니다. Vertex에는 mistral-ocr-2505도 나열되어 있지만, 이 모델은 채팅 모델이 아니라 OCR 모델입니다.

Application Default Credentials를 사용하려면 google-auth-library를 설치하거나 authClient 또는 getAccessToken을 전달합니다.

Vertex 에 있는 Gemini 는 @tanstack/ai-vertex 에 존재합니다.

예시: 채팅 완성

import { chat, toServerSentEventsResponse } from "@tanstack/ai";
import { mistralText } from "@tanstack/ai-mistral";

export async function POST(request: Request) {
const { messages } = await request.json();

const stream = chat({
adapter: mistralText("mistral-large-latest"),
messages,
});

return toServerSentEventsResponse(stream);
}

예시: 도구 사용

import { chat, toolDefinition } from "@tanstack/ai";
import { mistralText } from "@tanstack/ai-mistral";
import { z } from "zod";

const getWeatherDef = toolDefinition({
name: "get_weather",
description: "Get the current weather for a location",
inputSchema: z.object({
location: z.string(),
}),
});

const getWeather = getWeatherDef.server(async ({ location }) => {
return { temperature: 72, conditions: "sunny" };
});

const stream = chat({
adapter: mistralText("mistral-large-latest"),
messages: [{ role: "user", content: "What's the weather in Paris?" }],
tools: [getWeather],
});

예시: 멀티모달(비전)

비전을 지원하는 모델인 pixtral-large-latest, pixtral-12b-2409, mistral-medium-latest 또는 mistral-small-latest를 사용하면 텍스트와 함께 이미지를 보낼 수 있습니다.

import { chat } from "@tanstack/ai";
import { mistralText } from "@tanstack/ai-mistral";

const stream = chat({
adapter: mistralText("pixtral-large-latest"),
messages: [
{
role: "user",
content: [
{ type: "text", content: "What's in this image?" },
{
type: "image",
source: {
type: "url",
value: "https://example.com/photo.jpg",
},
},
],
},
],
});

data-URL 또는 base64 이미지의 경우 source.type"data"로 설정하고 mimeType을 제공합니다.

import { chat } from "@tanstack/ai";
import { mistralText } from "@tanstack/ai-mistral";

const base64String = "..."; // your base64-encoded image bytes

const stream = chat({
adapter: mistralText("pixtral-large-latest"),
messages: [
{
role: "user",
content: [
{ type: "text", content: "What's in this image?" },
{
type: "image",
source: {
type: "data",
mimeType: "image/png",
value: base64String,
},
},
],
},
],
});

전체 콘텐츠 파트 형태는 멀티모달 콘텐츠를 참조합니다.

예시: 추론(Magistral)

Magistral 모델(magistral-medium-latest, magistral-small-latest)은 최종 답변 전에 추론을 별도의 이벤트로 스트리밍합니다. 어댑터는 사고 콘텐츠에 대해 AG-UI REASONING_* 청크를, 답변에 대해 TEXT_MESSAGE_* 청크를 내보냅니다.

// ignore: narrowing the raw AG-UI stream by `chunk.type` relies on @ag-ui/core's
// discriminated-union `type` field, which kiira can't resolve in a source-only
// check. The runtime behaviour is exactly as shown.
import { chat } from "@tanstack/ai";
import { mistralText } from "@tanstack/ai-mistral";

const stream = chat({
adapter: mistralText("magistral-medium-latest"),
messages: [{ role: "user", content: "Why is the sky blue?" }],
});

for await (const chunk of stream) {
if (chunk.type === "REASONING_MESSAGE_CONTENT") {
process.stdout.write(`[thinking] ${chunk.delta}`);
} else if (chunk.type === "TEXT_MESSAGE_CONTENT") {
process.stdout.write(chunk.delta);
}
}

추론 이벤트는 텍스트 또는 도구 출력이 시작되기 전에 항상 종료되므로, 소비자는 먼저 완전한 REASONING_START → REASONING_MESSAGE_START → REASONING_MESSAGE_CONTENT* → REASONING_MESSAGE_END → REASONING_END 시퀀스를 확인합니다.

프로바이더 간 이벤트 사양은 사고 및 추론을 참조합니다.

예시: 구조화된 출력

Mistral의 json_schema 응답 형식을 사용해 Zod 스키마를 준수하는 JSON을 생성합니다.

import { chat } from "@tanstack/ai";
import { mistralText } from "@tanstack/ai-mistral";
import { z } from "zod";

const recipeSchema = z.object({
name: z.string(),
ingredients: z.array(z.string()),
steps: z.array(z.string()),
});

const recipe = await chat({
adapter: mistralText("mistral-large-latest"),
messages: [
{ role: "user", content: "Give me a chocolate chip cookie recipe." },
],
outputSchema: recipeSchema,
});

console.log(recipe.name); // typed as z.infer<typeof recipeSchema>

전체 가이드는 구조화된 출력을 참조합니다.

모델 옵션

Mistral은 modelOptions를 통해 프로바이더별 옵션을 제공합니다.

import { chat } from "@tanstack/ai";
import { mistralText } from "@tanstack/ai-mistral";

const stream = chat({
adapter: mistralText("mistral-large-latest"),
messages: [{ role: "user", content: "Hello!" }],
modelOptions: {
temperature: 0.7,
top_p: 0.9,
max_tokens: 1024,
random_seed: 42,
stop: ["END"],
safe_prompt: true,
frequency_penalty: 0.5,
presence_penalty: 0.5,
parallel_tool_calls: true,
tool_choice: "auto",
},
});

temperature, top_p, max_tokens를 비롯한 모든 샘플링 매개변수는 Mistral의 기본 (snake_case) 이름을 사용해 modelOptions 안에 지정합니다.

임베딩

mistral-embed 또는 codestral-embed로 임베딩 벡터를 생성합니다.

import { embed } from "@tanstack/ai";
import { mistralEmbedding } from "@tanstack/ai-mistral";

const result = await embed({
adapter: mistralEmbedding("mistral-embed"),
input: ["a red guitar", "a blue drum kit"],
});

console.log(result.embeddings[0]?.vector); // 1024 dimensions

mistral-embed의 출력 차원은 1024로 고정됩니다. 코드에 맞게 조정된 codestral-embed는 최상위 dimensions 옵션을 지원합니다.

import { embed } from "@tanstack/ai";
import { mistralEmbedding } from "@tanstack/ai-mistral";

const result = await embed({
adapter: mistralEmbedding("codestral-embed"),
input: "function add(a, b) { return a + b }",
dimensions: 512,
});

전체 API는 임베딩 가이드를 참조합니다.

환경 변수

환경 변수에 API 키를 설정합니다.

MISTRAL_API_KEY=...

Mistral Console에서 키를 발급받습니다.

지원되는 모델

채팅

  • mistral-large-latest — 대표 범용 모델(128k 컨텍스트)
  • mistral-medium-latest — 비전을 지원하는 멀티모달 중급 모델
  • mistral-small-latest — 빠르고 경제적인 비전 지원 멀티모달 모델
  • ministral-8b-latest — 8B 엣지 모델
  • ministral-3b-latest — 3B 엣지 모델
  • open-mistral-nemo — 오픈 12B 모델

코드

  • codestral-latest — 코드 특화 모델(256k 컨텍스트)

비전

  • pixtral-large-latest — 대형 비전 모델
  • pixtral-12b-2409 — 12B 비전 모델

추론

추론 콘텐츠는 최종 답변 전에 REASONING_* 이벤트로 스트리밍됩니다.

  • magistral-medium-latest — 중급 추론 모델
  • magistral-small-latest — 소형 추론 모델

자세한 내용은 Mistral 모델 비교를 참조합니다.

API 레퍼런스

mistralText(model, config?)

MISTRAL_API_KEY 환경 변수를 사용해 Mistral 텍스트 어댑터를 생성합니다.

매개변수:

  • model — 모델 이름(예: 'mistral-large-latest')
  • config.serverURL? — 사용자 지정 기본 URL(선택 사항)
  • config.defaultHeaders? — 모든 요청에 추가할 헤더(선택 사항)

반환값: Mistral 텍스트 어댑터 인스턴스입니다.

createMistralText(model, apiKey, config?)

명시적인 API 키로 Mistral 텍스트 어댑터를 생성합니다.

Parameters:

  • model — 모델 이름
  • apiKey — Mistral API 키
  • config.serverURL? — 사용자 지정 기본 URL(선택 사항)
  • config.defaultHeaders? — 모든 요청에 추가할 헤더(선택 사항)

반환값: Mistral 텍스트 어댑터 인스턴스입니다.

제한 사항

  • 임베딩: mistral-embed에는 Mistral SDK를 직접 사용합니다.
  • 이미지 / 오디오 / 동영상 생성: Mistral은 이러한 엔드포인트를 제공하지 않습니다. OpenAI, Gemini 또는 fal.ai를 사용합니다.
  • 음성 합성 / 전사: 지원되지 않습니다. OpenAI 또는 ElevenLabs를 사용합니다.

다음 단계

프로바이더 도구

Mistral은 현재 프로바이더별 도구 팩토리를 노출하지 않습니다. @tanstack/aitoolDefinition()으로 직접 도구를 정의합니다.

일반적인 도구 정의 흐름은 도구를, 다른 프로바이더의 네이티브 도구 제공 기능은 프로바이더 도구를 참조합니다.