IntelliJ IDEA快速接入LLMs大模型API

IntelliJ IDEA快速接入LLMs大模型API

时隔很久没写文章,这次记录下自己在使用Spring AI来接入大模型的方式。由于2024年7月之后OpenAI,Google gemini很多大公司开始了限制中国区访问,这也让我在实验过程中浪费了很多时间。本次选用了百度文心一言的千帆大模型进行实验。对于简单的测试效果速度还是可以接受的,同时最重要的是,可以调通!

一、创建个人API Key

1.1 登录智能云

https://cloud.baidu.com/?from=console

1.2 搜索"千帆大模型服务与开发平台ModelBuilder"

1.3 选择应用接入 -》 创建应用 来获得我们的

获取access token方式,将如下的连接替换为自己的API Key与Secret Key,并在浏览器中打开

https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials\&client_id=\[API_Key\]\&client_secret=\[Secret_Key\]

其中的access token就是我们需要的,我们可以将其配置在自己的spring boot项目中。

二、代码示例

我们通过创建自己的spring boot 项目进行测试

spring boot 版本控制在3.0以上

导入依赖

xml 复制代码
		<dependency>
			<groupId>cn.hutool</groupId>
			<artifactId>hutool-all</artifactId>
			<version>5.8.25</version>
		</dependency>
java 复制代码
	public static void main(String[] args) {
		String url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions";
		String accessToken = "自己的access token";

		HashMap<String, String> msg = new HashMap<>();
		msg.put("role", "user");
		msg.put("content", "你是谁?");

		ArrayList<HashMap> messages = new ArrayList<>();
		messages.add(msg);

		HashMap<String, Object> requestBody = new HashMap<>();
		requestBody.put("messages", messages);

		String response = HttpUtil.post(url + "?access_token=" + accessToken, JSONUtil.toJsonStr(requestBody));

		System.out.println(response);
	}

Output

powershell 复制代码
{
    "id": "as-acbg25ytgj",
    "object": "chat.completion",
    "created": ,
    "result": "您好,我是文心一言,英文名是ERNIE Bot。我能够与人对话互动,回答问题,协助创作,高效便捷地帮助人们获取信息、知识和灵感。",
    "is_truncated": false,
    "need_clear_history": false,
    "usage": {
        "prompt_tokens": 12,
        "completion_tokens": 32,
        "total_tokens": 317
    }
}

Tips:新用户应该是有个20元免费券可以使用哦,如果超过了,就要自己付费了,大家且用且珍惜。

相关推荐
日月云棠1 天前
各版本JDK对比:JDK 25 特性详解
java
用户8307196840821 天前
Spring Boot 项目中日期处理的最佳实践
java·spring boot
JavaGuide1 天前
Claude Opus 4.6 真的用不起了!我换成了国产 M2.5,实测真香!!
java·spring·ai·claude code
IT探险家1 天前
Java 基本数据类型:8 种原始类型 + 数组 + 6 个新手必踩的坑
java
花花无缺1 天前
搞懂new 关键字(构造函数)和 .builder() 模式(建造者模式)创建对象
java
用户908324602731 天前
Spring Boot + MyBatis-Plus 多租户实战:从数据隔离到权限控制的完整方案
java·后端
桦说编程1 天前
实战分析 ConcurrentHashMap.computeIfAbsent 的锁冲突问题
java·后端·性能优化
程序员清风1 天前
用了三年AI,我总结出高效使用AI的3个习惯!
java·后端·面试
beata1 天前
Java基础-13: Java反射机制详解:原理、使用与实战示例
java·后端
用户0332126663671 天前
Java 使用 Spire.Presentation 在 PowerPoint 中添加或删除表格行与列
java