You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在CodeIgniter 4中调用OpenAI API如何仅提取响应内容?

在CodeIgniter 4中提取OpenAI Chat Completion的assistant内容

你可以通过解析API返回的响应结构,精准提取assistant角色的content字段,具体实现如下:

完整控制器方法示例

public function openAIPost()
{
    // 初始化OpenAI实例
    $openAi = new \Orhanerday\OpenAi\OpenAi('你的API密钥');

    // 构造对话消息
    $messages = [
        [
            "role" => "user",
            "content" => "请输入你的提问内容"
        ]
    ];

    // 调用Chat Completion接口
    $apiResponse = $openAi->createChatCompletion([
        'model' => 'gpt-3.5-turbo',
        'messages' => $messages,
        'temperature' => 0.7,
    ]);

    // 将JSON响应解码为关联数组
    $result = json_decode($apiResponse, true);

    // 处理API返回的错误
    if (isset($result['error'])) {
        return $this->response->setJSON([
            'error' => $result['error']['message']
        ])->setStatusCode($result['error']['code'] ?? 500);
    }

    // 提取assistant的回复内容
    if (isset($result['choices'][0]['message']['content'])) {
        $assistantContent = trim($result['choices'][0]['message']['content']);
        // 返回仅包含目标内容的响应
        return $this->response->setJSON([
            'reply' => $assistantContent
        ]);
    } else {
        // 处理响应结构异常的情况
        return $this->response->setJSON([
            'error' => '无法获取assistant的回复内容'
        ])->setStatusCode(400);
    }
}

核心提取逻辑说明

OpenAI Chat Completion的响应结构中,assistant的内容固定位于choices数组第一个元素的message对象内,通过$result['choices'][0]['message']['content']即可直接获取。如果习惯使用对象操作,也可以将解码参数设为false,通过对象属性访问:

$result = json_decode($apiResponse);
$assistantContent = trim($result->choices[0]->message->content);

内容的提问来源于stack exchange,提问作者Agata

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 17:42:19