bobbai00 commented on code in PR #9593:
URL: https://github.com/apache/texera/pull/9593#discussion_r4675716854


##########
agent-service/src/agent/texera-agent.ts:
##########
@@ -671,6 +695,26 @@ export class TexeraAgent {
         },
       });
 
+      // A turn the limit cut short has no closing answer, so the agent says 
why it stopped. A turn
+      // the user stopped needs no such notice, even when the stop lands on 
the last allowed step.
+      if (stoppedAtStepLimit && !this.abortController?.signal.aborted) {
+        stepIndex++;
+        const noticeStepId = this.generateStepId();
+        const noticeStep: ReActStep = {
+          id: noticeStepId,
+          parentId: this.head,
+          messageId,
+          stepId: stepIndex,
+          timestamp: Date.now(),
+          role: "agent",
+          content: stepLimitNotice(maxSteps),
+          isBegin: false,
+          isEnd: true,
+        };
+        this.addStep(noticeStep);
+        this.head = noticeStepId;
+      }

Review Comment:
   Done in 8dadf34cb: `addClosingStep(content)` sits next to `stepIndex`, and 
the notice, the stopped step and the error step each call it.



##########
agent-service/src/agent/texera-agent.spec.ts:
##########
@@ -729,6 +729,149 @@ describe("sendMessage", () => {
     expect(agent.getWorkflowState().getOperator("op1")).toBeDefined();
   });
 
+  /**
+   * A turn the step limit cuts short ends on a tool call, with no answer from 
the model. The agent
+   * then closes the turn itself, with a step that says why it stopped and 
what the user can do.
+   */
+  describe("step limit notice", () => {
+    const notice = (limit: string) =>
+      `I stopped because I reached the limit of ${limit} for one message, so 
the task may be unfinished. ` +
+      "Send another message to continue, or raise the limit in the agent's 
settings.";
+
+    /**
+     * A model that calls a tool on each of its first `toolCalls` calls and 
then answers "done".
+     * `reason` is the finish reason it reports along with a tool call, and 
`onCall` is called at
+     * the start of every call with the call's number.
+     */
+    const toolCallingModel = (
+      toolCalls: number,
+      options: { reason?: "tool-calls" | "stop" | "length"; onCall?: (n: 
number) => void } = {}
+    ) => {
+      let n = 0;
+      return new MockLanguageModelV4({
+        doGenerate: async () => {
+          n++;
+          if (n > 20) throw new Error("runaway");
+          options.onCall?.(n);
+          const callsTool = n <= toolCalls;
+          return {
+            content: callsTool
+              ? [
+                  {
+                    type: "tool-call",
+                    toolCallId: "c" + n,
+                    toolName: "deleteOperator",
+                    input: JSON.stringify({ operatorId: "ghost" }),
+                  },
+                ]
+              : [{ type: "text", text: "done" }],
+            finishReason: finish(callsTool ? (options.reason ?? "tool-calls") 
: "stop"),
+            usage: usage(1, 1),
+            warnings: [],
+          } as any;
+        },
+      });
+    };
+
+    test("closes a turn the limit cut short with a step that says so", async 
() => {
+      const agent = makeAgentWith(toolCallingModel(Infinity));
+      agent.updateSettings({ maxSteps: 3 });
+      // The server streams a step to the chat as it is announced, so what is 
announced is what
+      // the user sees.
+      const announced: ReActStep[] = [];
+      agent.setStepCallback(step => announced.push({ ...step }));
+      const res = await agent.sendMessage("go");
+      const steps = agent.getAllSteps();
+      expect(steps.map(s => [s.role, s.stepId, s.content, s.isBegin, 
s.isEnd])).toEqual([
+        ["user", 0, "go", true, true],
+        ["agent", 1, "", true, false],
+        ["agent", 2, "", false, false],
+        ["agent", 3, "", false, false],
+        ["agent", 4, notice("3 steps"), false, true],
+      ]);
+      expect(steps[4].toolCalls).toBeUndefined();
+      expect(steps[4].parentId).toBe(steps[3].id);
+      expect(steps[4].messageId).toBe(steps[0].messageId);
+      expect(agent.getHead()).toBe(steps[4].id);
+      expect(announced.at(-1)).toEqual(steps[4]);
+      expect(res.stopped).toBe(false);
+      expect(res.error).toBeUndefined();
+      expect(agent.getState()).toBe(AgentState.AVAILABLE);
+    });
+
+    test("adds nothing when the model answers on the last allowed step", async 
() => {
+      const agent = makeAgentWith(toolCallingModel(2));
+      agent.updateSettings({ maxSteps: 3 });
+      await agent.sendMessage("go");
+      expect(agent.getAllSteps().map(s => [s.stepId, s.content, 
s.isEnd])).toEqual([
+        [0, "go", true],
+        [1, "", false],
+        [2, "", false],
+        [3, "done", true],
+      ]);
+    });
+
+    test("names the limit the turn started with, in the singular for one 
step", async () => {
+      let agent!: TexeraAgent;
+      // A limit saved while the turn is in flight applies from the next 
message on.
+      const model = toolCallingModel(Infinity, { onCall: () => 
agent.updateSettings({ maxSteps: 7 }) });
+      agent = makeAgentWith(model);
+      agent.updateSettings({ maxSteps: 1 });
+      await agent.sendMessage("go");
+      expect(agent.getAllSteps().map(s => s.content)).toEqual(["go", "", 
notice("1 step")]);
+      await agent.sendMessage("go on");
+      expect(agent.getAllSteps().at(-1)?.content).toBe(notice("7 steps"));
+    });
+
+    test("still appears when the provider reports a tool call as a plain 
stop", async () => {
+      // The AI SDK goes on whenever a step's tool calls were executed, 
whatever finish reason the
+      // provider gave, so the limit is what ends this turn too.
+      const agent = makeAgentWith(toolCallingModel(Infinity, { reason: "stop" 
}));
+      agent.updateSettings({ maxSteps: 2 });
+      await agent.sendMessage("go");
+      expect(agent.getAllSteps().at(-1)?.content).toBe(notice("2 steps"));
+    });
+
+    test("adds nothing when a cut-off tool call ends the turn on the last 
allowed step", async () => {
+      // The call was never executed, so the turn would have ended here under 
any limit.
+      const agent = makeAgentWith(toolCallingModel(Infinity, { reason: 
"length" }));
+      agent.updateSettings({ maxSteps: 1 });
+      await agent.sendMessage("go");
+      expect(agent.getAllSteps().map(s => [s.stepId, s.content, 
s.isEnd])).toEqual([
+        [0, "go", true],
+        [1, "", true],
+      ]);
+    });
+
+    test.each([
+      ["before the limit", 1, ["go", "", "Generation stopped by user."]],
+      ["on the last allowed step", 2, ["go", "", ""]],
+    ])("adds nothing when the user stops the turn %s", async (_when, 
stopAtCall, contents) => {

Review Comment:
   Fixed here in c68286dd9 rather than as a follow-up. After `generateText` 
returns, `signal.throwIfAborted()` sends a stopped turn to the catch, so a stop 
on the last allowed step also ends with "Generation stopped by user." and 
`stopped: true`. The test now expects that in both rows.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to