Browse Source

链接夺宝奇兵数据

hongxilin
no99 2 months ago
parent
commit
96788c3779
  1. 2
      .env.development
  2. 3
      .env.production
  3. 25
      src/api/sword.js
  4. 213
      src/views/chat.vue

2
.env.development

@ -7,5 +7,7 @@ VITE_PUBLIC_PATH=/
#新数据接口 #新数据接口
VITE_APP_API_BASE_URL="http://39.101.133.168:8828/link" VITE_APP_API_BASE_URL="http://39.101.133.168:8828/link"
#RAGFlow API
VITE_APP_RAGFLOW_API_BASE_URL = http://hsy8b7.natappfree.cc/api/v1/chats
# Whether to open mock # Whether to open mock
VITE_USE_MOCK=true VITE_USE_MOCK=true

3
.env.production

@ -9,7 +9,8 @@ VITE_USE_MOCK = true
#新数据接口 #新数据接口
VITE_APP_API_BASE_URL = https://api.homilychart.com/link VITE_APP_API_BASE_URL = https://api.homilychart.com/link
#RAGFlow API
VITE_APP_RAGFLOW_API_BASE_URL = http://hsy8b7.natappfree.cc/api/v1/chats
# Whether to enable gzip or brotli compression # Whether to enable gzip or brotli compression
# Optional: gzip | brotli | none # Optional: gzip | brotli | none
# If you need multiple forms, you can use `,` to separate # If you need multiple forms, you can use `,` to separate

25
src/api/sword.js

@ -2,6 +2,31 @@ import request from '../utils/request'
// 路径 // 路径
const APIurl = import.meta.env.VITE_APP_API_BASE_URL const APIurl = import.meta.env.VITE_APP_API_BASE_URL
const RAGFlowAPIurl = import.meta.env.VITE_APP_RAGFLOW_API_BASE_URL
// 创建客服新对话接口
export const newSessionAPI = function (params) {
return request({
url: `${APIurl}/api/deepseek/getResponse`,
method: 'post',
data: new URLSearchParams(params),
headers: {
Authorization: 'Bearer ragflow-hkNjEwYjcwZjBlMDExZWZiYjYzMDI0Mm'
}
})
}
// 股票代码对话接口
export const codeAPI = function (params) {
return request({
url: `${RAGFlowAPIurl}/d107d300f38211ef93e60242ac120003/completions`,
method: 'post',
data: new URLSearchParams(params.data),
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ragflow-hkNjEwYjcwZjBlMDExZWZiYjYzMDI0Mm'
},
body: JSON.stringify({ question: content, stream: true, session_id: params.sessionId.value }) // 设置 stream 为 true
})
}
//统计用户行为接口 //统计用户行为接口
export const computedUsersAPI = function (params) { export const computedUsersAPI = function (params) {

213
src/views/chat.vue

@ -1,87 +1,105 @@
<script setup> <script setup>
import { ref, nextTick, watch, onMounted } from 'vue' import { ref, nextTick, watch, onMounted } from 'vue'
import { useUserInfo } from '../store/userPermissionCode' import { useUserInfo } from '../store/userPermissionCode'
import axios from 'axios'
import { ElMessage } from 'element-plus';
import { Loading, Position } from '@element-plus/icons-vue'; //
import { marked } from 'marked'; // marked import { marked } from 'marked'; // marked
import katex from 'katex'; // KaTeX import katex from 'katex'; // KaTeX
import 'katex/dist/katex.min.css'; // KaTeX import 'katex/dist/katex.min.css'; // KaTeX
const { getQueryVariable,getSessionId,fetchUserInfo,loading,isReady } = useUserInfo()
import { newSessionAPI, codeAPI,dataListAPI } from '../api/sword'
const { getQueryVariable, getSessionId, fetchUserInfo, isReady,
brainPermission, // brainPerssion
swordPermission,
pricePermission,
timePermission,
aibullPermission,
aiGnbullPermission,
airadarPermission,
aiGoldMarketList, } = useUserInfo()
//
const errorMsg = ref('') const errorMsg = ref('')
// token
const isTokenValid = ref(false) const isTokenValid = ref(false)
//
const isSessionValid = ref(false)
// token
const fnGetToken = () => { const fnGetToken = () => {
localStorage.setItem('localToken', decodeURIComponent(String(getQueryVariable('token')))) localStorage.setItem('localToken', decodeURIComponent(String(getQueryVariable('token'))))
// console.log(localStorage.getItem('localToken')); // console.log(localStorage.getItem('localToken'));
} }
//
setTimeout(() => { setTimeout(() => {
fnGetToken() fnGetToken()
}, 800) }, 800)
// token // token
const validateToken = async () => { const validateToken = async () => {
const token = localStorage.getItem('localToken') const token = localStorage.getItem('localToken')
// console.log('token', token);
// token
if (!token) { if (!token) {
console.error('未找到 token,请重新登录') console.error('未找到 token,请重新登录')
errorMsg.value = '用户未登录' errorMsg.value = '用户未登录'
return false return false
} }
// token
// token
await fetchUserInfo(); await fetchUserInfo();
console.log('loading', loading.value);
if(!isReady.value){
if (!isReady.value) {
console.log('token校验失败,请重新登录')
errorMsg.value = 'token 验证失败' errorMsg.value = 'token 验证失败'
return false
return false
} }
return true return true
} }
// //
const sessionId = ref(localStorage.getItem('sessionId') || {});
// sessionId
const sessionSessionId = ref(localStorage.getItem('sessionSessionId') || {});
// sessionId
const codeSessionId = ref(localStorage.getItem('codeSessionId') || {});
const add = async () => {
const createNewSessionSession = async () => {
try { try {
const result = await axios.post(
"http://whi3s4.natappfree.cc/api/v1/chats/8b37cd9cf0c811efa4210242ac120003/completions",
{},
{
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ragflow-hkNjEwYjcwZjBlMDExZWZiYjYzMDI0Mm'
}
}
);
const data = result.data;
console.log(data);
console.log(data, 'data11111111');
// data
if (Object.keys(data).length === 0) {
return;
}
// getSessionId
const sss = String(getSessionId("session_id", data));
sessionId.value = sss;
localStorage.setItem('sessionId', sss);
console.log('sss', sss);
// API
const sessionResult = await newSessionAPI({ token: localStorage.getItem('localToken') });
// session_id
const sessionData = sessionResult.data;
console.log(sessionData, 'sessionData');
// getSessionId ,session_id
sessionSessionId.value = String(sessionData.sessionId);
codeSessionId.value = String(sessionData.codeSessionId);
// session_idlocalStorage
localStorage.setItem('sessionSessionId', sessionSessionId.value);
localStorage.setItem('codeSessionId', codeSessionId.value);
// session_id
console.log('session_session_id:', sessionSessionId.value);
console.log('code_session_id:', codeSessionId.value);
} catch (error) { } catch (error) {
console.log("请求失败", error); console.log("请求失败", error);
ElMessage.error("添加失败,请检查输入内容是否正确");
} }
}; };
// token
validateToken().then((isValid) => {
isTokenValid.value = isValid
if (isValid) {
console.log('Token 验证成功')
if (!localStorage.getItem('sessionId')) {
console.log('没有sessionId,创建新对话')
add()
// token
const createNewSession = async () => {
try {
if (isTokenValid.value) {
console.log('Token 验证成功')
if (!localStorage.getItem('sessionSessionId')) {
console.log('没有sessionSessionId,创建新对话')
await createNewSessionSession()
}
if (!localStorage.getItem('codeSessionId')) {
console.log('没有codeSessionId,创建新对话')
}
if (localStorage.getItem('sessionSessionId') && localStorage.getItem('codeSessionId')) {
isSessionValid.value = true
console.log('sessionSessionId和codeSessionId都存在,对话创建成功')
} else {
errorMsg.value = '对话创建失败'
console.log('sessionSessionId或codeSessionId不存在,对话创建失败')
}
} }
} catch (error) {
console.error(error);
} }
})
}
// Props // Props
const props = defineProps({ const props = defineProps({
apiUrl: { apiUrl: {
@ -119,7 +137,7 @@ const sendMessage = async () => {
return; return;
} }
if (isLoading.value) return; if (isLoading.value) return;
const content = inputMessage.value.trim();
let content = inputMessage.value.trim();
if (!content) return; if (!content) return;
// //
messages.value.push({ messages.value.push({
@ -142,16 +160,96 @@ const sendMessage = async () => {
scrollToBottom(); scrollToBottom();
try { try {
// API
const response = await fetch("http://whi3s4.natappfree.cc/api/v1/chats/8b37cd9cf0c811efa4210242ac120003/completions", {
// API
const judgeCode = await fetch("http://192.168.1.162/api/v1/chats/d107d300f38211ef93e60242ac120003/completions", {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ragflow-hkNjEwYjcwZjBlMDExZWZiYjYzMDI0Mm' }, headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ragflow-hkNjEwYjcwZjBlMDExZWZiYjYzMDI0Mm' },
body: JSON.stringify({ question: content, stream: true, session_id: sessionId.value }) // stream true
body: JSON.stringify({ question: content, stream: true, session_id: codeSessionId.value }) // stream true
}); });
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
// API
const judgeCodeData = judgeCode.body.getReader();
const judegeDecoer = new TextDecoder('utf-8');
let judgepartialData = '';
let prevJudgeData = null; //
let lastJudgeData = null; //
while (true) {
const { done, value } = await judgeCodeData.read();
if (done) {
if (judgepartialData) {
const lines = judgepartialData.split('\n');
for (const line of lines) {
if (line.startsWith('data:')) {
prevJudgeData = lastJudgeData; //
lastJudgeData = JSON.parse(line.slice(5));
}
}
}
break;
}
judgepartialData += judegeDecoer.decode(value);
const lines = judgepartialData.split('\n');
judgepartialData = lines.pop();
for (const line of lines) {
if (line.startsWith('data:')) {
try {
prevJudgeData = lastJudgeData; //
lastJudgeData = JSON.parse(line.slice(5));
console.log('倒数第二条:', prevJudgeData);
console.log('最新数据:', lastJudgeData);
} catch (e) {
console.error('JSON解析错误:', e);
}
}
}
}
console.log('最后接收的数据:', prevJudgeData.data.answer); //
const params = ref({});
const codeRegex = /<think>([\s\S]*?)<\/think>([\s\S]*)/;
const codeMatch = prevJudgeData.data.answer.match(codeRegex);
let answer = prevJudgeData.data.answer;
if (codeMatch) {
answer = codeMatch[2].trim();
}
const codes = answer.split(',');
if (codes[0] === 'true') {
params.value.market = codes[1];
params.value.code = codes[2];
params.value.token = localStorage.getItem('localToken');
params.value.brainPrivilegeState = brainPermission; // brainPerssion
params.value.swordPrivilegeState = swordPermission;
params.value.stockForecastPrivilegeState = pricePermission;
params.value.spaceForecastPrivilegeState = timePermission;
params.value.aibullPrivilegeState = aibullPermission;
params.value.aigoldBullPrivilegeState = aiGnbullPermission;
params.value.airadarPrivilegeState = airadarPermission;
params.value.marketList = aiGoldMarketList;
// API
const dataList=await dataListAPI(params.value);
const dataListData = JSON.stringify(dataList.data);
console.log(dataListData,'dataListData');
content=content+'请结合下方夺宝奇兵的数据,成体系,有表格的回答'+dataListData;
} }
// API
const response = await fetch("http://192.168.1.162/api/v1/chats/8b37cd9cf0c811efa4210242ac120003/completions", {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ragflow-hkNjEwYjcwZjBlMDExZWZiYjYzMDI0Mm' },
body: JSON.stringify({ question: content, stream: true, session_id: sessionSessionId.value }) // stream true
});
// //
messages.value = messages.value.filter(msg => !msg.isLoading); messages.value = messages.value.filter(msg => !msg.isLoading);
@ -257,8 +355,11 @@ onMounted(async () => {
// token // token
fnGetToken() fnGetToken()
// token // token
const isValid = await validateToken()
isTokenValid.value = isValid
isTokenValid.value = await validateToken()
// codeSessionId
localStorage.setItem('codeSessionId', codeSessionId.value);
await createNewSession()
}) })
</script> </script>
<template> <template>
@ -310,8 +411,8 @@ onMounted(async () => {
</el-tooltip> </el-tooltip>
</div> </div>
<!-- 未登录覆盖层 --> <!-- 未登录覆盖层 -->
<div v-if="!isTokenValid" class="overlay">
<div class="overlay-content">{{errorMsg}}</div>
<div v-if="!isTokenValid || !isSessionValid" class="overlay">
<div class="overlay-content">{{ errorMsg }}</div>
</div> </div>
</div> </div>
</template> </template>

Loading…
Cancel
Save