ChatMistralAI 통합

ChatMistralAI 통합

LangChain JavaScript로 ChatMistralAI 채팅 모델과 통합하는 방법을 안내할게요.

출처: 문서

본문

Mistral AI는 자사의 강력한 오픈소스 모델 호스팅을 제공하는 플랫폼이에요.

이 문서는 Mistral 채팅 모델을 시작하는 데 도움을 줘요. 모든 ChatMistralAI 기능과 구성에 대한 자세한 문서는 API 레퍼런스를 참고하세요.

개요

통합 세부 정보

클래스 패키지 Serializable PY 지원 Downloads Version
ChatMistralAI @langchain/mistralai NPM - Downloads NPM - Version

모델 기능

아래 표 헤더의 링크에서 특정 기능을 사용하는 방법에 대한 가이드를 확인할 수 있어요.

Tool calling Structured output Image input Audio input Video input Token-level streaming Token usage Logprobs

설정

Mistral AI 모델에 접근하려면 Mistral AI 계정을 만들고 API 키를 받은 뒤 @langchain/mistralai 통합 패키지를 설치해야 해요.

자격 증명

Mistral 콘솔을 방문해 가입하고 API 키를 생성하세요. 완료되면 MISTRAL_API_KEY 환경 변수를 설정하세요:

export MISTRAL_API_KEY="your-api-key"

모델 호출의 자동 추적(tracing)을 원한다면 아래 주석을 해제해 LangSmith API 키를 설정할 수도 있어요:

# export LANGSMITH_TRACING="true"
# export LANGSMITH_API_KEY="your-api-key"

설치

LangChain ChatMistralAI 통합은 @langchain/mistralai 패키지에 있어요:

```bash npm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}} npm install @langchain/mistralai @langchain/core ```
yarn add @langchain/mistralai @langchain/core
pnpm add @langchain/mistralai @langchain/core

인스턴스 생성

이제 모델 객체를 생성하고 채팅 완성을 생성할 수 있어요:

import { ChatMistralAI } from "@langchain/mistralai"

const llm = new ChatMistralAI({
    model: "mistral-large-latest",
    temperature: 0,
    maxRetries: 2,
    // other params...
})

호출

Mistral에 채팅 메시지를 보낼 때 따라야 할 몇 가지 요구사항이 있어요:

  • 첫 번째 메시지는 assistant (ai) 메시지가 될 수 없어요.
  • 메시지는 user와 assistant (ai) 메시지가 반드시 번갈아 와야 해요.
  • 메시지는 assistant (ai) 또는 system 메시지로 끝날 수 없어요.
const aiMsg = await llm.invoke([
    [
        "system",
        "You are a helpful assistant that translates English to French. Translate the user sentence.",
    ],
    ["human", "I love programming."],
])
aiMsg
AIMessage {
  "content": "J'adore la programmation.",
  "additional_kwargs": {},
  "response_metadata": {
    "tokenUsage": {
      "completionTokens": 9,
      "promptTokens": 27,
      "totalTokens": 36
    },
    "finish_reason": "stop"
  },
  "tool_calls": [],
  "invalid_tool_calls": [],
  "usage_metadata": {
    "input_tokens": 27,
    "output_tokens": 9,
    "total_tokens": 36
  }
}
console.log(aiMsg.content)
J'adore la programmation.

Tool calling

Mistral의 API는 일부 모델에 대해 tool calling을 지원해요. 어떤 모델이 tool calling을 지원하는지는 이 페이지에서 확인할 수 있어요.

아래 예제는 사용 방법을 보여줘요:

import { ChatMistralAI } from "@langchain/mistralai";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import * as z from "zod";
import { tool } from "@langchain/core/tools";

const calculatorSchema = z.object({
  operation: z
    .enum(["add", "subtract", "multiply", "divide"])
    .describe("The type of operation to execute."),
  number1: z.number().describe("The first number to operate on."),
  number2: z.number().describe("The second number to operate on."),
});

const calculatorTool = tool((input) => {
  return JSON.stringify(input);
}, {
  name: "calculator",
  description: "A simple calculator tool",
  schema: calculatorSchema,
});

// Bind the tool to the model
const modelWithTool = new ChatMistralAI({
  model: "mistral-large-latest",
}).bindTools([calculatorTool]);


const calcToolPrompt = ChatPromptTemplate.fromMessages([
  [
    "system",
    "You are a helpful assistant who always needs to use a calculator.",
  ],
  ["human", "{input}"],
]);

// Chain your prompt, model, and output parser together
const chainWithCalcTool = calcToolPrompt.pipe(modelWithTool);

const calcToolRes = await chainWithCalcTool.invoke({
  input: "What is 2 + 2?",
});
console.log(calcToolRes.tool_calls);
[
  {
    name: 'calculator',
    args: { operation: 'add', number1: 2, number2: 2 },
    type: 'tool_call',
    id: 'DD9diCL1W'
  }
]

훅 (Hooks)

Mistral AI는 세 가지 이벤트에 대한 커스텀 훅을 지원해요: beforeRequest, requestError, response. 각 훅 유형의 함수 시그니처 예시는 아래에서 확인할 수 있어요:

const beforeRequestHook = (req: Request): Request | void | Promise<Request | void> => {
    // Code to run before a request is processed by Mistral
};

const requestErrorHook = (err: unknown, req: Request): void | Promise<void> => {
    // Code to run when an error occurs as Mistral is processing a request
};

const responseHook = (res: Response, req: Request): void | Promise<void> => {
    // Code to run before Mistral sends a successful response
};

이 훅들을 채팅 모델에 추가하려면 인자로 전달하면 자동으로 추가돼요:

import { ChatMistralAI } from "@langchain/mistralai"

const modelWithHooks = new ChatMistralAI({
    model: "mistral-large-latest",
    temperature: 0,
    maxRetries: 2,
    beforeRequestHooks: [ beforeRequestHook ],
    requestErrorHooks: [ requestErrorHook ],
    responseHooks: [ responseHook ],
    // other params...
});

또는 인스턴스 생성 후 수동으로 할당하고 추가할 수도 있어요:

import { ChatMistralAI } from "@langchain/mistralai"

const model = new ChatMistralAI({
    model: "mistral-large-latest",
    temperature: 0,
    maxRetries: 2,
    // other params...
});

model.beforeRequestHooks = [ ...model.beforeRequestHooks, beforeRequestHook ];
model.requestErrorHooks = [ ...model.requestErrorHooks, requestErrorHook ];
model.responseHooks = [ ...model.responseHooks, responseHook ];

model.addAllHooksToHttpClient();

addAllHooksToHttpClient 메서드는 훅 중복을 피하기 위해 업데이트된 전체 훅 목록을 할당하기 전에 현재 추가된 모든 훅을 지워요.

훅은 하나씩 제거하거나 한 번에 모두 지울 수 있어요.

model.removeHookFromHttpClient(beforeRequestHook);

model.removeAllHooksFromHttpClient();

API 레퍼런스

모든 ChatMistralAI 기능과 구성에 대한 자세한 문서는 API 레퍼런스를 참고하세요.


[Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers. [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/oss/javascript/integrations/chat/mistral.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).

더 알아보기