Skip to content

MiniMax API完全指南

MiniMax以其创新的多模态能力和语音合成著称,是国内AI领域的新锐力量

概述

MiniMax是一家专注于多模态AI的公司,其模型以语音合成、视频生成和多模态理解著称。本教程将带你全面掌握MiniMax API的使用方法。

为什么选择MiniMax?

优势说明
语音合成高质量语音合成能力
多模态支持文本、语音、图像、视频
创新技术独特的技术路线
API友好简洁易用的API设计

MiniMax模型概览

MiniMax模型家族:

文本模型
├── abab6.5-chat        # 最新对话模型
├── abab6.5s-chat       # 快速版本
└── abab5.5-chat        # 经典版本

多模态模型
├── abab6.5-vision      # 图像理解
├── speech-01           # 语音合成
└── video-01            # 视频生成

嵌入模型
└── embedding-01        # 文本嵌入

基本概念

API Key

php
<?php
// 在MiniMax开放平台获取API Key
// https://www.minimaxi.com/

// API Key格式
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

$apiKey = getenv('MINIMAX_API_KEY');
$groupId = getenv('MINIMAX_GROUP_ID');

Group ID

MiniMax使用Group ID进行资源隔离:

php
<?php
// Group ID用于标识用户组
// 在API请求中需要携带Group ID
$groupId = getenv('MINIMAX_GROUP_ID');

环境准备

创建MiniMax客户端

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

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

class MiniMaxClient
{
    private $client;
    private $apiKey;
    private $groupId;
    private $baseUrl = 'https://api.minimax.chat/v1';

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

    public function chat(
        array $messages,
        string $model = 'abab6.5s-chat',
        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'];
        }

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

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

// 使用示例
$apiKey = getenv('MINIMAX_API_KEY');
$groupId = getenv('MINIMAX_GROUP_ID');
$client = new MiniMaxClient($apiKey, $groupId);

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

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

运行结果:

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

语音合成

使用speech-01进行语音合成

php
<?php
class MiniMaxSpeechClient
{
    private $client;
    private $apiKey;
    private $groupId;
    private $baseUrl = 'https://api.minimax.chat/v1';

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

    public function textToSpeech(
        string $text,
        string $voiceId = 'male-qn-qingse',
        string $model = 'speech-01-turbo',
        string $outputFormat = 'mp3'
    ): string {
        $response = $this->client->post('/text_to_speech', [
            'json' => [
                'text' => $text,
                'voice_id' => $voiceId,
                'model' => $model,
                'audio_setting' => [
                    'sample_rate' => 32000,
                    'bitrate' => 128000,
                    'format' => $outputFormat,
                ],
            ],
            'query' => ['GroupId' => $this->groupId],
        ]);

        return $response->getBody()->getContents();
    }

    public function saveSpeech(string $text, string $outputPath, string $voiceId = 'male-qn-qingse'): bool
    {
        $audioData = $this->textToSpeech($text, $voiceId);
        return file_put_contents($outputPath, $audioData) !== false;
    }
}

// 使用示例
$speechClient = new MiniMaxSpeechClient($apiKey, $groupId);

// 文本转语音
$text = '欢迎使用MiniMax语音合成服务';
$speechClient->saveSpeech($text, 'output.mp3');

echo "语音文件已保存到 output.mp3";

可用语音列表

语音ID描述
male-qn-qingse男声-青涩
male-qn-jingying男声-精英
female-shaonv女声-少女
female-yujie女声-御姐
presenter_male男声-主持人
presenter_female女声-主持人
audiobook_male_1有声书男声1
audiobook_female_1有声书女声1

高级参数配置

完整参数示例

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

    public function chatAdvanced(
        array $messages,
        string $model = 'abab6.5s-chat',
        array $options = []
    ): array {
        $params = [
            'model' => $model,
            'messages' => $messages,
        ];

        $optionalParams = ['temperature', 'max_tokens', 'top_p', 'stop', 'presence_penalty', 'frequency_penalty'];

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

        // 启用搜索增强
        if (!empty($options['enable_search'])) {
            $params['enable_search'] = true;
        }

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

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

// 使用示例
$result = $client->chatAdvanced(
    [['role' => 'user', 'content' => '写一首关于程序员的诗']],
    'abab6.5s-chat',
    [
        'temperature' => 0.8,
        'max_tokens' => 500,
    ]
);

参数详解

参数范围默认值说明
temperature0-20.9控制随机性
max_tokens1-模型上限2048最大输出Token
top_p0-10.95核采样参数
stop字符串或数组-停止序列
presence_penalty0-20存在惩罚
frequency_penalty0-20频率惩罚

流式响应处理

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

    public function chatStream(
        array $messages,
        string $model = 'abab6.5s-chat'
    ): Generator {
        $response = $this->client->post('/chat/completions', [
            'json' => [
                'model' => $model,
                'messages' => $messages,
                'stream' => true,
            ],
            'query' => ['GroupId' => $this->groupId],
            '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 "MiniMax回复:";
foreach ($client->chatStream([['role' => 'user', 'content' => '讲一个程序员笑话']]) as $chunk) {
    echo $chunk;
    flush();
}

常见错误与踩坑点

错误1:缺少Group ID

php
<?php
// ❌ 错误做法:不提供Group ID
$client = new MiniMaxClient($apiKey, '');

// ✅ 正确做法:提供Group ID
$groupId = 'xxxxxxxx';
$client = new MiniMaxClient($apiKey, $groupId);

错误2:语音ID错误

php
<?php
// ❌ 错误做法:使用不存在的语音ID
$audio = $speechClient->textToSpeech($text, 'voice-001');

// ✅ 正确做法:使用正确的语音ID
$audio = $speechClient->textToSpeech($text, 'male-qn-qingse');

错误3:忽略语音合成限制

php
<?php
// ❌ 错误做法:合成超长文本
$longText = str_repeat('测试', 10000);
$audio = $speechClient->textToSpeech($longText);

// ✅ 正确做法:分段处理长文本
function splitTextForSpeech(string $text, int $maxLength = 1000): array
{
    return str_split($text, $maxLength);
}

$chunks = splitTextForSpeech($longText);
foreach ($chunks as $index => $chunk) {
    $speechClient->saveSpeech($chunk, "output_{$index}.mp3");
}

常见应用场景

场景1:语音播报系统

php
<?php
class VoiceBroadcastSystem
{
    private MiniMaxSpeechClient $client;

    public function broadcast(string $message, string $outputPath): bool
    {
        return $this->client->saveSpeech($message, $outputPath);
    }

    public function broadcastNews(string $news): bool
    {
        $text = "新闻播报:{$news}";
        return $this->client->saveSpeech($text, 'news_broadcast.mp3');
    }
}

场景2:有声书生成

php
<?php
class AudiobookGenerator
{
    private MiniMaxSpeechClient $client;

    public function generateChapter(string $content, string $outputPath, string $voiceId = 'audiobook_male_1'): bool
    {
        return $this->client->saveSpeech($content, $outputPath, $voiceId);
    }

    public function generateBook(array $chapters, string $outputDir): array
    {
        $files = [];
        foreach ($chapters as $index => $content) {
            $filename = "chapter_{$index}.mp3";
            $outputPath = "{$outputDir}/{$filename}";
            $this->generateChapter($content, $outputPath);
            $files[] = $outputPath;
        }
        return $files;
    }
}

场景3:智能客服

php
<?php
class MiniMaxCustomerService
{
    private MiniMaxClient $chatClient;
    private MiniMaxSpeechClient $speechClient;
    private array $knowledgeBase = [];

    public function addKnowledge(string $category, string $content): void
    {
        $this->knowledgeBase[$category] = $content;
    }

    public function handleQuery(string $query): string
    {
        $context = '';
        foreach ($this->knowledgeBase as $category => $content) {
            $context .= "【{$category}】\n{$content}\n\n";
        }

        $result = $this->chatClient->chat([
            ['role' => 'user', 'content' => "知识库:\n{$context}\n\n客户问题:{$query}"]
        ]);

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

    public function handleQueryWithVoice(string $query): array
    {
        $textResponse = $this->handleQuery($query);
        $audioData = $this->speechClient->textToSpeech($textResponse);

        return [
            'text' => $textResponse,
            'audio' => base64_encode($audioData),
        ];
    }
}

场景4:内容创作

php
<?php
class MiniMaxContentCreator
{
    private MiniMaxClient $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'];
    }
}

场景5:翻译助手

php
<?php
class MiniMaxTranslator
{
    private MiniMaxClient $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'];
    }
}

常见问题答疑(FAQ)

Q1:MiniMax的定价如何?

回答

模型输入价格输出价格
abab6.5-chat¥0.03/千Token¥0.06/千Token
abab6.5s-chat¥0.01/千Token¥0.01/千Token
speech-01-turbo¥0.1/千字符-
speech-01¥0.2/千字符-

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

回答

场景推荐模型原因
快速响应abab6.5s-chat速度快,成本低
复杂任务abab6.5-chat能力强
语音合成speech-01-turbo高质量语音
有声书speech-01更自然的声音

Q3:如何获取Group ID?

回答

  1. 登录MiniMax开放平台
  2. 进入控制台
  3. 在账户设置中查看Group ID

Q4:如何处理API错误?

回答

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

    if (strpos($message, 'invalid_api_key') !== false) {
        return 'API Key无效';
    }
    if (strpos($message, 'invalid_group_id') !== false) {
        return 'Group ID无效';
    }
    if (strpos($message, 'rate_limit') !== false) {
        return '请求过于频繁';
    }

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

Q5:语音合成支持哪些格式?

回答

格式说明
mp3最常用,兼容性好
wav无损音质
flac高质量压缩
aac移动设备友好

Q6:如何实现多轮对话?

回答

php
<?php
class MiniMaxChatSession
{
    private MiniMaxClient $client;
    private array $messages = [];

    public function chat(string $message): string
    {
        $this->messages[] = ['role' => 'user', 'content' => $message];

        $result = $this->client->chat($this->messages);
        $response = $result['choices'][0]['message']['content'];

        $this->messages[] = ['role' => 'assistant', 'content' => $response];

        return $response;
    }
}

实战练习

基础练习

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

参考代码

php
<?php
$apiKey = getenv('MINIMAX_API_KEY');
$groupId = getenv('MINIMAX_GROUP_ID');
$client = new MiniMaxClient($apiKey, $groupId);

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

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

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

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

进阶练习

练习2:实现一个语音播报工具。

参考代码

php
<?php
class VoiceAnnouncer
{
    private MiniMaxSpeechClient $client;

    public function announce(string $message, string $outputPath): bool
    {
        return $this->client->saveSpeech($message, $outputPath);
    }
}

挑战练习

练习3:构建一个语音客服系统。

参考代码

php
<?php
class VoiceCustomerService
{
    private MiniMaxClient $chatClient;
    private MiniMaxSpeechClient $speechClient;

    public function handleQuery(string $query): array
    {
        $result = $this->chatClient->chat([
            ['role' => 'user', 'content' => $query]
        ]);

        $textResponse = $result['choices'][0]['message']['content'];
        $audioData = $this->speechClient->textToSpeech($textResponse);

        return [
            'text' => $textResponse,
            'audio' => base64_encode($audioData),
        ];
    }
}

知识点总结

核心要点

  1. Group ID:需要提供Group ID进行资源隔离
  2. 语音合成:高质量语音合成能力
  3. 多模态:支持文本、语音、图像、视频
  4. API友好:简洁易用的API设计
  5. 创新技术:独特的技术路线

易错点回顾

易错点正确做法
缺少Group ID提供Group ID
语音ID错误使用正确的语音ID
忽略语音合成限制分段处理长文本

拓展参考资料

官方文档

进阶学习路径

  1. 本知识点 → MiniMax API基础使用
  2. 下一步错误处理与重试
  3. 进阶Token优化策略
  4. 高级安全与鉴权

💡 记住:MiniMax的语音合成能力是其核心优势,善用speech-01可以构建高质量的语音应用。