avatar

mdo

Hello

  • 首页
  • 知识库
  • 归档
  • 标签
  • 关于
主页 OpenAI 标准接口
文章

OpenAI 标准接口

发表于 2026-08-22 更新于 2026-08- 22
作者 mdo
8~11 分钟 阅读

在 ThinkPHP 6 中对接 OpenAI 标准接口并实现同步阻塞返回,使用 TP6 内置的 think\facade\Http 客户端最为快捷。

以下是完整的生产级代码实现:

1. 配置环境变量 (.env)

在项目根目录的 .env 文件中配置大模型凭证,方便管理和切换(例如切换为国内的 DeepSeek、通义千问等 OpenAI 兼容接口):

env

[OPENAI]
API_KEY = sk-xxxxxxxxxxxxxxxxxxxxxxxx
BASE_URL = https://openai.com
MODEL = gpt-4o

请谨慎使用此类代码。

2. 创建大模型服务类

新建 app/service/OpenAiService.php,负责封装 HTTP 请求:

php

<?php
namespace app\service;

use think\facade\Http;
use think\facade\Log;

class OpenAiService
{
    protected $apiKey;
    protected $baseUrl;
    protected $model;

    public function __construct()
    {
        // 自动读取 .env 配置,设置默认值
        $this->apiKey  = env('OPENAI.API_KEY', '');
        $this->baseUrl = env('OPENAI.BASE_URL', 'https://openai.com');
        $this->model   = env('OPENAI.MODEL', 'gpt-4o');
    }

    /**
     * 发送同步阻塞请求
     * @param string $prompt 用户输入
     * @param float $temperature 随机性 (0-2)
     * @return string 模型的文本回复
     */
    public function ask(string $prompt, float $temperature = 0.7): string
    {
        if (empty($this->apiKey)) {
            throw new \Exception('OpenAI API Key 未配置');
        }

        // 构造 OpenAI 标准请求体
        $payload = [
            'model'       => $this->model,
            'temperature' => $temperature,
            'messages'    => [
                ['role' => 'user', 'content' => $prompt]
            ],
            'stream'      => false // 明确指定同步阻塞模式
        ];

        // 发起 HTTP POST 请求 (设置 60 秒超时防止大模型响应过慢)
        $response = Http::header([
            'Authorization' => 'Bearer ' . $this->apiKey,
            'Content-Type'  => 'application/json',
        ])->timeout(60)->post($this->baseUrl, $payload);

        // 处理响应
        if ($response->successful()) {
            $result = $response->json();
            // 解析 OpenAI 标准返回结构
            if (isset($result['choices'][0]['message']['content'])) {
                return $result['choices'][0]['message']['content'];
            }
            throw new \Exception('接口返回数据格式异常:' . $response->getBody());
        }

        // 记录错误日志并抛出异常
        Log::error('OpenAI API 请求失败:' . $response->getBody());
        throw new \Exception('AI 接口调用失败,状态码:' . $response->status());
    }
}

请谨慎使用此类代码。

3. 在控制器中调用

新建 app/controller/Chat.php,接收前端参数并调用服务:

php

<?php
namespace app\controller;

use app\BaseController;
use app\service\OpenAiService;
use think\Response;

class Chat extends BaseController
{
    /**
     * 对话接口
     * @param OpenAiService $aiService 自动依赖注入
     */
    public function index(OpenAiService $aiService): Response
    {
        // 获取前端传入的提示词
        $prompt = $this->request->param('prompt', '');
        
        if (empty($prompt)) {
            return json(['code' => 400, 'msg' => '提示词不能为空']);
        }

        try {
            // 调用服务层获取回复
            $reply = $aiService->ask($prompt);
            
            return json([
                'code' => 200,
                'msg'  => 'success',
                'data' => [
                    'reply' => $reply
                ]
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg'  => $e->getMessage()
            ]);
        }
    }
}

请谨慎使用此类代码。

为了让这个接口更贴合你的项目,请问:

  • 是否需要支持多轮对话(历史聊天记录传递)?

技术
许可协议:  CC BY 4.0
分享

相关文章

10月 2, 2026

iOS 侧载(Sideloading)工具

AltStore 和 Sideloadly 都是目前最流行的 iOS 侧载(Sideloading)工具。 简单来说,它们的作用就是让你绕过苹果的官方 App Store,直接把第三方的 IPA 安装包(也就是 iOS 的应用安装文件)安装到你的 iPhone 或 iPad 上。 通过这两个工具,你

9月 28, 2026

注册 Chat Participant

将当前服务接入 VS Code 的 AI 聊天窗口是完全可行的。VS Code 在近期的版本中正式推出了 Chat Extensions API(github.copilot.chat),允许第三方扩展将自定义的 LLM 服务或工具注册到 Copilot Chat 面板中。 结合当前 code_ge

9月 23, 2026

php intelephense 设置 if 空格

在 VS Code 中,如果你使用的是 PHP Intelephense 插件,控制 if 关键字后面是否加空格的设置是由其内置的格式化引擎(基于 PSR-12 标准)决定的。 你可以通过修改 VS Code 的 settings.json 来配置这个行为: 1. 开启 if 后面的空格(默认/推荐

下一篇

在 Linux 系统上部署本地 AI 模型用于编程辅助

上一篇

生产环境(Nginx 反向代理)

最近更新

  • 比尔盖茨的智慧:想多赚钱,就每天循环做这3件事
  • iOS 侧载(Sideloading)工具
  • 程序员越想创业,越不要急着动手
  • 注册 Chat Participant
  • 中秋给在外游子的一封信

热门标签

API CodeGeex Coding Cursor DeepSeek Docker Gitkraken Harness Laravel Management

目录

©2026 mdo. 保留部分权利。