@google/genai SDK:chat.sendMessage配置会覆盖ai.chats.create配置吗?

人工智能 2026-07-10

我在一个Vue.js应用中使用官方的 @google/genai SDK。我的目标是在聊天会话中建立一个持久的 systemInstruction,同时保留使用 AbortController 取消单个请求的能力。

因为一个 AbortController 是一次性的,我必须新建一个并将它的 abortSignal 传入每个单独的 sendMessage 调用。

然而,这样做似乎完全覆盖了在 chats.create 中建立的基础配置。LLM完全忘记了系统提示。

下面是一个最小可复现的示例:

<script setup>
import { ref } from 'vue';
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "BLABLABLABLABLABLA" });

const chat = ai.chats.create({
  model: "gemini-3-flash-preview",
  config: {
    systemInstruction: "You are an expert about tennis. Don't reply to other kinds of requests, but apologize and state that you're a tennis assistant only",
  }
});

const inputText = ref("");
const result = ref("");
let abortController;

async function sendRequest() {
  abortController = new AbortController();

  try {
    console.log("Sending message");
    const response = await chat.sendMessage({
      message: inputText.value,
      config: {
        abortSignal: abortController.signal
      }
    });
    console.log(response.text);
    result.value = response.text;
  }
  catch (e) {
    if (e && e.name === "AbortError") {
      console.log("Request was aborted");
    }
    else {
      console.log(e);
    }
  }
  finally{
    abortController = null;
  }
}

function abortRequest(){
  if(abortController){
    abortController.abort();
  }
  abortController = null;
}

</script>

<template>

  <input type="text" v-model="inputText">
  <button @click="sendRequest">Send</button>
  <button @click="abortRequest">Abort</button>
  <p>{{ result }}</p>

</template>

我原本期望这两个配置能够合并。结果,第二个配置完全覆盖了第一个。

  1. 这种完全覆盖配置的行为是SDK的预期吗?
  2. 是否将基础配置逐一展开并应用到每一个 sendMessage 调用(例如 config: { ...baseConfig, abortSignal })是这里唯一正确的架构方法?

解决方案

是的,这是预期中的行为;是的,你需要在每个请求中都将其展开应用。

你可以在 文档 中看到这一点。

请注意,单次请求的配置不会改变聊天级别的配置,也不会从它继承。如果你打算使用聊天默认配置中的某些值,必须将它们显式地拷贝到这个单次请求的配置中。

以及在 源码 代码中的实现。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章