自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

基于Agent的金融問(wèn)答系統(tǒng):前后端流程打通 原創(chuàng)

發(fā)布于 2024-11-25 10:16
瀏覽
0收藏

前言

在上一章??《【項(xiàng)目實(shí)戰(zhàn)】基于Agent的金融問(wèn)答系統(tǒng):Agent框架的構(gòu)建》??中,我們已經(jīng)完成了基于agent的問(wèn)答系統(tǒng)主流程構(gòu)建,本章將介紹如何將Agent通過(guò)langserve部署為后端服務(wù),同時(shí)基于Vue.js+Vite構(gòu)建前端頁(yè)面,完成問(wèn)答系統(tǒng)前后端聯(lián)調(diào)。

目標(biāo)

  • 將Agent部署為后端服務(wù)
  • 構(gòu)建前端頁(yè)面,完成問(wèn)答系統(tǒng)前后端聯(lián)調(diào)

后端實(shí)現(xiàn)

代碼實(shí)現(xiàn)

基于《大模型應(yīng)用開(kāi)發(fā)之Prompt初步了解》中l(wèi)angserve的所學(xué)內(nèi)容,我們需要做的第一步為: 1、安裝langserve依賴(lài)包:

pip install "langserve[all]"

2、創(chuàng)建一個(gè)server.py文件,具體如下;

代碼文件:??app/server.py??

from fastapi importFastAPI,HTTPException
from fastapi.middleware.cors importCORSMiddleware
from finance_bot_ex importFinanceBotEx

finance_bot_ex =FinanceBotEx()

# 創(chuàng)建 FastAPI 應(yīng)用
app =FastAPI(
    title="Qwen API",
    version="0.1",
    description="Qwen API",
)

# 添加 CORS 中間件
app.add_middleware(
CORSMiddleware,
    allow_origins=["*"],# 允許所有的來(lái)源
    allow_credentials=True,
    allow_methods=["*"],# 允許的HTTP方法
    allow_headers=["*"],# 允許的請(qǐng)求頭
)

@app.post("/queryex", response_model=dict)
asyncdefquery(query: dict):# 使用字典類(lèi)型代替Query模型
try:
# 從字典中獲取input
        input_data = query.get("input")
        result = finance_bot_ex.handle_query(input_data)

# 返回字典格式的響應(yīng)
return{"output": result}
exceptExceptionas e:
raiseHTTPException(status_code=500, detail=str(e))

# 運(yùn)行Uvicorn服務(wù)器
if __name__ =="__main__":
import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8082)

代碼說(shuō)明:

  • 首先,依賴(lài)包引入langserve的必要包:??from fastapi import FastAPI, HTTPException
    from fastapi.middleware.cors import CORSMiddleware?
    ?
  • 其次,將我們之前封裝好的FinanceBotEx類(lèi)引入進(jìn)來(lái):??from finance_bot_ex import FinanceBotEx??
  • 然后,初始化FinanceBotEx類(lèi),并且創(chuàng)建FastAPI應(yīng)用:??# 實(shí)例化FinanceBotEx類(lèi)
    finance_bot_ex =FinanceBotEx()
    # 創(chuàng)建 FastAPI 應(yīng)用
    app =FastAPI(
      title="Qwen API",
      version="0.1",
      description="Qwen API",
    )
    # 添加 CORS 中間件(允許跨域訪問(wèn))
    app.add_middleware(
    CORSMiddleware,
      allow_origins=["*"],# 允許所有的來(lái)源
      allow_credentials=True,
      allow_methods=["*"],# 允許的HTTP方法
      allow_headers=["*"],# 允許的請(qǐng)求頭
    )?
    ?
  • 最后,給定一個(gè)接口,接收用戶輸入,調(diào)用FinanceBotEx類(lèi)的handle_query方法,返回結(jié)果: ```python @app.post("/queryex", response_model=dict) async def query(query: dict): # 使用字典類(lèi)型代替Query模型 try: # 從字典中獲取input input_data = query.get("input") result = finance_bot_ex.handle_query(input_data) # 返回字典格式的響應(yīng) return {"output": result} except Exception as e: raise HTTPException(status_code=500, detail=str(e))

### 服務(wù)部署
目前,整個(gè)工程目錄結(jié)構(gòu)如下:
```bash
smart-finance-bot \
    |- app \   # 該目錄用于服務(wù)端代碼
        |- conf
            |- .qwen
        |- utils \  
            |- util.py          # 實(shí)現(xiàn)連接大模型的方法
        |- rag \   
            |- pdf_processor.py
            |- chroma_conn.py
        |- test_framework.py      
        |- finance_bot_ex.py    # 封裝好的FinanceBotEx類(lèi)
        |- server.py            # 新增的服務(wù)代碼

啟動(dòng)后端服務(wù)方法

# 切換至項(xiàng)目根目錄
cd smart-finance-bot

# 啟動(dòng)服務(wù)
python app/server.py

運(yùn)行結(jié)果:

基于Agent的金融問(wèn)答系統(tǒng):前后端流程打通-AI.x社區(qū)

接口測(cè)試

服務(wù)正常啟動(dòng)后,我們通過(guò)curl命令測(cè)試后端接口正常

curl -X POST http://localhost:8082/queryex \
-H "Content-Type: application/json" \
-d '{
  "config": {},
  "input": "在20190211,按照中信行業(yè)分類(lèi)的標(biāo)準(zhǔn),一級(jí)行業(yè)中的\"A股公司數(shù)量\"最多的是\"機(jī)械\"行業(yè),共有549家公司。"
}'

運(yùn)行結(jié)果:

基于Agent的金融問(wèn)答系統(tǒng):前后端流程打通-AI.x社區(qū)

后端接口可以接收請(qǐng)求,服務(wù)一切正常,接下來(lái)我們開(kāi)始構(gòu)建前端頁(yè)面,完成問(wèn)答系統(tǒng)前后端聯(lián)調(diào)。

前端實(shí)現(xiàn)

前端頁(yè)面的實(shí)現(xiàn)方案有很多種,可以寫(xiě)個(gè)簡(jiǎn)單的HTML頁(yè)面,也可以使用Vue.js框架來(lái)實(shí)現(xiàn)一個(gè)前端。 因?yàn)閂ue.js是目前主流的前端框架,它有豐富的生態(tài)和API說(shuō)明,在github上也有非常多的開(kāi)源項(xiàng)目供參考,所以本例中我們將使用Vue.js框架來(lái)實(shí)現(xiàn)前端頁(yè)面。

背景知識(shí)

Vue.js簡(jiǎn)介 Vue.js 是一個(gè)用于構(gòu)建用戶界面的漸進(jìn)式 JavaScript 框架。它的核心庫(kù)專(zhuān)注于視圖層,易于上手,并與其他庫(kù)或現(xiàn)有項(xiàng)目進(jìn)行整合。

Vue.js的特點(diǎn)

  • 響應(yīng)式數(shù)據(jù)綁定:Vue.js 提供了雙向數(shù)據(jù)綁定,能夠?qū)崟r(shí)更新視圖與數(shù)據(jù)之間的變化。
  • 指令:Vue.js 提供了一些內(nèi)置指令(如 v-bind、v-model、v-for 等),使得數(shù)據(jù)綁定和 DOM 操作變得簡(jiǎn)單直觀。
  • 生態(tài)系統(tǒng):Vue.js 擁有豐富的生態(tài)系統(tǒng),包括路由管理(Vue Router)、狀態(tài)管理(Vuex)等工具,支持構(gòu)建復(fù)雜的應(yīng)用。

Vue.js的簡(jiǎn)單示例

<div id="app">
  <h1>{{ message }}</h1>
  <input v-model="message" placeholder="編輯我">
</div>

<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script>
  newVue({
el:'#app',
data:{
message:'Hello Vue!'
}
});
</script>

說(shuō)明:

  • 在上面的示例中,{{ message }} 用于顯示數(shù)據(jù),v-model 用于實(shí)現(xiàn)雙向數(shù)據(jù)綁定,允許用戶通過(guò)輸入框修改 message 的內(nèi)容。
  • 更為詳細(xì)的Vue.js使用方法,請(qǐng)查看官方文檔地址:https://cn.vuejs.org/

代碼實(shí)現(xiàn)

在本例中,我們參考Github上的一個(gè)開(kāi)源項(xiàng)目進(jìn)行二次開(kāi)發(fā),該項(xiàng)目git clone之后目錄如下:

chatweb \
    |- index.html               # 前端入口文件
|- node_modules             # 依賴(lài)包目錄
|- package-lock.json        # 鎖定依賴(lài)版本的文件
|- package.json             # 項(xiàng)目描述和依賴(lài)配置文件
|- postcss.config.js        # PostCSS 配置文件
|- public                   # 公共資源目錄
|- src                      # 源代碼目錄
|-App.vue              # 主應(yīng)用組件
|- assets               # 資源文件目錄
|- components           # 組件目錄
|-ChatComponents.vue # 聊天組件
|-Home.vue        # 首頁(yè)組件
|-Login.vue       # 登錄組件
|-NotFound.vue    # 404 頁(yè)面組件
|- main.js              # 應(yīng)用入口文件
|- routes               # 路由配置目錄
|- tailwind.config.js       # Tailwind CSS 配置文件
|- tsconfig.json            # TypeScript 配置文件
|- vite.config.js           # Vite 配置文件

該項(xiàng)目是仿chatGPT的問(wèn)答系統(tǒng),倉(cāng)庫(kù)地址為:SinMu-L/chatweb

修改index.html

編輯index.html,修改如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="icon" href="./src/assets/icon.jpg">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>金融千問(wèn)機(jī)器人</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>

修改路由配置文件

編輯src/routes/routers.js,修改如下:

import ContainerTemplatefrom'../components/ChatComponents.vue'
importNotFoundfrom'../components/NotFound.vue'
importHomefrom'../components/Home.vue'

var routes =[
{path:"/",name:'root',component:Home},
{path:"/chat/:uuid?",component:ContainerTemplate,name:'chat'},
{path:'/404',name:'not_found',component:NotFound}// 捕獲所有未匹配的路徑
];
exportdefault routes;

說(shuō)明:

  • 配置文件用于控制頁(yè)面請(qǐng)求的路由信息
  • 當(dāng)用戶訪問(wèn)的路徑為/時(shí),將顯示Home組件;
  • 用戶訪問(wèn)的路徑為/chat時(shí),將顯示ChatComponents組件;
  • 當(dāng)用戶訪問(wèn)的路徑為其他路徑,將顯示404頁(yè)面。

由上也可以看到,后續(xù)修改的對(duì)話頁(yè)面在 ??ChatComponents.vue?? 中。

修改聊天組件頁(yè)面

由于原始的 ??ChatComponents.vue?? 代碼不夠規(guī)范,顯示布局、顯示樣式以及邏輯代碼沒(méi)有分離,所以我們對(duì)其進(jìn)行重構(gòu),重構(gòu)內(nèi)容分為三部分:

重構(gòu)頁(yè)面的顯示布局

<template>
<div>
<div v-if="centerLodding" class="loading-container">
<n-spin size="large" />
</div>
<Login class="border border-red-400" />
<div class="flex flex-row h-min" :class="hasLogin('main')">
<!-- 非移動(dòng)端模式下側(cè)邊欄的樣式 -->
<div class="sidebar" :class="controlSidebarHidden ? 'w-0' : ''">
<div class="hidden sm:flex sm:flex-col sm:h-screen sm:border">
<!-- 新建按鈕 -->
<div class="basis-1/12 flex justify-center items-center">
<n-button class="w-4/5" @click="addLeftListEle">新的會(huì)話</n-button>
</div>
<!-- 列表 -->
<div class="basis-10/12 overflow-auto border">
<div v-for="item in left_data.left_list" :key="item.uuid">
<router-link :to="`/chat/${item.uuid}`" class="sidebar-item">
<div class="w-4/5 flex items-center">
<n-icon size="medium">
<game-controller-outline />
</n-icon>
<div class="truncate mx-2" style="color: #000;">
<p v-if="!item.enable_edit" class="truncate h-full">{{ item.title }}</p>
<n-input v-else type="text" size="small" class="h-full" v-model:value="item.title" @keyup.enter="submit(item.uuid)" />
</div>
</div>
<div class="w-1/5 flex justify-center items-center" :class="route.params.uuid != item.uuid ? 'hidden' : ''">
<n-button-group size="small">
<n-button text @click="editLeftListEle(item.uuid)">
<n-icon><Edit /></n-icon>
</n-button>
<n-button text @click="delLeftListEle(item.uuid)">
<n-icon><Delete /></n-icon>
</n-button>
</n-button-group>
</div>
</router-link>
</div>
</div>
<!-- 設(shè)置頁(yè)面 -->
<div class="footer flex flex-col items-center justify-between p-4 h-15">
<div class="user-info font-bold text-lg">金融千問(wèn)機(jī)器人</div>
<div class="logo-container relative"><!-- 添加一個(gè)容器 -->
<img src="../assets/background.png" alt="Logo" class="logo" />
</div>
<div class="robot-description text-sm text-gray-600 mt-2">
              金融千問(wèn)機(jī)器人,通過(guò)RAG對(duì)既有的PDF招股書(shū)建立了知識(shí)庫(kù),同時(shí)借助大模型+Agent對(duì)金融SQL數(shù)據(jù)庫(kù)進(jìn)行動(dòng)態(tài)查詢(xún),旨在為用戶提供快速、準(zhǔn)確的金融信息和咨詢(xún)服務(wù)。
</div>
<div class="settings-icon">
<n-icon @click="showSettingFunc()">
<SettingsOutline />
</n-icon>
</div>
</div>
</div>
</div>

<!-- 移動(dòng)端模式下側(cè)邊欄的樣式 -->
<div class="sm:hidden absolute top-1 left-1 h-full w-full flex flex-col">
<div>
<n-button text style="font-size:32px" @click="controlSidebarHidden = !controlSidebarHidden">
<n-icon class="text-black">
<Menu />
</n-icon>
</n-button>
</div>
<div v-if="!controlSidebarHidden" class="mobile-sidebar">
<div class="w-full flex flex-col h-screen border">
<div class="basis-1/12 flex justify-center items-center">
<n-button class="w-4/5" @click="addLeftListEle">新的對(duì)話</n-button>
</div>
<div class="basis-10/12 overflow-auto border">
<div v-for="item in left_data.left_list" :key="item.uuid">
<router-link :to="`/chat/${item.uuid}`" class="sidebar-item">
<div class="w-4/5 flex items-center">
<n-icon size="medium">
<game-controller-outline />
</n-icon>
<div class="truncate mx-2">
<p v-if="!item.enable_edit" class="truncate h-full">{{ item.title }}</p>
<n-input v-else type="text" size="small" class="h-full" v-model:value="item.title" @keyup.enter="submit(item.uuid)" />
</div>
</div>
<div class="w-1/5 flex justify-center items-center" :class="route.params.uuid != item.uuid ? 'hidden' : ''">
<n-button-group size="small">
<n-button text @click="editLeftListEle(item.uuid)">
<n-icon><Edit /></n-icon>
</n-button>
<n-button text @click="delLeftListEle(item.uuid)">
<n-icon><Delete /></n-icon>
</n-button>
</n-button-group>
</div>
</router-link>
</div>
</div>
<div class="footer flex items-center justify-between p-4 h-15">
<div class="user-info font-bold">金融千問(wèn)機(jī)器人</div>
<div class="settings-icon">
<n-icon @click="showSettingFunc()">
<SettingsOutline />
</n-icon>
</div>
</div>
</div>
</div>
</div>

<div class="w-full sm:w-4/5 h-full">
<div class="flex flex-col h-screen">
<div v-if="left_list_is_empty" class="empty-chat-message">
            Hi
</div>
<div v-else class="chat-area" id="msgArea">
<div v-for="(msglist, index) in getMsgList(route.params.uuid)" :key="index" class="flex flex-col mt-1 msgItem">
<div :class="msglist.reversion ? 'flex-row-reverse' : 'flex-row'" class="flex justify-start items-center h-10">

<img
                    class="rounded-full avatar"
                    :src="msglist.reversion ? userAvatar : robotAvatar"
                    alt="頭像"
                />
<span class="ml-4 text-sm">{{ msglist.create_time }}</span>
</div>
<div class="flex" :class="msglist.reversion ? 'flex-row-reverse' : 'flex-row'">
<div class="message-container">
<n-spin v-if="msglist.msgload" size="small" stroke="red" />
<Markdown v-else :source="msglist.content"></Markdown>
</div>
</div>
</div>
</div>
<div v-if="!left_list_is_empty" class="input-area">
<div class="p-2">
<n-input-group>
<n-tooltip trigger="hover">
<template #trigger>
<n-button text size="large" class="px-2" @click="deleteChatItemHistory(route.params.uuid)">
<n-icon class="text-black">
<Delete />
</n-icon>
</n-button>
</template>
                  刪除當(dāng)前會(huì)話記錄
</n-tooltip>
<n-tooltip trigger="hover">
<template #trigger>
<n-button text size="large" class="pr-4" @click="dom2img()">
<n-icon class="text-black">
<Download />
</n-icon>
</n-button>
</template>
                  下載當(dāng)前會(huì)話為圖片
</n-tooltip>
<a href="" id="link" class="hidden"></a>
<n-input show-count @keyup.ctrl.enter="addMessageListItem(route.params.uuid)" placeholder="Ctrl+Enter 發(fā)送消息,發(fā)送消息長(zhǎng)度需要大于2個(gè)字" v-model:value="input_area_value" type="textarea" size="tiny" :autosize="{ minRows: 2, maxRows: 5 }" />
<n-button ghost class="h-auto" @click="addMessageListItem(route.params.uuid)">
                  發(fā)送
</n-button>
</n-input-group>
</div>
</div>
</div>
</div>
</div>

<!-- 設(shè)置模態(tài)框 -->
<n-modal v-model:show="showSetting" style="width: 600px" class="custom-card" preset="card" title="設(shè)置">
<n-tabs type="line" animated>
<n-tab-pane name="about" tab="關(guān)于">
<div>這是一個(gè)demo項(xiàng)目,僅用于學(xué)習(xí)。</div>
<div class="my-4">技術(shù)棧:Vue3 + Vite + tailwindCss3 + NaiveUi</div>
</n-tab-pane>
<n-tab-pane name="settings" tab="設(shè)置">
<div class="grid grid-rows-3 gap-4">
<div>
<span class="mr-4">Server URL: </span>
<n-input v-model:value="setting.server_url" placeholder="請(qǐng)輸入服務(wù)器 URL" />
</div>
<div>
<span class="mr-4">type: </span>
<n-select :style="{ width: '80%' }" :options="selectOptions" v-model:value="setting.type" />
</div>
<div class="flex justify-end">
<n-button
                  @click="confirmSettings"
                  class="custom-button">
                確認(rèn)
</n-button>
</div>
</div>
</n-tab-pane>
<n-tab-pane name="other" tab="其他">
          其他
</n-tab-pane>
</n-tabs>
</n-modal>
</div>
</template>

重構(gòu)頁(yè)面的顯示樣式

<style scoped>
.router-link-active{
border-color:#18a058;
color:#18a058;
}

.loading-container{
position: absolute;
top:33%;
left:33%;
background-color: gray;
width:33%;
height:33%;
display: flex;
justify-content: center;
align-items: center;
}

.sidebar{
width:20%;
height:100%;
}

.sidebar-item{
margin:0.5rem;
display: flex;
justify-content: space-between;
align-items: center;
border:1px solid gray;
border-radius:0.375rem;/* rounded-md */
padding:0.5rem;
color: white;
}

.settings-container{
display: flex;
justify-content: flex-start;
align-items: center;
height:50%;
}

.user-info{
width:50%;
height:100%;
display: grid;
grid-template-rows:repeat(2,1fr);
}

.settings-icon{
width:25%;
height:100%;
display: flex;
justify-content: center;
align-items: center;
}

.mobile-sidebar{
width:80%;
background-color: white;
  dark:bg-black;
}

.empty-chat-message{
flex-basis:91%;
width:100%;
padding:3rem;
overflow:auto;
display: flex;
justify-content: center;
align-items: flex-start;
color: gray;
font-style: italic;
}

.chat-area{
flex-basis:91%;
width:100%;
padding:3rem;
overflow:auto;
}

.message-container{
background-color:#bfdbfe; /* bg-blue-200 */
color: black;/* dark:text-black */
width:auto;
max-width:80%;
min-width:1%;
break-words:break-word;
overflow: hidden;
border-radius:0.375rem;/* rounded-sm */
padding:0.5rem;
margin:0.25rem0;
}

.input-area{
flex-basis:8%;
width:100%;
}

.avatar{
width:50px;
height:50px;
}

.footer{
text-align: center;/* 居中顯示 */
}

.robot-description{
margin-top:8px;/* 描述與 Logo 之間的間距 */
text-align: left;/* 左對(duì)齊 */
width:100%;/* 使描述占滿可用寬度 */
padding-left:16px;/* 可選:增加左側(cè)內(nèi)邊距 */
}

.logo-container{
position: relative;/* 設(shè)置容器為相對(duì)定位 */
}

.background-logo{
position: absolute;/* 設(shè)置背景圖為絕對(duì)定位 */
top:0;/* 頂部對(duì)齊 */
left:0;/* 左側(cè)對(duì)齊 */
width:240px;/* 設(shè)置背景圖寬度為240px */
height:auto;/* 保持比例 */
z-index:1;/* 確保背景圖在logo下方 */
}

.logo{
position: relative;/* 設(shè)置logo為相對(duì)定位 */
z-index:2;/* 確保logo在背景圖上方 */
width:200px;/* 根據(jù)需要調(diào)整 Logo 大小 */
height:auto;/* 保持比例 */
top:30%;/* 垂直居中 */
left:50%;/* 水平居中 */
transform:translate(-50%,-50%);/* 使 logo 在背景圖中心 */
}

.custom-button{
background-color:#007bff; /* 按鈕背景色 */
color: white;/* 字體顏色 */
border: none;/* 去掉邊框 */
padding:10px20px;/* 內(nèi)邊距 */
border-radius:5px;/* 圓角 */
cursor: pointer;/* 鼠標(biāo)樣式 */
transition: background-color 0.3s;/* 添加過(guò)渡效果 */
}

.custom-button:hover{
background-color:#0056b3; /* 懸停時(shí)的背景顏色 */
}

</style>

重構(gòu)頁(yè)面的JS代碼

<script setup>
import{
NButton,NInput,NIcon,NButtonGroup,NSpin,
NInputGroup,NCard,NModal,NTabs,NTabPane,NInputNumber,NSelect,
NTooltip,
    useMessage
}from'naive-ui'
import{GameControllerOutline,GameController}from'@vicons/ionicons5'
import{LogInOutlineasLogInIcon,SettingsOutline,Menu}from'@vicons/ionicons5'
import userAvatar from'@/assets/user-avatar.png';
import robotAvatar from'@/assets/robot-avatar.png';

import{Edit,Delete,Download}from'@vicons/carbon'
importMarkdownfrom'vue3-markdown-it';

importLoginfrom'./Login.vue'

import{ reactive, ref, getCurrentInstance, watch, watchEffect, nextTick }from'vue';
import{ useRouter, useRoute }from'vue-router'
import html2canvas from"html2canvas";


const router =useRouter()
const route =useRoute()
const instaceV =getCurrentInstance()
const message =useMessage()

import{ onMounted }from'vue';

// 在組件的 setup 函數(shù)中添加
onMounted(() =>{
// 檢查是否有會(huì)話記錄
if(left_data.chat.length>0){
// 獲取最后一個(gè)會(huì)話的 UUID
const lastChatUuid = left_data.chat[left_data.chat.length-1].uuid;
// 路由跳轉(zhuǎn)到最后一個(gè)會(huì)話
    router.push({name:'chat',params:{uuid: lastChatUuid }});
}else{
// 如果沒(méi)有會(huì)話,設(shè)置左側(cè)列表為空
    left_list_is_empty.value=true;
}
});

// 控制側(cè)邊欄顯示隱藏
var controlSidebarHidden =ref(true)
// 移動(dòng)端下側(cè)邊欄顯影

const showSetting =ref(false)

varLLM_APIKEY=ref("sk-cwtdeSy4Ownmy6Uh5e9b6a67Fe4c4454A3Dc524876348eB1")

var setting =reactive({
server_url:'http://localhost:8082/query',// 默認(rèn)值
type:'query',
})

let left_list_is_empty =ref(false)

var is404 =ref(false)

var segmented ={
content:'soft',
footer:'soft'
}

var selectOptions =ref([
{
label:'Query式訪問(wèn)',
value:'query'
},
{
label:'流式訪問(wèn)',
value:'stream_log'
}
])

var centerLodding =ref(false)

var input_area_value =ref('')
var left_data =reactive({
left_list:[
// { uuid: 1, title: 'New Chat1', enable_edit: false },
// { uuid: 2, title: 'New Chat2', enable_edit: false },
],
chat:[
// {
//     uuid: 1, msg_list: [
//         { content: 'hello1', create_time: '2023-11-09 11:50:23', reversion: false, msgload: false },
//     ]
// },
// {
//     uuid: 2, msg_list: [
//         { content: 'xxx', create_time: '2023-11-09 11:50:23', reversion: false, msgload: false },
//     ]
// },
],

})

// 監(jiān)聽(tīng)響應(yīng)式數(shù)據(jù)
watch(left_data,(newValue, oldValue) =>{
if(newValue.chat.length>0){
        left_list_is_empty.value=false
}else{
        left_list_is_empty.value=true
}
localStorage.setItem('chatweb',JSON.stringify(newValue))
})

// 創(chuàng)建響應(yīng)式變量后只執(zhí)行一次輸出的需求
watchEffect(() =>{
// 讀取 localstorage
const data =localStorage.getItem('chatweb')
if(data){

const history =JSON.parse(data)
        left_data.left_list= history.left_list
        left_data.chat= history.chat
}else{
        left_list_is_empty.value=true
}
})



// 添加側(cè)壁欄item
functionaddLeftListEle(){
const uuid =randomUuid()
    left_data.left_list.push({
uuid: uuid,
title:`新的對(duì)話${uuid}`,
enable_edit:false
})
    left_data.chat.push({
uuid: uuid,
msg_list:[]
})

// 路由跳轉(zhuǎn)到最新的item
    router.push({name:'chat',params:{uuid: uuid }})

}
// 點(diǎn)擊側(cè)邊欄某個(gè)item的編輯按鈕
functioneditLeftListEle(uuid){
const index = left_data.left_list.findIndex(v => v.uuid== uuid)
    left_data.left_list[index].enable_edit=!left_data.left_list[index].enable_edit

// all_data.left_list[index].enable_edit = !all_data.left_list[index].enable_edit
// ls.updateLeftListItemEnableEditButton(uuid)

}

// 點(diǎn)擊側(cè)邊欄某個(gè)item的刪除按鈕
asyncfunctiondelLeftListEle(uuid){


var index = left_data.left_list.findIndex(v => v.uuid== uuid)
    left_data.left_list.splice(index,1)

const chat_index = left_data.chat.findIndex(v => v.uuid== uuid)
    left_data.chat.splice(chat_index,1)

if(left_data.chat.length==0){
        left_list_is_empty =true
}else{
awaitnextTick()
// 默認(rèn)跳轉(zhuǎn)到最新的 chat
const last_chat_uuid = left_data.chat[left_data.chat.length-1].uuid

        router.push({name:'chat',params:{"uuid": last_chat_uuid }})
}
}

// 獲取每個(gè) chat 的msg list
functiongetMsgList(uuid){

if(uuid && uuid !=undefined){
var index = left_data.chat.findIndex(v => v.uuid== uuid)
if(index ==-1){
return[]
}
return left_data.chat[index].msg_list
}
return[]

}

functionrandomUuid(){
var len =9
var uuid ='';
for(let i =0; i < len; i++){
        uuid +=Math.floor(Math.random()*10)
}
returnNumber(uuid,10)
}

// 監(jiān)聽(tīng)側(cè)邊欄item的回車(chē)事件
functionsubmit(index){
editLeftListEle(index)
}

// 發(fā)送消息
functionaddMessageListItem(uuid){
if(input_area_value.value.length<=2){
        message.info('內(nèi)容長(zhǎng)度不得小于2')
returnfalse
}
var index = left_data.chat.findIndex(v => v.uuid== uuid)
constnow_t=(newDate()).toLocaleString('sv-SE',{"timeZone":"PRC"})
    left_data.chat[index].msg_list.push({
content: input_area_value.value,
create_time:now_t,
reversion:true,
msgload:false
})

const body ={
config:{},
input: input_area_value.value// 按要求的格式拼接

};

// 清空編輯框
    input_area_value.value=''
var ele =document.getElementById("msgArea")
    ele.scrollTop= ele.scrollHeight+ ele.offsetHeight

// 添加一個(gè)占位消息,表示正在加載
    left_data.chat[index].msg_list.push({
content:'',
create_time:now_t,
reversion:false,
msgload:true
})
console.info("開(kāi)始發(fā)送消息...")


// 使用編輯框中的 URL 進(jìn)行請(qǐng)求
const url = setting.server_url;// 獲取 URL

if(setting.type==='stream_log'){
startStream(index, body, url);// 傳遞 URL
}else{
startRequest(index, body, url);// 傳遞 URL
}
}

functionbuildMessagePromt(index){
const res =[]
    left_data.chat[index].msg_list.forEach(v =>{
let role = v.reversion?'user':'assistant'
        res.push({
role: role,
content: v.content
})
})
    res.pop()
return res
}

asyncfunctionstartRequest(index, body, url){
const key =LLM_APIKEY.value;
let response =null;

try{
    response =awaitfetch(url,{
method:"POST",
headers:{
"Content-Type":"application/json",
"Accept":"application/json",// 使用 JSON 作為接受格式
"Authorization":`Bearer ${key}`,// 如果需要 API 密鑰
},
mode:"cors",
body:JSON.stringify(body),
});

    left_data.chat[index].msg_list[left_data.chat[index].msg_list.length-1].msgload=false;
}catch(error){
    left_data.chat[index].msg_list[left_data.chat[index].msg_list.length-1].content+=`發(fā)生了一些錯(cuò)誤:${error.message}`;
returnfalse;
}

if(response.status!==200){
    left_data.chat[index].msg_list[left_data.chat[index].msg_list.length-1].content+=`發(fā)生了一些錯(cuò)誤:${response.status}-${response.statusText}`;
returnfalse;
}

try{
const data =await response.json();
if(data && data.output){// 檢查數(shù)據(jù)是否存在并包含 output
const outputText = data.output;
const currentContent = left_data.chat[index].msg_list[left_data.chat[index].msg_list.length-1].content;
if(!currentContent.includes(outputText)){
        left_data.chat[index].msg_list[left_data.chat[index].msg_list.length-1].content+= outputText;
}
}else{
thrownewError('返回的數(shù)據(jù)結(jié)構(gòu)不符合預(yù)期');
}
}catch(e){
console.error('Error parsing JSON:', e);
    left_data.chat[index].msg_list[left_data.chat[index].msg_list.length-1].content+='解析響應(yīng)時(shí)發(fā)生錯(cuò)誤';
}

returntrue;// 返回成功狀態(tài)
}


asyncfunctionstartStream(index, body, url){
let response =null;

try{
    response =awaitfetch(url,{
method:"POST",
headers:{
"Content-Type":"application/json",
"Accept":"text/event-stream",
"Accept-Encoding":"gzip, deflate, br, zstd",
"Accept-Language":"zh-CN,zh;q=0.9"
},
mode:"cors",
body:JSON.stringify(body),
});

    left_data.chat[index].msg_list[left_data.chat[index].msg_list.length-1].msgload=false;
}catch(error){
    left_data.chat[index].msg_list[left_data.chat[index].msg_list.length-1].content+=`發(fā)生了一些錯(cuò)誤:${error.message}`;
returnfalse;
}

if(response.status!==200){
    left_data.chat[index].msg_list[left_data.chat[index].msg_list.length-1].content+=`發(fā)生了一些錯(cuò)誤:${response.status}-${response.statusText}`;
returnfalse;
}

const reader = response.body.getReader();
const decoder =newTextDecoder('utf-8');
let buffer ='';

constreadStream=async()=>{
const{ done, value }=await reader.read();

if(done){
console.log('Stream reading complete');
return;
}

    buffer += decoder.decode(value,{stream:true});

let completeData ='';
let separatorIndex;
while((separatorIndex = buffer.indexOf('\n'))!==-1){
      completeData = buffer.slice(0, separatorIndex).trim();
      buffer = buffer.slice(separatorIndex +1);

if(completeData.startsWith('data: ')){
const jsonString = completeData.slice(6);// 去掉 'data: '
try{
const data =JSON.parse(jsonString);
          data.ops.forEach(op =>{
if(op.op==='add'&& op.path.includes('/streamed_output')){
const outputText = op.value;
if(outputText){
const currentContent = left_data.chat[index].msg_list[left_data.chat[index].msg_list.length-1].content;
if(!currentContent.includes(outputText)){
                  left_data.chat[index].msg_list[left_data.chat[index].msg_list.length-1].content+= outputText;
}
}
}
});
}catch(e){
console.error('Error parsing JSON:', e,'Complete Data:', completeData);
}
}else{
console.log('No valid JSON found in:', completeData);
}
}

returnreadStream();
};

returnreadStream();
}




functionhasLogin(compomentName = 'Login'){
if(compomentName =='login')return instaceV.proxy.hasLogin?'hidden':'';
if(compomentName =='main')return instaceV.proxy.hasLogin?'':'hidden';
}

functionshowSettingFunc(){
    showSetting.value=!showSetting.value
}

// 刪除當(dāng)前會(huì)話記錄
functiondeleteChatItemHistory(uuid){
const index = left_data.chat.findIndex(v => v.uuid== uuid);
    left_data.chat[index].msg_list=[]
    message.success('當(dāng)前會(huì)話記錄已清理')
}

functionconfirmSettings(){
// 這里可以添加保存設(shè)置的邏輯
console.log("設(shè)置已確認(rèn):", setting);
// 例如,你可以關(guān)閉模態(tài)框
  showSetting.value=false;
}

// 當(dāng)前會(huì)話下載為圖片
asyncfunctiondom2img(){
    centerLodding.value=true

var ele =document.querySelectorAll(".msgItem")
var msgAreaDom =document.getElementById("msgArea")

const width = msgAreaDom.offsetWidth*2
const height = msgAreaDom.scrollHeight*1.5


let canvas1 =document.createElement('canvas');
let context = canvas1.getContext('2d');
    canvas1.width= width;
    canvas1.height= height;
// 繪制矩形添加白色背景色
    context.rect(0,0, width, height);
    context.fillStyle="#fff";
    context.fill();

let beforeHeight =0
for(let i =0; i < ele.length; i++){
const dom_canvas =awaithtml2canvas(ele[i],{
scrollX:0,
scrollY:0,
height: ele[i].scrollHeight,
width: ele[i].scrollWidth,
})

// var image = dom_canvas.toDataURL("image/png");
        context.drawImage(dom_canvas,0, beforeHeight, dom_canvas.width, dom_canvas.height)
        beforeHeight = beforeHeight + dom_canvas.height;

}
var image = canvas1.toDataURL("image/png").replace("image/png","image/octet-stream");
var link =document.getElementById("link");
    link.setAttribute("download",`chatweb-${(new Date()).getTime()}.png`);
    link.setAttribute("href", image);
    link.click();

    centerLodding.value=false
    message.success('圖片下載完成')

}

</script>

服務(wù)部署

# 切換目錄到chatweb目錄
cd chatweb

# 安裝依賴(lài)的組件
npm install

# 啟動(dòng)服務(wù)
npm run dev

運(yùn)行效果:

基于Agent的金融問(wèn)答系統(tǒng):前后端流程打通-AI.x社區(qū)

接口聯(lián)調(diào)

接下來(lái),通過(guò)瀏覽器的開(kāi)發(fā)者工具進(jìn)行接口調(diào)試

  1. 在瀏覽器中打開(kāi) http://localhost:5173/
  2. 點(diǎn)擊開(kāi)始按鈕切換頁(yè)面至聊天頁(yè)面,打開(kāi)瀏覽器的開(kāi)發(fā)者工具

基于Agent的金融問(wèn)答系統(tǒng):前后端流程打通-AI.x社區(qū)

  1. 輸入問(wèn)題后點(diǎn)擊發(fā)送,觀察右側(cè)開(kāi)發(fā)者工具的Console面板,觀察請(qǐng)求發(fā)送情況,以及返回的響應(yīng)數(shù)據(jù)。


基于Agent的金融問(wèn)答系統(tǒng):前后端流程打通-AI.x社區(qū)


具體調(diào)試遇到的問(wèn)題不盡相同,所以本章不再贅述具體調(diào)試方式,請(qǐng)讀者根據(jù)問(wèn)題自行調(diào)試。

待整體調(diào)試通過(guò)之后,問(wèn)答系統(tǒng)的前后端即完成主流程。


本文轉(zhuǎn)載自公眾號(hào)一起AI技術(shù) 作者:Dongming

原文鏈接:??https://mp.weixin.qq.com/s/7NjAO2a_6j8QU_3069_Jbw??

?著作權(quán)歸作者所有,如需轉(zhuǎn)載,請(qǐng)注明出處,否則將追究法律責(zé)任
標(biāo)簽
已于2024-11-25 10:35:30修改
收藏
回復(fù)
舉報(bào)
回復(fù)
相關(guān)推薦