Last active
December 29, 2025 22:37
-
-
Save iTrooz/a2c3f0f50da2ec31d075ca751985ab4b to your computer and use it in GitHub Desktop.
Return Cloudflare AIChatAgent response from raw string (2 solutions)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export class Chat extends AIChatAgent<Env, CommonState> { | |
| async sendChatMessage(s: string, role: "user" | "assistant") { | |
| const msg = { | |
| sentFromServer: true, | |
| id: generateId(), | |
| role, | |
| parts: [ | |
| { | |
| type: "text", | |
| text: s, | |
| } | |
| ], | |
| metadata: { | |
| createdAt: new Date() | |
| } | |
| }; | |
| await this.saveMessages([...this.messages, msg as any]); | |
| } | |
| async onChatMessage() { | |
| // Ensure we do not reply to ourselves | |
| let lastMsg = this.messages[this.messages.length - 1]; | |
| if ((lastMsg as any).sentFromServer) return; | |
| this.sendChatMessage("Hello !", "assistant"); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export class Chat extends AIChatAgent<Env, CommonState> { | |
| async responseFromString(s: string): Promise<Response> { | |
| let id = Math.random().toString(36).slice(2, 7); | |
| let TEXT = `\ | |
| data: {"type":"text-start","id":"${id}"} | |
| data: {"type":"text-delta","id":"${id}","delta":" ${s}"} | |
| data: {"type":"text-end","id":"${id}"} | |
| data: [DONE] | |
| `; | |
| const resp = new Response(TEXT, { | |
| headers: { | |
| "Content-Type": "text/event-stream", | |
| } | |
| }); | |
| return resp; | |
| } | |
| async onChatMessage() { | |
| return this.responseFromString("Hello !"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment