Skip to content

Idiomatic way to handle final message in onChatMessage #1276

@O4epegb

Description

@O4epegb

Potentially this is not an agents issue even, but it feels "buggy" that onFinish callback of toUIMessageStreamResponse does not have id of the last message (responseMessage or last message in messages).

Example might explain it better:

export class ChatAgent extends AIChatAgent<Env> {
  async onChatMessage() {
    // ......
    return result.toUIMessageStreamResponse({
      originalMessages: this.messages,
      onFinish: ({ messages, responseMessage }) => {
        // neither of these has id for the last message
        console.log("Chat finished. Final messages:", messages);
        console.log("Final response message:", responseMessage);

        setTimeout(() => {
          // here you can actually grab latest message and it has an id
          // but it feels hacky that you have to wait for the next tick to get it
          // not sure if this is a correct way
          console.log(this.messages);
        });
      }
    });
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions