php无需sdk原生调用腾讯混元大模型api示例代码

代码语言:php

所属分类:其他

代码描述:php无需sdk原生调用腾讯混元大模型api示例代码,不需要composer下载tencentcloud-sdk,直接通过curl请求接口方式实现。

代码标签: php 无需 sdk 原生 调用 腾讯 混元 大模型 ap i示例 代码

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

<?php

class Hunyuan {
    // 腾讯云的 SecretId
    protected $secretId;
    // 腾讯云的 SecretKey
    protected $secretKey;
    // Hunyuan API 终端
    protected $endpoint = "hunyuan.tencentcloudapi.com";
    // 当前使用的地域
    protected $region = "ap-guangzhou";
    // 所使用的大语言模型
    protected $model = "hunyuan-pro";
    // API 版本号
    protected $version = "2023-09-01";
    
    /**
     * 构造函数
     *
     * @param string $secretId
     * @param string $secretKey
     */
    public function __construct($secretId, $secretKey) {
        $this->secretId = $secretId;
        $this->secretKey = $secretKey;
    }
    
    /**
     * 腾讯混元大语言模型调用函数
     *
     * @param array $messages 聊天上下文信息
     * @param float $topP 多样性控制参数
     * @param float $temperature 随机性控制参数
     * @param bool $stream 是否流式调用
     * @param bool $streamModeration 是否使用流式输出审核
     * 
     * @return string API 返回结果
     */
    public function callModel($messages, $topP = 1.0, $temperature = 1.0, $stream = false, $streamModeration = false) {
        $params = [
            "Model" => $this->model,
            "Messages" => $messages,
            "TopP" => $topP,
            "Temperature" => $temperature,
            "Stream" => $stream,
            "StreamModeration" => $streamModeration,
        ];

        $timestamp = time();
        $date = gmdate("Y-m-d", $timestamp);
        
        // 构建 HTTP 请求信息
        $method = "POST";
        $canonicalUri = "/";
        $canonicalQueryString = "";
        $canonicalHeaders = "content-type:application/json\nhost:{$this->endpoint}\n";
        $signedHeaders = "content-type;host";
        $hashedRequestPayload = hash("sha256", json_encode($params));
        $canonicalRequest = "{$method}\n{$canonicalUri}\n{$canonicalQueryString}\n{$canonicalHeaders}\n{$signedHeaders}\n{$hashedRequestPayload}";
        
        // 构建 String to Sign
        $algorithm = "TC3-HMAC-SHA256";
        $credentialScope = "{$date}/hunyuan/tc3_request";
        $stringToSign = "{$algorithm}\n{$timestamp}\n{$credentialScope}\n" . hash("sha256", $canonicalRequest);
        
        // 计算签名
        $secretDate = hash_hmac("sha256", $date, "TC3" . $this->secretKey, true);
        $secretService = hash_hmac("sha256", "hunyuan", $secretDate,.........完整代码请登录后点击上方下载按钮下载查看

网友评论0