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

api.chat.ts

47 lines1.5 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 chat,
4 chatParamsFromRequest,
5 maxIterations,
6 toServerSentEventsResponse,
7} from '@tanstack/ai'
8import { openaiText } from '@tanstack/ai-openai'
9import { createComputerUse } from '@tanstack/ai-computer-use'
10import { playwrightComputer } from '@tanstack/ai-computer-playwright'
11​
12// One computer for the whole server. Each chat thread gets its own page.
13const computerUse = createComputerUse({
14 driver: playwrightComputer({
15 startUrl: 'https://tanstack.com',
16 // Show the Chromium window, so you can watch the model work.
17 launch: { headless: false },
18 }),
19 // tanstack.com renders in the browser. Give each page time to draw.
20 screenshotDelay: 1000,
21})
22​
23export async function POST({ request }: { request: Request }) {
24 const params = await chatParamsFromRequest(request)
25 const stream = chat({
26 adapter: openaiText('gpt-6.1-sol'),
27 messages: params.messages,
28 threadId: params.threadId,
29 runId: params.runId,
30 ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),
31 ...(params.resume ? { resume: params.resume } : {}),
32 tools: computerUse.tools,
33 middleware: [computerUse.middleware],
34 interrupts: [computerUse.interrupt],
35 // Each action is one step. A search takes more than the default 5.
36 agentLoopStrategy: maxIterations(20),
37 })
38 return toServerSentEventsResponse(stream)
40​
41export const Route = createFileRoute('/api/chat')({
42 server: {
43 handlers: {
44 POST,
45 },
46 },
47})