Spring 对接 Coze
实现智能体对接,让你的智能体随处可达。ELIZA(1960年代)和 PARRY(1970年代)
,主要基于关键词匹配和预设回答逻辑。这些早期机器人在语句理解上极为有限,无法进行自然流畅的对话。Siri、Cortana、Alexa
等基于统计和深度学习方法,能够处理更复杂的对话场景,并具有一定的自我学习能力。例如 云雀、GPT-4、BERT 等
),这些模型虽然功能强大,但也带来了显著的困难:Coze
等智能体发展给第三代聊天机器人带来的机遇Coze
等智能体的出现解决了这一问题,让即使普通人也可以实现自己的第三代聊天机器人,并提供了自定义数据库、大模型切换、工作流等一些高级功能,如果不了解 Coze
等智能体的朋友强烈建议大家去了解一下:https://www.coze.cn/Coze
等智能体通过智能化的配置界面与预设功能降低了操作难度,实现了开箱即用的用户体验。用户只需登录平台,按指引配置,即可拥有一个具备自然语言处理能力的智能体。这种低门槛的设计让个人用户和小微企业不再需要专业开发团队,就可以享受到智能对话技术带来的便利与效率提升。Coze
平台还提供了丰富的接口和外部集成选项,支持用户将智能体无缝集成到现有的业务系统中。通过 API 调用,智能体能够获取实时数据、连接 CRM 系统或 ERP 系统,提供更全面的用户支持和业务服务。此外,开放的 API 让企业能够按照需求扩展智能体功能,比如对接支付系统、工单管理等,打造高度匹配业务需求的专属智能体服务。Spring 应用
对接 Coze
实现随处可达的第三代聊天机器人Coze
等智能体提供了强大自定义能力,我们可以直接使用 WebSDK
和 API
的方式集成到我们的应用程序中,为我们的应用程序赋能,相比 WebSDK
, API
介入是一种更加深度的接入方式,下面我将使用我以前文章中实现的 你的专属程序员鼓励师女友 实现 API
对接。pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>spring-ai-coze</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- Spring Boot Web Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Thymeleaf Starter for frontend integration -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- Spring Boot DevTools for hot reload (optional) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!-- Spring Boot Starter Test for testing (optional) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Spring Boot Starter JSON for JSON processing (optional, included in web starter) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.6.4</version>
</plugin>
</plugins>
</build>
</project>
application.properties
server.port=8080
# Coze API Configuration
coze.api.url=https://api.coze.cn/v3/chat
coze.api.key=XXXXX
coze.bot.id=XXX
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chatbot</title>
<script>
let chatId;
let conversationId;
const userId = 'user_' + Math.floor(Math.random() * 100000);
async function sendMessage() {
const messageContent = document.getElementById("userMessage").value;
if (!messageContent) return;
const response = await fetch('/api/chat/message', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: new URLSearchParams({
userId: userId,
messageContent: messageContent
})
});
arr = await response.json(); // 获取 chatId
chatId = arr[0];
conversationId = arr[1];
checkChatStatus(); // 定时检查聊天状态
}
async function checkChatStatus() {
const intervalId = setInterval(async () => {
const response = await fetch(`/api/chat/checkStatus?chatId=${chatId}&conversationId=${conversationId}`);
const status = await response.text();
if (status === "completed") {
clearInterval(intervalId);
getChatResponse();
}
}, 3000); // 每隔 3 秒查询一次
}
async function getChatResponse() {
const response = await fetch(`/api/chat/getResponse?chatId=${chatId}&conversationId=${conversationId}`);
const result = await response.text();
document.getElementById("chatOutput").innerHTML += `<p><strong>Bot:</strong> ${result}</p>`;
}
</script>
</head>
<body>
<h2>Chatbot</h2>
<div id="chatOutput"></div>
<input type="text" id="userMessage" placeholder="Enter your message"/>
<button onclick="sendMessage()">Send</button>
</body>
</html>
css 文件:
.user-message {
color: blue;
font-weight: bold;
}
.bot-message {
color: green;
font-style: italic;
}
.container {
max-width: 600px;
margin: auto;
padding: 20px;
}
ChatbotApplication.java
@SpringBootApplication
public class ChatbotApplication {
public static void main(String[] args) {
SpringApplication.run(ChatbotApplication.class, args);
}
}
ChatbotService.java
@Service
public class ChatbotService {
@Value("${coze.api.url}")
private String cozeApiUrl;
@Value("${coze.api.key}")
private String cozeApiKey;
@Value("${coze.bot.id}")
private String botId;
private final RestTemplate restTemplate = new RestTemplate();
public List<String> initiateChat(String conversationId, String userId, String messageContent) {
String url = cozeApiUrl;
if (conversationId != null) {
url = url + "?conversation_id=" + conversationId;
}
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + cozeApiKey);
headers.set("Content-Type", "application/json");
Map<String, Object> body = new HashMap<>();
body.put("bot_id", botId);
body.put("user_id", userId);
body.put("stream", false);
body.put("auto_save_history", true);
Map<String, String> message = new HashMap<>();
message.put("role", "user");
message.put("content", messageContent);
message.put("content_type", "text");
body.put("additional_messages", new Object[]{message});
HttpEntity<Map<String, Object>> request = new HttpEntity<>(body, headers);
ResponseEntity<Map> response = restTemplate.exchange(
url,
HttpMethod.POST,
request,
Map.class
);
Map<String, Object> data = response.getBody() != null ? (Map<String, Object>) response.getBody().get("data") : null;
// 返回 chat ID
if (data != null) {
ArrayList<String> resArr = new ArrayList<>();
resArr.add(data.get("id").toString());
resArr.add(data.get("conversation_id").toString());
return resArr;
} else {
return null;
}
}
public String checkChatStatus(String chatId, String conversationId) {
String url = cozeApiUrl + "/retrieve?conversation_id=" + conversationId + "&chat_id=" + chatId;
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + cozeApiKey);
HttpEntity<Void> request = new HttpEntity<>(headers);
ResponseEntity<Map> response = restTemplate.exchange(
url,
HttpMethod.GET,
request,
Map.class
);
Map<String, Object> data = response.getBody() != null ? (Map<String, Object>) response.getBody().get("data") : null;
return data != null ? data.get("status").toString() : "pending";
}
public String getChatResponse(String chatId, String conversationId) {
String url = cozeApiUrl + "/message/list?conversation_id=" + conversationId + "&chat_id=" + chatId;
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + cozeApiKey);
HttpEntity<Void> request = new HttpEntity<>(headers);
ResponseEntity<Map> response = restTemplate.exchange(
url,
HttpMethod.GET,
request,
Map.class
);
Map<String, Object> body = response.getBody();
System.out.println(body);
if (body != null && body.containsKey("data")) {
for (Map<String, Object> message : (Iterable<Map<String, Object>>) body.get("data")) {
if ("answer".equals(message.get("type"))) {
return message.get("content").toString();
}
}
}
return "No response available yet.";
}
}
ChatbotController.java
@RestController
@RequestMapping("/api/chat")
public class ChatbotController {
@Autowired
private ChatbotService chatbotService;
private Map<String, List<String>> chatStatuses = new HashMap<>();
@PostMapping("/message")
public List<String> initiateChat(
@RequestParam(required = false) String conversationId,
@RequestParam String userId,
@RequestParam String messageContent
) {
return chatbotService.initiateChat(conversationId, userId, messageContent);
}
@GetMapping("/checkStatus")
public String checkChatStatus(@RequestParam String chatId, @RequestParam String conversationId) {
return chatbotService.checkChatStatus(chatId, conversationId);
}
@GetMapping("/getResponse")
public String getChatResponse(@RequestParam String chatId, @RequestParam String conversationId) {
return chatbotService.getChatResponse(chatId, conversationId);
}
Coze
等智能体正在推动聊天机器人进入新阶段,带来更强的灵活性和定制化能力。这些工具大幅降低了第三代聊天机器人的使用门槛,使个人和企业可以轻松构建专属的智能对话系统。通过支持自定义数据库、动态模型切换和灵活的工作流管理,Coze
等智能体为智能交互提供了更强的扩展性和适应性,满足了更多样化的业务需求。👋 你好,我是 Lorin 洛林,一位 Java 后端技术开发者!座右铭:Technology has the power to make the world a better place.
🚀 我对技术的热情是我不断学习和分享的动力。我的博客是一个关于Java生态系统、后端开发和最新技术趋势的地方。
🧠 作为一个 Java 后端技术爱好者,我不仅热衷于探索语言的新特性和技术的深度,还热衷于分享我的见解和最佳实践。我相信知识的分享和社区合作可以帮助我们共同成长。
💡 在我的博客上,你将找到关于Java核心概念、JVM 底层技术、常用框架如Spring和Mybatis 、MySQL等数据库管理、RabbitMQ、Rocketmq等消息中间件、性能优化等内容的深入文章。我也将分享一些编程技巧和解决问题的方法,以帮助你更好地掌握Java编程。
🌐 我鼓励互动和建立社区,因此请留下你的问题、建议或主题请求,让我知道你感兴趣的内容。此外,我将分享最新的互联网和技术资讯,以确保你与技术世界的最新发展保持联系。我期待与你一起在技术之路上前进,一起探讨技术世界的无限可能性。
📖 保持关注我的博客,让我们共同追求技术卓越。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。