JAVA项目接入百度文心一言文本对话功能

依赖

        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.0.0</version>
        </dependency>

       

1.获取参数

从百度云获取固定参数

        String client_id = "usl...............";
        String client_secret = "T5xrE5k...............";

2.完整代码
 

package com.center.common.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.common.constants.RedisConstant;
import com.common.core.HttpRequestServer;
import com.common.redis.RedisOperation;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap
### 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协议保护通信安全。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值