先看成果
一、旅小伴微信小程序


二、开发步骤
1、扣子开发平台智能体搭建
基于扣子低代码平台,搭建工作流

工作流嵌入智能体,智能体可以是多agents,也可以是单agent。

3、智能体发布为API

4、基于扣子java sdk开发接口,使用Server-Sent Events (SSE) 协议。
前端示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>扣子平台流式聊天 - SSE</title>
</head>
<body>
<input type="text" id="question" placeholder="请输入问题">
<button onclick="sendQuestion()">发送</button>
<div id="answer"></div>
<script>
function sendQuestion() {
const question = document.getElementById('question').value;
const eventSource = new EventSource(`/stream-chat?question=${encodeURIComponent(question)}`);
eventSource.onmessage = function (event) {
const answerDiv = document.getElementById('answer');
answerDiv.innerHTML += event.data;
};
eventSource.onerror = function (error) {
console.error('发生错误:', error);
eventSource.close();
};
}
</script>
</body>
</html>
后端示例代码
import com.coze.openapi.client.chat.ChatReq;
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;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import java.util.Collections;
@RestController
public class CozeStreamChatController {
@GetMapping(path = "/stream-chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ServerSentEvent<String>> streamChat(@RequestParam String question) {
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);
CozeAPI coze = new CozeAPI.Builder()
.baseURL(System.getenv("COZE_API_BASE"))
.auth(authCli)
.build();
ChatReq req = ChatReq.builder()
.botID(botID)
.userID(userID)
.messages(Collections.singletonList(Message.buildUserQuestionText(question)))
.build();
Flowable<ChatEvent> resp = coze.chat().stream(req);
return Flux.fromStream(resp.toStream())
.map(event -> {
if (ChatEventType.CONVERSATION_MESSAGE_DELTA.equals(event.getEvent())) {
return ServerSentEvent.<String>builder()
.data(event.getMessage().getContent())
.build();
}
return null;
})
.filter(event -> event != null);
}
}
搭建过程是这样,更具体的步骤扣子文档里有详细介绍。
456

被折叠的 条评论
为什么被折叠?



