对接讯飞聊天机器人接口--复盘

news2024/10/5 16:00:31

1、准备工作

        1)、进入以下平台进行注册,登录后,点击红框处

        2)、点击个人免费包(会弹出实名认证,先进行实名认证)

     3)、认证后,会进入以下界面,先添加应用

     4)、添加应用

    5)、选择套餐,提交订单

   6)、返回主页,点击控制台,找到自己的应用,点击进入应用

   7)、进入应用后找到自己的APPID、APISecret、APIKey。


2、先看效果 

3、前端完整代码

★★★注意★★★:个人只是写了前端代码,聊天记录刷新后就没有了。

<template>
  <a-layout style="max-width: 800px; margin: auto">
    <a-layout-content
      :style="{
        border: '3px solid #4fc3f7',
        borderRadius: '8px',
        boxShadow: '0 8px 16px rgba(0, 0, 0, 0.3)',
        overflow: 'hidden',
      }"
    >
      <h2 style="margin-bottom: 20px; text-align: center; color: #4fc3f7">
        Chat Record
      </h2>
      <div class="divider"></div>
      <div class="chat-messages" ref="chatMessages">
        <!-- 聊天记录显示区域Q -->
        <div v-if="dialogueHistory.length === 0" class="no-data-message">
          暂无数据
        </div>
        <div
          v-for="message in dialogueHistory"
          :key="message.id"
          class="message-container"
        >
          <!-- 修改部分 -->
          <div
            :class="[
              message.type === 'question'
                ? 'user-name-aline'
                : 'robot-name-aline',
            ]"
          >
            <div>{{ message.name }}:</div>
          </div>
          <div class="divider"></div>
          <div
            :class="[
              message.type === 'question' ? 'user-message' : 'bot-message',
              message.isCode ? 'code-message' : '',
            ]"
            style="position: relative"
          >
            <template v-if="message.isCode">
              <!-- 使用 extractCodeAndLanguage 函数 -->
              <pre
                v-html="
                  highlightCode(extractCodeAndLanguage(message.text).code)
                "
                style="
                  background-color: #f0f0f0;
                  padding: 15px;
                  box-shadow: #999999;
                  border-radius: 5px;
                  margin: 0;
                "
              ></pre>
            </template>
            <template v-else>
              {{ message.text }}
            </template>
            <!-- 添加复制按钮 -->
            <button
              v-if="message.isCode"
              @click="copyCode(message.text)"
              class="copy-button"
              style="
                position: absolute;
                top: 7px;
                right: 7px;
                cursor: pointer;
                border: none;
                background: transparent;
                color: #3498db;
              "
            >
              Copy
            </button>
          </div>
          <!-- 结束修改部分 -->
        </div>
      </div>
      <div class="user-input-container">
        <!-- 用户输入框 -->
        <a-input
          v-model="inputVal"
          @pressEnter="sendMsg"
          placeholder="请输入消息..."
          style="
            flex-grow: 1;
            padding: 8px;
            border: 1px solid #3498db;
            border-radius: 5px;
            margin-right: 10px;
          "
        />
        <!-- 发送按钮 -->
        <a-button type="primary" @click="sendMsg" style="cursor: pointer">
          发送
        </a-button>
      </div>
    </a-layout-content>
  </a-layout>
</template>
<script setup>
import { ref } from "vue";
import * as base64 from "base-64";
import CryptoJs from "crypto-js";
import hljs from "highlight.js/lib/core";
import "highlight.js/styles/default.css"; // 选择适合你项目的样式

// 导入你需要的语言支持
import javascript from "highlight.js/lib/languages/javascript";
import css from "highlight.js/lib/languages/css";
import html from "highlight.js/lib/languages/xml";
import ClipboardJS from "clipboard";

// 注册语言支持
hljs.registerLanguage("javascript", javascript);
hljs.registerLanguage("css", css);
hljs.registerLanguage("html", html);
const requestObj = {
  APPID: "填你自己的",
  APISecret: "填你自己的",
  APIKey: "填你自己的",
  Uid: "0",
  sparkResult: "",
};

const inputVal = ref("");
const result = ref("");
const dialogueHistory = ref([]);

const isCopyButtonClicked = ref(false);

// 检测回复是否为代码
const isCode = (text) => {
  // 简单的检测逻辑,您可以根据需要进行调整
  return text.startsWith("```") && text.endsWith("```");
};

// 获取鉴权 URL
const getWebsocketUrl = async () => {
  return new Promise((resolve, reject) => {
    const url = "wss://spark-api.xf-yun.com/v3.1/chat";
    const host = "spark-api.xf-yun.com";
    const apiKeyName = "api_key";
    const date = new Date().toGMTString();
    const algorithm = "hmac-sha256";
    const headers = "host date request-line";
    const signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v3.1/chat HTTP/1.1`;
    const signatureSha = CryptoJs.HmacSHA256(
      signatureOrigin,
      requestObj.APISecret
    );
    const signature = CryptoJs.enc.Base64.stringify(signatureSha);

    const authorizationOrigin = `${apiKeyName}="${requestObj.APIKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;

    const authorization = base64.encode(authorizationOrigin);

    // 将空格编码
    resolve(
      `${url}?authorization=${authorization}&date=${encodeURI(
        date
      )}&host=${host}`
    );
  });
};

// 发送消息
const sendMsg = async () => {
  const myUrl = await getWebsocketUrl();
  const socket = new WebSocket(myUrl);

  socket.onopen = (event) => {
    // 发送消息的逻辑
    // 发送消息
    const params = {
      header: {
        app_id: requestObj.APPID,
        uid: "redrun",
      },
      parameter: {
        chat: {
          domain: "generalv3",
          temperature: 0.5,
          max_tokens: 1024,
        },
      },
      payload: {
        message: {
          text: [{ role: "user", content: inputVal.value }],
        },
      },
    };
    dialogueHistory.value.push({
      type: "question",
      name: "我",
      text: inputVal.value,
      // timestamp: getTimestamp(),
    });
    socket.send(JSON.stringify(params));
  };

  socket.onmessage = (event) => {
    const data = JSON.parse(event.data);

    if (data.header.code !== 0) {
      console.error("Error:", data.header.code, data.header.message);
      socket.close();
      return;
    }

    // 累积所有接收到的消息
    if (data.payload.choices.text) {
      // 连接新接收到的消息片段
      const newMessage = data.payload.choices.text[0].content;

      if (
        dialogueHistory.value.length > 0 &&
        dialogueHistory.value[dialogueHistory.value.length - 1].type ===
          "answer"
      ) {
        // 连接新接收到的消息片段到最后一个回答
        dialogueHistory.value[dialogueHistory.value.length - 1].text +=
          newMessage;
      } else {
        // 添加新的回答
        dialogueHistory.value.push({
          type: "answer",
          name: "智能助手",
          text: newMessage,
          // timestamp: getTimestamp(),
        });
      }
      // 如果回复是代码,添加相应的标记和样式
      if (isCode(newMessage)) {
        dialogueHistory.value[dialogueHistory.value.length - 1].isCode = true;
      }
    }
    // 如果对话完成或者发生错误,则关闭 socket
    if (data.header.status === 2 || data.header.code !== 0) {
      setTimeout(() => {
        socket.close();
      }, 1000);
    }
  };

  socket.onclose = (event) => {
    inputVal.value = "";
  };

  socket.onerror = (event) => {
    console.error("WebSocket error:", event);
  };
};
// 移除代码块的标记和语言标识符
const extractCodeAndLanguage = (text) => {
  if (isCode(text)) {
    const lines = text.split("\n");
    const language = lines[0].substring(3).trim();
    const code = lines.slice(1, -1).join("\n");
    return { language, code };
  }
  return { language: null, code: text };
};
// 高亮代码的方法
const highlightCode = (code) => {
  // 判断是否包含代码标识符
  if (code.startsWith("```") && code.endsWith("```")) {
    // 去掉头尾的```标识符
    code = code.slice(3, -3);
  }
  const highlighted = hljs.highlightAuto(code);
  return highlighted.value;
};
//
// // 获取当前时间戳
// const getTimestamp = () => {
//   return Math.floor(new Date().getTime() / 1000);
// };
//
// // 格式化时间戳为可读的时间格式
// const formatTimestamp = (timestamp) => {
//   const date = new Date(timestamp * 1000);
//   const hours = date.getHours();
//   const minutes = "0" + date.getMinutes();
//   return `${hours}:${minutes.substr(-2)}`;
// };
const copyCode = (code) => {
  // 使用 clipboard.js 复制文本到剪贴板
  const parentButton = document.querySelector(".message-container button");

  // 获取处理后的代码,如果是代码块,提取其中的代码
  const processedCode =
    code.startsWith("```") && code.endsWith("```")
      ? extractCodeAndLanguage(code).code
      : code;
  // 获取按钮元素
  const copyButton = document.querySelector(".copy-button");

  // 按钮初始文本
  const initialButtonText = copyButton.innerText;

  // 修改按钮文本为勾
  copyButton.innerText = "✔ Copied";

  // 3秒后将按钮文本还原
  setTimeout(() => {
    copyButton.innerText = initialButtonText;
  }, 3000);

  if (parentButton && parentButton.parentNode) {
    const clipboard = new ClipboardJS(parentButton, {
      text: function () {
        return processedCode;
      },
    });

    clipboard.on("success", function (e) {
      console.log("Text copied to clipboard:", e.text);
      clipboard.destroy(); // 销毁 clipboard 实例,防止重复绑定
    });

    clipboard.on("error", function (e) {
      console.error("Unable to copy text to clipboard:", e.action);
      clipboard.destroy(); // 销毁 clipboard 实例,防止重复绑定
    });
  } else {
    console.error("Parent button or its parent node is null or undefined.");
  }
};
</script>

<style scoped>
#ChatRobotView {
  max-width: 800px;
  margin: auto;
}

.chat-container {
  border: 1px solid #ccc;
  border-radius: 8px;
  overflow: hidden;
}

.chat-messages {
  padding: 10px;
  max-height: 400px;
  overflow-y: auto;
}

.message {
  margin-bottom: 10px;
}

.user-message {
  background-color: #3498db;
  color: #ffffff;
  padding: 10px;
  border-radius: 5px;
  align-self: flex-end;
}

.bot-message {
  background-color: #e0e0e0;
  color: #000000;
  padding: 10px;
  border-radius: 5px;
  align-self: flex-start;
}

.user-input-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-top: 1px solid #ddd;
}

.user-input-container input {
  flex-grow: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 5px;
  margin-right: 10px;
}

.user-input-container button {
  background-color: #4caf50;
  color: #fff;
  border: none;
  padding: 8px 16px;
  border-radius: 5px;
  cursor: pointer;
}

.message-container {
  display: flex;
  flex-direction: column;
  margin-bottom: 10px;
}

.message-info {
  font-size: 12px;
  color: #888;
  margin-bottom: 5px;
}

.user-name-aline {
  align-self: flex-end;
  margin-bottom: 5px;
}

.robot-name-aline {
  align-self: flex-start;
  margin-bottom: 5px;
}

.no-data-message {
  font-size: large;
  color: #8c8c8c;
  height: 200px;

  display: flex;
  align-items: center;
  justify-content: center;
}

.message-container button.copy-button:active {
  background-color: #4caf50; /* 按下时的背景色 */
  color: #fff;
}

.divider {
  width: 100%;
  height: 1px;
  background-color: #4fc3f7;
  margin: 5px 0;
}
</style>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1366721.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

特征工程(一)

特征工程&#xff08;一&#xff09; 什么是特征工程 简单来讲将数据转换为能更好地表示潜在问题的特征&#xff0c;从而提高机器学习性能 特征工程包含的内容 转换数据的过程特征更好地表示潜在问题提高机器学习性能 数据和机器学习的基础知识 数据基础 以下为数据的一…

三剑客前端教程

前端教程 结构层&#xff08;html&#xff09;表现层&#xff08;css&#xff09;行为层&#xff08;javascript&#xff09; HTML 超文本标记语言&#xff09; HTML&#xff08;超文本标记语言——HyperText Markup Language&#xff09;是构成 Web 世界的一砖一瓦。它定义…

ssm基于HTML5的交流论坛的设计与实现+vue论文

摘 要 信息数据从传统到当代&#xff0c;是一直在变革当中&#xff0c;突如其来的互联网让传统的信息管理看到了革命性的曙光&#xff0c;因为传统信息管理从时效性&#xff0c;还是安全性&#xff0c;还是可操作性等各个方面来讲&#xff0c;遇到了互联网时代才发现能补上自古…

ME11/ME12拷贝采购信息记录

注意点&#xff1a; ECC没有好用的修改/创建采购信息记录BAPI所以使用BDC处理&#xff0c; 因为BDC执行过程如果遇到黄色提示消息就会暂停&#xff0c;所以如果遇到黄色提示需要增强处理 还有就是价格的小数位数问题&#xff0c;如JPY不能使用小数位数问题处理 增强调整 如下…

软件测试|Linux基础教程:cp命令详解,复制文件或目录

简介 在Linux系统中&#xff0c;cp命令是一个非常常用且强大的命令&#xff0c;用于复制文件和目录。cp命令允许我们在不同目录之间复制文件或目录&#xff0c;并可以根据需求对文件复制的行为进行调整。在本文中&#xff0c;我们将详细解释cp命令的用法以及一些常见的选项。 …

spark的任务提交方式及流程

本地模式 local 测试用,不多赘述 分布式模式 standalone standalone集群是spark 自带的一个资源调度集群&#xff0c;分为两个角色&#xff0c;master/worker&#xff0c;master负责接收任务请求、资源调度&#xff08;监听端口7077&#xff09;&#xff0c;worker负责运行exec…

深入了解鸿鹄工程项目管理系统源码:功能清单与项目模块的深度解析

工程项目管理软件是现代项目管理中不可或缺的工具&#xff0c;它能够帮助项目团队更高效地组织和协调工作。本文将介绍一款功能强大的工程项目管理软件&#xff0c;该软件采用先进的Vue、Uniapp、Layui等技术框架&#xff0c;涵盖了项目策划决策、规划设计、施工建设到竣工交付…

Java如何拷贝数据?

Java如何拷贝数据&#xff1f; 在 Java 中&#xff0c;数组和集合的深拷贝与浅拷贝的概念与复制对象的引用和内容相关。深拷贝是创建一个新对象&#xff0c;并递归地复制其所有内容&#xff0c;而浅拷贝则只是复制对象的引用。 数组的深拷贝与浅拷贝&#xff1a; 1. 深拷贝数…

金和OA C6 HomeService.asmx SQL注入漏洞复现

0x01 产品简介 金和网络是专业信息化服务商,为城市监管部门提供了互联网+监管解决方案,为企事业单位提供组织协同OA系统开发平台,电子政务一体化平台,智慧电商平台等服务。 0x02 漏洞概述 金和OA C6 HomeService.asmx接口处存在SQL注入漏洞,攻击者除了可以利用 SQL 注入漏洞…

量子革命的基础:激光冷却史(下)

本文是《激光冷却史》系列的最后一部分。 在20世纪的最后20年里&#xff0c;原子物理学家屡次打破宇宙中最冷温度的记录。这些成就有赖于一些进步&#xff0c;包括激光冷却&#xff08;《激光冷却史&#xff08;上&#xff09;》&#xff09;、磁光阱和西西弗斯冷却等技术&…

DES算法(Python实现)

一、具体描述 基于计算机高级语言&#xff08;如C语言&#xff09;实现DES算法 二、名词术语与相关知识 DES算法 DES&#xff08;Data Encryption Standard&#xff09;是一种对称加密算法&#xff0c;被广泛应用于数据加密领域。它使用64位密钥和64位明文&#xff0c;通过…

西门子WinCC的C脚本——对象的事件任务

1、 全局脚本编辑器&#xff1b; 2、 对象的属性任务&#xff1b; 3、 对象的事件任务。 本文探讨一下用C脚本来实现对象的事件任务。 一、例程说明引文&#xff1a;博途工控人平时在哪里技术交流博途工控人社群 如图1所示&#xff0c;为本例程的运行画面。本例程实现以下…

大数据 Hive - 实现SQL执行

文章目录 MapReduce实现SQL的原理Hive的架构Hive如何实现join操作小结 MapReduce的出现大大简化了大数据编程的难度&#xff0c;使得大数据计算不再是高不可攀的技术圣殿&#xff0c;普通工程师也能使用MapReduce开发大数据程序。 但是对于经常需要进行大数据计算的人&#xff…

没经验没资金,适合穷人创业项目的低成本生意

什么人可以赚到钱呢&#xff1f;不管你怎么都赚不到&#xff0c;那归根结底是因为你身边没有明白人。像我们普通人一没经验二没资金三没人脉&#xff0c;该如何创业呢&#xff1f; 第一点&#xff0c;如果你不知道干什么&#xff0c;就做黄牛&#xff0c;只当渠道&#xff0c;只…

Web前端篇——ElementUI之el-scrollbar + el-backtop + el-timeline实现时间轴触底刷新和一键返回页面顶部

ElementUI之el-scrollbar el-backtop el-timeline实现时间轴触底刷新和一键返回页面顶部。 背景&#xff1a;ElementUI的版本&#xff08;vue.global.js 3.2.36&#xff0c; index.css 2.4.4&#xff0c; index.full.js 2.4.4&#xff09; 废话不多说&#xff0c;先看动…

猫头虎分享已解决Bug || Error: ImagePullBackOff (K8s)

博主猫头虎的技术世界 &#x1f31f; 欢迎来到猫头虎的博客 — 探索技术的无限可能&#xff01; 专栏链接&#xff1a; &#x1f517; 精选专栏&#xff1a; 《面试题大全》 — 面试准备的宝典&#xff01;《IDEA开发秘籍》 — 提升你的IDEA技能&#xff01;《100天精通Golang》…

(二)Explain使用与详解

explain中的列 sql语句: EXPLAIN SELECT * from user WHERE userId=1340; 执行结果: 1. id列 id列的编号是 select 的序列号,有几个 select 就有几个id,并且id的顺序是按 select 出现的顺序增长的。 id列越大执行优先级越高,id相同则从上往下执行,id为NULL最后执行…

python股票分析挖掘预测技术指标知识之蜡烛图指标(6)

本人股市多年的老韭菜&#xff0c;各种股票分析书籍&#xff0c;技术指标书籍阅历无数&#xff0c;萌发想法&#xff0c;何不自己开发个股票预测分析软件&#xff0c;选择python因为够强大&#xff0c;它提供了很多高效便捷的数据分析工具包。 我们已经初步的接触与学习其中数…

7.27 SpringBoot项目实战 之 整合Swagger

文章目录 前言一、Maven依赖二、编写Swagger配置类三、编写接口配置3.1 控制器Controller 配置描述3.2 接口API 配置描述3.3 参数配置描述3.4 忽略API四、全局参数配置五、启用增强功能六、调试前言 在我们实现了那么多API以后,进入前后端联调阶段,需要给前端同学提供接口文…

软件测试|Python中的变量与关键字详解

简介 在Python编程中&#xff0c;变量和关键字是非常重要的概念。它们是构建和控制程序的基本要素。本文将深入介绍Python中的变量和关键字&#xff0c;包括它们的定义、使用方法以及一些常见注意事项。 变量 变量的定义 变量是用于存储数据值的名称。在Python中&#xff0…