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

api.json-transport.ts

102 lines3.4 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 chat,
4 chatParamsFromRequest,
5 memoryStream,
6 resumeJsonResponse,
7 toJsonResponse,
8} from '@tanstack/ai'
9import {
10 memoryPersistence,
11 reconstructChat,
12 withPersistence,
13} from '@tanstack/ai-persistence'
14import { createTextAdapter } from '@/lib/providers'
15import { guitarRecommendationSchema } from '@/lib/schemas'
16import { clientToolDefinitions, serverTools } from '@/lib/tools-test-tools'
17​
18/**
19 * JSON transport harness (server half). The client is `fetchJson`.
20 *
21 * - POST runs `chat()` through aimock and answers with one JSON body from
22 * `toJsonResponse`. The run drains into a `memoryStream` log, so a short
23 * `?maxWaitMs=` replies early with `done: false` and the client polls.
24 * - GET with a resume cursor (`?runId=&offset=`) reads the log through
25 * `resumeJsonResponse`. That is the poll and the `joinRun` path.
26 * - GET with `?threadId=` is the `persistence: true` mount hydrate. It reads
27 * `withPersistence` state through `reconstructChat`, so a reload during a
28 * run sees `activeRun` and the client joins it.
29 *
30 * - POST with `forwardedProps.structured` awaits `chat({ outputSchema })` and
31 * sends the typed object with `toJsonResponse`.
32 *
33 * aimock is reached through the OpenAI adapter; `testId` / `aimockPort` ride
34 * in `forwardedProps`.
35 */
36​
37const persistence = memoryPersistence()
38​
39const tools = [
40 serverTools.get_weather,
41 serverTools.delete_file,
42 clientToolDefinitions.show_notification,
44​
45function maxWaitMsFrom(request: Request) {
46 const raw = new URL(request.url).searchParams.get('maxWaitMs')
47 if (raw === null) return undefined
48 const value = Number.parseInt(raw, 10)
49 return Number.isNaN(value) ? undefined : value
51​
52export const Route = createFileRoute('/api/json-transport')({
53 server: {
54 handlers: {
55 POST: async ({ request }) => {
56 const params = await chatParamsFromRequest(request)
57 const fp = params.forwardedProps
58 const testId = typeof fp.testId === 'string' ? fp.testId : undefined
59 const aimockPort =
60 fp.aimockPort != null ? Number(fp.aimockPort) : undefined
61​
62 if (fp.structured === true) {
63 const guitar = await chat({
64 ...createTextAdapter('openai', undefined, aimockPort, testId),
65 messages: params.messages,
66 threadId: params.threadId,
67 runId: params.runId,
68 outputSchema: guitarRecommendationSchema,
69 })
70 return toJsonResponse(guitar)
71 }
72​
73 const stream = chat({
74 ...createTextAdapter('openai', undefined, aimockPort, testId),
75 messages: params.messages,
76 tools,
77 threadId: params.threadId,
78 runId: params.runId,
79 ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),
80 ...(params.resume ? { resume: params.resume } : {}),
81 middleware: [withPersistence(persistence)],
82 })
83​
84 return toJsonResponse(stream, {
85 durability: { adapter: memoryStream(request) },
86 signal: request.signal,
87 maxWaitMs: maxWaitMsFrom(request),
88 })
89 },
90​
91 GET: ({ request }) => {
92 const durability = memoryStream(request)
93 if (durability.resumeFrom() !== null) {
94 return resumeJsonResponse({ adapter: durability })
95 }
96 return reconstructChat(persistence, request, {
97 authorize: (threadId) => threadId.length > 0,
98 })
99 },
100 },
101 },
102})