创新实训周报2024.6.23

 前后端访问跨域问题

pip install flask_cors

在后端flask代码中使用flask_cors进行跨域来源允许 

from flask import Flask, request, jsonify
import back
import model
from flask_cors import CORS

app = Flask(__name__)
app.json.ensure_ascii = False
CORS(app, resources={r"/*": {"origins": "http://localhost:8080"}})

 

 echarts图显示不出来

对节点去重 

tmp_data = {}
        for item in data:
            if item['id'] in tmp_data.keys():
                continue
            tmp_data[item['id']] = item
        data = []
        for key in tmp_data.keys():
            data.append(tmp_data[key])
        graph_data = {'data': data, 'links': links, 'categories': [{'name': '中心概念'}, {'name': '相邻概念'}, {'name': '有关概念'}]}

 

大模型输出编码格式错误

if response and 'choices' in response and len(response['choices']) > 0:
            content = response['choices'][0]['message']['content']
            content_utf8 = json.dumps(content, ensure_ascii=False)
            print(response)
            return response['choices'][0]['message']
        else:
            raise ValueError("Unexpected response format")

 正确处理返回消息中的换行和制表符

async simulateBotResponse({ commit }, newMessage) {
      const response = await api.post('/query', {"query": newMessage});
      console.log("query response:", response)
      const ShowMessage = `${response.data.backmessage.replace(/\\n/g, '\n').replace(/\t/g, '')}`
      commit('addMessage', { sender: 'bot', text: ShowMessage});
      commit('setProbKnowledge', response.data.ProbKnowledge);
      // this.$router.push({ name: "knowledge", params: { KnowledgeName: response.data.KnowledgeName, ProbKnowledge: response.data.ProbKnowledge, computerNetworkInfo:response.data.computerNetworkInfo, graphData: response.data.graphData, questions: response.data.questions} });
      console.log("get back response data", response.data)
      return response.data;
    },

 

图谱显示没有边

echarts支持使用data和links的name字段进行连边,或者id字段,但注意id字段是字符串而不是整型数字 

需要在前端中使用name去重,并且去掉id字段

tmp_data = {}
        for item in data:
            if item['id'] in tmp_data.keys():
                continue
            tmp_data[item['id']] = item
        data = []
        for key in tmp_data.keys():
            data.append({
                "name": tmp_data[key]["name"],
                "des": tmp_data[key]["des"],
                "symbolSize": tmp_data[key]["symbolSize"],
                "category": tmp_data[key]["category"],
            })
        graph_data = {'data': data, 'links': links, 'categories': [{'name': '中心概念'}, {'name': '相邻概念'}, {'name': '有关概念'}]}
        return graph_data, description, questions, expands[:5], memos

使用name作为关键字进行连边

if node.id not in vertex_ids:
                    data.append({
                        "id": node.id,
                        "name": node["name"],
                        "des": node["name"],
                        "symbolSize": 50,
                        "category": 0,
                    })
                    vertex_ids.add(node.id)

                if first_level.id not in vertex_ids:
                    data.append({
                        "id": first_level.id,
                        "name": first_level["name"],
                        "des": first_level["name"],
                        "symbolSize": 50,
                        "category": 1,
                    })
                    vertex_ids.add(first_level.id)

                if second_level.id not in vertex_ids:
                    data.append({
                        "id": second_level.id,
                        "name": second_level["name"],
                        "des": second_level["name"],
                        "symbolSize": 50,
                        "category": 2,
                    })
                    vertex_ids.add(second_level.id)

                if r1.id not in edge_ids:
                    links.append({
                        "name": r1["type"],
                        "des": r1["type"],
                        "source": r1.start_node["name"],
                        "target": r1.end_node["name"],
                    })
                    edge_ids.add(r1.id)

                if r2.id not in edge_ids:
                    links.append({
                        "name": r2["type"],
                        "des": r2["type"],
                        "source": r2.start_node["name"],
                        "target": r2.end_node["name"],
                    })
                    edge_ids.add(r2.id)

 

加速推理和增强演示效果

使用不同api进行推理

qwen-max

response = dashscope.Generation.call(
            model='qwen-max',
            messages=self.dialog,
            result_format='message', )
        if response.status_code == HTTPStatus.OK:
            print(response)
            return response.output.choices[0]["message"]

        else:
            print('Request id: %s, Status code: %s, error code: %s, error message: %s' % (
                response.request_id, response.status_code,
                response.code, response.message
            ))

回复效果

 

调用效率 

存在前端timeout的风险

ChatGPT3.5

response = openai.ChatCompletion.create(
            model='gpt-3.5-turbo',
            messages=self.dialog,
            max_tokens=1024  # 你可以根据需要调整生成内容的长度
        )
        
        if response and 'choices' in response and len(response['choices']) > 0:
            content = response['choices'][0]['message']['content']
            content_utf8 = json.dumps(content, ensure_ascii=False)
            print(response)
            return {
                'role': 'assistant',
                'content': content_utf8
            }
        else:
            raise ValueError("Unexpected response format")

回复效果

调用效率

较快

 前端请求超时

经过调试发现由于本地部署模型对机器性能要求较高,有时无法在设定时间内返回结果,因此需要将timeout设置增大

import axios from 'axios';

const api = axios.create({
  baseURL: 'http://localhost:5000',
  timeout: 100000,
  headers: {
    'Content-Type': 'application/json',
  },
});
export default api;

前端切换显示实体并刷新页面内容

存在前端点击切换实体,访问后端并得到resoponse但前端页面并未刷新的情况

使用vue的watch,检测数据更改,当从前端获取刷新数据时重新调用数据载入函数

  watch: {
    knowledgeData(newData) {
      console.log("flush")
      this.updateComponentData(newData);
      this.loadTreeData();
    }
  },

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值