Skip to content

腾讯混元API完全指南

混元是腾讯推出的大语言模型,与腾讯云生态深度集成,适合企业级应用

概述

混元是腾讯推出的大语言模型系列,以其强大的中文理解能力、多模态支持和腾讯云生态集成著称。本教程将带你全面掌握腾讯混元API的使用方法。

为什么选择混元?

优势说明
中文能力强专为中文优化
多模态支持文本、图像、语音
腾讯生态与微信、腾讯云等集成
企业级服务完善的企业级支持

混元模型概览

混元模型家族:

Hunyuan系列
├── hunyuan-lite        # 轻量版,免费
├── hunyuan-standard    # 标准版
├── hunyuan-pro         # 专业版
├── hunyuan-turbo       # 快速版
└── hunyuan-large       # 大型版本

专业模型
├── hunyuan-vision      # 多模态模型
└── hunyuan-embedding   # 嵌入模型

基本概念

API密钥

php
<?php
// 在腾讯云控制台获取API密钥
// https://console.cloud.tencent.com/cam/capi

$secretId = getenv('TENCENT_SECRET_ID');
$secretKey = getenv('TENCENT_SECRET_KEY');

签名认证

腾讯云API使用签名认证:

php
<?php
function generateSignature(string $secretKey, string $payload): string
{
    return hash_hmac('sha256', $payload, $secretKey);
}

环境准备

创建混元客户端

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

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

class HunyuanClient
{
    private $client;
    private $secretId;
    private $secretKey;
    private $baseUrl = 'hunyuan.tencentcloudapi.com';

    public function __construct(string $secretId, string $secretKey)
    {
        $this->secretId = $secretId;
        $this->secretKey = $secretKey;
        $this->client = new Client([
            'base_uri' => 'https://' . $this->baseUrl,
            'timeout' => 120,
        ]);
    }

    private function generateSignature(array $params): string
    {
        ksort($params);
        $queryString = http_build_query($params);
        $stringToSign = 'POST' . $this->baseUrl . '/?' . $queryString;
        return hash_hmac('sha256', $stringToSign, $this->secretKey);
    }

    public function chat(
        array $messages,
        string $model = 'hunyuan-lite',
        array $options = []
    ): array {
        $timestamp = time();
        $nonce = mt_rand();

        $params = [
            'Action' => 'ChatCompletions',
            'Version' => '2023-09-01',
            'Region' => 'ap-guangzhou',
            'Timestamp' => $timestamp,
            'Nonce' => $nonce,
            'SecretId' => $this->secretId,
            'Model' => $model,
            'Messages' => $messages,
        ];

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

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

        $signature = $this->generateSignature($params);
        $params['Signature'] = $signature;

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

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

// 使用示例
$secretId = getenv('TENCENT_SECRET_ID');
$secretKey = getenv('TENCENT_SECRET_KEY');
$client = new HunyuanClient($secretId, $secretKey);

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

echo $result['Choices'][0]['Message']['Content'];

运行结果:

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

使用腾讯云SDK

安装SDK

bash
composer require tencentcloud/tencentcloud-sdk-php

使用SDK调用

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

use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Hunyuan\V20230901\HunyuanClient;
use TencentCloud\Hunyuan\V20230901\Models\ChatCompletionsRequest;

class HunyuanSDKClient
{
    private $client;

    public function __construct(string $secretId, string $secretKey)
    {
        $cred = new Credential($secretId, $secretKey);
        $httpProfile = new HttpProfile();
        $httpProfile->setEndpoint('hunyuan.tencentcloudapi.com');

        $clientProfile = new ClientProfile();
        $clientProfile->setHttpProfile($httpProfile);

        $this->client = new HunyuanClient($cred, 'ap-guangzhou', $clientProfile);
    }

    public function chat(array $messages, string $model = 'hunyuan-lite'): string
    {
        $req = new ChatCompletionsRequest();
        $params = [
            'Model' => $model,
            'Messages' => $messages,
        ];
        $req->fromJsonString(json_encode($params));

        $resp = $this->client->ChatCompletions($req);
        return $resp->getChoices()[0]->getMessage()->getContent();
    }
}

// 使用示例
$client = new HunyuanSDKClient($secretId, $secretKey);
$response = $client->chat([
    ['Role' => 'user', 'Content' => '请用一句话介绍PHP语言']
]);
echo $response;

高级参数配置

完整参数示例

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

    public function chatAdvanced(
        array $messages,
        string $model = 'hunyuan-lite',
        array $options = []
    ): array {
        $timestamp = time();
        $nonce = mt_rand();

        $params = [
            'Action' => 'ChatCompletions',
            'Version' => '2023-09-01',
            'Region' => 'ap-guangzhou',
            'Timestamp' => $timestamp,
            'Nonce' => $nonce,
            'SecretId' => $this->secretId,
            'Model' => $model,
            'Messages' => $messages,
        ];

        $optionalParams = [
            'temperature' => 'Temperature',
            'max_tokens' => 'MaxTokens',
            'top_p' => 'TopP',
        ];

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

        $signature = $this->generateSignature($params);
        $params['Signature'] = $signature;

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

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

// 使用示例
$result = $client->chatAdvanced(
    [['Role' => 'user', 'Content' => '写一首关于程序员的诗']],
    'hunyuan-lite',
    [
        'temperature' => 0.8,
        'max_tokens' => 500,
    ]
);

参数详解

参数范围默认值说明
Temperature0-21控制随机性
TopP0-11核采样参数
MaxTokens1-模型上限1024最大输出Token

流式响应处理

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

    public function chatStream(array $messages, string $model = 'hunyuan-lite'): Generator
    {
        $timestamp = time();
        $nonce = mt_rand();

        $params = [
            'Action' => 'ChatCompletions',
            'Version' => '2023-09-01',
            'Region' => 'ap-guangzhou',
            'Timestamp' => $timestamp,
            'Nonce' => $nonce,
            'SecretId' => $this->secretId,
            'Model' => $model,
            'Messages' => $messages,
            'Stream' => true,
        ];

        $signature = $this->generateSignature($params);
        $params['Signature'] = $signature;

        $response = $this->client->post('/', [
            'form_params' => $params,
            '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 "混元回复:";
foreach ($client->chatStream([['Role' => 'user', 'Content' => '讲一个程序员笑话']]) as $chunk) {
    echo $chunk;
    flush();
}

常见错误与踩坑点

错误1:签名错误

php
<?php
// ❌ 错误做法:签名参数顺序错误
$params = ['Action' => 'ChatCompletions', 'Version' => '2023-09-01'];
// 未按字母顺序排序

// ✅ 正确做法:按字母顺序排序参数
private function generateSignature(array $params): string
{
    ksort($params); // 按字母顺序排序
    $queryString = http_build_query($params);
    $stringToSign = 'POST' . $this->baseUrl . '/?' . $queryString;
    return hash_hmac('sha256', $stringToSign, $this->secretKey);
}

错误2:模型名称错误

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

// ✅ 正确做法:使用正确的模型名称
$result = $client->chat($messages, 'hunyuan-lite');
$result = $client->chat($messages, 'hunyuan-pro');

错误3:消息格式错误

php
<?php
// ❌ 错误做法:使用错误的消息格式
$messages = [
    ['role' => 'user', 'content' => '你好'] // 小写字段名
];

// ✅ 正确做法:使用正确的消息格式
$messages = [
    ['Role' => 'user', 'Content' => '你好'] // 首字母大写
];

常见应用场景

场景1:智能客服

php
<?php
class HunyuanCustomerService
{
    private HunyuanClient $client;
    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->client->chat([
            ['Role' => 'user', 'Content' => "知识库:\n{$context}\n\n客户问题:{$query}"]
        ]);

        return $result['Choices'][0]['Message']['Content'];
    }
}

场景2:内容创作

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

场景3:代码助手

php
<?php
class HunyuanCodeAssistant
{
    private HunyuanClient $client;

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

        return $result['Choices'][0]['Message']['Content'];
    }
}

场景4:文档问答

php
<?php
class HunyuanDocumentQA
{
    private HunyuanClient $client;
    private string $document;

    public function loadDocument(string $filePath): void
    {
        $this->document = file_get_contents($filePath);
    }

    public function ask(string $question): string
    {
        $result = $this->client->chat([
            ['Role' => 'user', 'Content' => "文档内容:\n{$this->document}\n\n问题:{$question}"]
        ]);

        return $result['Choices'][0]['Message']['Content'];
    }
}

场景5:翻译助手

php
<?php
class HunyuanTranslator
{
    private HunyuanClient $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:混元的定价如何?

回答

模型输入价格输出价格
hunyuan-lite免费免费
hunyuan-standard¥0.008/千Token¥0.008/千Token
hunyuan-pro¥0.03/千Token¥0.06/千Token
hunyuan-turbo¥0.015/千Token¥0.06/千Token

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

回答

场景推荐模型原因
测试开发hunyuan-lite免费
快速响应hunyuan-turbo速度快
复杂任务hunyuan-pro能力强
日常对话hunyuan-standard平衡选择

Q3:如何生成签名?

回答

php
<?php
function generateSignature(string $secretKey, string $baseUrl, array $params): string
{
    ksort($params);
    $queryString = http_build_query($params);
    $stringToSign = 'POST' . $baseUrl . '/?' . $queryString;
    return hash_hmac('sha256', $stringToSign, $secretKey);
}

Q4:如何处理API错误?

回答

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

    if (strpos($message, 'AuthFailure') !== false) {
        return '认证失败,请检查SecretId和SecretKey';
    }
    if (strpos($message, 'RequestLimitExceeded') !== false) {
        return '请求过于频繁';
    }
    if (strpos($message, 'InvalidParameter') !== false) {
        return '参数错误';
    }

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

Q5:支持哪些区域?

回答

区域代码
广州ap-guangzhou
上海ap-shanghai
北京ap-beijing

Q6:如何实现多轮对话?

回答

php
<?php
class HunyuanChatSession
{
    private HunyuanClient $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:编写一个简单的混元聊天程序。

参考代码

php
<?php
$secretId = getenv('TENCENT_SECRET_ID');
$secretKey = getenv('TENCENT_SECRET_KEY');
$client = new HunyuanClient($secretId, $secretKey);

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

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

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

    $result = $client->chat([['Role' => 'user', 'Content' => $input]]);
    echo "混元: " . $result['Choices'][0]['Message']['Content'] . "\n";
}

进阶练习

练习2:实现一个文档摘要工具。

参考代码

php
<?php
class DocumentSummarizer
{
    private HunyuanClient $client;

    public function summarize(string $document, int $maxLength = 500): string
    {
        $result = $this->client->chat([
            ['Role' => 'user', 'Content' => "请将以下文档总结为不超过{$maxLength}字:\n\n{$document}"]
        ]);

        return $result['Choices'][0]['Message']['Content'];
    }
}

挑战练习

练习3:构建一个智能问答系统。

参考代码

php
<?php
class IntelligentQA
{
    private HunyuanClient $client;
    private array $context = [];

    public function addContext(string $content): void
    {
        $this->context[] = $content;
    }

    public function answer(string $question): string
    {
        $contextStr = implode("\n\n", $this->context);
        $result = $this->client->chat([
            ['Role' => 'user', 'Content' => "背景信息:\n{$contextStr}\n\n问题:{$question}"]
        ]);

        return $result['Choices'][0]['Message']['Content'];
    }
}

知识点总结

核心要点

  1. 签名认证:使用腾讯云签名认证
  2. 免费模型:hunyuan-lite免费使用
  3. 腾讯生态:与微信、腾讯云等集成
  4. 多模态:支持文本、图像、语音
  5. 企业级服务:完善的企业级支持

易错点回顾

易错点正确做法
签名错误按字母顺序排序参数
模型名称错误使用正确的模型名称
消息格式错误使用首字母大写的字段名

拓展参考资料

官方文档

进阶学习路径

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

💡 记住:混元使用腾讯云签名认证,hunyuan-lite免费使用,与腾讯生态深度集成适合企业级应用。