import { createOpenRouter } from "@openrouter/ai-sdk-provider"; import { streamText, Message } from "ai"; import { Hono } from "hono"; import { stream } from "hono/streaming"; import { personalAssistantAgent } from "./agents/personalAssistant.js"; import { chefAgent } from "./agents/chef.js"; import { Agent } from "./types.js"; import { processPendingToolCalls } from "./util.js"; // This declaration is primarily for providing type hints in your code // and it doesn't directly define the *values* of the environment variables. interface Env { OPENROUTER_API_KEY: string; // Add other environment variables here } declare global { const env: Env; } const app = new Hono(); const openrouter = createOpenRouter({ apiKey: import.meta.env.VITE_OPENROUTER_API_KEY || env.OPENROUTER_API_KEY, }); const agentsById: Record = { "personal-assistant": personalAssistantAgent, chef: chefAgent, }; app.post("/api/chat/:agent_id", async (c) => { const input: { messages: Message[] } = await c.req.json(); const agentId = c.req.param("agent_id"); const agent = agentsById[agentId]; if (!agent) { c.status(404); return c.json({ error: `No such agent: ${agentId}` }); } await processPendingToolCalls(input.messages); const result = streamText({ model: openrouter(agent.modelName), maxSteps: 5, messages: [ { role: "system", content: agent.systemMessage }, ...Object.values(agentsById).map((agent) => ({ role: "system" as const, content: `Agent ${JSON.stringify({ id: agent.id, name: agent.name, description: agent.description, skills: agent.skills, })}`, })), ...input.messages, ], tools: agent.tools, onError: (error) => { console.log(error); }, }); // Mark the response as a v1 data stream: c.header("X-Vercel-AI-Data-Stream", "v1"); c.header("Content-Type", "text/plain; charset=utf-8"); return stream(c, (stream) => stream.pipe(result.toDataStream())); }); export default app;