项目目标

使用SpringBoot集成火山引擎大模型官方SDK,实现模型对话的调用功能。

业务场景

由后端保管API Key,前端直接调用对话接口(推理点调用/应用调用)。

核心功能

  1. ChatCompletions 基础对话 功能
    接口文档
  2. BotsChatCompletions 应用对话 功能
    接口文档
  3. GetApiKey 获取临时API Key
    接口文档

相关文档

  • 访问控制控制台
    用户管理
    管理用户、管理项目 等
  • API文档
    接口概览
    模型调用接口文档介绍
  • 火山方舟控制台
    管理控制台
    模型广场、管理应用、管理推理接入点、管理ApiKey 等

接口调用示例

基础对话调用

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集合

注意事项

  1. 使用应用临时API Key调用应用对话时,需确保:
    • 应用的 推理接入点 选择 自定义接入点
    • 推理接入点与应用处于同一项目
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐