thinkphp 接入百度文心一言大模型
时间: 2025-06-13 10:50:26 浏览: 12
### ThinkPHP集成百度文心一言大模型API的教程
要在ThinkPHP框架中接入百度文心一言大模型API,可以按照以下方法实现。此过程涉及配置API请求参数、发送HTTP请求并处理返回的数据。
#### 1. 准备工作
在开始之前,需要完成以下准备工作:
- **获取API Key和Secret Key**:登录百度AI开放平台[^3],创建应用并获取对应的API Key和Secret Key。
- **安装必要的依赖库**:确保项目中有用于发起HTTP请求的库,例如`GuzzleHttp/Guzzle`或其他类似的库。
```bash
composer require guzzlehttp/guzzle
```
---
#### 2. 创建服务类
为了更好地管理和调用API,在项目的`app/service`目录下创建一个新的服务类文件,命名为`BaiduWenxinService.php`。
```php
<?php
namespace app\service;
use GuzzleHttp\Client;
use think\facade\Log;
class BaiduWenxinService
{
private $apiKey;
private $secretKey;
private $accessTokenUrl;
private $apiEndpoint;
public function __construct($apiKey, $secretKey)
{
$this->apiKey = $apiKey;
$this->secretKey = $secretKey;
$this->accessTokenUrl = 'https://aip.baidubce.com/oauth/2.0/token';
$this->apiEndpoint = 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat'; // 替换为目标接口URL
}
/**
* 获取AccessToken
*/
public function getAccessToken()
{
try {
$client = new Client();
$response = $client->request('POST', $this->accessTokenUrl, [
'query' => [
'grant_type' => 'client_credentials',
'client_id' => $this->apiKey,
'client_secret' => $this->secretKey,
]
]);
$result = json_decode((string)$response->getBody(), true);
if (isset($result['access_token'])) {
return $result['access_token'];
} else {
Log::error('Failed to fetch access token: ' . json_encode($result));
throw new \Exception('Access Token Fetch Failed');
}
} catch (\Throwable $th) {
Log::error('Error fetching access token: ' . $th->getMessage());
throw $th;
}
}
/**
* 调用文心一言API
*
* @param string $message 用户输入的消息
* @return array API响应数据
*/
public function callApi(string $message): array
{
try {
$accessToken = $this->getAccessToken();
$client = new Client();
$response = $client->post($this->apiEndpoint, [
'headers' => [
'Content-Type' => 'application/json'
],
'json' => [
'access_token' => $accessToken,
'messages' => [['role' => 'user', 'content' => $message]]
]
]);
return json_decode((string)$response->getBody(), true);
} catch (\Throwable $th) {
Log::error('Error calling Wenxin API: ' . $th->getMessage());
return ['error' => $th->getMessage()];
}
}
}
```
---
#### 3. 控制器调用逻辑
在控制器中实例化服务类并调用其方法:
```php
<?php
namespace app\Controller;
use app\service\BaiduWenxinService;
class ChatController extends BaseController
{
public function chat()
{
$apiKey = config('baidu.api_key'); // 从配置文件读取API Key
$secretKey = config('baidu.secret_key'); // 从配置文件读取Secret Key
$wenxinService = new BaiduWenxinService($apiKey, $secretKey);
$inputMessage = input('post.message/s', ''); // 获取用户输入消息
if (!$inputMessage) {
return json(['code' => 400, 'msg' => '请输入有效的内容']);
}
$response = $wenxinService->callApi($inputMessage);
if (isset($response['error_code']) && $response['error_code'] !== 0) {
return json(['code' => 500, 'msg' => 'API调用失败', 'data' => $response]);
}
return json([
'code' => 200,
'msg' => '成功',
'data' => isset($response['result']['content']) ? $response['result']['content'] : ''
]);
}
}
```
---
#### 4. 配置文件设置
在`config/baidu.php`中定义API Key和Secret Key:
```php
<?php
return [
'api_key' => 'your_api_key_here',
'secret_key' => 'your_secret_key_here',
];
```
---
#### 5. 测试接口
通过Postman或浏览器访问接口地址,传递用户提问内容作为参数,验证是否能够正常接收来自文心一言的回答。
---
### 注意事项
- 确保服务器环境满足最低要求,如PHP >= 8.0[^1]。
- 如果频繁调用API,请注意速率限制,并合理设计缓存机制以减少不必要的请求次数。
- 对于敏感业务场景,建议启用HTTPS协议保护通信安全。
---
阅读全文
相关推荐

















