开发工具/SDK 参考/Java SDK/快速开始
快速开始
更新于: 2026-06-25 19:29:14
本文介绍如何使用 Coze Java SDK 完成扣子编程的常用操作,例如如何初始化 SDK、创建一个智能体草稿、发布智能体为 API 服务、和智能体对话等。
说明
初始化之前,请确认已完成以下操作:
初始化 Coze client 之后,才可以向扣子编程服务端发送 OpenAPI 请求。初始化时推荐通过环境变量动态获取访问密钥,以免硬编码引发数据安全风险。
初始化代码如下:
import com.coze.openapi.service.auth.TokenAuth;
import com.coze.openapi.service.config.Consts;
import com.coze.openapi.service.service.CozeAPI;
import okhttp3.OkHttpClient;
public class InitClientExample {
public static void main(String[] args) {
// Get an access_token through personal access token or oauth.
// Coze suggest that you manage access keys through environment variables.
String token = System.getenv("COZE_API_TOKEN");
TokenAuth authCli = new TokenAuth(token);
CozeAPI coze =
new CozeAPI.Builder()
.baseURL(Consts.COZE_CN_BASE_URL)
.auth(authCli)
.client(new OkHttpClient.Builder().build())
.build();
}
}
通过 API 方式和智能体对话之前,你需要先创建一个智能体,并将其发布为 API 服务。你可以在扣子编程中创建智能体并发布,也可以通过调用相关的 API 实现。调用 API 创建智能体时,部分配置对应的 API 参数暂未开放,你只能为智能体添加知识库等有限的配置。创建智能体的操作步骤可参考搭建一个 AI 助手智能体,将智能体发布为 API 服务的操作步骤可参考发布智能体为 API 服务。
示例代码如下:
package example.bot;
import java.util.Arrays;
import com.coze.openapi.client.bots.*;
import com.coze.openapi.client.bots.model.BotOnboardingInfo;
import com.coze.openapi.client.bots.model.BotPromptInfo;
import com.coze.openapi.client.files.UploadFileReq;
import com.coze.openapi.client.files.UploadFileResp;
import com.coze.openapi.service.auth.TokenAuth;
import com.coze.openapi.service.service.CozeAPI;
/*
This example is for describing how to create a bot, update a bot and publish a bot to the API.
The document for those interface:
* */
public class BotPublishExample {
public static void main(String[] args) {
// Get an access_token through personal access token or oauth.
String token = System.getenv("COZE_API_TOKEN");
TokenAuth authCli = new TokenAuth(token);
// Init the Coze client through the access_token.
CozeAPI coze =
new CozeAPI.Builder()
.baseURL(Consts.COZE_CN_BASE_URL)
.auth(authCli)
.readTimeout(10000)
.build();
;
/*
* step one, create a bot
* */
String workspaceID = System.getenv("WORKSPACE_ID");
// set the prompt of your bot
BotPromptInfo promptInfo = new BotPromptInfo("your prompt");
// set the onboarding info of your bot
BotOnboardingInfo onboardingInfo =
BotOnboardingInfo.builder()
.prologue("the prologue of your bot")
.suggestedQuestions(Arrays.asList("question 1", "question 2"))
.build();
// Call the upload file interface to get the avatar id.
String avatarPath = System.getenv("IMAGE_FILE_PATH");
UploadFileResp avatarInfo = coze.files().upload(UploadFileReq.of(avatarPath));
System.out.println(avatarInfo);
// build the request
CreateBotReq createReq =
CreateBotReq.builder()
.spaceID(workspaceID)
.description("the description of your bot")
.name("the name of your bot")
.promptInfo(promptInfo)
.onboardingInfo(onboardingInfo)
.iconFileID(avatarInfo.getFileInfo().getID())
.build();
// Invoke the creation interface to create a bot in the draft status, and you can get the bot
// id.
CreateBotResp createResp = coze.bots().create(createReq);
String botID = createResp.getBotID();
System.out.println(createResp);
/*
* step two, update the bot, you can update the bot after being created
* in this example, we will update the avatar of the bot
*/
PublishBotReq publishReq =
PublishBotReq.builder().botID(botID).connectorIDs(Arrays.asList("1024")).build();
}
}
发起对话接口用于向指定智能体发起一次对话,支持在对话时添加对话的上下文消息,以便智能体基于历史消息做出合理的回复。开发者可以按需选择响应方式,即流式或非流式响应,响应方式决定了开发者获取智能体回复的方式。
本文档以流式响应为例,演示通过 API 方式和智能体对话相关实例代码。你也可以查看 Coze Java SDK 示例代码目录,查看发起对话接口的其他实现方式,例如非流式响应、对话中发送多模态内容等。
示例代码如下:
/* (C)2024 */
package example.chat;
import java.util.Collections;
import com.coze.openapi.client.chat.CreateChatReq;
import com.coze.openapi.client.chat.model.ChatEvent;
import com.coze.openapi.client.chat.model.ChatEventType;
import com.coze.openapi.client.connversations.message.model.Message;
import com.coze.openapi.service.auth.TokenAuth;
import com.coze.openapi.service.service.CozeAPI;
import io.reactivex.Flowable;
/*
* This example is about how to use the streaming interface to start a chat request
* and handle chat events
* */
public class StreamChatExample {
public static void main(String[] args) {
// Get an access_token through personal access token or oauth.
String token = System.getenv("COZE_API_TOKEN");
String botID = System.getenv("PUBLISHED_BOT_ID");
String userID = System.getenv("USER_ID");
TokenAuth authCli = new TokenAuth(token);
// Init the Coze client through the access_token.
CozeAPI coze =
new CozeAPI.Builder()
.baseURL(Consts.COZE_CN_BASE_URL)
.auth(authCli)
.readTimeout(10000)
.build();
;
/*
* Step one, create chat
* Call the coze.chat().stream() method to create a chat. The create method is a streaming
* chat and will return a Flowable ChatEvent. Developers should iterate the iterator to get
* chat event and handle them.
* */
CreateChatReq req =
CreateChatReq.builder()
.botID(botID)
.userID(userID)
.messages(Collections.singletonList(Message.buildUserQuestionText("What can you do?")))
.build();
Flowable<ChatEvent> resp = coze.chat().stream(req);
resp.blockingForEach(
event -> {
if (ChatEventType.CONVERSATION_MESSAGE_DELTA.equals(event.getEvent())) {
System.out.print(event.getMessage().getContent());
}
if (ChatEventType.CONVERSATION_CHAT_COMPLETED.equals(event.getEvent())) {
System.out.println("Token usage:" + event.getChat().getUsage().getTokenCount());
}
});
System.out.println("done");
coze.shutdownExecutor();
}
}