Agent流式输送

篇章目录

修改创建LLM方法

设置streaming为true

ts 复制代码
function createLLM() {
  // 创建LLM
  const llm = new ChatOpenAI({
   ...... // 省略其它
    streaming: true, // 设置
    
  })
  return llm
}

修改chat方法

ts 复制代码
export default async function chat(
  input: string,
  onChat: (text: string) => void,
  messages: Chat[] = []) {
    ......
  const res = await chain.stream({
    chat_history: allMessages,
    input: input,
  })

  let resText = ""
  // 必须等待每一段数据到达,才能循环处理
  for await (const chunk of res) {
    const content = String(chunk.content) ?? ""
    resText += content
    if (onChat) {
      onChat(String(chunk.content) || "")
    }
  }
}

pinia状态管理

请参考pinia文档

ts 复制代码
import type { Chat } from "@/types/chat";
import { defineStore } from "pinia";
import { reactive } from "vue";

export const useChat = defineStore('chat', () => {
  const history = reactive<Chat[]>([])

  const add = (chat: Chat) => {
    return history.push(chat) - 1 // 返回新增的索引

  }

  return { history, add }
})

输入组件修改

vue 复制代码
<template>
    ......
</template>

<script setup lang="ts">
import chat from '@/agent';
import type { Chat } from '@/types/chat';
import { ElButton, ElMessage } from 'element-plus';
import { computed, ref } from 'vue';
import { useChat } from '@/stores/chat'; // 导入pinia状态管理
const value = ref<string>('');
const loading = ref(false);
const history = useChat().history; // 应用全局状态
const isDisabled = computed(() => !value.value && !loading.value);
const btnText = computed(() => loading.value ? '正在思考...' : '发送');

function randomId() {
  return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
}
const onChatHandler = async () => {
  if (!value.value) return ElMessage.error('请输入内容');
  loading.value = true;

  // 添加用户消息
  useChat().add({
    id: randomId(),
    name: 'user',
    messages: value.value,
    role: "user",
    created_at: new Date(),
  })

  // 获取AI回复
  const aiResponseItemIndex = useChat().add({
    id: randomId(),
    name: 'assistant',
    messages: '',
    role: "assistant",
    created_at: new Date(),
  })

  try {
    await chat(value.value, (text) => {

      history[aiResponseItemIndex]!.messages += text

    }, history);

  } catch (error) {
    if (error instanceof Error)
      ElMessage.error('请求错误' + error.message);
  } finally {
    value.value = '';
    loading.value = false;
  }
};

</script>

主页面修改

vue 复制代码
<script setup lang="ts">
import InputArea from '@/components/InputArea.vue';
import { useChat } from '@/stores/chat';

const { history } = useChat()

</script>

<template>

  <div>
    <div>
      <InputArea />
      {{ history }}
    </div>
  </div>
</template>
相关推荐
不简说17 分钟前
JS 代码技巧 vol.9 — 20 个设计模式在真实项目里的应用
前端·javascript·github
CoderLiu21 分钟前
Agent 工程的下一层:为什么「把流程写成图」还不够,还需要 Graph Engineering
前端·人工智能·后端
勇往直前plus25 分钟前
Vue3(篇三) Element Plus
前端·javascript·typescript·vue
爱勇宝34 分钟前
《道德经》第 8 章:真正高级的能力,像水一样成事
前端·后端·程序员
Revolution6140 分钟前
数组本身没有 map,为什么还能直接调用:原型链怎样查找属性
前端·javascript·面试
bonechips40 分钟前
RAG实战(一):EPUB 加载、文本切割与向量入库
前端·数据库
swipe41 分钟前
10|(前端转全栈)库存扣减为什么最容易出事故?SKU、并发与原子更新
前端·后端·全栈
cdcdhj41 分钟前
vue3中的watchEffect()监听,什么时候监听,什么时候清理,什么时候停止
前端·javascript·vue.js
huabuyu42 分钟前
几百 MB 的文件为什么等几分钟才能打开?文件分片下载与渐进预览原理
前端·javascript
虚惊一场43 分钟前
麻将桌上的并发控制:扫码进房、乐观版本与零和结算
前端·javascript