Springboot 集成火山大模型(豆包)配置及代码全流程
摘要:本项目基于SpringBoot框架集成火山引擎大模型SDK,实现后端管理的对话API调用功能。核心功能包括基础对话、应用对话和临时API Key获取,通过后端保管长期密钥并生成临时Token保障安全性。项目使用Maven依赖volcengine-java-sdk-ark-runtime,提供Java代码示例展示如何获取时效性API Key。关键注意事项包括:资源类型需与调用方式匹配(endp
·
项目目标
使用SpringBoot集成火山引擎大模型官方SDK,实现模型对话的调用功能。
业务场景
由后端保管API Key,前端直接调用对话接口(推理点调用/应用调用)。
核心功能
相关文档
接口调用示例
基础对话调用
POST https://ark.cn-beijing.volces.com/api/v3/chat/completions
Authorization: Bearer <ApiKey>
{
"model": "ep-202********331-wd456",
"messages": [
{
"content": [
{
"text": "你是谁?",
"type": "text"
}
],
"role": "user"
}
],
"stream": true
}
应用对话调用
POST https://ark.cn-beijing.volces.com/api/v3/bots/chat/completions
Authorization: Bearer <ApiKey>
{
"model": "bot-20**********41-47676",
"stream": true,
"stream_options": {
"include_usage": true
},
"messages": [
{
"role": "user",
"content": "你是谁"
}
]
}
临时API Key获取
以上接口均需要设置请求头 Authorization Bearer ,但是APIKEy 是长期有效的,所以不适合使用 长期apiKey 显示传递调用接口。所以这里就需要使用获取临时的有时效性的 ApiKey;
Maven依赖:
<dependency>
<groupId>com.volcengine</groupId>
<artifactId>volcengine-java-sdk-ark-runtime</artifactId>
<version>0.2.30</version>
</dependency>
@Service
@Log4j2
public class DouBaoSignService {
@Value("${doubao.ak}")
private String ak;
@Value("${doubao.sk}")
private String sk;
public String getApiKey(String modelKey, String sourceType) {
// 注意示例代码安全,代码泄漏会导致AK/SK泄漏,有极大的安全风险。
// PS: 这里是使用配置文件当时保存 ak/sk 官方建议可以通过 环境变量进行设置
String region = "cn-beijing";
ApiClient apiClient = new ApiClient()
.setCredentials(Credentials.getCredentials(ak, sk))
.setRegion(region);
ArkApi api = new ArkApi(apiClient);
GetApiKeyRequest request = new GetApiKeyRequest();
request.setDurationSeconds(60);
request.setResourceType(sourceType);
request.setResourceIds(new ArrayList<>(List.of(modelKey)));
try {
GetApiKeyResponse response = api.getApiKey(request);
return response.getApiKey();
} catch (ApiException e) {
log.error("获取临时apiKey异常", e);
throw new ServiceException("获取配置超时,请联系管理员");
}
}
}
参数说明
- DurationSeconds:临时API Key有效期(秒)
- ResourceType:资源类型(endpoint:模型推理接入点 / bot:智能体应用)
- ResourceIds:资源ID集合
注意事项
- 使用应用临时API Key调用应用对话时,需确保:
- 应用的 推理接入点 选择 自定义接入点
- 推理接入点与应用处于同一项目下
更多推荐
所有评论(0)