File tree Expand file tree Collapse file tree 1 file changed +57
-2
lines changed
Expand file tree Collapse file tree 1 file changed +57
-2
lines changed Original file line number Diff line number Diff line change @@ -19,9 +19,64 @@ yarn add @tanstack/ai @tanstack/ai-react @tanstack/ai-openai
1919
2020First, create an API route that handles chat requests. Here's a simplified example:
2121
22+ ### TanStack Start
23+
24+ ``` typescript
25+ import { chat , toStreamResponse } from " @tanstack/ai" ;
26+ import { openai } from " @tanstack/ai-openai" ;
27+ import { createFileRoute } from " @tanstack/react-router" ;
28+
29+ export const Route = createFileRoute (" /api/chat" )({
30+ server: {
31+ handlers: {
32+ POST : async ({ request }) => {
33+ // Check for API key
34+ if (! process .env .OPENAI_API_KEY ) {
35+ return new Response (
36+ JSON .stringify ({
37+ error: " OPENAI_API_KEY not configured" ,
38+ }),
39+ {
40+ status: 500 ,
41+ headers: { " Content-Type" : " application/json" },
42+ },
43+ );
44+ }
45+
46+ const { messages, conversationId } = await request .json ();
47+
48+ try {
49+ // Create a streaming chat response
50+ const stream = chat ({
51+ adapter: openai (),
52+ messages ,
53+ model: " gpt-4o" ,
54+ conversationId ,
55+ });
56+
57+ // Convert stream to HTTP response
58+ return toStreamResponse (stream );
59+ } catch (error ) {
60+ return new Response (
61+ JSON .stringify ({
62+ error:
63+ error instanceof Error ? error .message : " An error occurred" ,
64+ }),
65+ {
66+ status: 500 ,
67+ headers: { " Content-Type" : " application/json" },
68+ },
69+ );
70+ }
71+ },
72+ },
73+ },
74+ });
75+ ```
76+
77+ ### Next.js
78+
2279``` typescript
23- // app/api/chat/route.ts (Next.js)
24- // or src/routes/api/chat.ts (TanStack Start)
2580import { chat , toStreamResponse } from " @tanstack/ai" ;
2681import { openai } from " @tanstack/ai-openai" ;
2782
You can’t perform that action at this time.
0 commit comments