Mistral Large 4 · 在应用中调用 Mistral

服务端接入清单、最小请求示例与流式处理说明。

本页目录

服务端接入

将自己的 Mistral 提供方密钥放入 MISTRAL_API_KEY,不放浏览器。示例使用 Node.js 24+、Python 3.11+ 和 cURL,运行前下载下方对应文件。调用使用提供方账户,与本站积分分开。

示例

cURL

代码
#!/usr/bin/env sh
# Server-side cURL example; set your own provider key. No automatic retry.
# Source: https://docs.mistral.ai/api/endpoint/chat; checked 2026-10-12.
set -eu
: "${MISTRAL_API_KEY:?Set MISTRAL_API_KEY on the server}"
curl --fail --silent --show-error --max-time 35 \
  https://api.mistral.ai/v1/chat/completions \
  -H "Authorization: Bearer $MISTRAL_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"model":"mistral-large-4","messages":[{"role":"user","content":"Explain safe retries in three sentences."}],"max_tokens":1024}'

Python

代码
"""Python 3.11+ standard-library example; importing makes no request.
Source: https://docs.mistral.ai/api/endpoint/chat; checked 2026-10-12.
Run: python mistral-chat.py [text|json|image|stream] [public HTTPS image URL]
"""
import json, os, sys, urllib.request, urllib.error, urllib.parse

def body(mode='text', image_url=None):
    content = 'Explain safe retries in three sentences.'
    result = {'model': 'mistral-large-4', 'max_tokens': 1024, 'stream': mode == 'stream'}
    if mode == 'image':
        image = urllib.parse.urlparse(image_url or '')
        if image.scheme != 'https' or not image.hostname or image.username or image.password:
            raise ValueError('Use a public HTTPS image URL')
        content = [{'type': 'text', 'text': 'Describe visible labels; mark unreadable text.'}, {'type': 'image_url', 'image_url': image_url}]
    if mode == 'json':
        content = 'Return JSON with a string summary and an array of string checks for safe retries.'
        result['response_format'] = {'type': 'json_schema', 'json_schema': {'name': 'retry_summary', 'strict': True, 'schema': {'type': 'object', 'properties': {'summary': {'type': 'string'}, 'checks': {'type': 'array', 'items': {'type': 'string'}}}, 'required': ['summary', 'checks'], 'additionalProperties': False}}}
    result['messages'] = [{'role': 'user', 'content': content}]
    return result

def validate_summary(text):
    value = json.loads(text)
    if not isinstance(value, dict) or set(value) != {'summary', 'checks'} or not isinstance(value['summary'], str) or not isinstance(value['checks'], list) or not all(isinstance(item, str) for item in value['checks']):
        raise ValueError('JSON did not match the requested schema')
    return value

def chat(key, mode='text', image_url=None, opener=urllib.request.urlopen):
    if not key:
        raise ValueError('Set MISTRAL_API_KEY on the server')
    request = urllib.request.Request('https://api.mistral.ai/v1/chat/completions', data=json.dumps(body(mode, image_url)).encode(), headers={'Authorization': 'Bearer ' + key, 'Content-Type': 'application/json'})
    try:
        with opener(request, timeout=35) as response:
            if mode != 'stream':
                result = json.load(response); choices = result.get('choices') or []
                if not choices or not isinstance(choices[0].get('message', {}).get('content'), str):
                    raise ValueError('Provider returned no text choice')
                if choices[0].get('finish_reason') == 'length':
                    raise ValueError('Output reached its token limit')
                text = choices[0]['message']['content']
                return validate_summary(text) if mode == 'json' else text
            text = ''; data = []; done = False; limited = False
            for line in response:
                line = line.decode().rstrip('\r\n')
                if line.startswith('data:'):
                    data.append(line[5:].lstrip())
                if line == '' and data:
                    payload = '\n'.join(data); data = []
                    if payload == '[DONE]':
                        done = True; break
                    event = json.loads(payload)
                    if event.get('error'):
                        raise ValueError('Provider interrupted the response')
                    for choice in event.get('choices', []):
                        limited |= choice.get('finish_reason') == 'length'
                        delta = choice.get('delta', {}).get('content')
                        if isinstance(delta, str):
                            text += delta
            if not done:
                raise ValueError('Stream interrupted; partial text is not a completed answer')
            if limited or not text:
                raise ValueError('Output was limited or empty')
            return text
    except urllib.error.HTTPError as error:
        # Do not print provider bodies, prompts or credentials.
        if error.code == 429:
            raise RuntimeError('Provider rate limit; Retry-After: ' + (error.headers.get('Retry-After') or 'unspecified')) from None
        raise RuntimeError('Provider request failed (' + str(error.code) + ')') from None

if __name__ == '__main__':
    try:
        mode = sys.argv[1] if len(sys.argv) > 1 else 'text'
        if mode not in {'text', 'json', 'image', 'stream'}:
            raise ValueError('Choose text, json, image or stream')
        result = chat(os.environ.get('MISTRAL_API_KEY', ''), mode, sys.argv[2] if len(sys.argv) > 2 else None)
        print(json.dumps(result, ensure_ascii=False) if isinstance(result, dict) else result)
    except (ValueError, RuntimeError, TimeoutError, urllib.error.URLError, KeyboardInterrupt):
        print('Request did not complete. Check settings, connectivity and rate limits; no automatic retry.', file=sys.stderr)
        sys.exit(1)

TypeScript

代码
// Server-side Node.js 24+ example. Importing this file performs no request.
// Source: https://docs.mistral.ai/api/endpoint/chat (checked 2026-10-12).
export type Mode = 'text' | 'image' | 'json' | 'stream'
export function requestBody(mode: Mode, imageUrl?: string) {
  if (mode === 'image') {
    const image = new URL(imageUrl || '')
    if (image.protocol !== 'https:' || image.username || image.password)
      throw new Error('Use a public HTTPS image URL')
  }
  return {
    model: 'mistral-large-4',
    max_tokens: 1024,
    stream: mode === 'stream',
    messages: [
      {
        role: 'user',
        content:
          mode === 'image'
            ? [
                { type: 'text', text: 'Describe the visible labels; mark unreadable text.' },
                { type: 'image_url', image_url: imageUrl },
              ]
            : mode === 'json'
              ? 'Return JSON with a string summary and an array of string checks for safe retries.'
              : 'Explain safe retries in three sentences.',
      },
    ],
    ...(mode === 'json'
      ? {
          response_format: {
            type: 'json_schema',
            json_schema: {
              name: 'retry_summary',
              strict: true,
              schema: {
                type: 'object',
                properties: {
                  summary: { type: 'string' },
                  checks: { type: 'array', items: { type: 'string' } },
                },
                required: ['summary', 'checks'],
                additionalProperties: false,
              },
            },
          },
        }
      : {}),
  }
}
export function validateSummary(text: string) {
  const value = JSON.parse(text)
  if (
    !value ||
    typeof value !== 'object' ||
    Array.isArray(value) ||
    typeof value.summary !== 'string' ||
    !Array.isArray(value.checks) ||
    !value.checks.every((item: unknown) => typeof item === 'string') ||
    Object.keys(value).some((key) => !['summary', 'checks'].includes(key))
  )
    throw new Error('JSON did not match the requested schema')
  return value as { summary: string; checks: string[] }
}
export class ExampleError extends Error {
  status: number
  retryAfter: string | null
  constructor(status: number, retryAfter: string | null) {
    super(
      status === 429
        ? 'Provider rate limit; inspect Retry-After before retrying'
        : `Provider request failed (${status})`,
    )
    this.status = status
    this.retryAfter = retryAfter
  }
}
export async function chat({
  key,
  mode = 'text',
  imageUrl,
  signal,
  fetcher = fetch,
  onText = () => {},
}: {
  key: string
  mode?: Mode
  imageUrl?: string
  signal?: AbortSignal
  fetcher?: typeof fetch
  onText?: (text: string) => void
}) {
  if (!key) throw new Error('Set MISTRAL_API_KEY on the server')
  const timeout = AbortSignal.timeout(35_000)
  const response = await fetcher('https://api.mistral.ai/v1/chat/completions', {
    method: 'POST',
    signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
    headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },
    body: JSON.stringify(requestBody(mode, imageUrl)),
  })
  if (!response.ok) throw new ExampleError(response.status, response.headers.get('Retry-After'))
  if (mode !== 'stream') {
    const result = await response.json()
    const choice = result.choices?.[0]
    if (!choice || typeof choice.message?.content !== 'string')
      throw new Error('Provider returned no text choice')
    if (choice.finish_reason === 'length') throw new Error('Output reached its token limit')
    return mode === 'json' ? validateSummary(choice.message.content) : choice.message.content
  }
  if (!response.body) throw new Error('Provider returned no stream')
  const reader = response.body.getReader(),
    decoder = new TextDecoder()
  let buffer = '',
    text = '',
    done = false,
    limited = false
  try {
    while (!done) {
      const part = await reader.read()
      buffer += decoder.decode(part.value, { stream: !part.done })
      buffer = buffer.replace(/\r\n/g, '\n')
      let end: number
      while ((end = buffer.indexOf('\n\n')) >= 0) {
        const lines = buffer.slice(0, end).split('\n')
        buffer = buffer.slice(end + 2)
        const data = lines
          .filter((line) => line.startsWith('data:'))
          .map((line) => line.slice(5).trimStart())
          .join('\n')
        if (!data) continue
        if (data === '[DONE]') {
          done = true
          break
        }
        const event = JSON.parse(data)
        if (event.error) throw new Error('Provider interrupted the response')
        for (const choice of event.choices || []) {
          if (choice.finish_reason === 'length') limited = true
          if (typeof choice.delta?.content === 'string') {
            text += choice.delta.content
            onText(choice.delta.content)
          }
        }
      }
      if (part.done) break
    }
    if (!done) throw new Error('Stream interrupted; partial text is not a completed answer')
    if (limited) throw new Error('Output reached its token limit')
    if (!text) throw new Error('Provider returned no text')
    return text
  } finally {
    await reader.cancel().catch(() => {})
    reader.releaseLock()
  }
}

文字、图片、JSON 与流式处理

Python 命令:python mistral-chat.py text;将 text 换成 image、json 或 stream。图片模式第二个参数为公开 HTTPS 图片 URL。导入 TypeScript chat 函数,传入 key、mode 和可选 AbortSignal。导入和下载不会发起请求。

校验与恢复

帮助函数设置 35 秒超时,识别空 choices、处理 HTTP 错误并解析分块 SSE。JSON 在本地再次校验,语法和结构正确不代表事实正确。流中断不算完成;取消或 429 后查看 Retry-After,再决定是否重试,不自动重试。工具授权留在服务端。本地样例验证这些路径,未执行真实提供方请求。

下载服务端示例

TypeScript 与 Python 包含文字、图片 URL、JSON 校验和流式处理。本地样例检查错误与流中断;真实提供方执行尚未验证。

Node.js 24+ · Python 3.11+ · cURL。仅在服务端设置 MISTRAL_API_KEY,下载不会执行请求。

TypeScript ↓Python ↓cURL ↓

试试你自己的任务。

带上原始资料,核查输出结果。

打开聊天