vue编写本地ollama支持插件工具调用、多智能体、语音通话功能的ai聊天助手代码

代码语言:html

所属分类:其他

代码描述:vue编写本地ollama支持插件工具调用、多智能体、语音通话功能的ai聊天助手代码,支持代码高亮和流式输出打字动画、支持代码复制、支持语音朗读、支持语音识别、支持语音唤醒通话、支持选择本地模型和参数设置,支持工具插件本地调用,支持pdf、word、excel、ppt等文件拖拽加入问答对话。

代码标签: vue 编写 本地 ollama 支持 插件 工具 调用 智能体 语音 通话 功能 ai 聊天 助手

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">

    <link type="text/css" rel="stylesheet"
        href="//repo.bfw.wiki/bfwrepo/css/font-awesome-4.7.0/css/font-awesome.css">
    <script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/chinese_lunar_calendar.min.js"></script>
    <script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/highlight.js"></script>
    <link type="text/css" rel="stylesheet" href="//repo.bfw.wiki/bfwrepo/css/highlight.9.9.css">
    <script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/marked.umd.min.js"></script>
    <script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/localforage.min.js"></script>
    <script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/vue@2.6.1-dev.js"></script>
    <script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/xlsx.full.min.js"></script>
    <script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/pdf.2.2.js"></script>
    <script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/mammoth.browser.js"></script>
    <script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/jszip.js"></script>
    <script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/pptxgen.bundle.js"></script>

    <style>
        body {
            padding: 0;
            margin: 0;
            transition: background-color 0.3s ease;

        }

        .filebox img {
            height: 60px;
            width: auto;
        }

        .filebox p {
            margin: 0 !important;
            padding: 0 !important;
        }

        .filebox .fname {
            font-size: 12px;
            color: grey;
        }

        .cont {

            display: flex;
            flex-direction: column;
            height: 100vh;
            overflow: hidden;
        }

        .historylist {

            flex: 1;
            overflow-y: scroll;

        }

        .historylist img {
            max-width: 100px;
        }

        .mesay,
        .aisay {
            padding: 10px;
            margin: 10px;
            border-radius: 5px;
            line-height: 30px;
        }

        .mesay {
            background-color: #d0e7ff;
            text-align: right;
        }

        .aisay {
            background-color: aliceblue;
            text-align: left;
        }

        .inputpannel {
            display: flex;
            margin: 10px;
            background: white;
            align-items: flex-end;
            border: 2px solid grey;
            border-radius: 14px;
        }

        .footer {
            position: relative;

        }

        .inputpannel:focus-within {
            border-color: blue;
        }

        .inputtext {
            margin-top: 4px;

            width: 100%;
            background: white;
            line-height: 20px;
            box-sizing: border-box;
            padding: 8px;
            font-family: inherit;
            font-size: 16px;
            resize: none;
            overflow: hidden;
            border: none;
            outline: none;
            height: 40px;

            min-height: 40px;
            overflow-y: auto;
            max-height: calc(24px * 5);

        }

        .inputtext:focus {
            border: none;
            outline: none;
        }


        textarea::placeholder {}


        .historylist pre {
            white-space: pre-wrap;
            color: #ececec;
            background: black;
            border-radius: 4px;
            padding: 10px;
            margin: 0;

        }

        .historylist p {
            margin: 0;
            padding: 2px;
        }

        .typing-text {
            font-size: 24px;
            white-space: pre-wrap;
            border-right: 2px solid black;
            animation: blink 0.7s steps(2, start) infinite;
        }

        @keyframes blink {
            to {
                border-color: transparent;
            }
        }

        .code-header {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            width: 100%;
            color: #cdcdcd;
            height: 24px;
            background: #6767;


        }

        .language-label {
            position: absolute;
            top: -4px;
            left: 0;
            padding: 0 10px;

            font-size: 0.8em;

        }

        .copy-button {
            position: absolute;
            top: 0;
            right: 0px;
            padding: 0.3em 0.6em;


            border: none;
            border-radius: 3px;
            cursor: pointer;
            font-size: 0.8em;
        }

        .code-content {
            line-height: 20px;
            display: block;
            text-wrap: nowrap;
            margin-top: -40px;
            margin-bottom: -63px;
            overflow-x: scroll;
        }

        .historylist pre {
            position: relative;
            background: black;
            color: white;
            border-radius: 6px;
            padding: 1em;
            margin: 1em 0;
        }

        .file-upload {
            position: relative;
            width: 30px;
            height: 30px;
            margin: 6px -1px 3px 10px;

            overflow: hidden;



        }

        .sendbtn {
            margin: 13px;
        }

        .file-upload input[type=file] {
            position: absolute;
            top: 0;
            left: 0;


            opacity: 0;
            cursor: pointer;
        }



        ol {
            list-style: none;
            padding: 0;
            margin: 10px;
        }

        i {
            cursor: pointer;

        }

        .recomminput li {
            background: aliceblue;
            border: 1px solid aliceblue;
            margin: 2px 0 4px 0;
            padding: 5px;

            width: 64%;
            font-size: 12px;
            cursor: pointer;
            border-radius: 5px;
        }

        .copybtn,
        .regenbtn {
            cursor: pointer;
            margin-right: 20px;
        }

        .scrollbar {
            position: absolute;
            top: -20px;
            width: 100%;
            right: 0;
            left: 0;
        }

        .scrollbar i {
            width: 30px;
            height: 30px;
            border-radius: 15px;
            background: white;
            line-height: 30px;
        }

        .attachpannel {
            position: absolute;

            border-radius: 20px;
            display: flex;

            width: 100%;
            height: 100px;

            left: 0;
            top: -80px;
        }

        /* 隐藏默认滚动条 */
        textarea::-webkit-scrollbar {
            display: none;
        }

        /* 添加自定义滚动条 */
        textarea {
            scrollbar-width: thin;
            /* 调整滚动条宽度 */
            scrollbar-color: #ccc transparent;
            /* 调整滚动条颜色 */
            overflow-y: auto;
            /* 确保溢出时出现滚动条 */
        }

        /* Firefox 上的滚动条样式 */
        textarea {
            scrollbar-width: thin;
        }

        /* WebKit 上的滚动条样式 */
        textarea::-webkit-scrollbar {
            width: 8px;
            /* 调整滚动条宽度 */
        }

        textarea::-webkit-scrollbar-track {
            background-color: transparent;
            /* 滚动条背景颜色 */
        }

        textarea::-webkit-scrollbar-thumb {
            background-color: #ccc;
            /* 滚动条颜色 */
            border-radius: 4px;
            /* 滚动条圆角 */
        }

        textarea::-webkit-scrollbar-thumb:hover {

            background-color: #999;
            /* 鼠标悬停时的滚动条颜色 */
        }


        /* 隐藏默认滚动条 */
        .historylist::-webkit-scrollbar {
            display: none;
        }

        /* 添加自定义滚动条 */
        .historylist {
            scrollbar-width: thin;
            /* 调整滚动条宽度 */
            scrollbar-color: #ccc transparent;
            /* 调整滚动条颜色 */
            overflow-y: auto;
            /* 确保溢出时出现滚动条 */
        }

        /* Firefox 上的滚动条样式 */
        .historylist {
            scrollbar-width: thin;
        }

        /* WebKit 上的滚动条样式 */
        .historylist::-webkit-scrollbar {
            width: 8px;
            /* 调整滚动条宽度 */
        }

        .historylist::-webkit-scrollbar-track {
            background-color: transparent;
            /* 滚动条背景颜色 */
        }

        .historylist::-webkit-scrollbar-thumb {
            background-color: #ccc;
            /* 滚动条颜色 */
            border-radius: 4px;
            /* 滚动条圆角 */
        }

        .historylist::-webkit-scrollbar-thumb:hover {

            background-color: #999;
            /* 鼠标悬停时的滚动条颜色 */
        }

        /* 隐藏默认滚动条 */
        .code-content::-webkit-scrollbar {
            display: none;
        }

        /* 添加自定义滚动条 */
        .code-content {
            scrollbar-width: thin;
            /* 调整滚动条宽度 */
            scrollbar-color: #ccc transparent;
            /* 调整滚动条颜色 */
            overflow-y: auto;
            /* 确保溢出时出现滚动条 */
        }

        /* Firefox 上的滚动条样式 */
        .code-content {
            scrollbar-width: thin;
        }

        /* WebKit 上的滚动条样式 */
        .code-content::-webkit-scrollbar {
            width: 8px;
            /* 调整滚动条宽度 */
        }

        .code-content::-webkit-scrollbar-track {
            background-color: transparent;
            /* 滚动条背景颜色 */
        }

        .code-content::-webkit-scrollbar-thumb {
            background-color: #ccc;
            /* 滚动条颜色 */
            border-radius: 4px;
            /* 滚动条圆角 */
        }

        .code-content::-webkit-scrollbar-thumb:hover {

            background-color: #999;
            /* 鼠标悬停时的滚动条颜色 */
        }

        #overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.8);
            z-index: 9999;
            justify-content: center;
            align-items: center;
        }

        #overlay img {
            max-width: 100%;
            max-height: 100%;
        }

        #closeBtn {
            position: absolute;
            top: 10px;
            right: 10px;

            color: white;
            border: none;
            padding: 10px;
            cursor: pointer;
            font-size: 16px;
        }

        .feedbackpanel {
            font-size: 12px;
        }

        #chatlist {

            width: 200px;
            padding: 10px;
            height: 90vh;
            overflow-y: scroll;
            background: aliceblue;

        }

        #setting {

            width: 300px;
            height: 90vh;
            background: white;
            padding: 4px;
            overflow-y: scroll;

        }

        .bodycont {
            display: flex;
            flex-direction: row;
        }

        #bodychat {
            flex: 1;
        }

        #voicechat {
            flex: 1;
            text-align: center;
            vertical-align: middle;
            margin-top: 100px;

        }

        .del {
            display: none;
            margin-top: 5px;

            margin-right: 7px;

        }

        .agentname {
            font-weight: bold;
            font-size: 14px;
            margin-right: 4px;

        }

        .hischatitem .messagetext {

            width: 84px;
            flex: 1;
        }

        .hischatitem {
            overflow: hidden;
            margin: 5px;
            display: flex;
            border-radius: 5px;
            cursor: pointer;
            height: 26px;
            font-size: 12px;

            display: flex;
            padding: 2px 4px;
            line-height: 26px;
            color: grey;
        }


        .hischatitem:hover .del {
            display: block;


        }

        .nowchatitem {
            background: #d0e7ff;
        }

        .hischatitem:hover {
            background: #d0e7ff;
        }

        /* Range styling */
        input[type="range"] {
            -webkit-appearance: none;
            /* 移除默认样式 */
            width: 100%;
            height: 10px;
            background: #ddd;
            outline: none;
            opacity: 0.7;
            transition: opacity .2s;
        }

        input[type="range"]:hover {
            opacity: 1;
        }

        input[type="range"]::-webkit-slider-runnable-track {
            width: 100%;
            height: 20px;
            background: #ddd;
            border-radius: 5px;
        }

        input[type="range"]::-webkit-slider-thumb {
            -webkit-appearance: none;
            appearance: none;
            width: 20px;
            height: 20px;
            background: blue;
            /* 设置滑块颜色为蓝色 */
            cursor: pointer;
            border-radius: 50%;
        }

        input[type="range"]::-moz-range-track {
            width: 100%;
            height: 10px;
            background: #ddd;
            border-radius: 5px;
        }

        input[type="range"]::-moz-range-thumb {
            width: 20px;
            height: 20px;
            background: blue;
            /* 设置滑块颜色为蓝色 */
            cursor: pointer;
            border-radius: 50%;
        }

        input[type="range"]::-ms-track {
            width: 100%;
            height: 10px;
            background: #ddd;
            border-radius: 5px;
        }

        input[type="range"]::-ms-thumb {
            width: 20px;
            height: 20px;
            background: blue;
            /* 设置滑块颜色为蓝色 */
            cursor: pointer;
            border-radius: 50%;
        }

        /* Select styling */
        select {
            width: 100%;
            padding: 10px;
            border: 2px solid blue;
            /* 设置边框颜色为蓝色 */
            border-radius: 5px;
            background-color: white;
            color: black;
            font-size: 16px;
            appearance: none;
            /* 移除默认箭头 */
            -webkit-appearance: none;
            -moz-appearance: none;
        }

        /* 基本表格样式 */
        table {
            width: 100%;
            border-collapse: collapse;
            font-family: Arial, sans-serif;
            margin: 20px 0;
        }

        /* 表头样式 */
        thead {
            background-color: #007BFF;
            color: white;
        }

        th,
        td {
            padding: 12px 15px;
            text-align: left;
        }

        /* 表格行样式 */
        tbody tr {
            border-bottom: 1px solid #ddd;
        }

        tbody tr:nth-of-type(even) {
            background-color: #f3f3f3;
        }

        tbody tr:last-of-type {
            border-bottom: 2px solid #007BFF;
        }

        /* 悬停效果 */
        tbody tr:hover {
            background-color: #e0e0e0;
            cursor: pointer;
        }

        select:hover {
            border-color: darkblue;
        }

        select:focus {
            outline: none;
            border-color: darkblue;
        }

        /* Custom arrow */
        .select-wrapper {
            position: relative;
            display: inline-block;
            width: 100%;
        }

        .select-wrapper::after {
            content: '▼';
            position: absolute;
            top: 67%;
            right: 10px;
            transform: translateY(-50%);
            pointer-events: none;
            color: blue;
            /* 设置箭头颜色为蓝色 */
        }


        .promptinput {
            width: 280px;
            min-height: 150px;
            border: 2px solid grey;
            /* 设置边框颜色为蓝色 */
            border-radius: 5px;
            background-color: white;
            color: black;
            font-size: 16px;
            resize: vertical;
            /* 允许垂直调整大小 */
        }

        .promptinput:hover {
            border-color: blue;
        }

        .promptinput:focus {
            outline: none;
            border-color: blue;
        }

        .textinput {
            padding: 8px 6px;
            border-radius: 5px;
            width: 270px;
            background-color: white;
            color: black;
            font-size: 16px;
            border: 2px solid grey;
        }

        .textinput:hover {
            border-color: blue;
        }

        .textinput:focus {
            outline: none;
            border-color: blue;
        }

        .recomlist {
            display: flex;

            margin: 20vh;
        }

        .recomlist .item {
            cursor: pointer;
            flex: 1;
            border: 1px solid #d0e7ff;
            border-radius: 6px;
            padding: 10px;
            text-align: center;
            line-height: 30px;
            margin: 20px;
        }

        .recomlist>.item:hover {
            background: #d0e7ff;
        }

        #micinput {
            position: absolute;

            top: -360px;
            left: calc(50% - 100px);
            background: aliceblue;
            border-radius: 6px;
            border: 2px solid blue;
            padding: 10px;
            text-align: center;
            cursor: pointer;
            width: 200px;

        }

        .hangoverbtn {
            margin-top: 14px;
            border-radius: 10px;
            background: red;
            color: white;
            border: none;
            padding: 10px 40px;
            text-align: center;
        }

        .tooldia {

            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: aliceblue;
            border-radius: 6px;
            border: 2px solid blue;
            padding: 20px;
            z-index: 111;

        }

        .subbtn {
            background: blue;
            color: white;
            padding: 4px 10px;
            margin: 10px;

        }
    </style>
</head>

<body>

    <div id="overlay" onclick="hideImage()">

        <i id="closeBtn" onclick="hideImage()" class="fa fa-lg fa-times-circle"></i>
        <img id="overlayImage" src="" alt="Fullscreen Image">
    </div>



    <div id="app" class="bodycont">

        <div class="tooldia" v-show="showtooldiaforagent" style="z-index: 113;">

            <i @click="showtooldiaforagent=false" class="fa fa-lg fa-times-circle" style="margin: 0; float: right;"></i>
            <div style="font-weight: bold;">选择你想要的工具</div>
            <p v-for="item in alltoollist" :key="item.toolname" style="cursor: pointer;;">
                <label>
                    <input type="checkbox" v-model="agentformdata.bottoollist" :value="item" />
                    {{item.toolname}}(<span style="color: grey;font-size: 12px;"> {{item.desc}}</span>)
                </label>
            </p>


        </div>
        <div class="tooldia" v-show="showaddagentdia" style="z-index: 112;max-height: 60vh;overflow: scroll;">
            <i @click="showaddagentdia=false" class="fa fa-lg fa-times-circle" style="margin: 0; float: right;"></i>
            <div style="font-weight: bold;">添加智能体 </div>
            <div>
                <p>智能体名称:</p>
                <input type="text" class="textinput" v-model="agentformdata.agentname" placeholder="智能体名称" />
            </div>
            <div>
                <p>智能体描述:</p>
                <textarea type="text" class="promptinput" v-model="agentformdata.desc" placeholder="智能体描述"></textarea>
            </div>
            <div class="select-wrapper">
                <p>模型</p>
                <p>
                    <select v-model="agentformdata.aimodel">
                        <option v-for="item in modellist" :key="item.model" :value="item.model">
                            {{ item.model }}
                        </option>
                    </select>
                </p>
            </div>
            <div>
                <p>随机性:{{agentformdata.temperature}}</p>
                <p><input type="range" v-model="agentformdata.temperature" min="0.1" max="1" step="0.1" /></p>
            </div>

            <div>
                <p>上下文历史记录轮数:{{agentformdata.maxlun}}</p>
                <p><input type="range" v-model="agentformdata.maxlun" min="1" max="10" step="1" /></p>
            </div>
            <div>
                <p>topN:{{agentformdata.topn}}</p>
                <p><input type="range" v-model="agentformdata.topn" min="0.1" max="1" step="0.1" /></p>
            </div>

            <div>
                <p>最大输出:{{agentformdata.maxtokens}}tokens</p>

                <p><input type="range" v-model="agentformdata.maxtokens" min="100" max="1000" step="100" /></p>
            </div>
            <div>
                <p>提示词</p>
                <p> <textarea class="promptinput" v-model="agentformdata.prompt" rows="3"
                        placeholder="输入你的提示词"></textarea></p>
            </div>

            <div>
                <p>插件<i @click="showtooldiaforagent=true" class="fa fa-lg fa-plus-circle"
                        style="margin-left: 20px;"></i></p>
                <p v-for="item in agentformdata.bottoollist">
                    {{item.toolname}}(<span style="color: grey;font-size: 12px;"> {{item.desc}}</span>)
                </p>
            </div>
            <div class="select-wrapper">
                <p>语音音色</p>
                <p>
                    <select v-model="agentformdata.voiceindex">
                        <option v-for="(voice,index) in chineseVoices" :key="voice.name" :value="index">
                            {{ voice.name }}
                        </option>
                    </select>
                </p>
            </div>

            <div>
                <p>语音唤醒词</p>
                <p> <input class="textinput" v-model="agentformdata.wakeupword" rows="1" placeholder="输入你的语音唤醒词" /></p>
            </div>




            <button class="subbtn" @click="addagentform">提交</button>
        </div>

        <div class="tooldia" v-show="showagentlist">

            <i @click="showagentlist=false" class="fa fa-lg fa-times-circle" style="margin: 0; float: right;"></i>
            <div style="font-weight: bold;">选择智能体 <i @click="showaddagentdia=true" class="fa fa-lg fa-plus-circle"
                    style="margin-left: 20px;"></i></div>
            <p v-for="(item,index) in aiagentlist" :key="index" @click="startchatbyagent(index)"
                style="cursor: pointer;;">


                {{item.agentname}}(<span style="color: grey;font-size: 12px;"> {{item.desc}}</span>)

            </p>





        </div>


        <div class="tooldia" v-show="showtooldia">

            <i @click="showtooldia=false" class="fa fa-lg fa-times-circle" style="margin: 0; float: right;"></i>
            <div style="font-weight: bold;">选择你想要的工具<i @click="showaddtooldia=true" class="fa fa-lg fa-plus-circle"
                    style="margin-left: 20px;"></i></div>
            <p v-for="item in alltoollist" :key="item.toolname" style="cursor: pointer;;">
                <label>
                    <input type="checkbox" v-model="agentconfig.bottoollist" :value="item" />
                    {{item.toolname}}(<span style="color: grey;font-size: 12px;"> {{item.desc}}</span>)
                </label>
            </p>





        </div>


        <div id="chatlist" v-show="showhis">
            <div style="display: flex;margin-bottom: 10px;;">
                <a style="cursor: pointer; flex: 1;margin-top: 20px;border: 1px solid grey; border-radius: 10px;text-align: center; padding: 5px;"
                    @click="newchat"> <i class="fa fa-lg fa-comments" style="margin-right: 10px;;"></i>新会话</a> <i
                    @click="showhis=false" class="fa fa-lg fa-times-circle" style="margin: 0;"></i>
            </div>



            <div v-for="(item,index) in hischatlist" :key="item.id" @click="openchat(item.id)"
                :class="nowchatid==item.id ? 'nowchatitem hischatitem' : 'hischatitem'">
                <span class="agentname">{{item.agent.agentname}}</span>

                <span v-if="item.data.length>0" class="messagetext">{{item.data[0].content}}</span>
                <span v-if="item.data.length==0" class="messagetext">新聊天</span>
                <i class="fa fa-trash del" @click.stop="delchat(index)"></i>
            </div>

        </div>
        <div id="bodychat" class="cont">

            <div style="display: flex;padding: 10px;line-height: 20px;">
                <i v-show="!showhis" class="fa fa-lg fa-comments" @click="showhis=!showhis"></i>
                <h2 style="margin: 0 auto;padding: 0;">Ollama API实现AI聊天</h2> <i class="fa fa-lg fa-cog"
                    style="margin-right: 0px;" @click="showsetting=!showsetting"
                    v-show="!showsetting&&nowchatid!=''"></i>
            </div>

            <div id="voicechat" v-if="vociechating">

                <div @click="newvoicechat">
                    <img v-if="aivoicestate==1" style="height:100px;"
                        src="//repo.bfw.wiki/bfwrepo/icon/6687d86e43686.png" />
                    <img v-if="aivoicestate==2" style="height:100px;"
                        src="//repo.bfw.wiki/bfwrepo/icon/6687d064d941c.gif" />
                    <img v-if="aivoicestate==3" style="height:100px;"
                        src="//repo.bfw.wiki/bfwrepo/icon/6687d047c924b.gif" />
                    <img v-if="aivoicestate==4" style="height:100px;"
                        src="//repo.bfw.wiki/bfwrepo/icon/6687d07c0a4d8.gif" />
                </div>

                <p v-if="aivoicestate==1"> 请说关键词"{{agentconfig.wakeupword}}"或点击上面图标唤醒我</p>
                <p v-if="aivoicestate==2">我在听,您请说……</p>
                <p v-if="aivoicestate==3">思考中……</p>
                <p v-if="aivoicestate==4">回答中,可说关键字"{{agentconfig.wakeupword}}"或点击上面图标进行提问</p>


                <p><button class="hangoverbtn" @click="hangout">
                        <i class="fa  fa-stop-circle" style="margin-right: 10px;"></i>挂断
                    </button></p>

            </div>
            <div v-if="nowchatid==''&&modellist.length>0" class="historylist">
                <div class="recomlist">
                    <div class="item" @click="askagentnew('说说《三国演义》有啥?')">
                        <p><i class="fa fa-lg fa-leanpub"></i></p>
                        <p> 说说《三国演义》有啥?
                    </div>
                    <div class="item" @click="askagentnew('电脑蓝屏怎么办?')">
                        <p> <i class="fa fa-lg fa-th-large"></i></p>
                        <p> 电脑蓝屏怎么办?</p>
                    </div>
                    <div class="item" @click="askagentnew('如何锻炼身体?')">
                        <p> <i class="fa fa-lg fa-universal-access"></i></p>
                        <p> 如何锻炼身体?</p>
                    </div>
                </div>
            </div>
            <div v-if="nowchatid==''&&modellist.length==0" class="historylist">
                <div class="recomlist">
                    <div class="item">
                        <p> <i class="fa fa-lg fa-universal-access"></i></p>
                        <p> 请打开ollama</p>

                    </div>

                </div>
            </div>
            <div id="historylist" @scroll="handleScroll" class="historylist" v-if="nowchatid!=''&&!vociechating">
                <div v-for="(msg,index) in newmess" :key="index"
                    :class="{'mesay': msg.role === 'user', 'aisay': msg.role === 'system'}">

                    <div v-html="msg.content"></div>
                    <div v-if="aistatus==1&&msg.content==''&&msg.role === 'system'"><img style="height:30px;"
                            src='https://repo.bfw.wiki/bfwrepo/icon/667d490a27acd.gif' /></div>
                    <div v-if="aistatus==2&&msg.content==''&&msg.role === 'system'">调用插件中……</div>

                    <div v-if="msg.role === 'system'&&msg.isfinished" class="feedbackpanel"><a title="复制"
                            class="copybtn" @click="copy(index)"><i class="fa  fa-copy"></i></a><a title="重新生成"
                            class="regenbtn" @click="regen(index)"><i class="fa  fa-rotate-left"></i></a>
                        <a title="非常好" class="regenbtn"><i class="fa  fa-thumbs-o-up"></i></a>

                        <a title="不好" class="regenbtn"><i class="fa fa-thumbs-o-down"></i></a>

                        <a @click="speakorstop(index)" v-if="sayingid!=msg.id" title="语音播放" class="regenbtn"><i
                                class="fa fa-play"></i></a>
                        <a @click="speakorstop(index)" v-if="sayingid==msg.id" title="停止播放" class="regenbtn"><i
                                class="fa fa-stop"></i></a>
                    </div>



                </div>
                <div class="recomminput">
                    <ol>
                        <li v-for="msg in recommtips" @click="askai(msg)">
                            {{msg}}
                        </li>
                    </ol>
                </div>

            </div>
            <div class="footer">

                <div class="scrollbar" v-if="!autoscroll" @click="tobottom" title="滚动到底部" style="text-align:center;">
                    <i class="fa fa-lg fa-angle-double-down"></i>
                </div>
                <div v-if="!isEmptyAttach" class="attachpannel">

                    <div class="filebox">
                        <p><img :title="attachfileinfo.name" :src="attachfileinfo.imgsrc" /></p>
                        <p class="fname" style="width: 70px;overflow: hidden;overflow-wrap: break-word;">
                            {{attachfileinfo.name}}</p>
                    </div>

                    <i @click="attachfileinfo={}" class="fa fa-lg fa-times-circle"></i>


                </div>

                <div v-show="micinputing" id="micinput">
                    <i @click="micinputing=false" class="fa fa-lg fa-times-circle" style="margin-left:180px;"></i>
                    <div @mousedown="startRecognition" @mouseup="stopRecognition" @touchstart="startRecognition"
                        @touchend="stopRecognition"><img v-if="!recognitioning"
                            src='https://repo.bfw.wiki/bfwrepo/icon/6687d86e43686.png' style="margin: 20px auto;" />
                        <img v-if="recognitioning" src='https://repo.bfw.wiki/bfwrepo/icon/6687d064d941c.gif'
                            style="margin: 20px auto;" />

                    </div>
                    <p v-if="recognitioning">请说</p>
                    <p v-if="!recognitioning">单击不放开始语音识别输入</p>
                </div>


                <div id="inputpannel" class="inputpannel" v-show="nowchatid!=''&&!vociechating">

                    <div class="file-upload" id="fileUpload">
                        <input type="file" id="fileInput" name="file"
                            accept="image/*,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx">

                        <i title="上传附件" class="fa fa-lg fa-plus-circle"></i>

                    </div>
                    <textarea class="inputtext" v-model="userInput" @input="adjustTextareaHeight" @paste="handlePaste"
                        ref="textarea" @keydown.enter.prevent="sendai" placeholder="请输入问题"></textarea>
                    <div class="sendbtn" @click="voicechat"> <i title="语音通话" class="   fa fa-lg fa-phone"> </i></div>

                    <div class="sendbtn" @click="micinputing=true"> <i title="语音输入" class="  fa fa-lg fa-microphone">
                        </i></div>
                    <div @click="sendai" class="sendbtn">
                        <i title="发送" v-if="!aireplying" class="fa fa-lg fa-send"> </i>

                        <i title="停止" v-if="aireplying" class="fa fa-lg fa-stop-circle"> </i>
                    </div>



                </div>
            </div>

        </div>

        <div id="setting" v-show="showsetting&&nowchatid!=''">

            <div style="display: flex;margin: 10px;">
                <a style="flex: 1;text-align: center; font-weight: bold;">设置</a><i @click="showsetting=false"
                    class="fa fa-lg fa-times-circle" style="margin: 0;"></i>
            </div>




            <div class="select-wrapper">
                <p>当前模型</p>
                <p>
                    <select v-model="agentconfig.aimodel" @change="handleChange">
                        <option v-for="item in modellist" :key="item.model" :value="item.model">
                            {{ item.model }}
                        </option>
                    </select>
                </p>
            </div>
            <div>
                <p>随机性:{{agentconfig.temperature}}</p>
                <p><input type="range" v-model="agentconfig.temperature" min="0.1" max="1" step="0.1" /></p>
            </div>
            <div>
                <p>topN:{{agentconfig.topn}}</p>
                <p><input type="range" v-model="agentconfig.topn" min="0.1" max="1" step="0.1" /></p>
            </div>
            <div>
                <p>几轮:{{agentconfig.maxlun}}</p>
                <p><input type="range" v-model="agentconfig.maxlun" min="3" max="10" step="1" /></p>
            </div>
            <div>
                <p>最大输出:{{agentconfig.maxtokens}}</p>

                <p><input type="range" v-model="agentconfig.maxtokens" min="100" max="1000" step="100" /></p>
            </div>
            <div>
                <p>提示词</p>
                <p> <textarea class="promptinput" v-model="agentconfig.prompt" rows="3"
                        placeholder="输入你的提示词"></textarea></p>
            </div>

            <div>
                <p>插件<i @click="showtooldia=true" class="fa fa-lg fa-plus-circle" style="margin-left: 20px;"></i></p>
                <p v-for="item in agentconfig.bottoollist">
                    {{item.toolname}}(<span style="color: grey;font-size: 12px;"> {{item.desc}}</span>)
                </p>
            </div>

            <div class="select-wrapper">
                <p>语音音色</p>
                <p>
                    <select v-model="agentconfig.voiceindex">
                        <option v-for="(voice,index) in chineseVoices" :key="voice.name" :value="index">
                            {{ voice.name }}
                        </option>
                    </select>
                </p>
            </div>

            <div>
                <p>语音唤醒词</p>
                <p> <input class="textinput" v-model="agentconfig.wakeupword" rows="1" placeholder="输入你的语音唤醒词" /></p>
            </div>



        </div>


    </div>

    <script>

        localforage.setDriver([
            localforage.INDEXEDDB,
            localforage.WEBSQL,
            localforage.LOCALSTORAGE]);

        const audioContext = new (window.AudioContext || window.webkitAudioContext)();
        // 自定义渲染器
        const renderer = new marked.Renderer();
        renderer.code = function (code, language) {
            const escapedCode = this.options.highlight(code, language);
            return `
                <pre class="prettyprint language-${language}">
                <div class="code-header">
                    <span class="language-label">${language}</span>
                    <button class="copy-button" onclick="copyCode(this)">Copy</button></div>
                    <code class="code-content language-${language}">${escapedCode}</code>
                </pre>
            `;
        };

        // 重写 image 渲染方法
        renderer.image = (href, title, text) => {
            return `
    <img src="${href}" alt="${text}" title="${title}" onclick="handleImageClick('${href}')">
  `;
        };



        // 自定义标签的正则表达式
        const customTagRegex = /\[\[(.*?)\|\|\|(.*?)\]\]/g;

        // 自定义标签的渲染函数
        renderer.text = (text) => {
            return text.replace(customTagRegex, (match, url, alt) => {
                // 对自定义标签内容进行处理
                return `<div class="filebox"><p><img src="${url}" onclick="handleImageClick('${url}')" alt="${alt}" /></p><p class="fname">${alt}</p></div>`;
            });
        };






        // 定义图像点击处理函数
        window.handleImageClick = (src) => {
            showImage(src);
            // 你可以在这里添加更多的处理逻辑
        };

        // 设置 marked 选项
        marked.setOptions({
            renderer: renderer,
            highlight: function (code) {
                return hljs.highlightAuto(code).value;
            },
            sanitize: true
        });
        // 创建一个全局的 SpeechSynthesisUtterance 实例
        const utterance = new SpeechSynthesisUtterance();
        const aiutterance = new SpeechSynthesisUtterance();


        var vueinstance = new Vue({
            el: '#app',
            data() {
                return {
                    homerecqustion: [],
                    wakeupword: "天猫精灵",
                    chatlist: [],
                    selectedVoiceindex: 0,
                    maxlun: 3,
                    topn: 1,
                    attachfileinfo: {},
                    showagentlist: false,
                    showtooldiaforagent: false,
                    //  bottoollist: [],
                    agentformdata: { aimodel: "", voiceindex: 0, wakeupword: "芝麻开门", maxlun: 3, agentname: "", desc: "", prompt: "", temperature: 1, maxtokens: 400, bottoollist: [], topn: 1 },
                    alltoollist: [
                        { toolname: "get_nowdatetime", desc: "获取当前系统时间日期", para: [] },
                        { toolname: "get_webpagecontent", desc: "根据url地址获取网页内容", para: [{ name: "url", type: "string", desc: "url地址", isrequired: true }] },
                        { toolname: "add_baoming", desc: "提交个人姓名和身份证号码报名体检活动", para: [{ name: "idcard", type: "string", desc: "身份证号码", isrequired: true }, { name: "realname", type: "string", desc: "姓名", isrequired: true }, { name: "phone", type: "string", desc: "姓名", isrequired: false }] },
                        {
                            toolname: "get_img_content", desc: "理解图片中的内容", para: [{ name: "imgdata", type: "string", desc: "图片url地址", isrequired: true }]
                        },
                        {
                            toolname: "search_internet", desc: "互联网搜索关键词获取内容", para: [{ name: "keyword", type: "string", desc: "搜索关键词", isrequired: true }]
                        },

                        {
                            toolname: "write_file_content", desc: "写入文件到本地文件目录中", para: [{ name: "pathname", type: "string", desc: "文件路径", isrequired: true },{ name: "content", type: "string", desc: "文件内容", isrequired: true }]
                        },

                        {
                            toolname: "read_file_content", desc: "读取本地文件内容", para: [{ name: "pathname", type: "string", desc: "文件路径", isrequired: true }]
                        },

                        {
                            toolname: "list_dir", desc: "获取目录文件及子目录列表", para: [{ name: "pathname", type: "string", desc: "目录名", isrequired: true }]
                        },


                    ],
                    aiagentlist: [
                    ],
                    aiagentlistinit: [
                        { aimodel: "", voiceindex: 0, wakeupword: "芝麻开门", maxlun: 3, agentname: "文章总结", desc: "可以总结文章", prompt: "你是一个专门总结文章的ai助手", temperature: 1, maxtokens: 600, bottoollist: [], topn: 1 },
                        { aimodel: "", voiceindex: 0, wakeupword: "芝麻开门", maxlun: 3, agentname: "代码编写", desc: "帮你写代码", prompt: "你是一个专业的编程助手,可以帮用户写代码,解决编程上的问题", temperature: 0.1, maxtokens: 500, bottoollist: [], topn: 1 },
                        { aimodel: "", voiceindex: 0, wakeupword: "芝麻开门", maxlun: 3, agentname: "报名信息收集", desc: "可以收集报名信息", prompt: "你是一个专门收集用户报名个人信息的ai助手,询问用户的姓名和身份证号码,调用工具保存,确保用户的姓名和身份证号码不能缺失后再保存。", temperature: 0.1, max_tokens: 100, bottoollist: [], topn: 1 },
                    ],
                    agentconfig: { agentname: "", desc: "", maxtokens: 100, temperature: 1, topn: 1, prompt: "你是一个ai助手", bottoollist: [] },
                    vociechating: false,
                    speaking: false,
                    maxtokens: 300,
                    recognitioning: false,
                    prompttext: "你是一个ai助手",
                    showhis: true,
                    showsetting: false,
                    modellist: [],
                    temperature: 1,
                    aistatus: 1,
                    showtooldia: false,
                    recommtips: [],
                    showaddtooldia: false,
                    showaddagentdia: false,
                    messages: [],
                    attachfile: "",
                    autoscroll: true,
                    btntext: "发送",
                    chineseVoices: [],
                    selectedVoice: null,
                    aivoicestate: 1,
                    userInput: '',
                    apiUrl: 'http://localhost:11434/api/chat',
                    apiKey: "gemma:2b",
                    model: "gemma:7b",
                    controller: null,
                    displayedText: "",
                    sayingid: "",
                    // bottools: [{ "name": "getnowtime", "desc": "获取当前时间", "para": [] }, { "name": "getwebpagecontent", "desc": "根据url参数获取网页内容", "para": [{ "name": "url", "type": "string", "desc": "url地址" }, { "name": "type", "type": "string", "desc": "返回类型,json或html" }], "example": "getwebpagecontent?url=https://www.baidu.com&type=json" }, { "name": "getnowtime", "desc": "获取当前时间", "para": [{ "name": "url", "type": "string", "desc": "网址url" }] }],
                    currentIndex: 0,
                    micinputing: false,
                    gettext: "",
                    fullText: '',
                    diatoai: false,
                    nowchatid: "",
                    aireplying: false,
                    typingSpeed: 40, // Typing speed in milliseconds
                    typingTimer: null,
                    vociequene: [],
                    startrecg: false,
                };
            },
            watch: {
                agentconfig: {

                    handler: function (newVal, oldVal) {
                        console.log('User object changed');
                        console.log('New value:', newVal);
                        console.log('Old value:', oldVal);

                        this.savelocaldb();
                    },
                    deep: true
                }
            },
            computed: {
                isEmptyAttach() {
                    return Object.keys(this.attachfileinfo).length === 0;
                },
                newmess() {

                    let newmessdat = [];
                    this.messages.forEach(element => {
                        if (this.isEmpty(element.attach)) {
                            newmessdat.push({ role: element.role, attach: element.attach, content: marked.parse(element.content), isfinished: element.isfinished, id: element.id });
                        } else {
                            newmessdat.push({ role: element.role, attach: element.attach, content: marked.parse(element.content + "[[" + element.attach.imgsrc + "|||" + element.attach.name + "]]"), isfinished: element.isfinished, id: element.id });
                        }

                    })
                    return newmessdat;


                    // return this.messages.map(element => {

                    //     return { role: element.role,attach:element.attach, content: marked.parse(element.content), isfinished: element.isfinished, id: element.id };
                    // });
                },
                hischatlist() {
                    return JSON.parse(JSON.stringify(this.chatlist)).reverse();
                }
            },
            mounted() {
                var that = this;
                /// this.imgundersandapi("d");
                document.body.addEventListener('dragover', this.handleDragOver);
                document.body.addEventListener('dragleave', this.handleDragLeave);
                document.body.addEventListener('drop', this.handleDrop);
                //获取模型数据
                // console.log(that.apireq("我要提交联系方式,我叫王凯"));
                fetch('http://localhost:11434/api/tags', {
                })
                    .then(response => response.json())
                    .then(data => {
                        that.modellist = data.models;
                        if (that.modellist.length > 0) {
                            that.model = that.modellist[0].model;
                        }
                    })
                    .catch(error => console.error('Error:', error));
                //获取embedding

                // fetch('http://localhost:11434/api/embeddings', {
                //     method: 'POST',
                //     headers: {
                //         'Content-Type': 'application/json'
                //     },
                //     body: JSON.stringify({
                //         model: this.model,
                //         prompt: 'Here is an article about llamas...'
                //     })
                // })
                //     .then(response => response.json())
                //     .then(data => console.log(data))
                //     .catch(error => console.error('Error:', error));
                // localforage.getItem("localmessage").then(function (readValue) {
                //     if (readValue) {
                //         that.messages = readValue;
                //     }


                //     that.scrollToBottom();

                //     console.log('Read: ', readValue);
                // });
                that.getlocallist();
                that.getlocalagentlist();
                that.loadVoices();


                // window.speechSynthesis.onvoiceschanged = this.loadVoices;



            },
            methods: {
                handlePaste(event) {
                    const items = event.clipboardData.items;
                    for (let i = 0; i < items.length; i++) {
                        const item = items[i];
                        if (item.type.indexOf('image') !== -1) {
                            const file = item.getAsFile();
                            const reader = new FileReader();
                            reader.onload = (e) => {
                                // this.base64Image = e.target.result;

                                vueinstance.attachfileinfo = { stype: "image", name: file.name, type: file.type, textcontent: "一个孩子在给妈妈洗衣服", imgsrc: e.target.result }
                            };
                            reader.readAsDataURL(file);
                            break;
                        }
                    }
                },
                handleDragOver(event) {
                    event.preventDefault();
                    document.body.style.backgroundColor = '#e0f7fa'; // 拖动时改变背景颜色
                },
                handleDragLeave() {
                    document.body.style.backgroundColor = ''; // 拖动离开时恢复背景颜色
                },
                handleDrop(event) {
                    event.preventDefault();
                    document.body.style.backgroundColor = ''; // 放开时恢复背景颜色
                    // const files = event.dataTransfer.files;
                    // if (files.length === 1) {
                    //     const file = files[0];


                    handlefile(event.dataTransfer.files[0])

                    // } else {
                    //     alert('只能拖拽单个文件');
                    // }
                },
                adjustTextareaHeight() {
                    const textarea = this.$refs.textarea;
                    textarea.style.height = ''; // Reset the height
                    textarea.style.height = `${textarea.scrollHeight}px`; // Set the height to scrollHeight
                },
                resetTextareaHeight() {
                    const textarea = this.$refs.textarea;
                    textarea.style.height = '40px'; // Reset the height
                    // textarea.style.height = `${textarea.scrollHeight}px`; // Set the height to scrollHeight
                },
                isEmpty(obj) {
                    return Object.keys(obj).length === 0;
                },
                addagentform() {
                    this.aiagentlist.push(this.agentformdata);
                    this.showaddagentdia = false;
                    this.savelocalagentdb();
                },
                loadVoices() {
                    const voices = window.speechSynthesis.getVoices();
                    var that = this;
                    setTimeout(function () {
                        const voices = window.speechSynthesis.getVoices();
                        console.log(voices)
                        that.chineseVoices = voices.filter(voice => voice.lang.includes('zh'));
                        if (that.chineseVoices.length > 0) {
                            that.selectedVoiceindex = 0;
                            //that.selectedVoice = that.chineseVoices[0];
                        }
                    }, 5000);
                    //

                },

                newvoicechat() {
                    var that = this;
                    setTimeout(() => {
                        that.startrecg = true;
                    }, 2000);
                    this.aivoicestate = 2;
                    this.abortRequest();
                    this.voicestop();

                    // this.aisayhere();
                },
                startRecognition() {
                    try {
                        if (!('webkitSpeechRecognition' in window)) {
                            alert('你的浏览器不支持语音识别功能。');
                            return;
                        }

                        this.recognition = new webkitSpeechRecognition();
                        this.recognition.lang = 'zh-CN';
                        this.recognition.continuous = true;
                        this.recognition.interimResults = true;
                        this.recognitioning = true;

                        this.recognition.onresult = (event) => {
                            console.log(event)
                            for (let i = event.resultIndex; i < event.results.length; ++i) {
                                if (event.results[i].isFinal) {
                                    this.userInput += event.results[i][0].transcript;
                                } else {

                                }
                            }

                        };

                        this.recognition.onerror = (event) => {
                            console.error('语音识别错误:', event.error);
                            this.recognitioning = false;
                        };

                        this.recognition.start();
                    } catch (error) {
                        console.error('无法获取麦克风权限:', error);
                        alert("无法获取麦克风");
                        this.recognitioning = false;
                    }
                },
                stopRecognition() {
                    var that = this;
                    if (this.recognition) {
                        setTimeout(() => {
                            that.sendai();
                        }, 1000);

                        this.recognition.stop();
                        this.recognitioning = false;
                    }
                },
                hangout() {
                    this.aivoicestate = 1;
                    this.vociechating = false;
                    speechSynthesis.cancel();
                    this.aireplying = false;
                    this.abortRequest();
                    this.recognition.stop();

                },
                aisayhere() {
                    var that = this;
                    aiutterance.text = "在呢";
                    aiutterance.voice = that.chineseVoices[that.agentconfig.voiceindex];
                    aiutterance.onend = () => {
                        console.log("我在  说完了")
                        setTimeout(() => {
                            that.startrecg = true;

                        }, 1000); // 2秒钟的静音后停止识别

                    };

                    // 使用 speechSynthesis 播放 utterance
                    speechSynthesis.speak(aiutterance);


                },
                voicechat() {
                    var that = this;
                    if (this.aireplying) {
                        alert("正在生成中,请稍后");
                        return;
                    }
                    if (this.nowchatid == "") {
                        alert("请打开一个聊天");
                        return;
                    }
                    try {
                        if (!('webkitSpeechRecognition' in window)) {
                            alert('你的浏览器不支持语音识别功能。');
                            return;
                        }






                        let saywords = "";
                        this.recognition = new webkitSpeechRecognition();
                        this.recognition.lang = 'zh-CN';
                        this.recognition.continuous = true;
                        this.recognition.interimResults = false;
                        this.aivoicestate = 1;
                        this.vociechating = true;
                        let silenceTimer;
                        // let startrecg = false;



                        // let mediaStreamSource = null;
                        // let processor = null;

                        // navigator.mediaDevices.getUserMedia({ audio: true })
                        //     .then(stream => {
                        //         mediaStreamSource = audioContext.createMediaStreamSource(stream);
                        //         processor = audioContext.createScriptProcessor(4096, 1, 1);
                        //         mediaStreamSource.connect(processor);
                        //         processor.connect(audioContext.destination);

                        //         processor.onaudioprocess = function (e) {
                        //             const inputData = e.inputBuffer.getChannelData(0);
                        //             const outputData = e.outputBuffer.getChannelData(0);

                        //             // 简单的降噪处理
                        //             for (let i = 0; i < inputData.length; i++) {
                        //                 outputData[i] = inputData[i] * 0.5; // 调整增益来减少噪音
                        //             }
                        //         };
                        //     })
                        //     .catch(err => {
                        //         console.error('获取音频流失败:', err);
                        //     });

                        this.recognition.onresult = (event) => {
                            //  clearTimeout(silenceTimer); // 清除之前的静音定时器
                            //
                            // console.log(event)
                            for (let i = event.resultIndex; i < event.results.length; ++i) {
                                if (event.results[i].isFinal) {
                                    saywords += event.results[i][0].transcript;
                                } else {

                                }
                            }
                            console.log(saywords)

                            if (!that.startrecg && saywords.includes(that.agentconfig.wakeupword)).........完整代码请登录后点击上方下载按钮下载查看

网友评论0