Skip to content

Mistral AI API完全指南

Mistral AI以其开源精神和高性能模型著称,是欧洲AI的代表力量

概述

Mistral AI是法国的AI公司,以开源高性能模型著称。其模型在性能和效率之间取得了良好平衡,适合各种应用场景。本教程将带你全面掌握Mistral AI API的使用方法。

为什么选择Mistral?

优势说明
开源精神多个模型开源,可本地部署
高性能模型性能优秀,性价比高
欧洲合规符合GDPR等欧洲法规
灵活部署支持云端和本地部署

Mistral模型概览

Mistral模型家族:

旗舰模型
├── mistral-large-2411    # 最强能力
├── mistral-large-2407    # 大型模型
└── mistral-medium-2312   # 中型模型

高效模型
├── mistral-small-latest  # 小型高效模型
├── open-mistral-nemo     # 开源中型模型
└── open-mixtral-8x22b    # 开源混合专家模型

专业模型
├── codestral-latest      # 代码专用模型
├── mistral-embed         # 嵌入模型
└── ministral-8b-latest   # 边缘设备模型

基本概念

API Key

php
<?php
// 在Mistral AI官网获取API Key
// https://console.mistral.ai/

// API Key格式
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

$apiKey = getenv('MISTRAL_API_KEY');

兼容性

Mistral API兼容OpenAI API格式:

php
<?php
// Mistral API使用与OpenAI相同的接口格式
// 只需更改base_url和API Key即可
$baseUrl = 'https://api.mistral.ai/v1';

环境准备

创建Mistral客户端

php
<?php
require 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class MistralClient
{
    private $client;
    private $apiKey;
    private $baseUrl = 'https://api.mistral.ai/v1';

    public function __construct(string $apiKey)
    {
        $this->apiKey = $apiKey;
        $this->client = new Client([
            'base_uri' => $this->baseUrl,
            'timeout' => 60,
            'headers' => [
                'Authorization' => 'Bearer ' . $this->apiKey,
                'Content-Type' => 'application/json',
            ],
        ]);
    }

    public function chat(
        array $messages,
        string $model = 'mistral-small-latest',
        array $options = []
    ): array {
        $params = [
            'model' => $model,
            'messages' => $messages,
        ];

        if (isset($options['temperature'])) {
            $params['temperature'] = $options['temperature'];
        }

        if (isset($options['max_tokens'])) {
            $params['max_tokens'] = $options['max_tokens'];
        }

        if (isset($options['top_p'])) {
            $params['top_p'] = $options['top_p'];
        }

        if (isset($options['random_seed'])) {
            $params['random_seed'] = $options['random_seed'];
        }

        try {
            $response = $this->client->post('/chat/completions', [
                'json' => $params,
            ]);

            return json_decode($response->getBody(), true);
        } catch (RequestException $e) {
            $errorBody = $e->getResponse() ? $e->getResponse()->getBody()->getContents() : 'Unknown error';
            throw new Exception('Mistral API Error: ' . $errorBody);
        }
    }
}

// 使用示例
$apiKey = getenv('MISTRAL_API_KEY');
$client = new MistralClient($apiKey);

$result = $client->chat([
    ['role' => 'user', 'content' => '请用一句话介绍PHP语言']
]);

echo $result['choices'][0]['message']['content'];

运行结果:

PHP是一种广泛使用的开源服务器端脚本语言,特别适合Web开发,可以嵌入HTML中执行。

代码专用模型

使用Codestral进行代码生成

php
<?php
class CodeGenerator
{
    private MistralClient $client;

    public function __construct(MistralClient $client)
    {
        $this->client = $client;
    }

    public function generateCode(string $description, string $language = 'PHP'): string
    {
        $result = $this->client->chat(
            [
                ['role' => 'user', 'content' => "请生成{$language}代码:{$description}"]
            ],
            'codestral-latest',
            ['temperature' => 0.2]
        );

        return $result['choices'][0]['message']['content'];
    }

    public function completeCode(string $code, string $language = 'PHP'): string
    {
        $result = $this->client->chat(
            [
                ['role' => 'user', 'content' => "请补全以下{$language}代码:\n```\n{$code}\n```"]
            ],
            'codestral-latest',
            ['temperature' => 0.1]
        );

        return $result['choices'][0]['message']['content'];
    }

    public function explainCode(string $code): string
    {
        $result = $this->client->chat(
            [
                ['role' => 'user', 'content' => "请解释以下代码的功能:\n```\n{$code}\n```"]
            ],
            'codestral-latest'
        );

        return $result['choices'][0]['message']['content'];
    }

    public function debugCode(string $code, string $error): string
    {
        $result = $this->client->chat(
            [
                [
                    'role' => 'user',
                    'content' => "以下代码出错,请帮我修复:\n代码:\n```\n{$code}\n```\n错误信息:{$error}"
                ]
            ],
            'codestral-latest'
        );

        return $result['choices'][0]['message']['content'];
    }
}

// 使用示例
$codeGen = new CodeGenerator($client);

$code = $codeGen->generateCode('实现一个单例模式的数据库连接类');
echo $code;

高级参数配置

完整参数示例

php
<?php
class MistralClient
{
    // ... 前面的代码 ...

    public function chatAdvanced(
        array $messages,
        string $model = 'mistral-small-latest',
        array $options = []
    ): array {
        $params = [
            'model' => $model,
            'messages' => $messages,
        ];

        $optionalParams = [
            'temperature',
            'max_tokens',
            'top_p',
            'random_seed',
            'safe_prompt',
            'response_format',
        ];

        foreach ($optionalParams as $param) {
            if (isset($options[$param])) {
                $params[$param] = $options[$param];
            }
        }

        try {
            $response = $this->client->post('/chat/completions', [
                'json' => $params,
            ]);

            return json_decode($response->getBody(), true);
        } catch (RequestException $e) {
            $errorBody = $e->getResponse() ? $e->getResponse()->getBody()->getContents() : 'Unknown error';
            throw new Exception('Mistral API Error: ' . $errorBody);
        }
    }
}

// 使用示例
$result = $client->chatAdvanced(
    [['role' => 'user', 'content' => '生成一个用户注册表单的HTML代码']],
    'mistral-small-latest',
    [
        'temperature' => 0.7,
        'max_tokens' => 1000,
        'random_seed' => 42,
    ]
);

参数详解

参数范围默认值说明
temperature0-10.7控制随机性
max_tokens1-模型上限无限制最大输出Token
top_p0-11核采样参数
random_seed整数-随机种子,确保可复现
safe_promptbooleanfalse是否过滤敏感内容
response_formatobject-输出格式设置

流式响应处理

php
<?php
class MistralClient
{
    // ... 前面的代码 ...

    public function chatStream(
        array $messages,
        string $model = 'mistral-small-latest'
    ): Generator {
        $response = $this->client->post('/chat/completions', [
            'json' => [
                'model' => $model,
                'messages' => $messages,
                'stream' => true,
            ],
            'stream' => true,
        ]);

        $body = $response->getBody();
        $buffer = '';

        while (!$body->eof()) {
            $chunk = $body->read(1024);
            $buffer .= $chunk;

            while (($pos = strpos($buffer, "\n")) !== false) {
                $line = substr($buffer, 0, $pos);
                $buffer = substr($buffer, $pos + 1);

                $line = trim($line);
                if (empty($line) || $line === 'data: [DONE]') {
                    continue;
                }

                if (strpos($line, 'data: ') === 0) {
                    $json = substr($line, 6);
                    $data = json_decode($json, true);

                    if (isset($data['choices'][0]['delta']['content'])) {
                        yield $data['choices'][0]['delta']['content'];
                    }
                }
            }
        }
    }
}

// 使用示例
echo "Mistral回复:";
foreach ($client->chatStream([['role' => 'user', 'content' => '讲一个程序员笑话']]) as $chunk) {
    echo $chunk;
    flush();
}

文本嵌入

使用Mistral Embed进行向量化

php
<?php
class MistralEmbedding
{
    private $client;
    private $apiKey;

    public function __construct(string $apiKey)
    {
        $this->apiKey = $apiKey;
        $this->client = new Client([
            'base_uri' => 'https://api.mistral.ai/v1',
            'timeout' => 30,
            'headers' => [
                'Authorization' => 'Bearer ' . $this->apiKey,
                'Content-Type' => 'application/json',
            ],
        ]);
    }

    public function embed(array $texts): array
    {
        $response = $this->client->post('/embeddings', [
            'json' => [
                'model' => 'mistral-embed',
                'input' => $texts,
            ],
        ]);

        $result = json_decode($response->getBody(), true);

        $embeddings = [];
        foreach ($result['data'] as $item) {
            $embeddings[] = $item['embedding'];
        }

        return $embeddings;
    }

    public function embedSingle(string $text): array
    {
        $embeddings = $this->embed([$text]);
        return $embeddings[0];
    }

    public function cosineSimilarity(array $a, array $b): float
    {
        $dotProduct = 0;
        $normA = 0;
        $normB = 0;

        for ($i = 0; $i < count($a); $i++) {
            $dotProduct += $a[$i] * $b[$i];
            $normA += $a[$i] * $a[$i];
            $normB += $b[$i] * $b[$i];
        }

        return $dotProduct / (sqrt($normA) * sqrt($normB));
    }

    public function findSimilar(string $query, array $documents, int $topK = 3): array
    {
        $queryEmbedding = $this->embedSingle($query);
        $docEmbeddings = $this->embed($documents);

        $similarities = [];
        foreach ($docEmbeddings as $index => $embedding) {
            $similarities[$index] = $this->cosineSimilarity($queryEmbedding, $embedding);
        }

        arsort($similarities);
        $topIndices = array_slice(array_keys($similarities), 0, $topK, true);

        $results = [];
        foreach ($topIndices as $index) {
            $results[] = [
                'document' => $documents[$index],
                'similarity' => $similarities[$index],
            ];
        }

        return $results;
    }
}

// 使用示例
$embedding = new MistralEmbedding($apiKey);

$documents = [
    'PHP是一种服务器端脚本语言',
    'JavaScript是一种客户端脚本语言',
    'Python是一种通用编程语言',
];

$similar = $embedding->findSimilar('Web开发用什么语言', $documents);
print_r($similar);

常见错误与踩坑点

错误1:模型名称错误

php
<?php
// ❌ 错误做法:使用不存在的模型
$result = $client->chat($messages, 'mistral-7b');

// ✅ 正确做法:使用正确的模型名称
$result = $client->chat($messages, 'mistral-small-latest');
$result = $client->chat($messages, 'codestral-latest'); // 代码专用

错误2:忽略随机种子

php
<?php
// ❌ 错误做法:每次结果不同
$result1 = $client->chat($messages);
$result2 = $client->chat($messages); // 可能不同

// ✅ 正确做法:使用random_seed确保可复现
$result1 = $client->chat($messages, 'mistral-small-latest', ['random_seed' => 42]);
$result2 = $client->chat($messages, 'mistral-small-latest', ['random_seed' => 42]); // 相同

错误3:忽略safe_prompt选项

php
<?php
// ❌ 错误做法:不处理敏感内容
$result = $client->chat($messages);

// ✅ 正确做法:使用safe_prompt过滤
$result = $client->chat($messages, 'mistral-small-latest', ['safe_prompt' => true]);

常见应用场景

场景1:智能代码补全

php
<?php
class IntelligentCodeCompletion
{
    private MistralClient $client;

    public function complete(string $code, string $cursorContext): string
    {
        $prompt = <<<PROMPT
当前代码:


光标位置上下文:{$cursorContext}

请补全代码:
PROMPT;

        $result = $this->client->chat(
            [['role' => 'user', 'content' => $prompt]],
            'codestral-latest',
            ['temperature' => 0.1, 'max_tokens' => 100]
        );

        return $result['choices'][0]['message']['content'];
    }
}

场景2:文档问答系统

php
<?php
class DocumentQA
{
    private MistralClient $client;
    private MistralEmbedding $embedding;
    private array $documents = [];

    public function addDocument(string $id, string $content): void
    {
        $this->documents[$id] = [
            'content' => $content,
            'embedding' => $this->embedding->embedSingle($content),
        ];
    }

    public function ask(string $question): string
    {
        $queryEmbedding = $this->embedding->embedSingle($question);

        $similarities = [];
        foreach ($this->documents as $id => $doc) {
            $similarities[$id] = $this->embedding->cosineSimilarity(
                $queryEmbedding,
                $doc['embedding']
            );
        }

        arsort($similarities);
        $topDocs = array_slice($similarities, 0, 3, true);

        $context = '';
        foreach ($topDocs as $id => $score) {
            $context .= $this->documents[$id]['content'] . "\n\n";
        }

        $result = $this->client->chat([
            [
                'role' => 'user',
                'content' => "根据以下内容回答问题:\n\n{$context}\n\n问题:{$question}"
            ]
        ]);

        return $result['choices'][0]['message']['content'];
    }
}

场景3:多语言翻译

php
<?php
class TranslationService
{
    private MistralClient $client;

    public function translate(string $text, string $from, string $to): string
    {
        $result = $this->client->chat([
            [
                'role' => 'user',
                'content' => "将以下{$from}文本翻译成{$to}:\n\n{$text}"
            ]
        ]);

        return $result['choices'][0]['message']['content'];
    }

    public function batchTranslate(array $texts, string $from, string $to): array
    {
        $results = [];
        foreach ($texts as $key => $text) {
            $results[$key] = $this->translate($text, $from, $to);
        }
        return $results;
    }
}

场景4:内容生成

php
<?php
class ContentGenerator
{
    private MistralClient $client;

    public function generateArticle(string $topic, int $wordCount = 800): string
    {
        $result = $this->client->chat([
            [
                'role' => 'user',
                'content' => "请写一篇关于{$topic}的文章,字数约{$wordCount}字。"
            ]
        ]);

        return $result['choices'][0]['message']['content'];
    }

    public function generateSummary(string $content, int $maxLength = 200): string
    {
        $result = $this->client->chat([
            [
                'role' => 'user',
                'content' => "请将以下内容总结为不超过{$maxLength}字:\n\n{$content}"
            ]
        ]);

        return $result['choices'][0]['message']['content'];
    }
}

场景5:智能助手

php
<?php
class IntelligentAssistant
{
    private MistralClient $client;
    private array $history = [];

    public function chat(string $message, string $systemPrompt = ''): string
    {
        $messages = [];

        if (!empty($systemPrompt)) {
            $messages[] = ['role' => 'system', 'content' => $systemPrompt];
        }

        foreach ($this->history as $item) {
            $messages[] = ['role' => $item['role'], 'content' => $item['content']];
        }

        $messages[] = ['role' => 'user', 'content' => $message];

        $result = $this->client->chat($messages);

        $response = $result['choices'][0]['message']['content'];

        $this->history[] = ['role' => 'user', 'content' => $message];
        $this->history[] = ['role' => 'assistant', 'content' => $response];

        return $response;
    }

    public function clearHistory(): void
    {
        $this->history = [];
    }
}

常见问题答疑(FAQ)

Q1:Mistral和GPT如何选择?

回答

场景推荐选择原因
代码生成Codestral专门优化的代码模型
成本敏感Mistral Small性价比高
开源需求Mistral多个模型开源
欧洲合规Mistral符合GDPR

Q2:如何本地部署Mistral模型?

回答

bash
# 使用Ollama部署
ollama pull mistral

# 使用vLLM部署
pip install vllm
python -m vllm.entrypoints.api_server --model mistralai/Mistral-7B-v0.1

Q3:如何处理API错误?

回答

php
<?php
function handleMistralError(Exception $e): string
{
    $message = $e->getMessage();

    if (strpos($message, '401') !== false) {
        return 'API Key无效';
    }
    if (strpos($message, '429') !== false) {
        return '请求过于频繁';
    }
    if (strpos($message, '500') !== false) {
        return '服务器错误';
    }

    return '服务暂时不可用';
}

Q4:如何选择合适的模型?

回答

场景推荐模型原因
代码生成codestral-latest代码专用
日常对话mistral-small-latest性价比高
复杂推理mistral-large-latest能力强
文本嵌入mistral-embed专用嵌入模型

Q5:如何确保结果可复现?

回答

php
<?php
// 使用random_seed参数
$result = $client->chat(
    $messages,
    'mistral-small-latest',
    [
        'temperature' => 0,
        'random_seed' => 42,
    ]
);

Q6:如何优化Token使用?

回答

php
<?php
// 1. 选择合适的模型
$model = 'mistral-small-latest'; // 简单任务用小模型

// 2. 限制输出长度
$result = $client->chat($messages, $model, ['max_tokens' => 500]);

// 3. 使用缓存
class CachedMistralClient extends MistralClient
{
    private array $cache = [];

    public function chatWithCache(array $messages, string $model = 'mistral-small-latest'): array
    {
        $key = md5($model . serialize($messages));
        if (isset($this->cache[$key])) {
            return $this->cache[$key];
        }

        $result = $this->chat($messages, $model);
        $this->cache[$key] = $result;
        return $result;
    }
}

实战练习

基础练习

练习1:编写一个简单的Mistral聊天程序。

参考代码

php
<?php
$apiKey = getenv('MISTRAL_API_KEY');
$client = new MistralClient($apiKey);

echo "Mistral聊天助手 (输入 'quit' 退出)\n";

while (true) {
    echo "\n你: ";
    $input = trim(fgets(STDIN));

    if ($input === 'quit') {
        break;
    }

    $result = $client->chat([['role' => 'user', 'content' => $input]]);
    echo "Mistral: " . $result['choices'][0]['message']['content'] . "\n";
}

进阶练习

练习2:实现一个代码审查工具。

参考代码

php
<?php
class CodeReviewer
{
    private MistralClient $client;

    public function review(string $code, string $language = 'PHP'): array
    {
        $result = $this->client->chat([
            [
                'role' => 'user',
                'content' => "请审查以下{$language}代码,从代码质量、安全性、性能三个维度给出评价:\n```\n{$code}\n```"
            ]
        ], 'codestral-latest');

        return ['review' => $result['choices'][0]['message']['content']];
    }
}

挑战练习

练习3:构建一个语义搜索引擎。

参考代码

php
<?php
class SemanticSearchEngine
{
    private MistralEmbedding $embedding;
    private array $index = [];

    public function __construct(MistralEmbedding $embedding)
    {
        $this->embedding = $embedding;
    }

    public function indexDocument(string $id, string $content): void
    {
        $this->index[$id] = [
            'content' => $content,
            'embedding' => $this->embedding->embedSingle($content),
        ];
    }

    public function search(string $query, int $topK = 5): array
    {
        $queryEmbedding = $this->embedding->embedSingle($query);

        $scores = [];
        foreach ($this->index as $id => $doc) {
            $scores[$id] = $this->embedding->cosineSimilarity(
                $queryEmbedding,
                $doc['embedding']
            );
        }

        arsort($scores);
        $topIds = array_slice(array_keys($scores), 0, $topK, true);

        $results = [];
        foreach ($topIds as $id) {
            $results[] = [
                'id' => $id,
                'content' => $this->index[$id]['content'],
                'score' => $scores[$id],
            ];
        }

        return $results;
    }
}

知识点总结

核心要点

  1. API兼容:兼容OpenAI API格式,易于迁移
  2. 开源精神:多个模型开源,可本地部署
  3. 代码专用:Codestral专为代码生成优化
  4. 嵌入支持:提供文本嵌入API
  5. 欧洲合规:符合GDPR等欧洲法规

易错点回顾

易错点正确做法
模型名称错误使用正确的模型名称
忽略随机种子使用random_seed确保可复现
忽略safe_prompt根据需要设置safe_prompt
不使用专用模型代码任务使用Codestral

拓展参考资料

官方文档

进阶学习路径

  1. 本知识点 → Mistral AI API基础使用
  2. 下一步Meta Llama API
  3. 进阶错误处理与重试
  4. 高级安全与鉴权

💡 记住:Mistral AI以其开源精神和高性能著称,善用Codestral可以大大提升代码开发效率。