| 16 | providedIn: 'root' |
| 17 | }) |
| 18 | export class AgentService { |
| 19 | userInput = signal(''); |
| 20 | |
| 21 | // Only set this on the initial request |
| 22 | // Note: for demonstration purposes only; use security best practices for managing sessions |
| 23 | sessionId = linkedSignal<string, string>({ |
| 24 | source: () => this.agentResource.value()?.agentResponse || '', |
| 25 | computation: (_agentResponse, previous): string => |
| 26 | (!previous ? Date.now() + '' + Math.floor(Math.random() * 1000000000) : previous.value) |
| 27 | }); |
| 28 | |
| 29 | // Set to true on the initial request, otherwise false to preserve the session |
| 30 | clearSession = linkedSignal({ |
| 31 | source: () => this.agentResource.value()?.agentResponse, |
| 32 | computation: (_agentResponse, previous): boolean => !previous |
| 33 | }); |
| 34 | |
| 35 | chat = linkedSignal<string, Chat[]>({ |
| 36 | source: () => this.agentResource.value().agentResponse, |
| 37 | computation: (agentResponse, previous): Chat[] => { |
| 38 | if (agentResponse === '') { |
| 39 | return previous?.value || []; |
| 40 | } |
| 41 | |
| 42 | const chatItem = this.chatItem(agentResponse, AGENT); |
| 43 | return (previous) ? [chatItem, ...previous.value] : [chatItem]; |
| 44 | } |
| 45 | }); |
| 46 | |
| 47 | agentResource = resource({ |
| 48 | defaultValue: { agentResponse: '', options: [] }, |
| 49 | request: () => this.userInput(), |
| 50 | loader: ({request}): Promise<AgentResponse> => { |
| 51 | return runFlow({ url: ENDPOINT, input: { |
| 52 | userInput: request, |
| 53 | sessionId: this.sessionId(), |
| 54 | clearSession: this.clearSession() |
| 55 | }}); |
| 56 | } |
| 57 | }); |
| 58 | |
| 59 | updateChatFromUser(userInput: string): void { |
| 60 | const chatItem = this.chatItem(userInput, USER); |
| 61 | this.chat.update(value => [chatItem, ...value]); |
| 62 | this.userInput.set(userInput); |
| 63 | } |
| 64 | |
| 65 | chatItem(text: string, role: Role): Chat { |
| 66 | return { |
| 67 | id: Math.floor(Math.random() * 2000), |
| 68 | role, |
| 69 | text |
| 70 | }; |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | type Role = 'AGENT' | 'USER'; |
| 75 | |