Java 调用 Coze API 完整方案,一套智能体开发过程代码

核心依赖

<!-- Maven pom.xml --> 
<dependencies>
 <!-- OkHttp - HTTP 客户端 --> 
<dependency> 
<groupId>com.squareup.okhttp3</groupId> 
<artifactId>okhttp</artifactId> 
<version>4.12.0</version> 
</dependency>
 <!-- Gson - JSON 处理 --> 
<dependency> 
<groupId>com.google.code.gson</groupId> 
<artifactId>gson</artifactId> 
<version>2.10.1</version> 
</dependency> 
<!-- Lombok - 简化代码 --> 
<dependency> 
<groupId>org.projectlombok</groupId> 
<artifactId>lombok</artifactId> 
<version>1.18.30</version> 
<scope>provided</scope> 
</dependency> 
</dependencies>

API 配置类

package com.coze.api; 
/** * Coze API 配置 */
 public class CozeConfig {
 // Coze API 基础地址
 public static final String BASE_URL = "https://api.coze.cn";
 // API 版本 
public static final String API_VERSION = "/v3"; 
// 你的访问令牌(从 Coze 控制台获取) 
private String accessToken; 
// 工作空间 ID(可选) 
private String workspaceId; 
public CozeConfig(String accessToken) {
 this.accessToken = accessToken;
 } 
public CozeConfig(String accessToken, String workspaceId) {
 this.accessToken = accessToken; 
this.workspaceId = workspaceId;
 } 
// Getters 
public String getAccessToken() { 
return accessToken;
 } 
public String getWorkspaceId() { 
return workspaceId;
 } 
public String getAuthorizationHeader() {
 return "Bearer " + accessToken; 
} 
}

HTTP 客户端封装

package com.coze.api; 
import com.google.gson.Gson; 
import com.google.gson.GsonBuilder;
 import okhttp3.*; 
import java.io.IOException; 
import java.util.concurrent.TimeUnit; 
/** * HTTP 客户端封装 */ 
public class CozeHttpClient { 
private final OkHttpClient httpClient; 
private final Gson gson; 
private final CozeConfig config; 
public CozeHttpClient(CozeConfig config) { 
this.config = config; 
this.gson = new GsonBuilder() .setPrettyPrinting() .create(); 
this.httpClient = new OkHttpClient.Builder() 
.connectTimeout(30, TimeUnit.SECONDS) 
.readTimeout(60, TimeUnit.SECONDS) 
.writeTimeout(30, TimeUnit.SECONDS) .build();

} 
/** * 发送 POST 请求 */ 
public <T> T post(String endpoint, Object requestBody, Class<T> responseClass) throws IOException {
 String json = gson.toJson(requestBody); 
Request request = new Request.Builder() 
.url(CozeConfig.BASE_URL + endpoint) 
.addHeader("Authorization",config.getAuthorizationHeader()) 
.addHeader("Content-Type", "application/json") 
.post(RequestBody.create(json, MediaType.parse("application/json"))) 
.build(); 
try (Response response = httpClient.newCall(request).execute()) { 
if (!response.isSuccessful())
 { 
throw new IOException("请求失败: " + response.code() + " - " + response.message());
 } 
String responseBody = response.body().string();
 return gson.fromJson(responseBody, responseClass); } } 
/** * 发送 GET 请求 */
 public <T> T get(String endpoint, Class<T> responseClass) throws IOException { 
Request request = new Request.Builder() 
.url(CozeConfig.BASE_URL + endpoint) 
.addHeader("Authorization", config.getAuthorizationHeader()) 
.build(); 
try (Response response = httpClient.newCall(request).execute()) 
{ 
if (!response.isSuccessful()) {
 throw new IOException("请求失败: " + response.code() + " - " + response.message()); 
} 
String responseBody = response.body().string(); 
return gson.fromJson(responseBody, responseClass); 
} 
} 
public Gson getGson() { 
return gson;
 }
 }

智能体相关模型类

package com.coze.model;
 import com.google.gson.annotations.SerializedName;
 import lombok.Data; 
import java.util.List; 
/** * 创建智能体请求 */ 
@Data 
public class CreateBotRequest {
 private String name; 
// 智能体名称 
private String description; 
// 描述 
private String iconUrl; 
// 图标 URL 
@SerializedName("workspace_id") 
private String workspaceId; 
// 工作空间 ID 
private PromptInfo promptInfo; 
// 提示词配置 
private ModelInfo modelInfo; 
// 模型配置 
private List<PluginInfo> plugins; 
// 插件/工具列表 
@Data
 public static class PromptInfo {
 private String prompt; 
// 系统提示词 
@SerializedName("display_prompt") 
private String displayPrompt; 
// 展示提示词 
} 
@Data 
public static class ModelInfo { 
private String model;
 // 模型 ID 
@SerializedName("response_format") 
private String responseFormat; 
// 响应格式
 }
 @Data 
public static class PluginInfo {
 private String id; 
// 插件 ID 
private String name; 
// 插件名称 
@SerializedName("api_schema") 
private ApiSchema apiSchema; 
// API 定义 
@Data 
public static class ApiSchema { 
private String type; 
// 类型 
private String url; 
// API URL
 private String method; 
// HTTP 方法
 } 
} 
} 
/** * 创建智能体响应 */ 
@Data 
public class CreateBotResponse { 
private String code; 
private String msg;
 private BotData data; 
@Data 
public static class BotData { 
@SerializedName("bot_id")
 private String botId; 
// 智能体 ID 
private String name; 
private String description; 
} 
} 
/** * 发布智能体请求 */
 @Data
 public class PublishBotRequest { 
@SerializedName("bot_id") 
private String botId; 
@SerializedName("connector_ids") 
private List<String> connectorIds; 
// 发布渠道 ID 
private List<VersionInfo> versions; 
@Data 
public static class VersionInfo { 
private String version;
 // 版本号 
private String desc; 
// 版本描述 
} 
} 
/** * 对话请求 */ 
@Data 
public class ChatRequest { 
@SerializedName("bot_id")
 private String botId; 
private String userId; 
// 用户 ID 
private String stream;
 // 是否流式: true/false 
private List<Message> messages; 
// 消息列表 
@SerializedName("custom_variables") 
private Object customVariables; 
// 自定义变量 
@Data 
public static class Message { 
private String role;
 // user/assistant 
private String content; 
// 消息内容 
private String contentType; 
// text/image 
} 
} 
/** * 对话响应 */ 
@Data
 public class ChatResponse { 
private String code;
 private String msg;
 private ChatData data;
 @Data 
public static class ChatData {
 private String id;
 // 会话 ID 
@SerializedName("conversation_id") 
private String conversationId; 
private List<Message> messages; 
private Usage usage; 
@Data 
public static class Message { 
private String role; 
private String content; 
private String type; 
// answer/function_call 
} 
@Data 
public static class Usage { 
@SerializedName("token_count") 
private Integer tokenCount; 
@SerializedName("input_tokens") 
private Integer inputTokens; 
@SerializedName("output_tokens") 
private Integer outputTokens; 
}
 } 
}

智能体服务类

package com.coze.service; 
import com.coze.api.CozeConfig;
 import com.coze.api.CozeHttpClient; 
import com.coze.model.*; 
import java.io.IOException; 
import java.util.Arrays; 
import java.util.Collections; 
/** * 智能体管理服务 */ 
public class BotService { 
private final CozeHttpClient httpClient;
 public BotService(CozeConfig config) {
 this.httpClient = new CozeHttpClient(config);
 } 
/** * 创建智能体 */
 public CreateBotResponse createBot(String name, String description, String systemPrompt) throws IOException {
 CreateBotRequest request = new CreateBotRequest(); 
request.setName(name);
 request.setDescription(description); 
request.setWorkspaceId(httpClient.getConfig().getWorkspaceId());
 // 配置提示词 
CreateBotRequest.PromptInfo promptInfo = new CreateBotRequest.PromptInfo(); 
promptInfo.setPrompt(systemPrompt); request.setPromptInfo(promptInfo); 
// 配置模型 
CreateBotRequest.ModelInfo modelInfo = new CreateBotRequest.ModelInfo(); 
modelInfo.setModel("doubao-seed-1-8-251228");
 // 使用默认模型 
request.setModelInfo(modelInfo);
 return httpClient.post("/v3/bot/create", request, CreateBotResponse.class); 
} 
/** * 创建带工具的智能体 */ 
public CreateBotResponse createBotWithTools( String name, String description, String systemPrompt, String[] pluginIds ) throws IOException {
 CreateBotRequest request = new CreateBotRequest(); 
request.setName(name); 
request.setDescription(description);
 CreateBotRequest.PromptInfo promptInfo = new CreateBotRequest.PromptInfo(); 
promptInfo.setPrompt(systemPrompt); request.setPromptInfo(promptInfo); 
CreateBotRequest.ModelInfo modelInfo = new CreateBotRequest.ModelInfo(); 
modelInfo.setModel("doubao-seed-1-8-251228"); request.setModelInfo(modelInfo); 
// 添加插件/工具 
if (pluginIds != null && pluginIds.length > 0) { 
request.setPlugins(Arrays.stream(pluginIds) .map(id -> {
 CreateBotRequest.PluginInfo plugin = new CreateBotRequest.PluginInfo();
 plugin.setId(id);
 return plugin; 
}) .toList()); 
} 
return httpClient.post("/v3/bot/create", request, 
CreateBotResponse.class); 
}
 /** * 更新智能体 */ 
public void updateBot(String botId, String name, String description, String systemPrompt) throws IOException {
 UpdateBotRequest request = new UpdateBotRequest(); 
request.setBotId(botId);
 request.setName(name); 
request.setDescription(description);
 CreateBotRequest.PromptInfo promptInfo = new CreateBotRequest.PromptInfo(); 
promptInfo.setPrompt(systemPrompt); 
request.setPromptInfo(promptInfo); 
httpClient.post("/v3/bot/update", request, Void.class);
 } 
/** * 发布智能体 */
 public void publishBot(String botId) throws IOException { 
PublishBotRequest request = new PublishBotRequest(); request.setBotId(botId);
 httpClient.post("/v3/bot/publish", request, Void.class); 
} 
/** * 删除智能体 */ 
public void deleteBot(String botId) throws IOException {
 DeleteBotRequest request = new DeleteBotRequest(); request.setBotId(botId);
 httpClient.post("/v3/bot/delete", request, Void.class);
 } 
} 
// 辅助请求类 
@Data
 class UpdateBotRequest { 
@SerializedName("bot_id") 
private String botId; 
private String name; 
private String description; 
private CreateBotRequest.PromptInfo promptInfo; 
} 
@Data 
class DeleteBotRequest { 
@SerializedName("bot_id")
 private String botId;
 }

对话服务类

package com.coze.service; 
import com.coze.api.CozeConfig;
 import com.coze.api.CozeHttpClient; 
import com.coze.model.*; 
import java.io.IOException; 
import java.util.Collections;
 import java.util.UUID;
 /** * 对话服务 */ 
public class ChatService { 
private final CozeHttpClient httpClient; 
public ChatService(CozeConfig config) {
 this.httpClient = new CozeHttpClient(config); 
} 
/** * 发送消息(非流式) */
 public ChatResponse sendMessage(String botId, String userId, String message) throws IOException { 
ChatRequest request = new ChatRequest();
 request.setBotId(botId);
 request.setUserId(userId); 
request.setStream("false"); 
ChatRequest.Message msg = new ChatRequest.Message(); 
msg.setRole("user");
 msg.setContent(message);
 msg.setContentType("text"); 
request.setMessages(Collections.singletonList(msg));
 return httpClient.post("/v3/chat", request, ChatResponse.class);
 } 
/** * 多轮对话 */ 
public ChatResponse sendMessage( String botId, String userId, String message, String conversationId ) throws IOException { 
ChatRequest request = new ChatRequest(); 
request.setBotId(botId); 
request.setUserId(userId); 
request.setStream("false"); 
ChatRequest.Message msg = new ChatRequest.Message(); msg.setRole("user");
 msg.setContent(message); 
msg.setContentType("text"); request.setMessages(Collections.singletonList(msg)); 
// 如果有 conversationId,会继续之前的对话 
return httpClient.post("/v3/chat", request, ChatResponse.class);
 } 
/** * 快速对话(生成随机用户 ID) */ 
public ChatResponse quickChat(String botId, String message) throws IOException {
 String userId = UUID.randomUUID().toString();
 return sendMessage(botId, userId, message);
 } 
}

完整使用示例

package com.coze.example;
 import com.coze.api.CozeConfig;
 import com.coze.model.*; 
import com.coze.service.BotService; 
import com.coze.service.ChatService;
 import java.io.IOException; 
/** * 完整使用示例 */ 
public class CozeBotExample { 
public static void main(String[] args) { 
// 1. 配置访问令牌(从 Coze 控制台获取) 
String accessToken = "YOUR_ACCESS_TOKEN"; 
// 替换为你的令牌 
String workspaceId = "YOUR_WORKSPACE_ID"; 
// 替换为你的工作空间 ID 
CozeConfig config = new CozeConfig(accessToken, workspaceId); 
try { 
// 2. 创建智能体服务
 BotService botService = new BotService(config); 
// 3. 创建智能体 
System.out.println("=== 创建智能体 ===");
 CreateBotResponse createResponse = botService.createBot( "Java 客服机器人", "这是一个基于 Java 创建的智能客服机器人", "你是一个专业的客服助手,请用友好、专业的语气回答用户问题。" + "回答要简洁明了,不超过200字。" ); 
if (!"0".equals(createResponse.getCode())) { 
System.err.println("创建失败: " + createResponse.getMsg());
 return; 
} 
String botId = createResponse.getData().getBotId(); 
System.out.println("智能体创建成功!Bot ID: " + botId); 
System.out.println("智能体名称: " + 
createResponse.getData().getName());
 // 4. 发布智能体 
System.out.println("\n=== 发布智能体 ==="); 
botService.publishBot(botId); 
System.out.println("智能体发布成功!"); 
// 5. 测试对话 
System.out.println("\n=== 测试对话 ==="); 
ChatService chatService = new ChatService(config);
 String[] testMessages = { "你好,请介绍一下你自己", "你能帮我做什么?", "如何联系人工客服?" }; 
for (String msg : testMessages) { 
System.out.println("\n用户: " + msg);
 ChatResponse chatResponse = chatService.quickChat(botId, msg);
 if ("0".equals(chatResponse.getCode())) {
 String reply = 
chatResponse.getData() 
.getMessages() 
.stream() 
.filter(m -> 
"answer".equals(m.getType())) 
.findFirst() 
.map(ChatResponse.ChatData.Message::getContent) 
.orElse("无回复"); 

System.out.println("助手: " + reply); 
System.out.println("Token 使用: " 
+ chatResponse.getData().getUsage().getTokenCount()); 
} else {
 System.err.println("对话失败: " + chatResponse.getMsg()); 
} 
// 避免请求过快 
Thread.sleep(1000); 
} 
// 6. 更新智能体(可选) 
System.out.println("\n=== 更新智能体 ==="); 
botService.updateBot( botId, "Java 客服机器人 Pro", "升级版的智能客
服机器人", "你是一个专业的客服助手,具有更强大的能力。" + "请用
友好、专业的语气回答用户问题,并提供详细的解决方案。" ); 
System.out.println("智能体更新成功!"); 
// 7. 删除智能体(可选) 
// System.out.println("\n=== 删除智能体 ==="); 
// botService.deleteBot(botId); 
// System.out.println("智能体已删除");
 } 
catch (IOException e) { 
System.err.println("请求错误: " + e.getMessage());
 e.printStackTrace(); 
} 
catch (InterruptedException e) { 
System.err.println("线程中断: " + e.getMessage()); 
}
 }
 }

流式对话实现(进阶)

package com.coze.service; 
import com.coze.api.CozeConfig;
 import com.google.gson.Gson; 
import okhttp3.*; 
import java.io.BufferedReader;
 import java.io.IOException; 
import java.io.InputStreamReader; 
/** * 流式对话服务 */
 public class StreamChatService { 
private final OkHttpClient httpClient; 
private final CozeConfig config;
 private final Gson gson; 
public StreamChatService(CozeConfig config) { 
this.config = config; 
this.gson = new Gson(); 
this.httpClient = new OkHttpClient();
 }
 /** * 流式对话(实时返回) */ 
public void streamChat(String botId, String userId, String message, StreamCallback callback) throws IOException { 
// 构建请求体 
String json = 
String.format( "{\"bot_id\":\"%s\",\"user_id\":\"%s\",\"stream\":true," + 
"\"messages\":[{\"role\":\"user\",\"content\":\"%s\",\"content_type\":\"
text\"}]}", botId, userId, message ); 
Request request 
= 
New Request.Builder() .url("https://api.coze.cn/v3/chat") 
.addHeader("Authorization", "Bearer " + config.getAccessToken()) 
.addHeader("Content-Type", "application/json") 
.post(RequestBody.create(json, MediaType.parse("application/json"))) 
.build(); 
// 发送请求并处理流式响应 
try (Response response = httpClient.newCall(request).execute()) { 
if (!response.isSuccessful()) { 
throw new IOException("请求失败: " + response.code()); 
} try (
BufferedReader reader = new BufferedReader( new InputStreamReader(response.body().byteStream()
)
)
) {
 String line; 
while ((line = reader.readLine()) != null) { 
if (line.startsWith("data:")) {
 String data = line.substring(5).trim();
 if ("[DONE]".equals(data)) { 
callback.onComplete(); break;
 } try { 
StreamResponse streamResponse = gson.fromJson(data, StreamResponse.class); 
if (streamResponse.getContent() != null) 
{ 
callback.onMessage(streamResponse.getContent()); 
} 
} catch (Exception e) { 
// 忽略解析错误
 } 
}
 } 
} 
}
 }
 /** * 流式回调接口 */ 
public interface StreamCallback { 
void onMessage(String content); 
void onComplete(); 
void onError(Exception e);
 } 
/** * 流式响应数据 */ 
private static class StreamResponse { 
private String content;
 public String getContent() { 
return content; 
} 
} 
} 
// 使用示例 
class StreamChatExample { 
public static void main(String[] args) throws IOException {
 CozeConfig config = new CozeConfig("YOUR_ACCESS_TOKEN"); 
StreamChatService service = new StreamChatService(config); 
System.out.println("用户: 你好"); 
System.out.print("助手: "); 
service.streamChat( "YOUR_BOT_ID", "user123", "你好,请介绍一下你自己",
 new StreamChatService.StreamCallback() {
 @Override 
public void onMessage(String content) { 
System.out.print(content);
// 实时输出 
} 
@Override
 public void onComplete() { 
System.out.println("\n[对话结束]");
 } 
@Override 
public void onError(Exception e) { 
System.err.println("\n错误: " + e.getMessage()); 
}
 } 
);
 } 
}

在这里插入图片描述

支持的模型

// 可选模型列表
String[] models = {
“doubao-seed-1-8-251228”,
// 默认多模态模型
“doubao-seed-2-0-pro-260215”,
// 旗舰模型
“doubao-seed-2-0-lite-260215”,
// 轻量模型
“deepseek-v3-2-251201”,
// DeepSeek
“kimi-k2-250905”,
// Kimi 长文本
};

完整项目结构

coze-java-sdk/
├── src/main/java/com/coze/
│ ├── api/
│ │ ├── CozeConfig.java # 配置类
│ │ └── CozeHttpClient.java # HTTP 客户端
│ ├── model/
│ │ ├── CreateBotRequest.java # 创建请求
│ │ ├── CreateBotResponse.java # 创建响应
│ │ ├── ChatRequest.java # 对话请求
│ │ └── ChatResponse.java # 对话响应
│ ├── service/
│ │ ├── BotService.java # 智能体服务
│ │ ├── ChatService.java # 对话服务
│ │ └── StreamChatService.java # 流式对话
│ └── example/
│ └── CozeBotExample.java # 使用示例
└── pom.xml
这个方案提供了完整的 Java 调用 Coze API 的实现,包括创建智能体、配置模型、发起对话等核心功能。如需更多功能(如知识库、插件等),可以在此基础上扩展。

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐