├── .gitignore ├── README.md ├── img └── coze.svg ├── pom.xml └── src ├── main └── java │ └── com │ └── yby6 │ └── coze │ └── sdk │ ├── ICoZeApi.java │ ├── common │ └── Constants.java │ ├── core │ └── CoZeApiKeyProvider.java │ ├── domain │ ├── CoZeCompletionEventResponse.java │ ├── CoZeCompletionRequest.java │ ├── CoZeCompletionResponse.java │ ├── CoZeWorkFlowRequest.java │ ├── CoZeWorkFlowResponse.java │ └── Message.java │ ├── interceptor │ └── CoZeInterceptor.java │ └── session │ ├── CoZeConfiguration.java │ ├── CoZeSession.java │ ├── CoZeSessionFactory.java │ └── defaults │ ├── DefaultCoZeSession.java │ └── DefaultCoZeSessionFactory.java └── test └── java └── com └── yby6 └── coze └── sdk ├── CozeAPI.java └── package-info.java /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | !**/src/main/**/target/ 4 | !**/src/test/**/target/ 5 | 6 | ### IntelliJ IDEA ### 7 | .idea/modules.xml 8 | .idea/jarRepositories.xml 9 | .idea/compiler.xml 10 | .idea/libraries/ 11 | *.iws 12 | *.iml 13 | *.ipr 14 | 15 | ### Eclipse ### 16 | .apt_generated 17 | .classpath 18 | .factorypath 19 | .project 20 | .settings 21 | .springBeans 22 | .sts4-cache 23 | 24 | ### NetBeans ### 25 | /nbproject/private/ 26 | /nbbuild/ 27 | /dist/ 28 | /nbdist/ 29 | /.nb-gradle/ 30 | build/ 31 | !**/src/main/**/build/ 32 | !**/src/test/**/build/ 33 | 34 | ### VS Code ### 35 | .vscode/ 36 | 37 | ### Mac OS ### 38 | .DS_Store 39 | /.fastRequest/ 40 | /.idea/ 41 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [//]: # (

) 2 | 3 | [//]: # (

) 4 | 5 | [//]: # ( 愿世界和平) 6 | 7 | [//]: # (

) 8 | 9 | [//]: # (

) 10 | 11 | [//]: # () 12 | [//]: # (

) 13 | 14 | [//]: # ( 铭记苦难,心系巴勒斯坦,哀悼逝者。) 15 | 16 | [//]: # (
中国屹立东方,自强自立,方能更好地守护和平,担当国际责任,为世界公正贡献力量。) 17 | 18 | [//]: # (
愿悲剧不再重演,和平永驻人间。) 19 | 20 | [//]: # (
) 21 | 22 | [//]: # ( Easy-Manager-Tool ) 23 | 24 | [//]: # ( Peace And Love) 25 | 26 | [//]: # ( Easy-Manager-Tool) 27 | 28 | [//]: # (

) 29 | 30 | [//]: # () 31 | [//]: # (
) 32 | 33 | [//]: # (
) 34 | 35 | [//]: # (
) 36 | 37 | [//]: # (
) 38 | 39 | [//]: # (
) 40 | 41 | [//]: # (
) 42 | 43 | [//]: # () 44 | 45 |

46 | 47 |
48 | COZE-SDK-JAVA v1.0.3 49 |

50 |

51 | 扣子智能体 API Java SDK 是对扣子智能体的API进行了封装,方便Java开发者接入系统调用。 52 |

53 | 54 |
您是第个访问COZE-SDK-JAVA~
55 | 56 | # 接入方式 57 | 58 | ## 引入依赖 59 | ### Maven 60 | ```yaml 61 | 62 | 最新版本获取:https://central.sonatype.com/artifact/com.yby6.coze/coze-sdk-java 63 | 64 | 65 | com.yby6.coze 66 | coze-sdk-java 67 | ${last} 68 | 69 | 70 | ``` 71 | ### Gradle 72 | ```yaml 73 | 74 | implementation group: 'com.yby6.coze', name: 'coze-sdk-java', version: '${last}' 75 | 76 | ``` 77 | 78 | ## 单元测试 79 | 80 | ```java 81 | 82 | @Before 83 | public void test_session_Factory() { 84 | // 1. 配置文件 85 | CoZeConfiguration cozeConfiguration = new CoZeConfiguration(); 86 | cozeConfiguration.setApiHost("https://api.coze.cn/open_api/"); 87 | cozeConfiguration.setApiKey("Bearer 你的APIKEY"); 88 | cozeConfiguration.setLevel(HttpLoggingInterceptor.Level.HEADERS); 89 | // 2. 会话工厂 90 | DefaultCoZeSessionFactory factory = new DefaultCoZeSessionFactory(cozeConfiguration); 91 | // 3. 开启会话 92 | this.coZeSession = factory.openSession(); 93 | log.info("openAiSession:{}", coZeSession); 94 | } 95 | 96 | 97 | ``` 98 | -------------------------------------------------------------------------------- /img/coze.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 12 | 4.0.0 13 | com.yby6.coze 14 | coze-sdk-java 15 | 1.0.3 16 | ${project.artifactId} 17 | 18 | 扣子智能体 API Java SDK 是对扣子智能体的API进行了封装,方便Java开发者接入系统调用。 19 | 20 | https://github.com/yangbuyiya/coze-sdk-java 21 | 22 | 23 | 24 | Github Issue 25 | https://github.com/yangbuyiya/coze-sdk-java/issues 26 | 27 | 28 | 29 | 30 | 31 | Yangbuyiya 32 | 1692700664@qq.com 33 | https://yby6.com 34 | YangBuYi 35 | https://bento.me/yby6 36 | 37 | lead 38 | 39 | 40 | 41 | 42 | 43 | 44 | scm:git:https://github.com/yangbuyiya/coze-sdk-java.git 45 | scm:git:https://github.com/yangbuyiya/coze-sdk-java.git 46 | https://github.com/yangbuyiya/coze-sdk-java.git 47 | 48 | 49 | 50 | 51 | Apache License, Version 2.0 52 | http://www.apache.org/licenses/LICENSE-2.0 53 | repo 54 | 55 | 56 | 57 | 58 | UTF-8 59 | VERBOSE 60 | 17 61 | 2.0.6 62 | 2.9.0 63 | 2.14.0-rc1 64 | 5.8.25 65 | 3.14.9 66 | 4.13.2 67 | 23.0.0 68 | 0.2.0 69 | 1.18.24 70 | 71 | 72 | 73 | 74 | 75 | org.slf4j 76 | slf4j-api 77 | ${slf4j.version} 78 | 79 | 80 | 81 | org.slf4j 82 | slf4j-simple 83 | ${slf4j.version} 84 | 85 | 86 | 87 | com.fasterxml.jackson.core 88 | jackson-databind 89 | ${jackson.version} 90 | 91 | 92 | 93 | cn.hutool 94 | hutool-all 95 | ${hutool.version} 96 | 97 | 98 | 99 | com.squareup.okhttp3 100 | okhttp-sse 101 | ${okhttp3.version} 102 | 103 | 104 | 105 | com.squareup.okhttp3 106 | logging-interceptor 107 | ${okhttp3.version} 108 | 109 | 110 | 111 | com.squareup.retrofit2 112 | retrofit 113 | ${retrofit2.version} 114 | 115 | 116 | 117 | com.squareup.retrofit2 118 | converter-jackson 119 | ${retrofit2.version} 120 | 121 | 122 | 123 | com.squareup.retrofit2 124 | adapter-rxjava2 125 | ${retrofit2.version} 126 | 127 | 128 | 129 | junit 130 | junit 131 | ${junit.version} 132 | test 133 | 134 | 135 | 136 | org.jetbrains 137 | annotations 138 | ${annotations.version} 139 | compile 140 | 141 | 142 | 143 | com.knuddels 144 | jtokkit 145 | ${jtokkit.version} 146 | 147 | 148 | 149 | org.projectlombok 150 | lombok 151 | ${lombok.version} 152 | compile 153 | 154 | 155 | 156 | 157 | 158 | coze-sdk-java 159 | 160 | 161 | org.apache.maven.plugins 162 | maven-surefire-plugin 163 | 2.12.4 164 | 165 | true 166 | 167 | 168 | 169 | org.apache.maven.plugins 170 | maven-compiler-plugin 171 | 172 | 17 173 | 17 174 | UTF-8 175 | 176 | 177 | 178 | 179 | 180 | org.sonatype.central 181 | central-publishing-maven-plugin 182 | 0.4.0 183 | true 184 | 185 | central 186 | true 187 | 188 | 189 | 190 | 191 | org.apache.maven.plugins 192 | maven-source-plugin 193 | 3.2.1 194 | 195 | 196 | oss 197 | package 198 | 199 | jar-no-fork 200 | 201 | 202 | 203 | 204 | 205 | 206 | org.apache.maven.plugins 207 | maven-javadoc-plugin 208 | 3.6.3 209 | 210 | 17 211 | UTF-8 212 | 213 | 214 | 215 | package 216 | 217 | jar 218 | 219 | 220 | 221 | 222 | 223 | 224 | org.apache.maven.plugins 225 | maven-gpg-plugin 226 | 3.2.3 227 | 228 | 229 | sign-artifacts 230 | verify 231 | 232 | sign 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | -------------------------------------------------------------------------------- /src/main/java/com/yby6/coze/sdk/ICoZeApi.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 您可以更改此项目但请不要删除作者署名谢谢,否则根据中华人民共和国版权法进行处理. 3 | * You may change this item but please do not remove the author's signature, 4 | * otherwise it will be dealt with according to the Copyright Law of the People's Republic of China. 5 | * 6 | * yangbuyi Copyright (c) https://yby6.com 2024. 7 | */ 8 | 9 | package com.yby6.coze.sdk; 10 | 11 | 12 | import com.yby6.coze.sdk.domain.CoZeCompletionRequest; 13 | import com.yby6.coze.sdk.domain.CoZeCompletionResponse; 14 | import com.yby6.coze.sdk.domain.CoZeWorkFlowRequest; 15 | import com.yby6.coze.sdk.domain.CoZeWorkFlowResponse; 16 | import io.reactivex.Single; 17 | import retrofit2.http.Body; 18 | import retrofit2.http.POST; 19 | 20 | /** 21 | * 以 CoZe 官网 API 模型,定义接口。 22 | *

23 | * 这里虽然说是定义接口但是也是http远程请求,根据对应的参数传递 24 | * 25 | * @author Yang Shuai 26 | * Create By 2024/07/04 27 | */ 28 | public interface ICoZeApi { 29 | 30 | /** 31 | * v1聊天完成 32 | */ 33 | String v1_chat_completions = "v2/chat"; 34 | 35 | /** 36 | * v1工作流 37 | */ 38 | String v1_workflow_completions = "v1/workflow/run"; 39 | 40 | /** 41 | * 问答智能体 42 | * 43 | * @param CoZeCompletionRequest 请求信息 44 | * @return 应答结果 45 | */ 46 | @POST(v1_chat_completions) 47 | Single completions(@Body CoZeCompletionRequest CoZeCompletionRequest); 48 | 49 | /** 50 | * 工作流 51 | * 52 | * @param CozeWorkFlowRequest 请求信息 53 | * @return 应答结果 54 | */ 55 | @POST(v1_workflow_completions) 56 | Single workflowCompletions(@Body CoZeWorkFlowRequest CozeWorkFlowRequest); 57 | 58 | 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/yby6/coze/sdk/common/Constants.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 您可以更改此项目但请不要删除作者署名谢谢,否则根据中华人民共和国版权法进行处理. 3 | * You may change this item but please do not remove the author's signature, 4 | * otherwise it will be dealt with according to the Copyright Law of the People's Republic of China. 5 | * 6 | * yangbuyi Copyright (c) https://yby6.com 2024. 7 | */ 8 | 9 | package com.yby6.coze.sdk.common; 10 | 11 | 12 | import lombok.Getter; 13 | 14 | /** 15 | * 常量 通用类 16 | * 17 | * @author Yang Shuai 18 | * Create By 2024/07/04 19 | */ 20 | public class Constants { 21 | /** 22 | * 空 23 | */ 24 | public final static String NULL = "NULL"; 25 | /** 26 | * 鉴权 27 | */ 28 | public final static String AUTHORIZATION = "Authorization"; 29 | /** 30 | * token前缀 31 | */ 32 | public final static String BEARER = "Bearer "; 33 | 34 | /** 35 | * 角色 36 | * 官网支持的请求角色类型;user、assistant 37 | */ 38 | @Getter 39 | public enum Role { 40 | 41 | /** 42 | * 使用者 43 | */ 44 | USER("user"), 45 | /** 46 | * 助理 47 | */ 48 | ASSISTANT("assistant"), 49 | ; 50 | 51 | /** 52 | * 密码 53 | */ 54 | private final String code; 55 | 56 | /** 57 | * 角色 58 | * 59 | * @param code 密码 60 | */ 61 | Role(String code) { 62 | this.code = code; 63 | } 64 | 65 | } 66 | 67 | /** 68 | * 问答类型 69 | */ 70 | @Getter 71 | public enum Type { 72 | 73 | /** 74 | * 文本 75 | */ 76 | TEXT("text"), 77 | /** 78 | * img 79 | */ 80 | IMG("file_url") 81 | ; 82 | 83 | /** 84 | * 密码 85 | */ 86 | private final String code; 87 | 88 | /** 89 | * 角色 90 | * 91 | * @param code 密码 92 | */ 93 | Type(String code) { 94 | this.code = code; 95 | } 96 | 97 | } 98 | 99 | } 100 | -------------------------------------------------------------------------------- /src/main/java/com/yby6/coze/sdk/core/CoZeApiKeyProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 您可以更改此项目但请不要删除作者署名谢谢,否则根据中华人民共和国版权法进行处理. 3 | * You may change this item but please do not remove the author's signature, 4 | * otherwise it will be dealt with according to the Copyright Law of the People's Republic of China. 5 | * 6 | * yangbuyi Copyright (c) https://yby6.com 2024. 7 | */ 8 | package com.yby6.coze.sdk.core; 9 | 10 | /** 11 | * Api密钥提供程序 Authorization Key Provider 12 | * 13 | *

14 | * 如果你需要在程序当中更新API密钥,可以使用{@link CoZeApiKeyProvider#setApiKey(String)}方法
15 | * 如果你需要获取API密钥,可以使用{@link CoZeApiKeyProvider#getApiKey()}方法
16 | * 请注意,这个类是线程安全的 17 | *

18 | * 19 | * @author Yang Shuai 20 | * Create By 2024/06/17 21 | */ 22 | public class CoZeApiKeyProvider { 23 | /** 24 | * api密钥 25 | */ 26 | private static volatile String apiKey; 27 | 28 | /** 29 | * 获取api密钥 30 | * 31 | * @return api密钥 32 | */ 33 | public static String getApiKey() { 34 | return apiKey; 35 | } 36 | 37 | /** 38 | * 设置api密钥 39 | * 40 | * @param newApiKey 新api密钥 41 | */ 42 | public static void setApiKey(String newApiKey) { 43 | apiKey = newApiKey; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/yby6/coze/sdk/domain/CoZeCompletionEventResponse.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 您可以更改此项目但请不要删除作者署名谢谢,否则根据中华人民共和国版权法进行处理. 3 | * You may change this item but please do not remove the author's signature, 4 | * otherwise it will be dealt with according to the Copyright Law of the People's Republic of China. 5 | * 6 | * yangbuyi Copyright (c) https://yby6.com 2024. 7 | */ 8 | 9 | package com.yby6.coze.sdk.domain; 10 | 11 | 12 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 13 | import com.fasterxml.jackson.annotation.JsonProperty; 14 | import lombok.Data; 15 | 16 | import java.io.Serializable; 17 | 18 | /** 19 | * 流式 - 对话结果信息 20 | * 21 | * @author Yang Shuai 22 | * Create By 2024/07/04 23 | */ 24 | @Data 25 | @JsonIgnoreProperties(ignoreUnknown = true) 26 | public class CoZeCompletionEventResponse implements Serializable { 27 | /** 28 | * 事件 29 | */ 30 | @JsonProperty("event") 31 | private String event; 32 | /** 33 | * 消息 34 | */ 35 | @JsonProperty("message") 36 | private Message message; 37 | /** 38 | * 已完成 39 | */ 40 | @JsonProperty("is_finish") 41 | private boolean isFinish; 42 | /** 43 | * 指数 44 | */ 45 | @JsonProperty("index") 46 | private int index; 47 | /** 48 | * 会话id 49 | */ 50 | @JsonProperty("conversation_id") 51 | private String conversationId; 52 | /** 53 | * 序列id 54 | */ 55 | @JsonProperty("seq_id") 56 | private int seqId; 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/yby6/coze/sdk/domain/CoZeCompletionRequest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 您可以更改此项目但请不要删除作者署名谢谢,否则根据中华人民共和国版权法进行处理. 3 | * You may change this item but please do not remove the author's signature, 4 | * otherwise it will be dealt with according to the Copyright Law of the People's Republic of China. 5 | * 6 | * yangbuyi Copyright (c) https://yby6.com 2024. 7 | */ 8 | 9 | package com.yby6.coze.sdk.domain; 10 | 11 | import com.fasterxml.jackson.annotation.JsonInclude; 12 | import com.fasterxml.jackson.annotation.JsonProperty; 13 | import lombok.AllArgsConstructor; 14 | import lombok.Builder; 15 | import lombok.Data; 16 | import lombok.NoArgsConstructor; 17 | import lombok.extern.slf4j.Slf4j; 18 | 19 | import java.io.Serializable; 20 | import java.util.List; 21 | 22 | /** 23 | * 构建请求 24 | * 25 | * @author Yang Shuai 26 | * Create By 2024/07/04 27 | */ 28 | @Data 29 | @Builder 30 | @Slf4j 31 | @JsonInclude(JsonInclude.Include.NON_NULL) 32 | @NoArgsConstructor 33 | @AllArgsConstructor 34 | public class CoZeCompletionRequest implements Serializable { 35 | 36 | /** 37 | * 智能体ID 38 | */ 39 | @JsonProperty("bot_id") 40 | private String botId; 41 | 42 | /** 43 | * 用户id 44 | */ 45 | @JsonProperty("user") 46 | private String user; 47 | 48 | /** 49 | * 用户id 50 | */ 51 | @JsonProperty("conversation_id") 52 | private String conversationId; 53 | 54 | /** 55 | * 问 - 内容 56 | */ 57 | private String query; 58 | 59 | /** 60 | * 历史消息 上下文用 61 | */ 62 | @JsonProperty("chat_history") 63 | private List chatHistory; 64 | 65 | /** 66 | * 流动 67 | */ 68 | @JsonProperty("stream") 69 | private Boolean stream; 70 | 71 | 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/com/yby6/coze/sdk/domain/CoZeCompletionResponse.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 您可以更改此项目但请不要删除作者署名谢谢,否则根据中华人民共和国版权法进行处理. 3 | * You may change this item but please do not remove the author's signature, 4 | * otherwise it will be dealt with according to the Copyright Law of the People's Republic of China. 5 | * 6 | * yangbuyi Copyright (c) https://yby6.com 2024. 7 | */ 8 | 9 | package com.yby6.coze.sdk.domain; 10 | 11 | 12 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 13 | import com.fasterxml.jackson.annotation.JsonProperty; 14 | import lombok.Data; 15 | 16 | import java.io.Serializable; 17 | import java.util.List; 18 | 19 | /** 20 | * 对话请求结果信息 21 | * 22 | * @author Yang Shuai 23 | * Create By 2024/07/04 24 | */ 25 | @Data 26 | @JsonIgnoreProperties(ignoreUnknown = true) 27 | public class CoZeCompletionResponse implements Serializable { 28 | 29 | /** 30 | * 返回码 31 | */ 32 | private Integer code; 33 | 34 | /** 35 | * 消息 36 | */ 37 | private String msg; 38 | 39 | /** 40 | * 会话id 41 | */ 42 | @JsonProperty("conversation_id") 43 | private String conversationId; 44 | 45 | /** 46 | * 返回内容 47 | */ 48 | private List messages; 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/yby6/coze/sdk/domain/CoZeWorkFlowRequest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 您可以更改此项目但请不要删除作者署名谢谢,否则根据中华人民共和国版权法进行处理. 3 | * You may change this item but please do not remove the author's signature, 4 | * otherwise it will be dealt with according to the Copyright Law of the People's Republic of China. 5 | * 6 | * yangbuyi Copyright (c) https://yby6.com 2024. 7 | */ 8 | 9 | package com.yby6.coze.sdk.domain; 10 | 11 | import cn.hutool.json.JSONObject; 12 | import com.fasterxml.jackson.annotation.JsonInclude; 13 | import com.fasterxml.jackson.annotation.JsonProperty; 14 | import lombok.AllArgsConstructor; 15 | import lombok.Builder; 16 | import lombok.Data; 17 | import lombok.NoArgsConstructor; 18 | import lombok.extern.slf4j.Slf4j; 19 | 20 | import java.io.Serializable; 21 | import java.util.HashMap; 22 | import java.util.List; 23 | 24 | /** 25 | * 构建请求 26 | * 27 | * @author XF4n 28 | * Create By 2024/09/24 29 | */ 30 | @Data 31 | @Builder 32 | @Slf4j 33 | @JsonInclude(JsonInclude.Include.NON_NULL) 34 | @NoArgsConstructor 35 | @AllArgsConstructor 36 | public class CoZeWorkFlowRequest implements Serializable { 37 | 38 | /** 39 | * 工作流ID 40 | * 必选 41 | */ 42 | @JsonProperty("workflow_id") 43 | private String workflowId; 44 | 45 | /** 46 | * 工作流开始节点的输入参数及取值,你可以在指定工作流的编排页面查看参数列表。 47 | * 可选 48 | */ 49 | @JsonProperty("parameters") 50 | private JSONObject parameters; 51 | 52 | /** 53 | * 需要关联的 Bot ID 54 | * 可选 55 | */ 56 | @JsonProperty("bot_id") 57 | private String botId; 58 | 59 | /** 60 | * 用于指定一些额外的字段,以 Map[String][String] 格式传入。例如某些插件 会隐式用到的经纬度等字段。 61 | * 目前仅支持以下字段: 62 | * latitude:String 类型,表示经度。 63 | * longitude:String 类型,表示纬度。 64 | * user_id:Integer 类型,表示用户 ID。 65 | * 可选 66 | */ 67 | @JsonProperty("ext") 68 | private HashMap ext; 69 | 70 | /** 71 | * 是否异步运行。异步运行时可通过 execute_id 调用【草稿】查询工作流执行结果 API 获取工作流的执行结果。 72 | * true:异步运行。 73 | * false:(默认)同步运行。 74 | * Optional 75 | */ 76 | @JsonProperty("is_async") 77 | private Boolean isAsync; 78 | 79 | 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/com/yby6/coze/sdk/domain/CoZeWorkFlowResponse.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 您可以更改此项目但请不要删除作者署名谢谢,否则根据中华人民共和国版权法进行处理. 3 | * You may change this item but please do not remove the author's signature, 4 | * otherwise it will be dealt with according to the Copyright Law of the People's Republic of China. 5 | * 6 | * yangbuyi Copyright (c) https://yby6.com 2024. 7 | */ 8 | 9 | package com.yby6.coze.sdk.domain; 10 | 11 | 12 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 13 | import com.fasterxml.jackson.annotation.JsonProperty; 14 | import lombok.Data; 15 | 16 | import java.io.Serializable; 17 | import java.util.List; 18 | 19 | /** 20 | * 对话请求结果信息 21 | * 22 | * @author XF4n 23 | * Create By 2024/09/24 24 | */ 25 | @Data 26 | @JsonIgnoreProperties(ignoreUnknown = true) 27 | public class CoZeWorkFlowResponse implements Serializable { 28 | 29 | /** 30 | * 返回码 31 | */ 32 | private Integer code; 33 | 34 | /** 35 | * 消息 36 | */ 37 | private String msg; 38 | 39 | /** 40 | * data 工作流执行结果 41 | */ 42 | private String data; 43 | 44 | /** 45 | * debug_url 工作流试运行调试页面 46 | */ 47 | private String debug_url; 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/yby6/coze/sdk/domain/Message.java: -------------------------------------------------------------------------------- 1 | package com.yby6.coze.sdk.domain; 2 | 3 | import com.fasterxml.jackson.annotation.JsonInclude; 4 | import com.fasterxml.jackson.annotation.JsonProperty; 5 | import com.yby6.coze.sdk.common.Constants; 6 | import lombok.AllArgsConstructor; 7 | import lombok.Data; 8 | import lombok.NoArgsConstructor; 9 | 10 | import java.io.Serializable; 11 | 12 | /** 13 | * 消息内容 14 | * 15 | * @author yangs 16 | * Create By 2024/07/04 17 | */ 18 | @Data 19 | @JsonInclude(JsonInclude.Include.NON_NULL) 20 | @AllArgsConstructor 21 | @NoArgsConstructor 22 | public class Message implements Serializable { 23 | 24 | /** 25 | * 角色 assistant 26 | */ 27 | private String role; 28 | 29 | /** 30 | * 消息类型 verbose、answer、follow_up 31 | */ 32 | private String type; 33 | 34 | /** 35 | * 会话内容 36 | */ 37 | private String content; 38 | 39 | /** 40 | * 内容类型 41 | */ 42 | @JsonProperty("content_type") 43 | private String contentType; 44 | 45 | /** 46 | * 消息 47 | * 48 | * @param builder 建设者 49 | */ 50 | private Message(Builder builder) { 51 | this.role = builder.role; 52 | this.content = builder.content; 53 | } 54 | 55 | /** 56 | * 建设者 57 | * 58 | * @return {@link Builder} 59 | */ 60 | public static Builder builder() { 61 | return new Builder(); 62 | } 63 | 64 | /** 65 | * 建造者模式 66 | * 67 | * @author yangs 68 | * Create By 2024/07/04 69 | */ 70 | public static final class Builder { 71 | 72 | /** 73 | * 角色 74 | */ 75 | private String role; 76 | /** 77 | * 所容纳之物 78 | */ 79 | private String content; 80 | 81 | /** 82 | * 建设者 83 | */ 84 | public Builder() { 85 | } 86 | 87 | /** 88 | * 角色 89 | * 90 | * @param role 角色 91 | * @return {@link Builder} 92 | */ 93 | public Builder role(Constants.Role role) { 94 | this.role = role.getCode(); 95 | return this; 96 | } 97 | 98 | /** 99 | * 所容纳之物 100 | * 101 | * @param content 所容纳之物 102 | * @return {@link Builder} 103 | */ 104 | public Builder content(String content) { 105 | this.content = content; 106 | return this; 107 | } 108 | 109 | /** 110 | * 建筑 111 | * 112 | * @return {@link Message} 113 | */ 114 | public Message build() { 115 | return new Message(this); 116 | } 117 | } 118 | 119 | } 120 | -------------------------------------------------------------------------------- /src/main/java/com/yby6/coze/sdk/interceptor/CoZeInterceptor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 您可以更改此项目但请不要删除作者署名谢谢,否则根据中华人民共和国版权法进行处理. 3 | * You may change this item but please do not remove the author's signature, 4 | * otherwise it will be dealt with according to the Copyright Law of the People's Republic of China. 5 | * 6 | * yangbuyi Copyright (c) https://yby6.com 2024. 7 | */ 8 | 9 | package com.yby6.coze.sdk.interceptor; 10 | 11 | import cn.hutool.core.util.StrUtil; 12 | import cn.hutool.http.ContentType; 13 | import cn.hutool.http.Header; 14 | import com.yby6.coze.sdk.common.Constants; 15 | import com.yby6.coze.sdk.core.CoZeApiKeyProvider; 16 | import okhttp3.Interceptor; 17 | import okhttp3.Request; 18 | import okhttp3.Response; 19 | import org.jetbrains.annotations.NotNull; 20 | 21 | import java.io.IOException; 22 | 23 | /** 24 | * 自定义 YuanQI 拦截器 25 | * 在 okhttp3 请求的时候拦截 26 | * 27 | * @author Yang Shuai 28 | * Create By 2024/07/04 29 | */ 30 | public class CoZeInterceptor implements Interceptor { 31 | 32 | 33 | /** 34 | * YuanQI apiKey 需要在官网申请 35 | */ 36 | private final String apiKeyBySystem; 37 | 38 | /** 39 | * 访问授权接口的认证 Token 40 | * 41 | * @param apiKeyBySystem 系统提供api密钥 42 | */ 43 | 44 | public CoZeInterceptor(String apiKeyBySystem) { 45 | this.apiKeyBySystem = apiKeyBySystem; 46 | } 47 | 48 | /** 49 | * 拦截okhttp请求 50 | * 51 | * @param chain 链 52 | * @return 是否继续执行 53 | */ 54 | @NotNull 55 | @Override 56 | public Response intercept(Chain chain) throws IOException { 57 | // 1. 获取原始 Request 58 | Request original = chain.request(); 59 | 60 | // 2. 如果调用者传递了apiKey,则使用调用者传递的apiKey 61 | String apiKeyByUser = original.header("apiKey"); 62 | // 如果动态设置了apiKey,则使用动态设置的apiKey 否则使用系统提供的apiKey 63 | String apiKey = null == apiKeyByUser || Constants.NULL.equals(apiKeyByUser) ? 64 | StrUtil.isNotEmpty(CoZeApiKeyProvider.getApiKey()) ? 65 | CoZeApiKeyProvider.getApiKey() : apiKeyBySystem : apiKeyByUser; 66 | // 如果鉴权头部没有Bearer则添加 67 | apiKey = apiKey.startsWith(Constants.BEARER) ? apiKey : Constants.BEARER.concat(apiKey); 68 | 69 | // 3. 构建 Request 70 | Request request = original.newBuilder() 71 | .url(original.url()) 72 | .header(Header.AUTHORIZATION.getValue(),apiKey) 73 | .header(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue()) 74 | .method(original.method(), original.body()) 75 | .build(); 76 | 77 | // 4. 返回执行结果 78 | return chain.proceed(request); 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/com/yby6/coze/sdk/session/CoZeConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 您可以更改此项目但请不要删除作者署名谢谢,否则根据中华人民共和国版权法进行处理. 3 | * You may change this item but please do not remove the author's signature, 4 | * otherwise it will be dealt with according to the Copyright Law of the People's Republic of China. 5 | * 6 | * yangbuyi Copyright (c) https://yby6.com 2024. 7 | */ 8 | 9 | package com.yby6.coze.sdk.session; 10 | 11 | import com.yby6.coze.sdk.ICoZeApi; 12 | import lombok.AllArgsConstructor; 13 | import lombok.Data; 14 | import lombok.Getter; 15 | import lombok.NoArgsConstructor; 16 | import lombok.extern.slf4j.Slf4j; 17 | import okhttp3.OkHttpClient; 18 | import okhttp3.logging.HttpLoggingInterceptor; 19 | import okhttp3.sse.EventSource; 20 | import okhttp3.sse.EventSources; 21 | import org.jetbrains.annotations.NotNull; 22 | 23 | 24 | /** 25 | * 配置信息 26 | * 27 | * @author Yang Shuai 28 | * Create By 2024/07/04 29 | */ 30 | @Getter 31 | @Slf4j 32 | @Data 33 | @NoArgsConstructor 34 | @AllArgsConstructor 35 | public class CoZeConfiguration { 36 | 37 | /** 38 | * 扣子api接口 39 | */ 40 | private ICoZeApi coZeApi; 41 | 42 | /** 43 | * 请求客户端 44 | */ 45 | private OkHttpClient okHttpClient; 46 | 47 | /** 48 | * 鉴权密钥 49 | */ 50 | @NotNull 51 | private String apiKey; 52 | 53 | /** 54 | * 请求地址 55 | */ 56 | private String apiHost; 57 | 58 | /** 59 | * 请求日志打印类型 Level 60 | * NONE, 61 | * BASIC, 62 | * HEADERS, 63 | * BODY; 64 | */ 65 | private HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.BODY; 66 | 67 | /** 68 | * 创建请求工厂 69 | * 70 | * @return {@link EventSource.Factory} 71 | */ 72 | public EventSource.Factory createRequestFactory() { 73 | return EventSources.createFactory(okHttpClient); 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/com/yby6/coze/sdk/session/CoZeSession.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 您可以更改此项目但请不要删除作者署名谢谢,否则根据中华人民共和国版权法进行处理. 3 | * You may change this item but please do not remove the author's signature, 4 | * otherwise it will be dealt with according to the Copyright Law of the People's Republic of China. 5 | * 6 | * yangbuyi Copyright (c) https://yby6.com 2024. 7 | */ 8 | 9 | package com.yby6.coze.sdk.session; 10 | 11 | 12 | import com.fasterxml.jackson.core.JsonProcessingException; 13 | import com.yby6.coze.sdk.domain.CoZeCompletionRequest; 14 | import com.yby6.coze.sdk.domain.CoZeCompletionResponse; 15 | import com.yby6.coze.sdk.domain.CoZeWorkFlowRequest; 16 | import com.yby6.coze.sdk.domain.CoZeWorkFlowResponse; 17 | import okhttp3.sse.EventSource; 18 | import okhttp3.sse.EventSourceListener; 19 | 20 | 21 | /** 22 | * 扣子会话 23 | * CoZe 会话接口 24 | * 25 | * @author Yang Shuai 26 | * Create By 2024/07/04 27 | */ 28 | public interface CoZeSession { 29 | 30 | 31 | /** 32 | * 简单问答 33 | * 34 | * @param cozeCompletionRequest 扣子完成请求 35 | * @return {@link CoZeCompletionResponse} 36 | */ 37 | CoZeCompletionResponse completions(CoZeCompletionRequest cozeCompletionRequest); 38 | 39 | 40 | /** 41 | * 简单问答 - 流式 42 | * 43 | * @param cozeCompletionRequest coze完成请求 44 | * @param eventSourceListener 事件源侦听器 45 | * @return {@link EventSource} 46 | * @throws JsonProcessingException json处理异常 47 | */ 48 | EventSource chatCompletions(CoZeCompletionRequest cozeCompletionRequest, EventSourceListener eventSourceListener) throws JsonProcessingException; 49 | 50 | 51 | /** 52 | * 简单问答 - 流式 - 自定义apiHost和apiKey 53 | * 54 | * @param apiHostByUser 用户提供api主机 55 | * @param apiKeyByUser 用户提供api密钥 56 | * @param cozeCompletionRequest coze完成请求 57 | * @param eventSourceListener 事件源侦听器 58 | * @return {@link EventSource} 59 | * @throws JsonProcessingException json处理异常 60 | */ 61 | EventSource chatCompletions(String apiHostByUser, String apiKeyByUser, CoZeCompletionRequest cozeCompletionRequest, EventSourceListener eventSourceListener) throws JsonProcessingException; 62 | 63 | /** 64 | * 工作流 65 | * 66 | * @param cozeWorkflowRequest 工作流请求 67 | * @return {@link CoZeCompletionResponse} 68 | */ 69 | CoZeWorkFlowResponse workflowCompletions(CoZeWorkFlowRequest cozeWorkflowRequest) throws JsonProcessingException; 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/com/yby6/coze/sdk/session/CoZeSessionFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 您可以更改此项目但请不要删除作者署名谢谢,否则根据中华人民共和国版权法进行处理. 3 | * You may change this item but please do not remove the author's signature, 4 | * otherwise it will be dealt with according to the Copyright Law of the People's Republic of China. 5 | * 6 | * yangbuyi Copyright (c) https://yby6.com 2024. 7 | */ 8 | 9 | package com.yby6.coze.sdk.session; 10 | 11 | 12 | /** 13 | * CoZe 会话工厂 14 | * 15 | * @author Yang Shuai 16 | * Create By 2024/07/04 17 | */ 18 | public interface CoZeSessionFactory { 19 | 20 | /** 21 | * 开启会话 22 | * 23 | * @return {@link CoZeSession} 24 | */ 25 | CoZeSession openSession(); 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/yby6/coze/sdk/session/defaults/DefaultCoZeSession.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 您可以更改此项目但请不要删除作者署名谢谢,否则根据中华人民共和国版权法进行处理. 3 | * You may change this item but please do not remove the author's signature, 4 | * otherwise it will be dealt with according to the Copyright Law of the People's Republic of China. 5 | * 6 | * yangbuyi Copyright (c) https://yby6.com 2024. 7 | */ 8 | 9 | package com.yby6.coze.sdk.session.defaults; 10 | 11 | 12 | import cn.hutool.core.lang.Assert; 13 | import cn.hutool.http.ContentType; 14 | import com.fasterxml.jackson.databind.ObjectMapper; 15 | import com.yby6.coze.sdk.ICoZeApi; 16 | import com.yby6.coze.sdk.common.Constants; 17 | import com.yby6.coze.sdk.domain.CoZeCompletionRequest; 18 | import com.yby6.coze.sdk.domain.CoZeCompletionResponse; 19 | import com.yby6.coze.sdk.domain.CoZeWorkFlowRequest; 20 | import com.yby6.coze.sdk.domain.CoZeWorkFlowResponse; 21 | import com.yby6.coze.sdk.session.CoZeConfiguration; 22 | import com.yby6.coze.sdk.session.CoZeSession; 23 | import okhttp3.MediaType; 24 | import okhttp3.Request; 25 | import okhttp3.RequestBody; 26 | import okhttp3.sse.*; 27 | import com.fasterxml.jackson.core.*; 28 | 29 | /** 30 | * 默认的 CoZe 会话实现CoZeSession 31 | * 32 | * @author Yang Shuai 33 | * Create By 2024/07/04 34 | */ 35 | public class DefaultCoZeSession implements CoZeSession { 36 | 37 | 38 | /** 39 | * 默认配置信息 40 | */ 41 | private final CoZeConfiguration cozeConfiguration; 42 | 43 | /** 44 | * CoZe 接口 45 | */ 46 | private final ICoZeApi cozeApi; 47 | /** 48 | * 工厂事件 49 | */ 50 | private final EventSource.Factory factory; 51 | 52 | public DefaultCoZeSession(CoZeConfiguration cozeConfiguration) { 53 | this.cozeConfiguration = cozeConfiguration; 54 | this.cozeApi = cozeConfiguration.getCoZeApi(); 55 | this.factory = cozeConfiguration.createRequestFactory(); 56 | } 57 | 58 | /** 59 | * 问答模型扣子智能体AI 60 | * 61 | * @param cozeCompletionRequest 请求信息 62 | * @return 应答结果 63 | */ 64 | @Override 65 | public CoZeCompletionResponse completions(CoZeCompletionRequest cozeCompletionRequest) { 66 | return this.cozeApi.completions(cozeCompletionRequest).blockingGet(); 67 | } 68 | 69 | /** 70 | * 聊天完成 71 | * 72 | * @param cozeCompletionRequest coze完成请求 73 | * @param eventSourceListener 事件源侦听器 74 | * @return {@link EventSource} 75 | * @throws JsonProcessingException json处理异常 76 | */ 77 | @Override 78 | public EventSource chatCompletions(CoZeCompletionRequest cozeCompletionRequest, EventSourceListener eventSourceListener) throws JsonProcessingException { 79 | return chatCompletions(Constants.NULL, Constants.NULL, cozeCompletionRequest, eventSourceListener); 80 | } 81 | 82 | 83 | /** 84 | * 问答模型扣子智能体AI 85 | * 86 | * @param apiHostByUser 用户提供api主机 87 | * @param apiKeyByUser 用户提供api密钥 88 | * @param cozeCompletionRequest coze完成请求 89 | * @param eventSourceListener 事件源侦听器 90 | * @return {@link EventSource} 91 | * @throws JsonProcessingException json处理异常 92 | */ 93 | @Override 94 | public EventSource chatCompletions(String apiHostByUser, String apiKeyByUser, CoZeCompletionRequest cozeCompletionRequest, EventSourceListener eventSourceListener) throws JsonProcessingException { 95 | // 当前为流式模式,如果为false则抛出异常 96 | Assert.isTrue(cozeCompletionRequest.getStream(), "illegal parameter stream is false!"); 97 | 98 | // 1. 先判断用户传递的 Host、Key 是否为空,为空则使用默认配置信息 99 | // 动态设置 Host、Key,便于用户传递自己的信息 100 | String apiHost = Constants.NULL.equals(apiHostByUser) ? cozeConfiguration.getApiHost() : apiHostByUser; 101 | String apiKey = Constants.NULL.equals(apiKeyByUser) ? cozeConfiguration.getApiKey() : apiKeyByUser; 102 | 103 | // 2. 构建请求信息,并设置请求头 Authorization 104 | Request request = new Request.Builder() 105 | // 通过 IYuanQiApi 配置的 POST 接口,用这样的方式从统一的地方获取配置信息 106 | .url(apiHost.concat(ICoZeApi.v1_chat_completions)) 107 | .addHeader(Constants.AUTHORIZATION, apiKey) 108 | // 封装请求参数信息 109 | .post(RequestBody.create(MediaType.parse(ContentType.JSON.getValue()), new ObjectMapper() 110 | .writeValueAsString(cozeCompletionRequest))) 111 | .build(); 112 | 113 | // 返回结果信息;EventSource 对象可以取消应答 114 | return factory.newEventSource(request, eventSourceListener); 115 | } 116 | 117 | /** 118 | * 工作流 119 | * 120 | * @param cozeWorkflowRequest 工作流请求 121 | * @return 应答结果 122 | */ 123 | @Override 124 | public CoZeWorkFlowResponse workflowCompletions(CoZeWorkFlowRequest cozeWorkflowRequest) { 125 | return this.cozeApi.workflowCompletions(cozeWorkflowRequest).blockingGet(); 126 | } 127 | 128 | 129 | 130 | } 131 | -------------------------------------------------------------------------------- /src/main/java/com/yby6/coze/sdk/session/defaults/DefaultCoZeSessionFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 您可以更改此项目但请不要删除作者署名谢谢,否则根据中华人民共和国版权法进行处理. 3 | * You may change this item but please do not remove the author's signature, 4 | * otherwise it will be dealt with according to the Copyright Law of the People's Republic of China. 5 | * 6 | * yangbuyi Copyright (c) https://yby6.com 2024. 7 | */ 8 | 9 | package com.yby6.coze.sdk.session.defaults; 10 | 11 | import com.yby6.coze.sdk.ICoZeApi; 12 | import com.yby6.coze.sdk.interceptor.CoZeInterceptor; 13 | import com.yby6.coze.sdk.session.CoZeConfiguration; 14 | import com.yby6.coze.sdk.session.CoZeSession; 15 | import com.yby6.coze.sdk.session.CoZeSessionFactory; 16 | import okhttp3.OkHttpClient; 17 | import okhttp3.logging.HttpLoggingInterceptor; 18 | import org.slf4j.Logger; 19 | import org.slf4j.LoggerFactory; 20 | import retrofit2.Retrofit; 21 | import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; 22 | import retrofit2.converter.jackson.JacksonConverterFactory; 23 | 24 | import java.util.concurrent.TimeUnit; 25 | 26 | 27 | /** 28 | * 默认的实现 OpenAi API Factory 会话工厂 29 | * 30 | * @author Yang Shuai 31 | * Create By 2024/07/04 32 | */ 33 | public class DefaultCoZeSessionFactory implements CoZeSessionFactory { 34 | private static final Logger log = LoggerFactory.getLogger(DefaultCoZeSessionFactory.class); 35 | 36 | private final CoZeConfiguration cozeConfiguration; 37 | 38 | public DefaultCoZeSessionFactory(CoZeConfiguration cozeConfiguration) { 39 | this.cozeConfiguration = cozeConfiguration; 40 | } 41 | 42 | static { 43 | // CoZe-SDK-JAVA 44 | log.info(""" 45 | / __| / _ \\ |_ / | __| ___ / __| | \\ | |/ / ___ _ | | / \\ \\ \\ / / / \\ \s 46 | | (__ | (_) | / / | _| |___| \\__ \\ | |) | | ' < |___| | || | | - | \\ V / | - | \s 47 | \\___| \\___/ /___| |___| _____ |___/ |___/ |_|\\_\\ _____ _\\__/ |_|_| _\\_/_ |_|_| \s 48 | _|""\"""|_|""\"""|_|""\"""|_|""\"""|_| |_|""\"""|_|""\"""|_|""\"""|_| |_|""\"""|_|""\"""|_| ""\""|_|""\"""|\s 49 | "`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'\s 50 | """); 51 | } 52 | 53 | /** 54 | * 初始化请求配置 55 | * 56 | * @return {@link CoZeSession} 57 | */ 58 | @Override 59 | public CoZeSession openSession() { 60 | // 1. 日志配置 61 | HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(); 62 | httpLoggingInterceptor.setLevel(cozeConfiguration.getLevel()); 63 | 64 | // 2. 开启 Http 客户端 65 | OkHttpClient okHttpClient = new OkHttpClient 66 | .Builder() 67 | .addInterceptor(httpLoggingInterceptor) 68 | .addInterceptor(new CoZeInterceptor(cozeConfiguration.getApiKey())) // 设置 apikey 69 | .connectTimeout(450, TimeUnit.SECONDS) 70 | .writeTimeout(450, TimeUnit.SECONDS) 71 | .readTimeout(450, TimeUnit.SECONDS) 72 | .build(); 73 | 74 | // 3. 创建 API 服务 75 | ICoZeApi cozeApi = new Retrofit.Builder() 76 | .baseUrl(cozeConfiguration.getApiHost()) 77 | .client(okHttpClient) 78 | .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) 79 | .addConverterFactory(JacksonConverterFactory.create()) 80 | .build().create(ICoZeApi.class); 81 | // 注入配置 82 | cozeConfiguration.setCoZeApi(cozeApi); 83 | cozeConfiguration.setOkHttpClient(okHttpClient); 84 | return new DefaultCoZeSession(cozeConfiguration); 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /src/test/java/com/yby6/coze/sdk/CozeAPI.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 您可以更改此项目但请不要删除作者署名谢谢,否则根据中华人民共和国版权法进行处理. 3 | * You may change this item but please do not remove the author's signature, 4 | * otherwise it will be dealt with according to the Copyright Law of the People's Republic of China. 5 | * 6 | * yangbuyi Copyright (c) https://yby6.com 2024. 7 | */ 8 | 9 | package com.yby6.coze.sdk; 10 | 11 | import cn.hutool.core.util.IdUtil; 12 | import cn.hutool.json.JSONObject; 13 | import cn.hutool.json.JSONUtil; 14 | import com.fasterxml.jackson.core.JsonProcessingException; 15 | import com.yby6.coze.sdk.domain.*; 16 | import com.yby6.coze.sdk.session.CoZeConfiguration; 17 | import com.yby6.coze.sdk.session.CoZeSession; 18 | import com.yby6.coze.sdk.session.defaults.DefaultCoZeSessionFactory; 19 | import lombok.extern.slf4j.Slf4j; 20 | import okhttp3.Response; 21 | import okhttp3.logging.HttpLoggingInterceptor; 22 | import okhttp3.sse.EventSource; 23 | import okhttp3.sse.EventSourceListener; 24 | import org.jetbrains.annotations.NotNull; 25 | import org.junit.Before; 26 | import org.junit.Test; 27 | 28 | import java.util.concurrent.CountDownLatch; 29 | 30 | /** 31 | * coze api 32 | * 33 | * @author yangs 34 | * Create By 2024/07/04 35 | */ 36 | @Slf4j 37 | public class CozeAPI { 38 | 39 | private CoZeSession coZeSession; 40 | 41 | /** 42 | * 测试会话工厂 43 | */ 44 | @Before 45 | public void test_session_Factory() { 46 | // 1. 配置文件 47 | CoZeConfiguration yuanQiConfiguration = new CoZeConfiguration(); 48 | yuanQiConfiguration.setApiHost("https://api.coze.cn/open_api/"); 49 | yuanQiConfiguration.setApiKey("Bearer 你的APIKEY"); 50 | yuanQiConfiguration.setLevel(HttpLoggingInterceptor.Level.HEADERS); 51 | // 2. 会话工厂 52 | DefaultCoZeSessionFactory factory = new DefaultCoZeSessionFactory(yuanQiConfiguration); 53 | // 3. 开启会话 54 | this.coZeSession = factory.openSession(); 55 | log.info("openAiSession:{}", coZeSession); 56 | } 57 | 58 | /** 59 | * 测试聊天完成 60 | */ 61 | @Test 62 | public void test_chat_completions() { 63 | // 1. 创建参数 64 | CoZeCompletionRequest chatCompletion = CoZeCompletionRequest 65 | .builder() 66 | .stream(false) 67 | .conversationId(IdUtil.nanoId()) 68 | .user("29032201862555") 69 | .botId("7387634479231434790") 70 | .query("你是谁呀?") 71 | .build(); 72 | // 2. 发起请求 73 | CoZeCompletionResponse yuanQiCompletionResponse = coZeSession.completions(chatCompletion); 74 | // 3. 解析结果 75 | for (Message message : yuanQiCompletionResponse.getMessages()) { 76 | // answer 是机器人回答的 77 | if (message.getType().equals("answer")) { 78 | log.info("返回内容: {}", message.getContent()); 79 | } 80 | } 81 | } 82 | 83 | 84 | /** 85 | * 流试返回参数: 86 | * { 87 | * "id": "82956d810a0ff9b413c8bf924c2190c3", 88 | * "created": 1717177832, 89 | * "choices": [ 90 | * { 91 | * "delta": { 92 | * "role": "assistant", 93 | * "content": "我是", 94 | * "time_cost": 0 95 | * } 96 | * } 97 | * ], 98 | * "assistant_id": "mmbnqMnLdYz0", 99 | * "usage": { 100 | * "prompt_tokens": 0, 101 | * "completion_tokens": 0, 102 | * "total_tokens": 0 103 | * } 104 | * } 105 | */ 106 | @Test 107 | public void test_chat_completions_stream() throws JsonProcessingException, InterruptedException { 108 | // 1. 创建参数 109 | CoZeCompletionRequest chatCompletion = CoZeCompletionRequest 110 | .builder() 111 | .stream(true) 112 | .conversationId(IdUtil.nanoId()) 113 | .user("29032201862555") 114 | .botId("7387634479231434790") 115 | .query("你是谁呀?") 116 | .build(); 117 | // 2. 发起请求 118 | EventSource eventSource = coZeSession.chatCompletions(chatCompletion, new EventSourceListener() { 119 | @Override 120 | public void onEvent(@NotNull EventSource eventSource, String id, String type, @NotNull String data) { 121 | try { 122 | CoZeCompletionEventResponse response = JSONUtil.toBean(data, CoZeCompletionEventResponse.class); 123 | 124 | if (response.getEvent().equals("done")) { 125 | return; 126 | } 127 | 128 | Message message = response.getMessage(); 129 | if (message.getType().equals("answer")) { 130 | log.info("返回内容: {}", message.getContent()); 131 | } 132 | } catch (Exception e) { 133 | throw new RuntimeException(e); 134 | } 135 | } 136 | 137 | @Override 138 | public void onFailure(EventSource eventSource, Throwable t, Response response) { 139 | log.error("错误: {}, {}", response.code(), t.getMessage()); 140 | } 141 | }); 142 | // 等待 143 | new CountDownLatch(1).await(); 144 | } 145 | 146 | 147 | /** 148 | * 测试工作流远程调用 149 | */ 150 | @Test 151 | public void test_workFlow_run() throws JsonProcessingException { 152 | 153 | // 1. 配置文件 154 | CoZeConfiguration cozeConfiguration = new CoZeConfiguration(); 155 | cozeConfiguration.setApiHost("https://api.coze.cn/"); 156 | cozeConfiguration.setApiKey("Bearer pat_QuWfmGwBQA8BsMG7cXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); 157 | cozeConfiguration.setLevel(HttpLoggingInterceptor.Level.HEADERS); 158 | 159 | // 2. 会话工厂 160 | DefaultCoZeSessionFactory factory = new DefaultCoZeSessionFactory(cozeConfiguration); 161 | 162 | // 3. 开启会话 163 | coZeSession = factory.openSession(); 164 | 165 | // 4. 设置入参 166 | String prompt = "a cat"; 167 | JSONObject jsonObj = new JSONObject(); 168 | jsonObj.append("prompt", prompt); 169 | 170 | // 5. 构建请求 171 | CoZeWorkFlowRequest coZeWorkFlowRequest = new CoZeWorkFlowRequest(); 172 | // 设置工作流ID 173 | coZeWorkFlowRequest.setWorkflowId("7417847815457701923"); 174 | // 设置参数 175 | coZeWorkFlowRequest.setParameters(jsonObj); 176 | 177 | // 6. 发起请求 178 | CoZeWorkFlowResponse coZeWorkFlowResponse = coZeSession.workflowCompletions(coZeWorkFlowRequest); 179 | 180 | // 7. 解析结果 181 | log.info("Code:{}", coZeWorkFlowResponse.getCode()); 182 | log.info("Msg:{}", coZeWorkFlowResponse.getMsg()); 183 | log.info("Data:{}", coZeWorkFlowResponse.getData()); 184 | log.info("Debug:{}", coZeWorkFlowResponse.getDebug_url()); 185 | 186 | } 187 | 188 | 189 | } 190 | -------------------------------------------------------------------------------- /src/test/java/com/yby6/coze/sdk/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 测试 3 | */ 4 | package com.yby6.coze.sdk; 5 | --------------------------------------------------------------------------------