Created
December 17, 2025 20:55
-
-
Save domitriusclark/d61483a77dcce03ddd0685bd82275dfa to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // src/routes/api/chat.ts | |
| // We'll need to import createFileRoute from Tanstack Router | |
| import { createFileRoute } from "@tanstack/react-router" | |
| import { chat, toStreamResponse } from "@tanstack/ai"; | |
| import { openai } from "@tanstack/ai-openai"; | |
| // Then we'll wrap the POST request in the expected shell using createFileRoute | |
| export const Route = createFileRoute("/api/chat")({ | |
| server: { | |
| handlers: { | |
| POST: async ({ request }: { request: Request }) => { | |
| // Check for API key | |
| if (!process.env.OPENAI_API_KEY) { | |
| return new Response( | |
| JSON.stringify({ | |
| error: "OPENAI_API_KEY not configured", | |
| }), | |
| { | |
| status: 500, | |
| headers: { "Content-Type": "application/json" }, | |
| } | |
| ); | |
| } | |
| const { messages, conversationId } = await request.json(); | |
| try { | |
| // Create a streaming chat response | |
| const stream = chat({ | |
| adapter: openai(), | |
| messages, | |
| model: "gpt-4o", | |
| conversationId | |
| }); | |
| // Convert stream to HTTP response | |
| return toStreamResponse(stream); | |
| } catch (error) { | |
| return new Response( | |
| JSON.stringify({ | |
| error: error instanceof Error ? error.message : "An error occurred", | |
| }), | |
| { | |
| status: 500, | |
| headers: { "Content-Type": "application/json" }, | |
| } | |
| ); | |
| } | |
| } | |
| } | |
| } | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment