使用Python来实现Coze+Dify
一、Coze 平台使用详解
Coze 基础配置
# coze_api_demo.py
import requests
import json
class CozeBot:
def __init__(self, api_key, bot_id):
self.api_key = api_key
self.bot_id = bot_id
self.base_url = "https://api.coze.com/v3/chat"
def send_message(self, message, conversation_id=None):
"""发送消息到Coze机器人"""
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
payload = {
"bot_id": self.bot_id,
"user_id": "user_123", # 实际使用时替换为真实用户ID
"message": {
"content": message,
"content_type": "text"
}
}
if conversation_id:
payload["conversation_id"] = conversation_id
response = requests.post(self.base_url, headers=headers, json=payload)
return response.json()
# 使用示例
if __name__ == "__main__":
# 初始化Coze机器人
coze_bot = CozeBot(
api_key="your_coze_api_key",
bot_id="your_bot_id"
)
# 发送消息
response = coze_bot.send_message("你好,请介绍一下AI的发展趋势")
print("Coze回复:", response)
Coze 工作流配置示例
# coze_workflow.yaml
name: "Customer Service Workflow"
version: "1.0"
description: "自动化客户服务流程"
triggers:
- type: "message_received"
conditions:
- field: "intent"
operator: "equals"
value: "complaint"
steps:
- name: "analyze_sentiment"
type: "nlp_analysis"
parameters:
text: "{{input.message}}"
analysis_type: "sentiment"
- name: "classify_issue"
type: "intent_classification"
parameters:
text: "{{input.message}}"
categories: ["billing", "technical", "account", "general"]
- name: "generate_response"
type: "llm_generation"
parameters:
prompt: |
根据以下信息生成客户回复:
用户情绪: {{steps.analyze_sentiment.result}}
问题类型: {{steps.classify_issue.result}}
原始问题: {{input.message}}
请生成专业、友好的回复。
- name: "escalate_check"
type: "condition"
parameters:
condition: "{{steps.analyze_sentiment.result.sentiment_score}} < 0.3"
true_step: "human_escalation"
false_step: "send_response"
- name: "send_response"
type: "send_message"
parameters:
message: "{{steps.generate_response.result}}"
- name: "human_escalation"
type: "assign_to_human"
parameters:
agent_id: "human_agent_001"
priority: "high"
二、Dify 平台使用详解
Dify API 集成
# dify_api_demo.py
import requests
import json
from typing import Dict, List, Any
class DifyClient:
def __init__(self, api_key, base_url="https://api.dify.ai/v1"):
self.api_key = api_key
self.base_url = base_url
self.headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
def create_application(self, app_config: Dict) -> Dict:
"""创建Dify应用"""
url = f"{self.base_url}/applications"
response = requests.post(url, headers=self.headers, json=app_config)
return response.json()
def send_message(self, app_id: str, message: str,
conversation_id: str = None) -> Dict:
"""发送消息到Dify应用"""
url = f"{self.base_url}/chat-messages"
payload = {
"inputs": {},
"query": message,
"response_mode": "streaming", # 或 "blocking"
"user": "user-123"
}
if conversation_id:
payload["conversation_id"] = conversation_id
response = requests.post(url, headers=self.headers, json=payload)
return self._handle_streaming_response(response)
def _handle_streaming_response(self, response):
"""处理流式响应"""
if response.headers.get('content-type') == 'text/event-stream':
for line in response.iter_lines():
if line:
decoded_line = line.decode('utf-8')
if decoded_line.startswith('data: '):
data = decoded_line[6:]
if data != '[DONE]':
yield json.loads(data)
else:
return response.json()
# 使用示例
def create_customer_service_bot():
"""创建客服机器人应用配置"""
client = DifyClient(api_key="your_dify_api_key")
app_config = {
"name": "智能客服助手",
"model_config": {
"provider": "openai",
"model": "gpt-4",
"configs": {
"temperature": 0.7,
"max_tokens": 1000
}
},
"prompt_template": """
你是一个专业的客服助手。请根据以下上下文信息回答用户问题:
上下文:{{#context#}}
{{context}}
{{/context#}}
用户问题:{{query}}
请按照以下要求回答:
1. 保持友好和专业
2. 如果问题涉及具体业务,请参考上下文信息
3. 如果信息不足,请礼貌地请求更多细节
4. 回答要简洁明了
""",
"tools": [
{
"type": "knowledge_retrieval",
"enabled": True,
"config": {
"knowledge_ids": ["your_knowledge_base_id"]
}
}
]
}
return client.create_application(app_config)
Dify 工作流配置
# dify_workflow.py
class DifyWorkflowBuilder:
def __init__(self):
self.workflow = {
"name": "",
"description": "",
"nodes": [],
"edges": []
}
def add_start_node(self, trigger_type: str = "webhook"):
"""添加入口节点"""
start_node = {
"id": "start",
"type": "start",
"data": {
"title": "开始",
"type": trigger_type
}
}
self.workflow["nodes"].append(start_node)
return self
def add_llm_node(self, node_id: str, prompt: str, variables: List[str] = None):
"""添加LLM处理节点"""
llm_node = {
"id": node_id,
"type": "llm",
"data": {
"title": "AI处理",
"prompt": prompt,
"variables": variables or [],
"model": {
"provider": "openai",
"name": "gpt-4",
"mode": "chat",
"configs": {
"temperature": 0.7,
"max_tokens": 2000
}
}
}
}
self.workflow["nodes"].append(llm_node)
return self
def add_condition_node(self, node_id: str, conditions: List[Dict]):
"""添加条件判断节点"""
condition_node = {
"id": node_id,
"type": "condition",
"data": {
"title": "条件判断",
"conditions": conditions
}
}
self.workflow["nodes"].append(condition_node)
return self
def add_edge(self, source_id: str, target_id: str, condition: str = None):
"""添加节点连接"""
edge = {
"id": f"edge_{source_id}_{target_id}",
"source": source_id,
"target": target_id
}
if condition:
edge["data"] = {"condition": condition}
self.workflow["edges"].append(edge)
return self
def build(self) -> Dict:
"""构建工作流配置"""
return self.workflow
# 创建客服工作流示例
def create_customer_service_workflow():
"""创建智能客服工作流"""
builder = DifyWorkflowBuilder()
workflow = (builder
.add_start_node("webhook")
.add_llm_node(
"sentiment_analysis",
"分析以下用户消息的情感倾向(积极/消极/中性)并给出置信度:\n{{input}}",
["input"]
)
.add_llm_node(
"intent_classification",
"分类用户意图:产品咨询、技术支持、投诉建议、账单问题、其他\n用户消息:{{input}}",
["input"]
)
.add_condition_node("urgency_check", [
{
"variable": "sentiment_analysis.output",
"operator": "contains",
"value": "消极"
}
])
.add_llm_node(
"generate_response",
"""根据以下信息生成回复:
用户情感:{{sentiment_analysis.output}}
用户意图:{{intent_classification.output}}
原始问题:{{input}}
请生成专业、贴切的回复。""",
["sentiment_analysis.output", "intent_classification.output", "input"]
)
.add_edge("start", "sentiment_analysis")
.add_edge("sentiment_analysis", "intent_classification")
.add_edge("intent_classification", "urgency_check")
.add_edge("urgency_check", "generate_response", "default")
.build()
)
return workflow
三、完整应用示例:智能客服系统
# intelligent_customer_service.py
import asyncio
from typing import Dict, List
import json
class IntelligentCustomerService:
def __init__(self, coze_config: Dict, dify_config: Dict):
self.coze_client = CozeBot(**coze_config)
self.dify_client = DifyClient(**dify_config)
async def process_customer_query(self, user_message: str, user_context: Dict) -> Dict:
"""处理客户查询"""
# 1. 情感分析
sentiment_result = await self.analyze_sentiment(user_message)
# 2. 意图识别
intent_result = await self.classify_intent(user_message)
# 3. 根据意图路由到不同处理流程
if intent_result.get("category") in ["billing", "technical"]:
# 使用Dify处理专业问题
response = self.dify_client.send_message(
app_id="your_app_id",
message=user_message
)
else:
# 使用Coze处理一般咨询
response = self.coze_client.send_message(user_message)
# 4. 生成最终回复
final_response = await self.generate_final_response(
user_message, sentiment_result, intent_result, response
)
return final_response
async def analyze_sentiment(self, text: str) -> Dict:
"""情感分析"""
# 可以使用Coze或Dify的NLP能力
prompt = f"分析以下文本的情感倾向,返回JSON格式:{{'sentiment': 'positive/negative/neutral', 'confidence': 0.0-1.0}}\n文本:{text}"
result = self.coze_client.send_message(prompt)
return json.loads(result.get("content", "{}"))
async def classify_intent(self, text: str) -> Dict:
"""意图分类"""
categories = ["产品咨询", "技术支持", "投诉建议", "账单问题", "售后服务", "其他"]
prompt = f"将以下用户消息分类到以下类别之一:{categories}。返回JSON格式:{{'category': '类别', 'confidence': 置信度}}\n消息:{text}"
result = self.coze_client.send_message(prompt)
return json.loads(result.get("content", "{}"))
async def generate_final_response(self, user_message: str, sentiment: Dict,
intent: Dict, ai_response: str) -> Dict:
"""生成最终回复"""
final_prompt = f"""
基于以下信息生成客户服务回复:
用户原始消息:{user_message}
情感分析结果:{sentiment}
意图分类结果:{intent}
AI初步回复:{ai_response}
请优化回复,确保:
1. 符合用户情感状态
2. 准确回应用户意图
3. 保持专业和友好
4. 提供有价值的解决方案
最终回复:
"""
final_result = self.dify_client.send_message(
app_id="your_app_id",
message=final_prompt
)
return {
"final_response": final_result,
"metadata": {
"sentiment": sentiment,
"intent": intent,
"processing_time": "实时",
"confidence_score": 0.95
}
}
# 使用示例
async def main():
# 配置信息
coze_config = {
"api_key": "your_coze_api_key",
"bot_id": "your_bot_id"
}
dify_config = {
"api_key": "your_dify_api_key"
}
# 创建客服系统实例
customer_service = IntelligentCustomerService(coze_config, dify_config)
# 处理客户查询
test_message = "我的订单已经延迟3天了,什么时候能发货?"
result = await customer_service.process_customer_query(
test_message,
{"user_id": "customer_001", "order_history": []}
)
print("客服回复:", json.dumps(result, ensure_ascii=False, indent=2))
if __name__ == "__main__":
asyncio.run(main())
四、前端集成示例
<!-- customer_service_ui.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>智能客服系统</title>
<style>
.chat-container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.message {
margin: 10px 0;
padding: 10px;
border-radius: 10px;
}
.user-message {
background-color: #e3f2fd;
margin-left: 50px;
}
.bot-message {
background-color: #f5f5f5;
margin-right: 50px;
}
.input-area {
position: fixed;
bottom: 0;
width: 100%;
background: white;
padding: 10px;
border-top: 1px solid #ddd;
}
</style>
</head>
<body>
<div class="chat-container" id="chatContainer">
<div id="messages"></div>
</div>
<div class="input-area">
<input type="text" id="userInput" placeholder="请输入您的问题..." style="width: 70%; padding: 10px;">
<button onclick="sendMessage()" style="padding: 10px 20px;">发送</button>
</div>
<script>
async function sendMessage() {
const userInput = document.getElementById('userInput');
const message = userInput.value.trim();
if (!message) return;
// 添加用户消息到界面
addMessage('user', message);
userInput.value = '';
try {
// 调用后端API(集成Coze/Dify)
const response = await fetch('/api/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
message: message,
user_id: 'user_123',
conversation_id: getConversationId()
})
});
const data = await response.json();
addMessage('bot', data.response);
} catch (error) {
console.error('Error:', error);
addMessage('bot', '抱歉,服务暂时不可用,请稍后重试。');
}
}
function addMessage(sender, content) {
const messagesDiv = document.getElementById('messages');
const messageDiv = document.createElement('div');
messageDiv.className = `message ${sender}-message`;
messageDiv.textContent = content;
messagesDiv.appendChild(messageDiv);
messagesDiv.scrollTop = messagesDiv.scrollHeight;
}
function getConversationId() {
// 从本地存储获取或生成会话ID
let convId = localStorage.getItem('conversation_id');
if (!convId) {
convId = 'conv_' + Date.now();
localStorage.setItem('conversation_id', convId);
}
return convId;
}
// 回车发送消息
document.getElementById('userInput').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
sendMessage();
}
});
</script>
</body>
</html>
关键优势总结
-
快速原型开发:使用低代码平台可以在几小时内搭建功能完整的AI应用
-
可视化配置:通过图形界面配置工作流,无需深入编码
-
模型灵活性:支持多种AI模型,可随时切换
-
扩展性强:支持自定义代码和API集成
-
成本效益:减少开发和维护成本
使用Java来实现Coze+Dify
一、集成 Coze 平台
Maven 依赖配置
<!-- pom.xml -->
<dependencies>
<!-- HTTP客户端 -->
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.2.1</version>
</dependency>
<!-- JSON处理 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
<!-- 异步处理 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>6.0.11</version>
</dependency>
</dependencies>
Coze API 客户端实现
// CozeClient.java
package com.example.aiclient.coze;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import java.io.IOException;
import java.util.List;
public class CozeClient {
private final String apiKey;
private final String botId;
private final String baseUrl = "https://api.coze.com/v3/chat";
private final ObjectMapper objectMapper = new ObjectMapper();
private final CloseableHttpClient httpClient;
public CozeClient(String apiKey, String botId) {
this.apiKey = apiKey;
this.botId = botId;
this.httpClient = HttpClients.createDefault();
}
// 请求DTO
public static class ChatRequest {
@JsonProperty("bot_id")
private String botId;
@JsonProperty("user_id")
private String userId;
private Message message;
private String stream;
@JsonProperty("conversation_id")
private String conversationId;
// 构造函数、getter、setter
public ChatRequest(String botId, String userId, Message message) {
this.botId = botId;
this.userId = userId;
this.message = message;
this.stream = "false";
}
// getters and setters
public String getBotId() { return botId; }
public void setBotId(String botId) { this.botId = botId; }
public String getUserId() { return userId; }
public void setUserId(String userId) { this.userId = userId; }
public Message getMessage() { return message; }
public void setMessage(Message message) { this.message = message; }
public String getStream() { return stream; }
public void setStream(String stream) { this.stream = stream; }
public String getConversationId() { return conversationId; }
public void setConversationId(String conversationId) { this.conversationId = conversationId; }
}
public static class Message {
private String content;
@JsonProperty("content_type")
private String contentType = "text";
public Message(String content) {
this.content = content;
}
// getters and setters
public String getContent() { return content; }
public void setContent(String content) { this.content = content; }
public String getContentType() { return contentType; }
public void setContentType(String contentType) { this.contentType = contentType; }
}
// 响应DTO
public static class ChatResponse {
private int code;
private String msg;
private ResponseData data;
// getters and setters
public int getCode() { return code; }
public void setCode(int code) { this.code = code; }
public String getMsg() { return msg; }
public void setMsg(String msg) { this.msg = msg; }
public ResponseData getData() { return data; }
public void setData(ResponseData data) { this.data = data; }
}
public static class ResponseData {
private List<MessageResponse> messages;
@JsonProperty("conversation_id")
private String conversationId;
// getters and setters
public List<MessageResponse> getMessages() { return messages; }
public void setMessages(List<MessageResponse> messages) { this.messages = messages; }
public String getConversationId() { return conversationId; }
public void setConversationId(String conversationId) { this.conversationId = conversationId; }
}
public static class MessageResponse {
private String content;
@JsonProperty("content_type")
private String contentType;
private String role;
// getters and setters
public String getContent() { return content; }
public void setContent(String content) { this.content = content; }
public String getContentType() { return contentType; }
public void setContentType(String contentType) { this.contentType = contentType; }
public String getRole() { return role; }
public void setRole(String role) { this.role = role; }
}
public ChatResponse sendMessage(String message, String userId, String conversationId) throws IOException {
HttpPost httpPost = new HttpPost(baseUrl);
// 设置headers
httpPost.setHeader("Authorization", "Bearer " + apiKey);
httpPost.setHeader("Content-Type", "application/json");
// 构建请求体
ChatRequest chatRequest = new ChatRequest(botId, userId, new Message(message));
if (conversationId != null && !conversationId.isEmpty()) {
chatRequest.setConversationId(conversationId);
}
String requestBody = objectMapper.writeValueAsString(chatRequest);
httpPost.setEntity(new StringEntity(requestBody));
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
String responseBody = EntityUtils.toString(response.getEntity());
return objectMapper.readValue(responseBody, ChatResponse.class);
}
}
public void close() throws IOException {
httpClient.close();
}
}
二、Java 集成 Dify 平台
Dify API 客户端实现
// DifyClient.java
package com.example.aiclient.dify;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class DifyClient {
private final String apiKey;
private final String baseUrl = "https://api.dify.ai/v1";
private final ObjectMapper objectMapper = new ObjectMapper();
private final CloseableHttpClient httpClient;
public DifyClient(String apiKey) {
this.apiKey = apiKey;
this.httpClient = HttpClients.createDefault();
}
// 聊天请求DTO
public static class ChatRequest {
private Map<String, Object> inputs = new HashMap<>();
private String query;
@JsonProperty("response_mode")
private String responseMode = "blocking"; // streaming or blocking
private String user;
@JsonProperty("conversation_id")
private String conversationId;
// 构造函数
public ChatRequest(String query, String user) {
this.query = query;
this.user = user;
}
// getters and setters
public Map<String, Object> getInputs() { return inputs; }
public void setInputs(Map<String, Object> inputs) { this.inputs = inputs; }
public String getQuery() { return query; }
public void setQuery(String query) { this.query = query; }
public String getResponseMode() { return responseMode; }
public void setResponseMode(String responseMode) { this.responseMode = responseMode; }
public String getUser() { return user; }
public void setUser(String user) { this.user = user; }
public String getConversationId() { return conversationId; }
public void setConversationId(String conversationId) { this.conversationId = conversationId; }
}
// 聊天响应DTO
public static class ChatResponse {
private String answer;
private Map<String, Object> metadata;
@JsonProperty("conversation_id")
private String conversationId;
// getters and setters
public String getAnswer() { return answer; }
public void setAnswer(String answer) { this.answer = answer; }
public Map<String, Object> getMetadata() { return metadata; }
public void setMetadata(Map<String, Object> metadata) { this.metadata = metadata; }
public String getConversationId() { return conversationId; }
public void setConversationId(String conversationId) { this.conversationId = conversationId; }
}
public ChatResponse sendMessage(String query, String userId, String conversationId) throws IOException {
String url = baseUrl + "/chat-messages";
HttpPost httpPost = new HttpPost(url);
// 设置headers
httpPost.setHeader("Authorization", "Bearer " + apiKey);
httpPost.setHeader("Content-Type", "application/json");
// 构建请求体
ChatRequest chatRequest = new ChatRequest(query, userId);
if (conversationId != null && !conversationId.isEmpty()) {
chatRequest.setConversationId(conversationId);
}
String requestBody = objectMapper.writeValueAsString(chatRequest);
httpPost.setEntity(new StringEntity(requestBody));
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
String responseBody = EntityUtils.toString(response.getEntity());
return objectMapper.readValue(responseBody, ChatResponse.class);
}
}
// 创建工作流执行
public WorkflowResponse executeWorkflow(String workflowId, Map<String, Object> inputs, String userId) throws IOException {
String url = baseUrl + "/workflows/" + workflowId + "/run";
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Authorization", "Bearer " + apiKey);
httpPost.setHeader("Content-Type", "application/json");
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("inputs", inputs);
requestBody.put("user", userId);
requestBody.put("response_mode", "blocking");
String jsonBody = objectMapper.writeValueAsString(requestBody);
httpPost.setEntity(new StringEntity(jsonBody));
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
String responseBody = EntityUtils.toString(response.getEntity());
return objectMapper.readValue(responseBody, WorkflowResponse.class);
}
}
public static class WorkflowResponse {
private Object data;
private Map<String, Object> metadata;
// getters and setters
public Object getData() { return data; }
public void setData(Object data) { this.data = data; }
public Map<String, Object> getMetadata() { return metadata; }
public void setMetadata(Map<String, Object> metadata) { this.metadata = metadata; }
}
public void close() throws IOException {
httpClient.close();
}
}
三、Spring Boot 集成示例
Spring Boot 配置类
// AiConfig.java
package com.example.aiclient.config;
import com.example.aiclient.coze.CozeClient;
import com.example.aiclient.dify.DifyClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AiConfig {
@Value("${coze.api.key}")
private String cozeApiKey;
@Value("${coze.bot.id}")
private String cozeBotId;
@Value("${dify.api.key}")
private String difyApiKey;
@Bean
public CozeClient cozeClient() {
return new CozeClient(cozeApiKey, cozeBotId);
}
@Bean
public DifyClient difyClient() {
return new DifyClient(difyApiKey);
}
}
应用配置文件
# application.yml
coze:
api:
key: ${COZE_API_KEY:your_coze_api_key}
bot:
id: ${COZE_BOT_ID:your_bot_id}
dify:
api:
key: ${DIFY_API_KEY:your_dify_api_key}
server:
port: 8080
spring:
application:
name: java-ai-assistant
Spring Boot 控制器
// AiChatController.java
package com.example.aiclient.controller;
import com.example.aiclient.coze.CozeClient;
import com.example.aiclient.dify.DifyClient;
import com.example.aiclient.service.AiOrchestrationService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/api/ai")
@CrossOrigin(origins = "*")
public class AiChatController {
private final CozeClient cozeClient;
private final DifyClient difyClient;
private final AiOrchestrationService aiOrchestrationService;
public AiChatController(CozeClient cozeClient, DifyClient difyClient,
AiOrchestrationService aiOrchestrationService) {
this.cozeClient = cozeClient;
this.difyClient = difyClient;
this.aiOrchestrationService = aiOrchestrationService;
}
@PostMapping("/chat")
public ResponseEntity<Map<String, Object>> chat(
@RequestBody ChatRequest request,
@RequestHeader(value = "User-Id", defaultValue = "anonymous") String userId) {
try {
Map<String, Object> response = aiOrchestrationService.processMessage(
request.getMessage(),
userId,
request.getConversationId()
);
return ResponseEntity.ok(response);
} catch (Exception e) {
Map<String, Object> errorResponse = new HashMap<>();
errorResponse.put("error", "处理请求时发生错误");
errorResponse.put("details", e.getMessage());
return ResponseEntity.internalServerError().body(errorResponse);
}
}
@PostMapping("/coze/chat")
public ResponseEntity<Map<String, Object>> cozeChat(
@RequestBody ChatRequest request,
@RequestHeader("User-Id") String userId) {
try {
CozeClient.ChatResponse response = cozeClient.sendMessage(
request.getMessage(),
userId,
request.getConversationId()
);
Map<String, Object> result = new HashMap<>();
result.put("response", response);
return ResponseEntity.ok(result);
} catch (Exception e) {
return ResponseEntity.internalServerError().body(Map.of("error", e.getMessage()));
}
}
@PostMapping("/dify/chat")
public ResponseEntity<Map<String, Object>> difyChat(
@RequestBody ChatRequest request,
@RequestHeader("User-Id") String userId) {
try {
DifyClient.ChatResponse response = difyClient.sendMessage(
request.getMessage(),
userId,
request.getConversationId()
);
Map<String, Object> result = new HashMap<>();
result.put("answer", response.getAnswer());
result.put("conversation_id", response.getConversationId());
return ResponseEntity.ok(result);
} catch (Exception e) {
return ResponseEntity.internalServerError().body(Map.of("error", e.getMessage()));
}
}
// 请求DTO
public static class ChatRequest {
private String message;
private String conversationId;
// getters and setters
public String getMessage() { return message; }
public void setMessage(String message) { this.message = message; }
public String getConversationId() { return conversationId; }
public void setConversationId(String conversationId) { this.conversationId = conversationId; }
}
}
四、智能业务流程编排服务
// AiOrchestrationService.java
package com.example.aiclient.service;
import com.example.aiclient.coze.CozeClient;
import com.example.aiclient.dify.DifyClient;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Service
public class AiOrchestrationService {
private final CozeClient cozeClient;
private final DifyClient difyClient;
private final ObjectMapper objectMapper;
private final Map<String, String> userConversations;
public AiOrchestrationService(CozeClient cozeClient, DifyClient difyClient) {
this.cozeClient = cozeClient;
this.difyClient = difyClient;
this.objectMapper = new ObjectMapper();
this.userConversations = new ConcurrentHashMap<>();
}
public Map<String, Object> processMessage(String message, String userId, String conversationId) {
try {
// 1. 情感分析
Map<String, Object> sentiment = analyzeSentiment(message);
// 2. 意图识别
Map<String, Object> intent = classifyIntent(message);
// 3. 根据意图路由到合适的AI服务
String finalResponse;
String usedService;
String intentCategory = (String) intent.get("category");
if (isComplexQuery(intentCategory, message)) {
// 复杂问题使用Dify
DifyClient.ChatResponse difyResponse = difyClient.sendMessage(
buildContextualPrompt(message, sentiment, intent),
userId,
conversationId
);
finalResponse = difyResponse.getAnswer();
usedService = "dify";
} else {
// 简单问题使用Coze
CozeClient.ChatResponse cozeResponse = cozeClient.sendMessage(
message, userId, conversationId
);
if (cozeResponse.getData() != null &&
!cozeResponse.getData().getMessages().isEmpty()) {
finalResponse = cozeResponse.getData().getMessages().get(0).getContent();
} else {
finalResponse = "抱歉,我无法处理这个问题。";
}
usedService = "coze";
}
// 4. 构建响应
Map<String, Object> response = new HashMap<>();
response.put("answer", finalResponse);
response.put("sentiment", sentiment);
response.put("intent", intent);
response.put("service_used", usedService);
response.put("conversation_id", conversationId);
response.put("user_id", userId);
return response;
} catch (Exception e) {
Map<String, Object> errorResponse = new HashMap<>();
errorResponse.put("error", "AI服务处理失败");
errorResponse.put("fallback_answer", "抱歉,服务暂时不可用,请稍后重试。");
return errorResponse;
}
}
private Map<String, Object> analyzeSentiment(String text) throws Exception {
String prompt = String.format(
"分析以下文本的情感倾向,返回JSON格式:{\"sentiment\": \"positive/negative/neutral\", \"confidence\": 0.95}\n文本:%s",
text
);
CozeClient.ChatResponse response = cozeClient.sendMessage(prompt, "system", null);
if (response.getData() != null && !response.getData().getMessages().isEmpty()) {
String content = response.getData().getMessages().get(0).getContent();
return objectMapper.readValue(content, Map.class);
}
return Map.of("sentiment", "neutral", "confidence", 0.5);
}
private Map<String, Object> classifyIntent(String text) throws Exception {
String[] categories = {"产品咨询", "技术支持", "投诉建议", "账单问题", "售后服务", "其他"};
String prompt = String.format(
"将以下用户消息分类到以下类别之一:%s。返回JSON格式:{\"category\": \"类别\", \"confidence\": 0.95}\n消息:%s",
String.join(",", categories), text
);
CozeClient.ChatResponse response = cozeClient.sendMessage(prompt, "system", null);
if (response.getData() != null && !response.getData().getMessages().isEmpty()) {
String content = response.getData().getMessages().get(0).getContent();
return objectMapper.readValue(content, Map.class);
}
return Map.of("category", "其他", "confidence", 0.5);
}
private boolean isComplexQuery(String intentCategory, String message) {
// 复杂查询判断逻辑
return message.length() > 100 ||
"技术支持".equals(intentCategory) ||
"投诉建议".equals(intentCategory) ||
message.toLowerCase().contains("如何") ||
message.toLowerCase().contains("为什么");
}
private String buildContextualPrompt(String message, Map<String, Object> sentiment,
Map<String, Object> intent) {
return String.format(
"基于以下上下文信息回答用户问题:\n" +
"用户情感:%s\n" +
"用户意图:%s\n" +
"原始问题:%s\n\n" +
"请提供专业、详细、有帮助的回答:",
sentiment.get("sentiment"),
intent.get("category"),
message
);
}
}
五、测试类
// AiClientApplicationTest.java
package com.example.aiclient;
import com.example.aiclient.coze.CozeClient;
import com.example.aiclient.dify.DifyClient;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class AiClientApplicationTest {
@Test
void testCozeIntegration() {
try {
CozeClient cozeClient = new CozeClient("your_coze_api_key", "your_bot_id");
CozeClient.ChatResponse response = cozeClient.sendMessage("你好,介绍一下AI", "test_user", null);
System.out.println("Coze Response: " + response.getData().getMessages().get(0).getContent());
cozeClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
void testDifyIntegration() {
try {
DifyClient difyClient = new DifyClient("your_dify_api_key");
DifyClient.ChatResponse response = difyClient.sendMessage("什么是机器学习?", "test_user", null);
System.out.println("Dify Response: " + response.getAnswer());
difyClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
六、主应用类
// AiClientApplication.java
package com.example.aiclient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AiClientApplication {
public static void main(String[] args) {
SpringApplication.run(AiClientApplication.class, args);
}
}
关键优势
-
企业级集成:Java + Spring Boot 提供稳定的企业级解决方案
-
高性能:使用连接池和异步处理提高性能
-
类型安全:强类型语言减少运行时错误
-
生态丰富:可以轻松集成数据库、消息队列等其他企业组件
-
监控完善:易于集成监控和日志系统
部署配置
# Dockerfile
FROM openjdk:17-jdk-slim
WORKDIR /app
COPY target/java-ai-assistant.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
这种 Java 集成方案特别适合:
-
企业级AI应用开发
-
需要高并发处理的场景
-
已有Java技术栈的项目
-
需要严格类型检查和稳定性的场景
541

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



