Mistral AI API
Mistral AI API
LiteLLM에서 Mistral AI의 모든 모델을 사용하는 방법을 알아봐요. 채팅 완성, 함수 호출, 추론, 오디오 전사, 임베딩까지 지원해요.
출처: 문서
본문
API 키
# env variable
os.environ['MISTRAL_API_KEY']
사용 예시
from litellm import completion
import os
os.environ['MISTRAL_API_KEY'] = ""
response = completion(
model="mistral/mistral-tiny",
messages=[
{"role": "user", "content": "hello from litellm"}
],
)
print(response)
사용 예시 - 스트리밍
from litellm import completion
import os
os.environ['MISTRAL_API_KEY'] = ""
response = completion(
model="mistral/mistral-tiny",
messages=[
{"role": "user", "content": "hello from litellm"}
],
stream=True
)
for chunk in response:
print(chunk)
LiteLLM Proxy 사용법
1. config.yaml에 Mistral 모델 설정
model_list:
- model_name: mistral-small-latest
litellm_params:
model: mistral/mistral-small-latest
api_key: "os.environ/MISTRAL_API_KEY" # ensure you have `MISTRAL_API_KEY` in your .env
2. Proxy 시작
litellm --config config.yaml
3. 테스트
curl --location 'http://0.0.0.0:4000/chat/completions' \
--header 'Content-Type: application/json' \
--data ' {
"model": "mistral-small-latest",
"messages": [
{
"role": "user",
"content": "what llm are you"
}
]
}
'
import openai
client = openai.OpenAI(
api_key="anything",
base_url="http://0.0.0.0:4000"
)
response = client.chat.completions.create(model="mistral-small-latest", messages = [
{
"role": "user",
"content": "this is a test request, write a short poem"
}
])
print(response)
from langchain.chat_models import ChatOpenAI
from langchain.prompts.chat import (
ChatPromptTemplate,
HumanMessagePromptTemplate,
SystemMessagePromptTemplate,
)
from langchain.schema import HumanMessage, SystemMessage
chat = ChatOpenAI(
openai_api_base="http://0.0.0.0:4000", # set openai_api_base to the LiteLLM Proxy
model = "mistral-small-latest",
temperature=0.1
)
messages = [
SystemMessage(
content="You are a helpful assistant that im using to make a test request to."
),
HumanMessage(
content="test from litellm. tell me why it's amazing in 1 sentence"
),
]
response = chat(messages)
print(response)
지원 모델
info: https://docs.mistral.ai/platform/endpoints 에 있는 모든 모델이 지원돼요. LiteLLM이 모델 목록, 가격, 토큰 윈도우 등을 여기서 적극 유지·관리하고 있어요.
| 모델명 | 함수 호출 | Reasoning 지원 |
|---|---|---|
| Mistral Small | completion(model="mistral/mistral-small-latest", messages) |
No |
| Mistral Medium | completion(model="mistral/mistral-medium-latest", messages) |
No |
| Mistral Large 2 | completion(model="mistral/mistral-large-2407", messages) |
No |
| Mistral Large Latest | completion(model="mistral/mistral-large-latest", messages) |
No |
| Magistral Small | completion(model="mistral/magistral-small-2506", messages) |
Yes |
| Magistral Medium | completion(model="mistral/magistral-medium-2506", messages) |
Yes |
| Mistral 7B | completion(model="mistral/open-mistral-7b", messages) |
No |
| Mixtral 8x7B | completion(model="mistral/open-mixtral-8x7b", messages) |
No |
| Mixtral 8x22B | completion(model="mistral/open-mixtral-8x22b", messages) |
No |
| Codestral | completion(model="mistral/codestral-latest", messages) |
No |
| Mistral NeMo | completion(model="mistral/open-mistral-nemo", messages) |
No |
| Mistral NeMo 2407 | completion(model="mistral/open-mistral-nemo-2407", messages) |
No |
| Codestral Mamba | completion(model="mistral/open-codestral-mamba", messages) |
No |
| Codestral Mamba | completion(model="mistral/codestral-mamba-latest"", messages) |
No |
함수 호출
from litellm import completion
# set env
os.environ["MISTRAL_API_KEY"] = "your-api-key"
tools = [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "Get the current weather in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
},
"required": ["location"],
},
},
}
]
messages = [{"role": "user", "content": "What's the weather like in Boston today?"}]
response = completion(
model="mistral/mistral-large-latest",
messages=messages,
tools=tools,
tool_choice="auto",
)
# Add any assertions, here to check response args
print(response)
assert isinstance(response.choices[0].message.tool_calls[0].function.name, str)
assert isinstance(
response.choices[0].message.tool_calls[0].function.arguments, str
)
추론 (Reasoning)
Mistral은 추론을 직접 지원하지 않고, magistral 모델에 사용할 특정 시스템 프롬프트를 권장해요. reasoning_effort 파라미터를 설정하면 LiteLLM이 요청 앞에 시스템 프롬프트를 붙여줘요.
기존 시스템 메시지가 있으면 LiteLLM은 두 시스템 메시지를 목록으로 보내요(litellm._turn_on_debug()로 확인 가능).
지원 모델
| 모델명 | 함수 호출 |
|---|---|
| Magistral Small | completion(model="mistral/magistral-small-2506", messages) |
| Magistral Medium | completion(model="mistral/magistral-medium-2506", messages) |
Reasoning Effort 사용
reasoning_effort 파라미터는 모델이 추론에 투자하는 노력을 제어해요. magistral 모델과 함께 사용돼요.
from litellm import completion
import os
os.environ['MISTRAL_API_KEY'] = "your-api-key"
response = completion(
model="mistral/magistral-medium-2506",
messages=[
{"role": "user", "content": "What is 15 multiplied by 7?"}
],
reasoning_effort="medium" # Options: "low", "medium", "high"
)
print(response)
시스템 메시지가 있는 예시
이미 시스템 메시지가 있다면 LiteLLM이 앞에 추론 지침을 붙여요:
response = completion(
model="mistral/magistral-medium-2506",
messages=[
{"role": "system", "content": "You are a helpful math tutor."},
{"role": "user", "content": "Explain how to solve quadratic equations."}
],
reasoning_effort="high"
)
# The system message becomes:
# "When solving problems, think step-by-step in tags before providing your final answer...
#
# You are a helpful math tutor."
LiteLLM Proxy 사용법
curl --location 'http://0.0.0.0:4000/chat/completions' \
--header 'Content-Type: application/json' \
--data '{
"model": "magistral-medium-2506",
"messages": [
{
"role": "user",
"content": "What is the square root of 144? Show your reasoning."
}
],
"reasoning_effort": "medium"
}'
import openai
client = openai.OpenAI(
api_key="anything",
base_url="http://0.0.0.0:4000"
)
response = client.chat.completions.create(
model="magistral-medium-2506",
messages=[
{
"role": "user",
"content": "Calculate the area of a circle with radius 5. Show your work."
}
],
reasoning_effort="high"
)
print(response)
중요 참고
- 모델 호환성: 추론 파라미터는 magistral 모델에서만 동작
- 하위 호환성: 비-magistral 모델은 추론 파라미터를 무시하고 정상 동작
오디오 전사
litellm.transcription()으로 Mistral의 Voxtral 모델을 사용해 오디오를 전사해요.
SDK 사용법
from litellm import transcription
import os
os.environ["MISTRAL_API_KEY"] = ""
audio_file = open("path/to/audio.wav", "rb")
response = transcription(
model="mistral/voxtral-mini-latest",
file=audio_file,
)
print(response.text)
선택 파라미터와 함께
response = transcription(
model="mistral/voxtral-mini-latest",
file=audio_file,
language="en",
temperature=0.0,
response_format="json",
)
Mistral 전용 파라미터
Mistral은 OpenAI 호환 파라미터 외에 추가 파라미터를 지원해요:
| 파라미터 | 타입 | 설명 |
|---|---|---|
diarize |
bool |
화자 분리(diarization) 활성화 |
response = transcription(
model="mistral/voxtral-mini-latest",
file=audio_file,
diarize=True,
)
LiteLLM Proxy 사용법
model_list:
- model_name: voxtral
litellm_params:
model: mistral/voxtral-mini-latest
api_key: os.environ/MISTRAL_API_KEY
model_info:
mode: audio_transcription
litellm --config /path/to/config.yaml
curl --location 'http://0.0.0.0:4000/v1/audio/transcriptions' \
--header "Authorization: Bearer ***" \
--form 'file=@"audio.wav"' \
--form 'model="voxtral"'
Files and Batches API
LiteLLM은 OpenAI 호환 /v1/files와 /v1/batches 엔드포인트를 Mistral의 Files 및 Batch API로 라우팅해요. Mistral 배치 작업은 입력 파일의 각 줄마다 하나의 모델을 실행하므로, 모델은 줄 단위가 아닌 파일 업로드 또는 배치 요청 시 한 번 선택돼요. 작업은 /v1/chat/completions 또는 /v1/ocr을 대상으로 할 수 있고, 배치 안의 OCR 페이지는 Mistral의 배치 요금으로 과금돼요.
| 기능 | 지원 |
|---|---|
| 파일 업로드·조회·목록·삭제 | ✅ |
| 파일 콘텐츠 다운로드 | ✅ |
| 배치 생성·조회 | ✅ |
| 배치 목록·취소 | 아직 미지원 |
| 배치 OCR 비용 추적 | ✅ 페이지당, 아래 Batch OCR cost tracking 참고 |
1. config.yaml에 Mistral 모델 추가
model_list:
- model_name: mistral-ocr
litellm_params:
model: mistral/mistral-ocr-latest
api_key: os.environ/MISTRAL_API_KEY
2. 배치 입력 파일 업로드
각 줄은 OpenAI 배치 요청이에요. OCR의 url은 /v1/ocr이고 body는 Mistral OCR 요청이에요:
{"custom_id": "doc-0", "method": "POST", "url": "/v1/ocr", "body": {"document": {"type": "document_url", "document_url": "https://arxiv.org/pdf/2201.04234"}}}
{"custom_id": "doc-1", "method": "POST", "url": "/v1/ocr", "body": {"document": {"type": "document_url", "document_url": "https://arxiv.org/pdf/2201.04234"}}}
업로드와 함께 model을 전달하면 LiteLLM이 해당 배포의 자격 증명으로 파일을 보내고 반환된 파일 id에 모델을 인코딩해요. id를 담은 이후의 모든 호출은 이를 재사용해요.
curl http://0.0.0.0:4000/v1/files \
-H "Authorization: Bearer ***" \
-F purpose="batch" \
-F model="mistral-ocr" \
-F file="@ocr_batch_input.jsonl"
Mistral은 batch, fine-tune, ocr purpose를 받아요. LiteLLM은 user_data를 ocr에 매핑하고, 그 외 purpose(assistants, vision, evals)는 Mistral에 해당 항목이 없어 400으로 거부해요.
3. 배치 생성
endpoint는 OCR 작업 시 /v1/ocr, 채팅 작업 시 /v1/chat/completions이에요. model은 인코딩된 파일 id에서 읽히므로 다시 보내는 것은 선택 사항이에요.
curl http://0.0.0.0:4000/v1/batches \
-H "Authorization: Bearer ***" \
-H "Content-Type: application/json" \
-d '{
"input_file_id": "file-bGl0ZWxsbTo1YTJm...",
"endpoint": "/v1/ocr",
"completion_window": "24h",
"model": "mistral-ocr"
}'
Mistral에는 completion_window가 없으며, 값은 받아 24h로 그대로 반향돼요.
4. 배치 폴링 및 출력 다운로드
curl http://0.0.0.0:4000/v1/batches/batch_bGl0ZWxsbTo1YzU4... \
-H "Authorization: Bearer ***"
Mistral의 작업 상태는 OpenAI 상태로 매핑돼요: QUEUED -> validating, RUNNING -> in_progress, SUCCESS -> completed, FAILED -> failed, TIMEOUT_EXCEEDED -> expired, CANCELLATION_REQUESTED -> cancelling, CANCELLED -> cancelled. 상태가 completed가 되면 output_file_id를 다운로드해요:
curl http://0.0.0.0:4000/v1/files/file-bGl0ZWxsbToyNjE0.../content \
-H "Authorization: Bearer ***"
각 출력 줄은 response.body 아래에 OCR 응답을 담고 있으며, usage_info.pages_processed를 포함해요.
파일 목록
LiteLLM이 인코딩한 파일 id는 자체 라우팅을 담지만, 일반 목록은 라우팅할 id가 없으므로 요청에 제공사를 명시해요:
curl "http://0.0.0.0:4000/v1/files?provider=mistral&purpose=batch" \
-H "Authorization: Bearer ***"
OCR 파일은 purpose=user_data로 읽히고, 업로드 엔드포인트가 받지 않는 purpose(playground, audio 등)로 다른 Mistral 제품이 만든 파일도 user_data로 읽히므로 필터링되지 않은 목록은 실패하지 않아요.
배치 OCR 비용 추적
/v1/ocr을 대상으로 하는 배치가 완료되면 LiteLLM은 출력 파일의 모든 줄에서 usage_info.pages_processed와 usage_info.pages_processed_annotation을 읽고 각 페이지를 모델의 배치 요금으로 과금해요. 요금은 모델 비용 맵에서 옵니다:
| 키 | 용도 |
|---|---|
ocr_cost_per_page_batches |
배치 안의 OCR 페이지 |
annotation_cost_per_page_batches |
배치 안의 annotation 페이지 |
ocr_cost_per_page |
동기 /v1/ocr 호출, 배치 요금 미설정 시 폴백 |
annotation_cost_per_page |
동기 annotation 페이지, 배치 요금 미설정 시 폴백 |
mistral/mistral-ocr-latest의 배치 요금은 동기 페이지 요금의 절반으로, Mistral의 50% 배치 할인과 일치해요. 다른 요금으로 과금하려면 해당 배포의 model_info에 키를 설정하세요. 이는 해당 배포의 비용 맵보다 우선해요:
model_list:
- model_name: mistral-ocr
litellm_params:
model: mistral/mistral-ocr-latest
api_key: os.environ/MISTRAL_API_KEY
model_info:
ocr_cost_per_page_batches: 0.002
annotation_cost_per_page_batches: 0.0025
스펜드는 완료된 배치를 처음 조회할 때, 생성한 키에, 배치 id와 _batch_cost 접미사로 기록되며 /spend/logs 라우트와 Admin UI Logs 페이지에 나타나요.
사용 예시 - 임베딩
from litellm import embedding
import os
os.environ['MISTRAL_API_KEY'] = ""
response = embedding(
model="mistral/mistral-embed",
input=["good morning from litellm"],
)
print(response)
지원 모델
https://docs.mistral.ai/platform/endpoints 에 있는 모든 모델이 지원돼요.
| 모델명 | 함수 호출 |
|---|---|
| Mistral Embeddings | embedding(model="mistral/mistral-embed", input) |
더 알아보기 (Learn more)
- Mistral AI 공식 문서
- Mistral API 엔드포인트