|
| 1 | +import type { BaseMessage } from "@langchain/core/messages"; |
| 2 | +import { StateGraph, MessagesZodMeta, START } from "@langchain/langgraph"; |
| 3 | +import { toLangGraphEventStreamResponse } from "@langchain/langgraph/ui"; |
| 4 | +import { registry } from "@langchain/langgraph/zod"; |
| 5 | +import { ChatOpenAI } from "@langchain/openai"; |
| 6 | +import { z } from "zod/v4"; |
| 7 | + |
| 8 | +import { serve } from "@hono/node-server"; |
| 9 | +import { Hono } from "hono"; |
| 10 | + |
| 11 | +const llm = new ChatOpenAI({ model: "gpt-4o-mini" }); |
| 12 | + |
| 13 | +const graph = new StateGraph( |
| 14 | + z.object({ |
| 15 | + messages: z.custom<BaseMessage[]>().register(registry, MessagesZodMeta), |
| 16 | + }) |
| 17 | +) |
| 18 | + .addNode("agent", async ({ messages }) => ({ |
| 19 | + messages: await llm.invoke(messages), |
| 20 | + })) |
| 21 | + .addEdge(START, "agent") |
| 22 | + .compile(); |
| 23 | + |
| 24 | +export type GraphType = typeof graph; |
| 25 | + |
| 26 | +const app = new Hono(); |
| 27 | + |
| 28 | +app.post("/api/stream", async (c) => { |
| 29 | + type InputType = GraphType["~InputType"]; |
| 30 | + const { input } = await c.req.json<{ input: InputType }>(); |
| 31 | + |
| 32 | + return toLangGraphEventStreamResponse({ |
| 33 | + stream: graph.streamEvents(input, { |
| 34 | + version: "v2", |
| 35 | + streamMode: ["values", "messages"], |
| 36 | + }), |
| 37 | + }); |
| 38 | +}); |
| 39 | + |
| 40 | +serve({ fetch: app.fetch, port: 9123 }, (c) => { |
| 41 | + console.log(`Server running at ${c.address}:${c.port}`); |
| 42 | +}); |
0 commit comments