|
| 1 | +# Event client |
| 2 | + |
| 3 | +The `@tanstack/ai` package offers you an event client for observability and debugging purposes. |
| 4 | +It's a fully type-safe decoupled event-driven system that emits events whenever they are internally |
| 5 | +triggered and you can subscribe to those events for observability. |
| 6 | + |
| 7 | +Because the same event client is used for both the TanStack Devtools system and observability locally it will work |
| 8 | +by subscribing to the event bus and emitting events to/from the event bus into the listeners by default. If you |
| 9 | +want to subscribe to events in production as well you need to pass in a third argument to the `on` function, |
| 10 | +the `{ withEventTarget: true }` option. |
| 11 | + |
| 12 | +This will not only emit to the event bus (which is not present in production), but to the current eventTarget that |
| 13 | +you will be able to listen to. |
| 14 | + |
| 15 | +## Server events |
| 16 | + |
| 17 | +There are both events that happen on the server and on the client, if you want to listen to either side you just need to |
| 18 | +subscribe on the server/client respectfully. |
| 19 | + |
| 20 | +Here is an example for the server: |
| 21 | +```ts |
| 22 | +import { aiEventClient } from "@tanstack/ai/event-client"; |
| 23 | + |
| 24 | +// server.ts file or wherever the root of your server is |
| 25 | +aiEventClient.on("chat:started", e => { |
| 26 | + // implement whatever you need to here |
| 27 | +}) |
| 28 | +// rest of your server logic |
| 29 | +const app = new Server(); |
| 30 | +app.get() |
| 31 | +``` |
| 32 | + |
| 33 | +## Client events |
| 34 | + |
| 35 | +Listening on the client is the same approach, just subscribe to the events: |
| 36 | + |
| 37 | +```tsx |
| 38 | +// App.tsx |
| 39 | +import { aiEventClient } from "@tanstack/ai/event-client"; |
| 40 | + |
| 41 | +const App = () => { |
| 42 | + useEffect(() => { |
| 43 | + const cleanup = aiEventClient.on("client:tool-call-updated", e => { |
| 44 | + // do whatever you need to do |
| 45 | + }) |
| 46 | + return cleanup; |
| 47 | + },[]) |
| 48 | + return <div></div> |
| 49 | +} |
| 50 | +``` |
| 51 | + |
| 52 | + |
0 commit comments