PHP-MiniMax调用示例
MiniMax SDK是一个PHP封装类,用于简化与MiniMax AI大模型API的交互。该SDK提供了简单易用的接口,帮助开发者快速集成MiniMax的文本生成(ChatCompletion)能力到自己的应用中。它支持MiniMax-M1和MiniMax-Text-01等模型,并提供了丰富的参数配置选项和高级功能。
MiniMax SDK
简介
MiniMax SDK是一个PHP封装类,用于简化与MiniMax AI大模型API的交互。该SDK提供了简单易用的接口,帮助开发者快速集成MiniMax的文本生成(ChatCompletion)能力到自己的应用中。它支持MiniMax-M1和MiniMax-Text-01等模型,并提供了丰富的参数配置选项和高级功能。
特性
- 支持文本对话生成
- 支持多模态输入(图片+文本)
- 支持历史对话上下文
- 支持敏感内容过滤与打码
- 支持工具调用能力
- 支持流式响应输出
- 支持JSON结构化输出
- 完整的错误处理机制
- 丰富的参数配置选项
安装
将CallMiniMax.php文件放置在您项目的extend/ai/model/目录下。
基本用法
<?php
use ai\model\CallMiniMax;
// 方式一:快速调用
try {
$result = CallMiniMax::run('你好,请介绍一下你自己', 'your_api_key');
echo $result['content'];
} catch (\Exception $e) {
echo $e->getMessage();
}
// 方式二:实例化后调用
try {
$minimax = new CallMiniMax('your_api_key');
$result = $minimax->chat('你好,请介绍一下你自己');
echo $result['content'];
} catch (\Exception $e) {
echo $e->getMessage();
}
带历史记录的对话示例
<?php
use ai\model\CallMiniMax;
try {
$history = [
['role' => 'user', 'content' => '你好,请介绍一下你自己'],
['role' => 'assistant', 'content' => '我是MiniMax AI助手,很高兴为你服务!']
];
$prompt = '你刚才说了什么?';
$result = CallMiniMax::run($prompt, 'your_api_key', 'MiniMax-M1', 'ai_chat', $history);
echo $result['content'];
} catch (\Exception $e) {
echo $e->getMessage();
}
多模态输入示例
<?php
use ai\model\CallMiniMax;
try {
// 包含图片的多模态输入
$prompt = "这张图片是什么内容?[image]https://example.com/image.jpg[/image]";
$result = CallMiniMax::run($prompt, 'your_api_key', 'MiniMax-M1');
echo $result['content'];
} catch (\Exception $e) {
echo $e->getMessage();
}
流式输出示例
<?php
use ai\model\CallMiniMax;
try {
$minimax = new CallMiniMax('your_api_key', 'MiniMax-M1');
// 设置流式输出
$minimax->setStream(true);
$result = $minimax->chat('请写一篇短文介绍人工智能');
echo $result['content'];
} catch (\Exception $e) {
echo $e->getMessage();
}
工具调用示例
<?php
use ai\model\CallMiniMax;
try {
$minimax = new CallMiniMax('your_api_key', 'MiniMax-M1');
// 设置工具调用
$minimax->setToolChoice('auto')
->setTools([
[
'type' => 'function',
'function' => [
'name' => 'get_weather',
'description' => '获取指定城市的天气信息',
'parameters' => [
'type' => 'object',
'properties' => [
'city' => [
'type' => 'string',
'description' => '城市名称'
]
],
'required' => ['city']
]
]
]
]);
$result = $minimax->chat('北京今天的天气怎么样?');
// 检查是否有工具调用
if (isset($result['tool_calls'])) {
print_r($result['tool_calls']);
}
echo $result['content'];
} catch (\Exception $e) {
echo $e->getMessage();
}
JSON结构化输出示例
<?php
use ai\model\CallMiniMax;
try {
$minimax = new CallMiniMax('your_api_key', 'MiniMax-Text-01');
// 设置JSON结构化输出
$minimax->setResponseFormat([
'type' => 'json_schema',
'json_schema' => [
'type' => 'object',
'properties' => [
'name' => ['type' => 'string'],
'age' => ['type' => 'integer'],
'skills' => ['type' => 'array', 'items' => ['type' => 'string']]
],
'required' => ['name', 'age', 'skills']
]
]);
$result = $minimax->chat('为我创建一个名为张三、年龄25岁、技能包括编程、写作和游泳的人物信息');
echo $result['content'];
} catch (\Exception $e) {
echo $e->getMessage();
}
API参考
构造函数
__construct($apiKey = '', $model = 'MiniMax-M1', $options = [])
$apiKey: MiniMax API密钥$model: 模型名称,默认为MiniMax-M1$options: 其他选项,包括温度、最大token等
参数设置方法
setApiKey($apiKey) // 设置API密钥
setModel($model) // 设置模型名称
setTemperature($temperature) // 设置温度参数(0-1)
setTopP($topP) // 设置top_p参数
setMaxTokens($maxTokens) // 设置最大生成token数
setStream($stream) // 设置是否使用流式输出
setMaskSensitiveInfo($maskSensitiveInfo) // 设置是否屏蔽敏感信息
setToolChoice($toolChoice) // 设置工具选择模式
setTools($tools) // 设置工具定义
setResponseFormat($responseFormat) // 设置响应格式
setStreamOptions($streamOptions) // 设置流式选项
setSystemPrompt($systemPrompt) // 设置系统提示词
发送对话请求
chat($prompt, $moduleType = 'ai_chat', $history = [], $stream = null)
$prompt: 用户问题/输入$moduleType: 模块类型,用于确定系统提示词$history: 历史对话记录数组$stream: 是否使用流式响应,为null时使用对象中的stream属性值
静态快速调用方法
run($prompt, $apiKey, $model = '', $moduleType = 'ai_chat', $history = [], $options = [])
$prompt: 用户问题/输入$apiKey: API密钥$model: 模型名称,为空时使用默认值$moduleType: 模块类型$history: 历史对话记录数组$options: 其他选项,包括温度、最大token等
返回数据格式
[
'content' => '模型回复内容',
'tokens' => 123, // 消耗的token数量
'finish_reason' => 'stop', // 结束原因
'model' => '使用的模型名称',
'input_sensitive' => false, // 输入是否包含敏感内容
'output_sensitive' => false, // 输出是否包含敏感内容
'tool_calls' => [] // 如果使用了工具调用,会包含工具调用结果
]
特殊功能说明
模型默认参数
MiniMax SDK会根据不同模型自动设置合适的默认参数:
-
MiniMax-M1:
- temperature: 1.0
- max_tokens: 8192
-
MiniMax-Text-01:
- temperature: 0.1
- max_tokens: 2048
多模态输入处理
MiniMax SDK支持图片+文本的多模态输入,使用特定的标记来标识图片:
这张图片是什么内容?[image]https://example.com/image.jpg[/image]
SDK会自动解析这种格式,并将其转换为MiniMax API支持的多模态输入格式。
敏感内容处理
MiniMax API内置了敏感内容检测机制,SDK会检测并记录敏感内容标记:
input_sensitive: 输入是否包含敏感内容output_sensitive: 输出是否包含敏感内容
可以通过setMaskSensitiveInfo(true)开启敏感信息打码功能,对敏感信息(如邮箱、域名、链接、证件号、家庭住址等)进行自动打码。
工具调用
MiniMax支持工具调用(Function Calling)能力,可通过以下步骤使用:
- 通过
setToolChoice('auto')开启工具调用 - 使用
setTools()方法定义可用工具 - 在返回结果中通过
tool_calls字段获取工具调用结果
JSON结构化输出
MiniMax-Text-01模型支持JSON结构化输出,可通过setResponseFormat()方法设置:
$minimax->setResponseFormat([
'type' => 'json_schema',
'json_schema' => {...} // 定义JSON Schema结构
]);
错误处理
SDK使用异常机制处理错误,并内置了对MiniMax API错误码的解析和处理。常见错误码包括:
| 错误码 | 描述 |
|---|---|
| 1000 | 未知错误 |
| 1001 | 请求超时 |
| 1002 | 触发RPM限流 |
| 1004 | 鉴权失败 |
| 1008 | 余额不足 |
| 1013 | 服务内部错误 |
| 1027 | 输出内容错误 |
| 1039 | Token限制 |
| 2013 | 参数错误 |
使用时请使用try-catch捕获可能的异常,例如:
try {
$result = CallMiniMax::run($prompt, $apiKey);
} catch (\Exception $e) {
echo '错误: ' . $e->getMessage();
// 可以从错误信息中提取错误码进行特定处理
}
注意事项
- 配置provider名称:在系统配置中,provider名称必须设置为小写的"minimax"
- API密钥设置:确保使用正确的API密钥,可在MiniMax账户管理>接口密钥中查看
- 模型选择:
- MiniMax-M1:适合推理型场景,支持更多tokens输出
- MiniMax-Text-01:适合文本生成场景,根据需求选择合适的温度参数
- 温度参数建议:
- MiniMax-M1:推荐范围[0.8, 1]
- MiniMax-Text-01:
- 明确场景(如知识问答、情感分析、文本分类):建议使用低温度(0.01~0.2)
- 开放场景(如营销文案生成、人设对话):建议使用高温度(0.7~1)
- 大型响应处理:处理大型响应时建议使用流式输出,以获得更稳定的网络连接
- 图片URL要求:确保图片URL是公开可访问的,并支持常见图片格式
- 频率限制:注意API调用频率限制,避免触发限流
与Index类集成
在系统中,可以通过Index类统一调用MiniMax SDK:
<?php
use ai\Index;
try {
// 使用默认AI配置调用
$result = Index::chat('你好,请介绍一下你自己', 'ai_chat');
echo $result['content'];
// 或使用指定配置ID调用
$result = Index::chat('你好,请介绍一下你自己', 'ai_chat', [], 3);
echo $result['content'];
} catch (\Exception $e) {
echo $e->getMessage();
}
Index类中的provider配置示例:
case 'minimax':
// 调用MiniMax SDK
return CallMiniMax::run(
$prompt,
$config['api_key'],
$config['model'] ?? 'MiniMax-M1',
$moduleType,
$history,
$options
);
SDK完整代码示例
<?php
/**
* @NodeAnotation(title="MiniMax SDK")
*/
namespace ai\model;
use ai\Index;
use think\facade\Log;
class CallMiniMax
{
/**
* API接口URL
* @var string
*/
protected $apiUrl = 'https://api.minimaxi.com/v1/text/chatcompletion_v2';
/**
* API密钥
* @var string
*/
protected $apiKey;
/**
* 模型名称
* @var string
*/
protected $model;
/**
* 温度参数,控制随机性,0-1之间,越大越随机
* @var float
*/
protected $temperature;
/**
* 控制输出文本的多样性
* @var float
*/
protected $topP = 0.95;
/**
* 最大生成的token数
* @var int
*/
protected $maxTokens;
/**
* 是否使用流式输出
* @var bool
*/
protected $stream = false;
/**
* 是否屏蔽敏感信息
* @var bool
*/
protected $maskSensitiveInfo = false;
/**
* 工具选择模式
* @var string
*/
protected $toolChoice = 'none';
/**
* 工具定义
* @var array
*/
protected $tools = [];
/**
* 响应格式
* @var array|null
*/
protected $responseFormat = null;
/**
* 流式选项
* @var array|null
*/
protected $streamOptions = null;
/**
* 系统提示词
* @var string
*/
protected $systemPrompt = '';
/**
* 构造函数
*
* @param string $apiKey API密钥
* @param string $model 模型名称
* @param array $options 其他选项
*/
public function __construct($apiKey = '', $model = 'MiniMax-M1', $options = [])
{
$this -> apiKey = $apiKey;
$this -> model = $model;
// 根据模型类型设置默认temperature和max_tokens
if ($model === 'MiniMax-M1') {
$this -> temperature = 1.0;
$this -> maxTokens = 8192;
} else if ($model === 'MiniMax-Text-01') {
$this -> temperature = 0.1;
$this -> maxTokens = 2048;
} else {
// 默认值
$this -> temperature = 0.7;
$this -> maxTokens = 8192;
}
// 如果传入了自定义URL,则直接使用自定义URL
if (!empty($options['base_url'])) {
$this -> apiUrl = trim($options['base_url']);
}
// 设置其他参数
if (isset($options['temperature'])) {
$this -> temperature = (float)$options['temperature'];
}
if (isset($options['top_p'])) {
$this -> topP = (float)$options['top_p'];
}
if (isset($options['max_tokens'])) {
$this -> maxTokens = (int)$options['max_tokens'];
}
if (isset($options['stream'])) {
$this -> stream = (bool)$options['stream'];
}
if (isset($options['system_prompt'])) {
$this -> systemPrompt = $options['system_prompt'];
}
if (isset($options['mask_sensitive_info'])) {
$this -> maskSensitiveInfo = (bool)$options['mask_sensitive_info'];
}
if (isset($options['tool_choice'])) {
$this -> toolChoice = $options['tool_choice'];
}
if (isset($options['tools'])) {
$this -> tools = $options['tools'];
}
if (isset($options['response_format'])) {
$this -> responseFormat = $options['response_format'];
}
if (isset($options['stream_options'])) {
$this -> streamOptions = $options['stream_options'];
}
}
/**
* 设置API密钥
*
* @param string $apiKey API密钥
* @return $this
*/
public function setApiKey($apiKey)
{
$this -> apiKey = $apiKey;
return $this;
}
/**
* 设置模型
*
* @param string $model 模型名称
* @return $this
*/
public function setModel($model)
{
$this -> model = $model;
// 根据模型类型自动调整默认参数
if ($model === 'MiniMax-M1') {
$this -> temperature = 1.0;
$this -> maxTokens = 8192;
} else if ($model === 'MiniMax-Text-01') {
$this -> temperature = 0.1;
$this -> maxTokens = 2048;
}
return $this;
}
/**
* 设置温度参数
*
* @param float $temperature 温度值(0-1)
* @return $this
*/
public function setTemperature($temperature)
{
$this -> temperature = $temperature;
return $this;
}
/**
* 设置top_p参数
*
* @param float $topP top_p值
* @return $this
*/
public function setTopP($topP)
{
$this -> topP = $topP;
return $this;
}
/**
* 设置最大token数
*
* @param int $maxTokens 最大token数
* @return $this
*/
public function setMaxTokens($maxTokens)
{
$this -> maxTokens = $maxTokens;
return $this;
}
/**
* 设置是否使用流式输出
*
* @param bool $stream 是否使用流式输出
* @return $this
*/
public function setStream($stream)
{
$this -> stream = $stream;
return $this;
}
/**
* 设置是否屏蔽敏感信息
*
* @param bool $maskSensitiveInfo 是否屏蔽敏感信息
* @return $this
*/
public function setMaskSensitiveInfo($maskSensitiveInfo)
{
$this -> maskSensitiveInfo = $maskSensitiveInfo;
return $this;
}
/**
* 设置工具选择模式
*
* @param string $toolChoice 工具选择模式
* @return $this
*/
public function setToolChoice($toolChoice)
{
$this -> toolChoice = $toolChoice;
return $this;
}
/**
* 设置工具定义
*
* @param array $tools 工具定义
* @return $this
*/
public function setTools($tools)
{
$this -> tools = $tools;
return $this;
}
/**
* 设置响应格式
*
* @param array $responseFormat 响应格式
* @return $this
*/
public function setResponseFormat($responseFormat)
{
$this -> responseFormat = $responseFormat;
return $this;
}
/**
* 设置流式选项
*
* @param array $streamOptions 流式选项
* @return $this
*/
public function setStreamOptions($streamOptions)
{
$this -> streamOptions = $streamOptions;
return $this;
}
/**
* 设置系统提示词
*
* @param string $systemPrompt 系统提示词
* @return $this
*/
public function setSystemPrompt($systemPrompt)
{
$this -> systemPrompt = $systemPrompt;
return $this;
}
/**
* 发送AI请求
*
* @param string $prompt 用户问题
* @param string $moduleType 模块类型,用于确定系统提示词
* @param array $history 历史对话记录
* @param bool $stream 是否使用流式响应
* @return array 响应结果
* @throws \Exception
*/
public function chat($prompt, $moduleType = 'ai_chat', $history = [], $stream = null)
{
try {
if (empty($this -> apiKey)) {
throw new \Exception('API密钥不能为空');
}
if (empty($this -> model)) {
throw new \Exception('模型名称不能为空');
}
// 如果明确传入了stream参数,则使用该参数
if ($stream !== null) {
$this -> stream = $stream;
}
// 构建消息数组
$messages = [];
// 处理系统提示词
$systemContent = $this -> systemPrompt;
// 如果系统提示词是数组格式,直接添加到messages中
if (is_array($systemContent)) {
// 检查是否已经是正确的消息格式
if (isset($systemContent[0]) && isset($systemContent[0]['role'])) {
$messages = array_merge($messages, $systemContent);
} else {
// 如果不是正确的格式,则将其转为system消息
$messages[] = ['role' => 'system', 'content' => json_encode($systemContent)];
}
} else if (!empty($systemContent)) {
// 如果是字符串且不为空,添加为系统提示词
$messages[] = ['role' => 'system', 'content' => $systemContent];
} else {
// 使用默认提示词
$messages[] = ['role' => 'system', 'content' => '你是一个有帮助的AI助手,可以提供有用的信息和建议。'];
}
$messages = $history ? array_merge($messages, $history) : $messages;
// 处理当前问题,如果包含图片标签
if (preg_match('/\[image\](.*?)\[\/image\]/i', $prompt, $matches)) {
$imageUrl = trim($matches[1]);
$textContent = trim(str_replace($matches[0], '', $prompt));
$content = [];
// 如果有文本内容,添加文本部分
if ($textContent !== '') {
$content[] = [
'type' => 'text',
'text' => $textContent
];
}
// 添加图片部分,MiniMax格式
$content[] = [
'type' => 'image_url',
'image_url' => [
'url' => $imageUrl
]
];
$messages[] = ['role' => 'user', 'content' => $content];
} else {
$messages[] = ['role' => 'user', 'content' => $prompt];
}
// 构建请求数据
$data = [
'model' => $this -> model,
'messages' => $messages,
'temperature' => $this -> temperature,
'top_p' => $this -> topP,
'max_tokens' => $this -> maxTokens,
'stream' => $this -> stream,
'mask_sensitive_info' => $this -> maskSensitiveInfo
];
// 添加工具选择(如果不是none)
if ($this -> toolChoice !== 'none') {
$data['tool_choice'] = $this -> toolChoice;
}
// 添加工具定义(如果有)
if (!empty($this -> tools)) {
$data['tools'] = $this -> tools;
}
// 添加响应格式(如果有)
if (!empty($this -> responseFormat)) {
$data['response_format'] = $this -> responseFormat;
}
// 添加流式选项(如果有)
if ($this -> stream && !empty($this -> streamOptions)) {
$data['stream_options'] = $this -> streamOptions;
}
// 发送请求
$response = $this -> httpRequest($this -> apiUrl, $data, [
'Authorization: Bearer ' . $this -> apiKey,
'Content-Type: application/json'
]);
// 处理错误响应
if (isset($response['base_resp']) && isset($response['base_resp']['status_code']) && $response['base_resp']['status_code'] != 0) {
$errorCode = $response['base_resp']['status_code'];
$errorMsg = $response['base_resp']['status_msg'] ?? '未知错误';
throw new \Exception("MiniMax API错误(代码{$errorCode}): {$errorMsg}");
}
// 检查敏感内容标记
$inputSensitive = $response['input_sensitive'] ?? false;
$outputSensitive = $response['output_sensitive'] ?? false;
if ($inputSensitive) {
Log ::warning('MiniMax检测到输入内容敏感');
}
if ($outputSensitive) {
Log ::warning('MiniMax检测到输出内容敏感');
}
// 处理API返回数据
if (!isset($response['choices'][0]['message']['content'])) {
throw new \Exception('MiniMax接口返回数据格式错误:' . json_encode($response));
}
// 组装返回结果
$result = [
'content' => $response['choices'][0]['message']['content'],
'tokens' => $response['usage']['total_tokens'] ?? 0,
'finish_reason' => $response['choices'][0]['finish_reason'] ?? null,
'model' => $response['model'] ?? $this -> model,
'input_sensitive' => $inputSensitive,
'output_sensitive' => $outputSensitive
];
// 如果有工具调用结果,也添加到返回值中
if (isset($response['choices'][0]['message']['tool_calls'])) {
$result['tool_calls'] = $response['choices'][0]['message']['tool_calls'];
}
return $result;
} catch (\Exception $e) {
throw new \Exception('MiniMax调用失败:' . $e -> getMessage());
}
}
/**
* HTTP请求封装
*
* @param string $url 请求URL
* @param array $data 请求数据
* @param array $headers 请求头
* @return array 响应结果
* @throws \Exception
*/
protected function httpRequest($url, $data, $headers = [])
{
try {
// 使用公共函数中的http_post方法
$result = http_post($url, $data, $headers);
if (empty($result)) {
throw new \Exception('接口返回数据为空');
}
return $result;
} catch (\Exception $e) {
// 增强错误处理,尝试解析错误代码
$message = $e -> getMessage();
$errorMatch = [];
if (preg_match('/status_code[\"\']?\s*:\s*(\d+)/', $message, $errorMatch)) {
$errorCode = $errorMatch[1];
$errorDescription = $this -> getErrorDescription($errorCode);
throw new \Exception("MiniMax API错误(代码{$errorCode}): {$errorDescription}. 原始错误: {$message}");
}
throw new \Exception('HTTP请求失败:' . $message);
}
}
/**
* 获取错误码描述
*
* @param int $code 错误码
* @return string 错误描述
*/
protected function getErrorDescription($code)
{
$errorDescriptions = [
1000 => '未知错误',
1001 => '请求超时',
1002 => '触发RPM限流',
1004 => '鉴权失败',
1008 => '余额不足',
1013 => '服务内部错误',
1027 => '输出内容错误',
1039 => 'Token限制',
2013 => '参数错误'
];
return $errorDescriptions[$code] ?? '未知错误代码';
}
/**
* 快速调用方法
*
* @param string $prompt 用户问题
* @param string $apiKey API密钥
* @param string $model 模型名称
* @param string $moduleType 模块类型
* @param array $history 历史对话记录
* @param array $options 其他选项
* @return array 响应结果
* @throws \Exception
*/
public static function run($prompt, $apiKey, $model = '', $moduleType = 'ai_chat', $history = [], $options = [])
{
$instance = new self($apiKey, $model, $options);
return $instance -> chat($prompt, $moduleType, $history);
}
}
调试与排错
调用MiniMax API时可能遇到的常见问题及解决方法:
-
鉴权失败 (错误码1004):
- 检查API密钥是否正确设置
- 确认provider名称为小写"minimax"
- 确认Authorization头格式为"Bearer {api_key}"
-
请求超时 (错误码1001):
- 检查网络连接
- 减少max_tokens值
- 尝试使用流式输出
-
余额不足 (错误码1008):
- 检查账户余额
- 可能需要充值或联系服务商
-
Token限制 (错误码1039):
- 减少输入文本长度
- 减少历史对话记录
- 调整max_tokens参数
-
敏感内容问题:
- 检查输入内容是否包含敏感信息
- 尝试开启mask_sensitive_info参数
- 修改提问方式,避免敏感词汇
更多推荐


所有评论(0)