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>
相关推荐
NiceCloud喜云8 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
wordbaby8 小时前
React Native + RNOH:跨页面数据回传的最佳实践与避坑指南
前端·react native
丷丩8 小时前
MapLibre GL JS第22课:查看本地GeoJSON
前端·javascript·map·mapbox·maplibre gl js
Front思9 小时前
AI前端工程师需要具备能力+
前端·人工智能·ai
ZC跨境爬虫11 小时前
跟着 MDN 学CSS day_29:(掌握文本与字体样式的核心艺术)
前端·css·ui·html·tensorflow
李子琪。12 小时前
网络空间安全深度实战:CSRF 漏洞原理剖析与基于 Token 的纵深防御体系构建(全栈实验报告)
前端·安全·csrf
冰暮流星12 小时前
javascript之history对象介绍
前端·笔记
IT_陈寒12 小时前
Vite热更新失灵?你可能漏了这个配置
前端·人工智能·后端
丷丩12 小时前
MapLibre GL JS第19课:实时更新要素
前端·javascript·gis·map·mapbox·maplibre gl js
Mr.Daozhi12 小时前
RAG 进阶实战:跑通 Demo 后我连续翻了 6 次车,逐一修复才真正可用(含 Gradio Web 版)
前端·数据库·langchain·大模型·gradio·rag·科研工具