MCPcopy Create free account
hub / github.com/Alphanimble/htmlstream / openRouterChatPlugin

Function openRouterChatPlugin

demo/server/openrouter-chat.ts:247–301  ·  view source on GitHub ↗
(env: Record<string, string>)

Source from the content-addressed store, hash-verified

245}
246
247export function openRouterChatPlugin(env: Record<string, string>): Plugin {
248 return {
249 name: "openrouter-chat-api",
250 configureServer(server) {
251 server.middlewares.use(async (req, res, next) => {
252 if (req.url !== "/api/chat" || req.method !== "POST") {
253 next();
254 return;
255 }
256
257 const apiKey = env.OPENROUTER_API_KEY;
258 const model = env.MODEL_NAME;
259
260 if (!apiKey || !model) {
261 res.statusCode = 500;
262 res.setHeader("Content-Type", "application/json");
263 res.end(
264 JSON.stringify({
265 error:
266 "Missing OPENROUTER_API_KEY or MODEL_NAME in .env (project root)",
267 }),
268 );
269 return;
270 }
271
272 try {
273 const raw = await readBody(req);
274 const { messages } = JSON.parse(raw) as {
275 messages?: { role: string; content: string }[];
276 };
277
278 if (!Array.isArray(messages) || messages.length === 0) {
279 res.statusCode = 400;
280 res.end(JSON.stringify({ error: "messages array required" }));
281 return;
282 }
283
284 await pipeOpenRouterStream(res, apiKey, model, messages);
285 } catch (err) {
286 if (!res.headersSent) {
287 res.statusCode = 500;
288 res.setHeader("Content-Type", "application/json");
289 res.end(
290 JSON.stringify({
291 error: err instanceof Error ? err.message : "Chat failed",
292 }),
293 );
294 } else {
295 res.end();
296 }
297 }
298 });
299 },
300 };
301}

Callers 1

vite.config.tsFile · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected