多轮会话和流式输入

本主题介绍向 Cortex Code Agent SDK 发送提示的主要方法:单提示查询**用于您希望 ``query()`` 为您管理会话生命周期时,**流式输入 用于增量提示传递,多轮会话 用于交互式对话,可在多次交互之间维护上下文。

输入模式

SDK 提供三种输入模式:

模式

何时使用

API

单提示输入

使用 query() 发送一个提示,并让 SDK 为您管理会话生命周期。输出仍采用流式传输形式,直到代理生成 ResultMessage

TypeScript 和 Python 中的 query()

流式输入

通过异步可迭代对象而不是单个提示字符串,以增量方式发送用户消息

TypeScript 和 Python 中的 query(),以及 TypeScript 中的 Query.streamInput()

多轮会话

交互式对话:发送多个提示、维护上下文、控制会话生命周期

createCortexCodeSession() (TypeScript) 或 CortexCodeSDKClient (Python)

单提示查询

query() 函数是使用 SDK 的最简单方式。它可以发送单个提示字符串或 SDK 用户消息的异步可迭代对象,且会流回事件,直到代理生成 ResultMessage。在此模式下,“单提示”是指输入模式:输出仍正常流式传输。

import { query } from "cortex-code-agent-sdk";

for await (const message of query({
  prompt: "Explain how the auth module works",
  options: { cwd: process.cwd() },
})) {
  if (message.type === "assistant") {
    for (const block of message.content) {
      if (block.type === "text") process.stdout.write(block.text);
    }
  }
}

query() 函数会为您管理整个会话生命周期:它会创建会话、发送提示、生成事件,并在结果达成或迭代器耗尽时关闭会话。

这与 maxTurns/max_turns 不同。单提示查询仍允许代理在您配置的轮次上限内,根据需要进行任意数量的内部轮次。设置 maxTurns: 1max_turns=1 是一个独立的约束条件,它将代理限制为仅进行一个轮次,并且可以生成 error_max_turns 结果。

多轮会话

对于需要多次交互的对话,请使用会话。代理会保留轮次之间的上下文,因此后面的提示可以引用先前轮次中读取的文件、执行的分析和讨论的主题。

import { createCortexCodeSession } from "cortex-code-agent-sdk";

const session = await createCortexCodeSession({ cwd: process.cwd() });

// First turn
await session.send("Read the database connection module");
for await (const event of session.stream()) {
  if (event.type === "assistant") {
    for (const b of event.content) {
      if (b.type === "text") process.stdout.write(b.text);
    }
  }
  if (event.type === "result") break;
}

// Second turn -- context from the first turn is preserved
await session.send("What error handling patterns does it use?");
for await (const event of session.stream()) {
  if (event.type === "assistant") {
    for (const b of event.content) {
      if (b.type === "text") process.stdout.write(b.text);
    }
  }
  if (event.type === "result") break;
}

await session.close();

会话生命周期

  1. 调用 createCortexCodeSession(options) 启动会话。这会启动 CLI 进程。

  2. 调用 session.send(prompt) 发送用户消息。

  3. 迭代 session.stream() 接收响应。看到 result 事件时停止迭代。

  4. 重复步骤 2 至 3 以进行其他轮次。

  5. 调用 session.close() 结束会话并清理进程。

继续上一个会话

您可以恢复上一个会话中的对话。代理会加载之前的对话历史记录,并从中断处继续。

import { createCortexCodeSession } from "cortex-code-agent-sdk";

// Continue the most recent conversation
const session = await createCortexCodeSession({
  cwd: process.cwd(),
  continue: true,
});

await session.send("What were we working on?");
for await (const event of session.stream()) {
  if (event.type === "result") break;
}
await session.close();

您还可以按 ID 恢复特定会话:

const session = await createCortexCodeSession({
  cwd: process.cwd(),
  resume: "previous-session-id",
});

创建会话分支

创建分支会创建一个新会话,该会话从现有会话的完整对话历史记录开始。不会修改原始会话。这对于在不丢失原始对话的情况下探索替代方法非常有用。

import { createCortexCodeSession } from "cortex-code-agent-sdk";

const forked = await createCortexCodeSession({
  cwd: process.cwd(),
  resume: "previous-session-id",
  forkSession: true,
});

await forked.send("Let's try a different approach");
for await (const event of forked.stream()) {
  if (event.type === "result") break;
}
await forked.close();

中断轮次

您的应用程序可以在代理处理轮次时请求中断。这与在 CLI 中按 Esc 具有相同的效果。会话保持活动状态,以供后续提示使用。

直接中断调用

调用 interrupt() 方法直接发送中断请求:

import { createCortexCodeSession } from "cortex-code-agent-sdk";

const session = await createCortexCodeSession({ cwd: process.cwd() });

await session.send("Analyze every file in this large codebase");

// Interrupt after 10 seconds
setTimeout(() => session.interrupt(), 10_000);

for await (const event of session.stream()) {
  if (event.type === "result") break;
}

// Session is still alive -- send another prompt
await session.send("Just summarize the top-level structure instead");
for await (const event of session.stream()) {
  if (event.type === "result") break;
}

await session.close();

中止控制器/中止事件

您还可以在会话创建时传递中止信号。当信号触发时,SDK 会自动发送相同的中断请求。

import { createCortexCodeSession } from "cortex-code-agent-sdk";

const controller = new AbortController();

const session = await createCortexCodeSession({
  cwd: process.cwd(),
  abortController: controller,
});

await session.send("Analyze every file in this large codebase");

// Trigger interrupt from anywhere
setTimeout(() => controller.abort(), 10_000);

for await (const event of session.stream()) {
  if (event.type === "result") break;
}
await session.close();

备注

在 TypeScript 中,传递 AbortController,其 abort() 方法会触发中断请求。在 Python 中,传递 asyncio.Event,其 set() 方法会触发中断请求。在这两种情况下,会话在中断后仍保持活动状态。