Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

api.foreign-client-tool.ts

91 lines2.7 KB

1import { createFileRoute } from '@tanstack/react-router'
2​
3/**
4 * A provider-free AG-UI producer that is not TanStack AI (issue #1464). It
5 * writes the SSE bytes itself, the way Pydantic AI's `AGUIAdapter` does.
6 *
7 * Turn 1 calls the frontend tool `ping` and ends the run with the call
8 * unanswered. Per the AG-UI spec that is a success outcome, not an interrupt.
9 *
10 * Turn 2 answers once the request history carries the `ping` tool message.
11 */
12const TOOL_CALL_ID = 'call-ping-1'
13​
14function sse(events: Array<Record<string, unknown>>): Response {
15 const body = events.map((event) => `data: ${JSON.stringify(event)}\n\n`)
16 return new Response(body.join(''), {
17 headers: { 'Content-Type': 'text/event-stream' },
18 })
20​
21function toolResultContent(body: unknown): string | undefined {
22 if (typeof body !== 'object' || body === null || !('messages' in body)) {
23 return undefined
24 }
25 const messages: unknown = body.messages
26 if (!Array.isArray(messages)) return undefined
27 for (const message of messages) {
28 if (
29 typeof message === 'object' &&
30 message !== null &&
31 'role' in message &&
32 message.role === 'tool' &&
33 'toolCallId' in message &&
34 message.toolCallId === TOOL_CALL_ID &&
35 'content' in message &&
36 typeof message.content === 'string'
37 ) {
38 return message.content
39 }
40 }
41 return undefined
43​
44export const Route = createFileRoute('/api/foreign-client-tool')({
45 server: {
46 handlers: {
47 POST: async ({ request }) => {
48 const body: unknown = await request.json()
49 const threadId = 'foreign-client-tool'
50 const result = toolResultContent(body)
51​
52 if (result === undefined) {
53 const runId = 'run-1'
54 return sse([
55 { type: 'RUN_STARTED', threadId, runId },
56 {
57 type: 'TOOL_CALL_START',
58 toolCallId: TOOL_CALL_ID,
59 toolCallName: 'ping',
60 },
61 { type: 'TOOL_CALL_ARGS', toolCallId: TOOL_CALL_ID, delta: '' },
62 { type: 'TOOL_CALL_END', toolCallId: TOOL_CALL_ID },
63 {
64 type: 'RUN_FINISHED',
65 threadId,
66 runId,
67 outcome: { type: 'success' },
68 },
69 ])
70 }
71​
72 const runId = 'run-2'
73 return sse([
74 { type: 'RUN_STARTED', threadId, runId },
75 {
76 type: 'TEXT_MESSAGE_START',
77 messageId: 'answer',
78 role: 'assistant',
79 },
80 {
81 type: 'TEXT_MESSAGE_CONTENT',
82 messageId: 'answer',
83 delta: `ping returned ${result}`,
84 },
85 { type: 'TEXT_MESSAGE_END', messageId: 'answer' },
86 { type: 'RUN_FINISHED', threadId, runId },
87 ])
88 },
89 },
90 },
91})