Commit f8edf3b5 authored by 水玉婷's avatar 水玉婷
Browse files

feat:优化请求

parent e11ffc0e
...@@ -40,8 +40,8 @@ ...@@ -40,8 +40,8 @@
stage: 'wechat-demo', stage: 'wechat-demo',
}; };
const dialogSessionId = '20251127180914709-00043912'; // const dialogSessionId = '20251127180914709-00043912';
// const dialogSessionId = ''; const dialogSessionId = '';
const detailData = ref({ const detailData = ref({
title: '国械小智', title: '国械小智',
}); });
......
...@@ -77,7 +77,11 @@ ...@@ -77,7 +77,11 @@
<div class="chat-input-container"> <div class="chat-input-container">
<div class="chat-input"> <div class="chat-input">
<!-- 语音识别按钮 --> <!-- 语音识别按钮 -->
<VoiceRecognition ref="voiceRecognitionRef" :disabled="loading" :debug="true" @audio="handleVoiceAudio" <VoiceRecognition ref="voiceRecognitionRef" :disabled="loading" :debug="true"
:token="props.token"
:appCode="props.appCode"
:apiBaseUrl="props.apiBaseUrl"
@audio="handleVoiceAudio"
@error="handleVoiceError" class="voice-recognition-wrapper" /> @error="handleVoiceError" class="voice-recognition-wrapper" />
<textarea ref="textarea" v-model="messageText" placeholder="输入消息..." @keypress="handleKeyPress" <textarea ref="textarea" v-model="messageText" placeholder="输入消息..." @keypress="handleKeyPress"
...@@ -93,7 +97,6 @@ ...@@ -93,7 +97,6 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, nextTick, watch } from 'vue'; import { ref, onMounted, onBeforeUnmount, nextTick, watch } from 'vue';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import { post, get } from '@/utils/axios.js'; // 导入axios的post方法
import { tableTemplate } from './utils/tableTemplate'; import { tableTemplate } from './utils/tableTemplate';
import { markdownTemplate, isLastBlockMarkdown, getLastMarkdownBlockIndex, mergeMarkdownContent } from './utils/markdownTemplate'; import { markdownTemplate, isLastBlockMarkdown, getLastMarkdownBlockIndex, mergeMarkdownContent } from './utils/markdownTemplate';
import { SendOutlined, UserOutlined } from '@ant-design/icons-vue'; import { SendOutlined, UserOutlined } from '@ant-design/icons-vue';
...@@ -103,6 +106,7 @@ import VoiceRecognition from './VoiceRecognition.vue'; // 导入语音识别组 ...@@ -103,6 +106,7 @@ import VoiceRecognition from './VoiceRecognition.vue'; // 导入语音识别组
import AudioPlayer from './AudioPlayer.vue'; // 导入音频播放器组件 import AudioPlayer from './AudioPlayer.vue'; // 导入音频播放器组件
import { createSSEService, type SSEData } from './utils/sseService'; // 导入SSE服务 import { createSSEService, type SSEData } from './utils/sseService'; // 导入SSE服务
import { createContentTemplateService, type Message } from './utils/contentTemplateService'; // 导入模板服务 import { createContentTemplateService, type Message } from './utils/contentTemplateService'; // 导入模板服务
import { init } from 'echarts/types/src/echarts.all.js';
// 定义组件属性接口 // 定义组件属性接口
interface Props { interface Props {
...@@ -129,8 +133,8 @@ interface Props { ...@@ -129,8 +133,8 @@ interface Props {
// 定义组件属性 // 定义组件属性
const props = withDefaults(defineProps<Props>(), { const props = withDefaults(defineProps<Props>(), {
dialogSessionId: '', dialogSessionId: '',
apiBaseUrl: import.meta.env.VITE_API_BASE_PATH || '/pedapi', apiBaseUrl: '',
appCode: import.meta.env.VITE_APP_CODE || 'ped.qywx', appCode: '',
token: '', token: '',
logoUrl: '', logoUrl: '',
detailData: () => ({}), detailData: () => ({}),
...@@ -287,7 +291,6 @@ const handleVoiceError = (error: string) => { ...@@ -287,7 +291,6 @@ const handleVoiceError = (error: string) => {
const startConversation = () => { const startConversation = () => {
if (!hasStartedConversation.value) { if (!hasStartedConversation.value) {
console.log('开始对话,初始化SSE连接'); console.log('开始对话,初始化SSE连接');
initSSE(); // 只在第一次发送消息时初始化SSE
hasStartedConversation.value = true; hasStartedConversation.value = true;
} }
}; };
...@@ -404,11 +407,18 @@ const sendMessage = async (type: MessageType = 'text', params: MessageParams = { ...@@ -404,11 +407,18 @@ const sendMessage = async (type: MessageType = 'text', params: MessageParams = {
...props.params, ...props.params,
}; };
const response = await post(`${props.apiBaseUrl}/aiService/ask/app/${props.params?.appId}`, const response = await fetch(`${props.apiBaseUrl}/aiService/ask/app/${props.params?.appId}`, {
requestData method: 'POST',
); headers: {
'Content-Type': 'application/json',
'token': props.token,
'x-session-id': props.token,
'x-app-code': props.appCode || ''
},
body: JSON.stringify(requestData)
});
const data = response.data; const data = await response.json();
if (data.code === 0) { if (data.code === 0) {
console.log(`发送成功`); console.log(`发送成功`);
} }
...@@ -465,9 +475,16 @@ const getChatRecord = async (dialogSessionId: string) => { ...@@ -465,9 +475,16 @@ const getChatRecord = async (dialogSessionId: string) => {
messages.value = [...recordList]; messages.value = [...recordList];
} }
} else { } else {
const response = await get(`${props.apiBaseUrl}/aiService/ask/list/chat/${dialogSessionId}`); const response = await fetch(`${props.apiBaseUrl}/aiService/ask/list/chat/${dialogSessionId}`, {
method: 'GET',
headers: {
'token': props.token,
'x-session-id': props.token,
'x-app-code': props.appCode || ''
}
});
const data = response.data; const data = await response.json();
if (data.code === 0) { if (data.code === 0) {
const recordList = processHistoryData(data.data || []); const recordList = processHistoryData(data.data || []);
messages.value = [...recordList]; messages.value = [...recordList];
...@@ -532,6 +549,7 @@ defineExpose({ ...@@ -532,6 +549,7 @@ defineExpose({
// 生命周期 // 生命周期
onMounted(() => { onMounted(() => {
console.log('组件挂载,初始 dialogSessionId:', props.dialogSessionId); console.log('组件挂载,初始 dialogSessionId:', props.dialogSessionId);
initSSE();
scrollToBottom(); scrollToBottom();
if (props.dialogSessionId) { if (props.dialogSessionId) {
getChatRecord(props.dialogSessionId); getChatRecord(props.dialogSessionId);
......
...@@ -52,19 +52,24 @@ ...@@ -52,19 +52,24 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, onUnmounted, nextTick } from 'vue' import { ref, computed, onUnmounted, nextTick } from 'vue'
import { AudioOutlined } from '@ant-design/icons-vue' import { AudioOutlined } from '@ant-design/icons-vue'
import { post } from '@/utils/axios' // 导入项目中的axios
// 组件属性 // 组件属性
interface Props { interface Props {
disabled?: boolean disabled?: boolean
debug?: boolean debug?: boolean
maxDuration?: number // 添加最大时长参数 maxDuration?: number, // 添加最大时长参数
token?: string,
appCode?: string,
apiBaseUrl?: string,
} }
const props = withDefaults(defineProps<Props>(), { const props = withDefaults(defineProps<Props>(), {
disabled: false, disabled: false,
debug: false, debug: false,
maxDuration: 30 // 默认最大时长为30秒 maxDuration: 30, // 默认最大时长为30秒
token: '',
appCode: '',
apiBaseUrl: '',
}) })
// 组件事件 // 组件事件
...@@ -291,23 +296,27 @@ const stopRecording = async () => { ...@@ -291,23 +296,27 @@ const stopRecording = async () => {
} }
} }
// 上传音频文件到服务器 - 修改为使用axios // 上传音频文件到服务器
const uploadAudioFile = async (audioBlob: Blob): Promise<{filePath: string, durationTime: number}> => { const uploadAudioFile = async (audioBlob: Blob): Promise<{filePath: string, durationTime: number}> => {
try { try {
const formData = new FormData(); const formData = new FormData();
formData.append('file', audioBlob, 'recording.wav'); formData.append('file', audioBlob, 'recording.wav');
formData.append('fileFolder', 'AI_TEMP'); formData.append('fileFolder', 'AI_TEMP');
// 使用项目中的axios post方法调用上传接口 const response = await fetch(`${props.apiBaseUrl}/platformService/upload/v2`, {
const result = await post(`${import.meta.env.VITE_API_BASE_PATH}/platformService/upload/v2`, formData, { method: 'POST',
headers: { headers: {
'Content-Type': 'multipart/form-data', 'x-app-code': props.appCode,
'x-app-code': 'ped.qywx' 'token': props.token,
} 'x-session-id': props.token,
},
body: formData
}); });
// 解析响应体为JSON
const result = await response.json();
if (result.data.code === 0) { if (result.data.code === 0) {
const filePath = result.data.data.filePath; const filePath = result.data.filePath;
// 计算音频时长(秒),四舍五入取整 // 计算音频时长(秒),四舍五入取整
const durationTime = recordingDuration.value; const durationTime = recordingDuration.value;
return {filePath,durationTime}; return {filePath,durationTime};
......
...@@ -627,7 +627,7 @@ li { ...@@ -627,7 +627,7 @@ li {
iframe { iframe {
width: 100%; width: 100%;
height: 100%; height: 100%;
min-height: 1800px; min-height: 800px;
border: none; border: none;
border-radius: 8px; border-radius: 8px;
background-color: @gray-1; background-color: @gray-1;
......
...@@ -128,8 +128,7 @@ export class ContentTemplateService { ...@@ -128,8 +128,7 @@ export class ContentTemplateService {
// 简化的iframe模板 - 移除全屏功能,设置宽高100%固定 // 简化的iframe模板 - 移除全屏功能,设置宽高100%固定
iframe: (iframeData: any) => { iframe: (iframeData: any) => {
const { tips, title, url } = iframeData || {}; const { tips, title, url, height } = iframeData || {};
console.log('iframeData', iframeData);
return `<div class="message-iframe iframe-loading"> return `<div class="message-iframe iframe-loading">
<!-- 加载状态 --> <!-- 加载状态 -->
<div class="iframe-loading"> <div class="iframe-loading">
...@@ -146,7 +145,7 @@ export class ContentTemplateService { ...@@ -146,7 +145,7 @@ export class ContentTemplateService {
<iframe <iframe
src="${url}" src="${url}"
width="100%" width="100%"
height="100%" height="${height}"
frameborder="0" frameborder="0"
sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox" sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"
scrolling="no" scrolling="no"
......
...@@ -44,8 +44,6 @@ export class SSEService { ...@@ -44,8 +44,6 @@ export class SSEService {
public initSSE(dialogSessionId: string): void { public initSSE(dialogSessionId: string): void {
try { try {
const url = `${this.config.apiBaseUrl}/aiService/sse/join/${this.config.params?.stage || ''}?app-id=${this.config.params?.appId || ''}&dialog-session-id=${dialogSessionId || ''}`; const url = `${this.config.apiBaseUrl}/aiService/sse/join/${this.config.params?.stage || ''}?app-id=${this.config.params?.appId || ''}&dialog-session-id=${dialogSessionId || ''}`;
console.log('初始化SSE连接,dialogSessionId:', dialogSessionId);
this.eventSource = new EventSourcePolyfill(url, { this.eventSource = new EventSourcePolyfill(url, {
headers: { headers: {
Token: this.config.token || '', Token: this.config.token || '',
...@@ -55,9 +53,9 @@ export class SSEService { ...@@ -55,9 +53,9 @@ export class SSEService {
withCredentials: true, withCredentials: true,
connectionTimeout: 30000, connectionTimeout: 30000,
}); });
this.eventSource.onopen = (event) => { this.eventSource.onopen = (event) => {
console.log('SSE连接已建立', event); // 移除这里的日志,只在外部处理器中打印
if (this.handlers.onOpen) { if (this.handlers.onOpen) {
this.handlers.onOpen(event); this.handlers.onOpen(event);
} }
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment