Mistral AI Chat
Mistral AI Chat
Spring AI는 Mistral AI의 다양한 언어 모델을 지원해요. Mistral 모델과 대화하면서 Mistral 기반의 다국어 대화형 비서를 만들 수 있어요.
출처: 공식문서
사전 준비
Mistral AI 언어 모델에 접근하려면 Mistral AI에서 API 키를 만들어야 해요.
Spring AI 프로젝트는 spring.ai.mistralai.api-key라는 구성 속성을 정의하는데, console.mistral.ai에서 얻은 API Key 값을 이 속성에 설정하면 돼요. application.properties 파일에 다음과 같이 설정해요.
spring.ai.mistralai.api-key=<your-mistralai-api-key>
API 키 같은 민감 정보를 다룰 때 보안을 강화하려면 Spring Expression Language(SpEL)로 사용자 정의 환경 변수를 참조할 수 있어요.
# In application.yml spring: ai: mistralai: api-key: ${MISTRALAI_API_KEY}
# In your environment or .env file export MISTRALAI_API_KEY=<your-mistralai-api-key>
애플리케이션 코드에서 프로그래밍 방식으로도 설정할 수 있어요.
// Retrieve API key from a secure source or environment variable String apiKey = System.getenv("MISTRALAI_API_KEY");
저장소와 BOM 추가
Spring AI 아티팩트는 Maven Central과 Spring Snapshot 저장소에 게시돼요. Artifact Repositories 섹션을 참고해 빌드 시스템에 저장소를 추가해요.
의존성 관리를 돕기 위해 Spring AI는 일관된 버전을 보장하는 BOM(일자재 명세서)을 제공해요. Dependency Management 섹션을 참고해 Spring AI BOM을 빌드 시스템에 추가해요.
자동 설정 (Auto-configuration)
Spring AI의 자동 설정과 스타터 모듈의 아티팩트 이름이 크게 바뀌었어요. 자세한 내용은 업그레이드 노트를 확인해주세요.
Spring AI는 Mistral AI 채팅 클라이언트를 위한 Spring Boot 자동 설정을 제공해요. Maven pom.xml에 다음 의존성을 추가하면 돼요.
<dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-starter-model-mistral-ai</artifactId> </dependency>
또는 Gradle build.gradle 파일에 추가해요.
dependencies { implementation 'org.springframework.ai:spring-ai-starter-model-mistral-ai' }
채팅 속성 (Chat Properties)
재시도 속성
Mistral AI 채팅 모델의 재시도 메커니즘을 구성하는 프리픽스는 spring.ai.retry예요.
| 속성 | 설명 | 기본값 |
|---|---|---|
| spring.ai.retry.max-attempts | 최대 재시도 횟수 | 10 |
| spring.ai.retry.backoff.initial-interval | 지수 백오프 정책의 초기 대기 시간 | 2 sec. |
| spring.ai.retry.backoff.multiplier | 백오프 간격 배수 | 5 |
| spring.ai.retry.backoff.max-interval | 최대 백오프 지속 시간 | 3 min. |
| spring.ai.retry.on-client-errors | false면 NonTransientAiException을 던지고 4xx 클라이언트 오류에 재시도하지 않음 |
false |
| spring.ai.retry.exclude-on-http-codes | 재시도를 트리거하지 않아야 하는 HTTP 상태 코드 목록 (예: NonTransientAiException 발생용) | empty |
| spring.ai.retry.on-http-codes | 재시도를 트리거해야 하는 HTTP 상태 코드 목록 (예: TransientAiException 발생용) | empty |
연결 속성
OpenAI에 연결하기 위한 프리픽스는 spring.ai.mistralai예요.
연결 속성 | 속성 | 설명 | 기본값 | |---|---|---| | spring.ai.mistralai.base-url | 연결할 URL | | | spring.ai.mistralai.api-key | API 키 | - |
구성 속성
채팅 자동 설정의 활성·비활성은 프리픽스 spring.ai.model.chat로 관리해요. 활성화하려면 spring.ai.model.chat=mistral(기본값), 비활성화하려면 spring.ai.model.chat=none을 쓰면 돼요.
Mistral AI의 채팅 모델 구현을 구성하는 프리픽스는 spring.ai.mistralai.chat이에요.
| 속성 | 설명 | 기본값 |
|---|---|---|
| spring.ai.mistralai.chat.enabled (제거됨, 더는 유효하지 않음) | Mistral AI 채팅 모델 활성화 | true |
| spring.ai.model.chat | Mistral AI 채팅 모델 활성화 | mistral |
| spring.ai.mistralai.chat.base-url | 채팅 전용 URL을 제공하기 위한 spring.ai.mistralai.base-url의 선택적 재정의 |
- |
| spring.ai.mistralai.chat.api-key | 채팅 전용 API 키를 제공하기 위한 spring.ai.mistralai.api-key의 선택적 재정의 |
- |
| spring.ai.mistralai.chat.model | 사용할 Mistral AI 채팅 모델 | open-mistral-7b, open-mixtral-8x7b, open-mixtral-8x22b, mistral-small-latest, mistral-large-latest |
| spring.ai.mistralai.chat.temperature | 생성 완료의 창의성을 제어하는 샘플링 온도. 높을수록 출력이 더 무작위, 낮을수록 더 집중적이고 결정적이에요. 같은 요청에서 temperature와 top_p를 함께 수정하는 건 권장하지 않아요. |
0.8 |
| spring.ai.mistralai.chat.max-tokens | 채팅 완료에서 생성할 최대 토큰 수. 입력 토큰과 생성 토큰의 총 길이는 모델의 컨텍스트 길이로 제한돼요. | - |
| spring.ai.mistralai.chat.safe-prompt | 모든 대화 앞에 보안 프롬프트를 주입할지 여부 | false |
| spring.ai.mistralai.chat.random-seed | Beta 기능. 지정하면 시스템이 결정적으로 샘플링하도록 최선을 다해, 동일한 seed와 파라미터로 반복 요청 시 동일한 결과를 반환해요. | - |
| spring.ai.mistralai.chat.stop | 이 토큰이 감지되면 생성을 중지. 배열을 제공하면 이 토큰 중 하나가 감지되면 중지. | - |
| spring.ai.mistralai.chat.top-p | nucleus sampling이라 불리는 temperature 대안. top_p 확률 질량을 가진 토큰의 결과를 고려해요. 0.1은 상위 10% 확률 질량만 구성하는 토큰만 고려한다는 뜻. 이 값이나 temperature 중 하나만 수정하는 걸 권장해요. |
- |
| spring.ai.mistralai.chat.response-format | 모델이 출력해야 하는 형식을 지정하는 객체. { "type": "json_object" }로 설정하면 JSON 모드가 켜져 생성 메시지가 유효한 JSON임을 보장해요. { "type": "json_schema" }와 함께 스키마를 제공하면 네이티브 구조화 출력이 활성화돼 제공한 JSON 스키마와 일치함을 보장해요. |
- |
| spring.ai.mistralai.chat.reasoning-effort | 조정 가능한 reasoning 모델의 추론 노력 수준 제어. high 또는 none 중 유효. |
- |
| spring.ai.mistralai.chat.tools | 모델이 호출할 수 있는 도구 목록. 현재 함수만 도구로 지원돼요. 모델이 JSON 입력을 생성할 수 있는 함수 목록을 제공할 때 사용해요. | - |
| spring.ai.mistralai.chat.tool-choice | 모델이 호출하는 함수(있는 경우)를 제어. none은 모델이 함수를 호출하지 않고 메시지를 생성. auto는 메시지 생성과 함수 호출 사이에서 모델이 선택. 특정 함수를 지정하면({"type: "function", "function": {"name": "my_function"}}) 그 함수를 강제로 호출. 함수가 없으면 none이 기본, 함수가 있으면 auto가 기본. |
- |
| spring.ai.mistralai.chat.tool-callbacks | ChatModel에 등록할 Tool 콜백 | - |
공통 spring.ai.mistralai.base-url과 spring.ai.mistralai.api-key를 ChatModel과 EmbeddingModel 구현에 대해 재정의할 수 있어요. spring.ai.mistralai.chat.base-url과 spring.ai.mistralai.chat.api-key 속성이 설정되면 공통 속성보다 우선해요. 서로 다른 모델·모델 엔드포인트에 다른 Mistral AI 계정을 쓰고 싶을 때 유용해요.
spring.ai.mistralai.chat 프리픽스가 붙은 모든 속성은 Prompt 호출에 요청별 runtime 옵션을 추가해 런타임에 덮어쓸 수 있어요.
런타임 옵션
MistralAiChatOptions.java는 사용할 모델, temperature, frequency penalty 같은 모델 구성을 제공해요.
시작 시 기본 옵션은 MistralAiChatModel(api, options) 생성자나 spring.ai.mistralai.chat.* 속성으로 구성해요. 런타임에는 Prompt 호출에 요청별 옵션을 추가해 기본값을 덮어쓸 수 있어요. 특정 요청의 기본 모델과 temperature를 덮어쓰는 예시예요.
ChatResponse response = chatModel.call( new Prompt( "Generate the names of 5 famous pirates.", MistralAiChatOptions.builder() .model(MistralAiApi.ChatModel.MISTRAL_LARGE.getValue()) .temperature(0.5) .build() ));
함수 호출 (Function Calling)
MistralAiChatModel에 사용자 정의 Java 함수를 등록하고, Mistral AI 모델이 등록된 함수 중 하나 이상을 호출하는 인자를 담은 JSON 객체를 출력하도록 지능적으로 선택하게 할 수 있어요. LLM 기능을 외부 도구·API와 연결하는 강력한 기법이에요. 자세한 내용은 Tool Calling을 참고해요.
MistralAiChatModel은 내부적으로 도구 호출을 실행하지 않아요. 도구 실행은 다음 두 가지 지원 방식 중 하나로 외부에서 처리해야 해요.
- ChatClient with ToolCallingAdvisor — 대부분의 사용 사례에 권장되는 방식.
ToolCallingAdvisor가 자동 등록되어 도구 호출 루프를 투명하게 관리해요. - User-controlled tool execution — 루프를 완전히 제어해야 할 때
DefaultToolCallingManager를 직접 사용.
ChatClient를 통한 도구 호출 (권장)
동기·스트리밍 도구 실행 모두 ChatClient와 ToolCallingAdvisor를 사용해요. 도구가 있으면 ToolCallingAdvisor가 자동 등록되므로 명시적 advisor 구성이 필요 없어요.
ToolCallback weatherCallback = FunctionToolCallback.builder("getCurrentWeather", new WeatherService()) .description("Get the weather in location") .inputType(WeatherService.Request.class) .build(); // Synchronous String response = ChatClient.create(chatModel) .prompt() .user("What's the weather in Paris, Tokyo, and New York?") .tools(weatherCallback) .call() .content(); // Streaming Flux<String> stream = ChatClient.create(chatModel) .prompt() .user("What's the weather in Paris, Tokyo, and New York?") .tools(weatherCallback) .stream() .content();
사용자 제어 도구 실행
MistralAiChatModel을 직접 사용하면서 도구 호출 루프를 직접 제어하고 싶다면 DefaultToolCallingManager를 사용해요. 이 경우 모델이 반환한 도구 호출을 직접 읽어 원하는 도구를 실행하고 그 결과를 다시 모델에 보내는 루프를 직접 짜야 해요.
수동 설정
Gradle build.gradle 파일에 다음과 같이 추가해요.
dependencies { implementation 'org.springframework.ai:spring-ai-mistral-ai' }
다음으로 MistralAiChatModel을 만들어 텍스트 생성에 사용해요.
var mistralAiApi = new MistralAiApi(System.getenv("MISTRAL_AI_API_KEY")); var chatModel = new MistralAiChatModel(this.mistralAiApi, MistralAiChatOptions.builder() .model(MistralAiApi.ChatModel.MISTRAL_LARGE.getValue()) .temperature(0.4) .maxTokens(200) .build()); ChatResponse response = this.chatModel.call( new Prompt("Generate the names of 5 famous pirates.")); // Or with streaming responses Flux<ChatResponse> response = this.chatModel.stream( new Prompt("Generate the names of 5 famous pirates."));
MistralAiChatOptions는 채팅 요청의 구성 정보를 제공하고, MistralAiChatOptions.Builder는 플루언트 옵션 빌더예요.
저수준 MistralAiApi 클라이언트
API를 프로그래밍 방식으로 사용하는 간단한 예시예요.
MistralAiApi mistralAiApi = new MistralAiApi(System.getenv("MISTRAL_AI_API_KEY")); ChatCompletionMessage chatCompletionMessage = new ChatCompletionMessage("Hello world", Role.USER); // Sync request ResponseEntity<ChatCompletion> response = this.mistralAiApi.chatCompletionEntity( new ChatCompletionRequest(List.of(this.chatCompletionMessage), MistralAiApi.ChatModel.MISTRAL_LARGE.getValue(), 0.8, false)); // Streaming request Flux<ChatCompletionChunk> streamResponse = this.mistralAiApi.chatCompletionStream( new ChatCompletionRequest(List.of(this.chatCompletionMessage), MistralAiApi.ChatModel.MISTRAL_LARGE.getValue(), 0.8, true));
MistralAiApi 샘플
- MistralAiApiIT.java 테스트는 가벼운 라이브러리 사용의 일반적인 예시를 제공해요.
- PaymentStatusFunctionCallingIT.java 테스트는 저수준 API로 도구 함수를 호출하는 방법을 보여줘요.
Mistral AI OCR
Spring AI는 Mistral AI의 광학 문자 인식(OCR)을 지원해요. 문서에서 텍스트·이미지 데이터를 추출할 수 있어요.
의존성 추가
Mistral AI OCR API를 사용하려면 spring-ai-mistral-ai 의존성을 추가해야 해요.
<dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-mistral-ai</artifactId> </dependency>
또는 Gradle build.gradle 파일에 추가해요.
dependencies { implementation 'org.springframework.ai:spring-ai-mistral-ai' }
저수준 MistralOcrApi 클라이언트
API를 프로그래밍 방식으로 사용하는 간단한 예시예요.
MistralOcrApi mistralAiApi = new MistralOcrApi(System.getenv("MISTRAL_AI_API_KEY")); String documentUrl = "https://arxiv.org/pdf/2201.04234"; MistralOcrApi.OCRRequest request = new MistralOcrApi.OCRRequest( MistralOcrApi.OCRModel.MISTRAL_OCR_LATEST.getValue(), "test_id", new MistralOcrApi.OCRRequest.DocumentURLChunk(documentUrl), List.of(0, 1, 2), true, 5, 50); ResponseEntity<MistralOcrApi.OCRResponse> response = mistralAiApi.ocr(request);
MistralOcrApi 샘플
- MistralOcrApiIT.java 테스트는 가벼운 라이브러리 사용의 일반적인 예시를 제공해요.