我在Nuxt.js应用程序中使用Vercel's AI SDK和它的useChat utility hook来创建聊天界面.我在一个 Select 菜单中有不同的代理(例如,普通、锻炼、心脏病),并且我想在useChats()‘S body对象中发送所选代理的值以及在服务器端 Select 适当系统提示的API请求.

However, I'm facing an issue where the 100 object is not updated reactively when the selected agent changes in the UI.

出于某种原因,这部分代码对用户SELECT没有react : body: { agent: selectedAgent.value } // <---- for some reason this is not being updated on menu change

这会导致客户端始终发送与General相同的agent:

image

Full client-side details below:

<template>
<div class="text-center mt-6">
      <select class="border border-2" v-model="selectedAgent" @change="changeAgent">
        <option v-for="(agent, index) in agentsList" :key="index" :value="agent">{{ agent }}</option>
      </select>
<div>
      <div v-for="m in messages" key="m.id" >
        {{ m.role === "user" ? "User: " : "AI: " }}
        {{ m.content }}
      </div>
<form @submit="handleSubmit">
        <input v-model="input" />
      </form>
</template>


<script>
import {useChat} from 'ai/vue'
const agentsList = ['General', 'Exercise', 'Cardiology']
const selectedAgent = ref(agentsList[0]); // Default agent

const { messages, input, handleSubmit } = useChat({
  api: '/api/chat',
  headers: { 'Content-Type': 'application/json' },
  body: { agent: selectedAgent.value } // <---- for some reason this is not being updated on menu change
})

const changeAgent = (e) => {
  selectedAgent.value = e.target.value;
  // Clear the chat messages when the agent is changed
  messages.value = []
};
</script>

完整的代码和演示:

GitHub回购:https://github.com/dosstx/nuxt-openai-demo

直播URL:https://main--chipper-snickerdoodle-13271f.netlify.app/

Server-side code that expects the agent value from the request body (server/api/chat.ts):

输出为:

import OpenAI from 'openai'
import { OpenAIStream } from 'ai'
import { CreateChatCompletionRequestMessage } from 'openai/resources/chat'

export default defineLazyEventHandler(async () => {
  const apiKey = useRuntimeConfig().OPENAI_API_KEY;
  if (!apiKey) throw new Error('Missing OpenAI API key')
  const openai = new OpenAI({
    apiKey: apiKey
  })

  const agents = {
    Exercise: [
      // ... system prompts for exercise agent
    ],
    Cardiology: [
      // ... system prompts for cardiology agent
    ],
    General: [
      // ... system prompts for General agent
    ]
    // ... other agents
  }

  return defineEventHandler(async event => {

    // Extract the `prompt` and `agent` from the body of the request
    const { messages, agent } = (await readBody(event)) as {
      messages: CreateChatCompletionRequestMessage[],
      agent: keyof typeof agents // Expecting one of the keys from the agents object
    }

    // Select the agent's system prompts
    const agentSystemMessages = agents[agent] || []

    console.log('from server: ', messages, agent)

    try {
      // Create a chat completion request with the system prompts and messages
      const request = {
        model: 'gpt-3.5-turbo',
        stream: true,
        messages: [...agentSystemMessages, ...messages],
        temperature: 0.2,
        // top_p: 1,
        frequency_penalty: 0,
        presence_penalty: 0,
        max_tokens: 400 // set this limit to length of assistants responses
      };

      // Send the request to OpenAI and get a response stream
      const response = await openai.chat.completions.create(request);

      // Return an OpenAIStream object that wraps the response stream
      return OpenAIStream(response)
    } catch (error) {
      console.error(error);
      // Return a 500 Internal Server Error response with a specific message
      return {
        status: 500,
        body: { error: 'An error occurred while processing your request. Please try again later.' },
      };
    }
  })
})

环境:

  • Nuxt版本:3.6.5

我试过的是:

  • 我已经更新了changeAgent函数中的selectedAgent值,但useChat钩子中的body对象没有反映更新后的值.

问题:

如何使useChat钩子内的body对象对 Select 菜单中所选代理的更改做出react ?需要将此值发送到服务器以 Select 适当的系统提示.如有任何见解或指导,我们将不胜感激.

推荐答案

useChat Composable存在设计问题,并且在选项中没有提供提供被动式body的方法.通常,Vue惯用的解决方案是在Composable的参数中传递react 值的引用,这就是引用模式所服务的目的.

一旦这个选项has been provided,它应该被用作:

...
const body = computed(() => ({ agent: selectedAgent.value }));

const { messages, input, handleSubmit } = useChat({
  body,
  ...
})

Vue.js相关问答推荐

在VITE-VUE APP-DEV模式上重定向HTTP请求

元素不会对react 性props 的更改做出react

VueJS 中的 VisJS 时间轴:带有图像的项目放错了位置

是否可以使用 Vuetify/VueJS 为轮播设置默认图像而不是第一个图像?

在 VueJS 中为 Get、Post、Patch 配置全局标头的最佳方法

Axios Intercept 在第一次调用时未从 localStorage 应用令牌

如何将 vuejs 项目部署到 heroku

在 Vue.js 中动态挂载单个文件组件

在 vue.js 中获取当前时间和日期

如何为使用 Vuex store的 Vue 表单组件编写 Jest 单元测试?

如何在 vuejs 中异步加载图像 src url?

React.js 是否有类似 Vue.js

取消选中单选按钮

如何在 vuetify 中将工具提示添加到数据表标题?

如何避免在 Vue 中一直写 this.$store.state.donkey 的需要?

如何从 vue 组件调用 App.vue 中的方法

在 VUE JS 的光标位置插入字符

来自 Vue.js 的 ESLint 插件的消息中的LHS是什么意思?

如何修复套接字 io 中的 400 错误错误请求?

这个业务逻辑有多少属于 Vuex?