-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.ts
More file actions
310 lines (264 loc) · 11.4 KB
/
Copy pathserver.ts
File metadata and controls
310 lines (264 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
import express, { Request, Response, NextFunction } from "express";
import Anthropic from "@anthropic-ai/sdk";
import * as dl from "dongnelibrary";
import type { SearchResult, Book } from "dongnelibrary";
import * as ansan from "dongnelibrary/dist/localLibraryModule/ansan";
import * as asan from "dongnelibrary/dist/localLibraryModule/asan";
import * as bcl from "dongnelibrary/dist/localLibraryModule/bcl";
import * as cbelib from "dongnelibrary/dist/localLibraryModule/cbelib";
import * as daegu from "dongnelibrary/dist/localLibraryModule/daegu";
import * as gangnam from "dongnelibrary/dist/localLibraryModule/gangnam";
import * as gangseo from "dongnelibrary/dist/localLibraryModule/gangseo";
import * as gbelib from "dongnelibrary/dist/localLibraryModule/gbelib";
import * as geoje from "dongnelibrary/dist/localLibraryModule/geoje";
import * as gg from "dongnelibrary/dist/localLibraryModule/gg";
import * as gimhae from "dongnelibrary/dist/localLibraryModule/gimhae";
import * as gjcity from "dongnelibrary/dist/localLibraryModule/gjcity";
import * as gunpo from "dongnelibrary/dist/localLibraryModule/gunpo";
import * as gunsan from "dongnelibrary/dist/localLibraryModule/gunsan";
import * as gwanak from "dongnelibrary/dist/localLibraryModule/gwanak";
import * as gwe from "dongnelibrary/dist/localLibraryModule/gwe";
import * as hanamlib from "dongnelibrary/dist/localLibraryModule/hanamlib";
import * as hscity from "dongnelibrary/dist/localLibraryModule/hscity";
import * as ice from "dongnelibrary/dist/localLibraryModule/ice";
import * as jeju from "dongnelibrary/dist/localLibraryModule/jeju";
import * as junggulib from "dongnelibrary/dist/localLibraryModule/junggulib";
import * as mokpolib from "dongnelibrary/dist/localLibraryModule/mokpolib";
import * as nowon from "dongnelibrary/dist/localLibraryModule/nowon";
import * as osan from "dongnelibrary/dist/localLibraryModule/osan";
import * as paju from "dongnelibrary/dist/localLibraryModule/paju";
import * as pohang from "dongnelibrary/dist/localLibraryModule/pohang";
import * as ptlib from "dongnelibrary/dist/localLibraryModule/ptlib";
import * as siheung from "dongnelibrary/dist/localLibraryModule/siheung";
import * as snlib from "dongnelibrary/dist/localLibraryModule/snlib";
import * as suwon from "dongnelibrary/dist/localLibraryModule/suwon";
import * as uwlib from "dongnelibrary/dist/localLibraryModule/uwlib";
import * as wonju from "dongnelibrary/dist/localLibraryModule/wonju";
import * as yangcheon from "dongnelibrary/dist/localLibraryModule/yangcheon";
import * as ydplib from "dongnelibrary/dist/localLibraryModule/ydplib";
import * as yjlib from "dongnelibrary/dist/localLibraryModule/yjlib";
import * as yongin from "dongnelibrary/dist/localLibraryModule/yongin";
import * as yplib from "dongnelibrary/dist/localLibraryModule/yplib";
import * as yslib from "dongnelibrary/dist/localLibraryModule/yslib";
const LIBRARY_MODULES = [ansan, asan, bcl, cbelib, daegu, gangnam, gangseo, gbelib, geoje, gg, gimhae, gjcity, gunpo, gunsan, gwanak, gwe, hanamlib, hscity, ice, jeju, junggulib, mokpolib, nowon, osan, paju, pohang, ptlib, siheung, snlib, suwon, uwlib, wonju, yangcheon, ydplib, yjlib, yongin, yplib, yslib];
const app = express();
app.use(express.json());
app.use("/", express.static(import.meta.dirname + "/dist"));
interface SearchParams {
title: string;
libraryName: string;
}
const searchBooks = (
title: string,
libraryName: string,
signal?: AbortSignal,
): Promise<SearchResult[]> => {
return new Promise((resolve, reject) => {
dl.search({ title, libraryName, signal }, undefined, (err, books) => {
if (err) {
console.error(err);
reject(err);
} else {
resolve(books ?? []);
}
});
});
};
const extractSearchParams = (
params: Record<string, unknown>,
): SearchParams => ({
title: (params.title as string) || "",
libraryName: (params.libraryName as string) || "",
});
const makeBookDescription = (book: Book): string => {
const mark = book.exist ? "✓ " : "✖ ";
return " " + mark + " " + book.title + "<br>";
};
app.get("/search", async (req: Request, res: Response) => {
const controller = new AbortController();
req.on("close", () => {
controller.abort();
});
const { title, libraryName } = extractSearchParams(req.query);
try {
const books = await searchBooks(title, libraryName, controller.signal);
if (res.writableEnded) return;
res.json(books);
} catch (err) {
if (res.writableEnded) return;
const error = err as { msg?: string };
res.json({ message: error.msg });
}
});
app.get("/libraryList", (_req: Request, res: Response) => {
const libs = dl.getAllLibraryNames();
res.json(libs);
});
app.get("/moduleList", (_req: Request, res: Response) => {
const modules = LIBRARY_MODULES.map((mod) => ({
name: mod.moduleName,
libraries: mod.getLibraryNames(),
}));
res.json(modules);
});
app.get("/:title/:libraryName", async (req: Request, res: Response) => {
const { title, libraryName } = extractSearchParams(req.params);
try {
const books = await searchBooks(title, libraryName);
res.send(
books[0].booklist.reduce((memo: string, book: Book) => {
return memo + makeBookDescription(book);
}, ""),
);
} catch (err) {
const error = err as { msg?: string };
res.json({ message: error.msg });
}
});
// ── Agent Stream proxy ──────────────────────────────────────────────────────
type AgentEventType = "core_agent" | "domain_agent" | "tool_call" | "tool_result" | "response";
interface AgentEvent { type: AgentEventType; data: unknown }
const AGENT_TOOLS: Anthropic.Messages.Tool[] = [
{
name: "list_libraries",
description: "검색 가능한 전체 도서관 목록을 반환합니다.",
input_schema: { type: "object" as const, properties: {}, required: [] },
},
{
name: "search_books",
description: "도서 제목과 도서관 이름으로 대출 가능 여부를 검색합니다.",
input_schema: {
type: "object" as const,
properties: {
title: { type: "string", description: "검색할 도서 제목" },
libraryName: { type: "string", description: "검색할 도서관 이름 (예: 판교)" },
},
required: ["title", "libraryName"],
},
},
];
async function callAgentTool(
name: string,
input: Record<string, unknown>,
signal: AbortSignal,
): Promise<string> {
if (name === "list_libraries") {
return JSON.stringify(dl.getAllLibraryNames());
}
if (name === "search_books") {
const { title, libraryName } = input as { title: string; libraryName: string };
try {
const books = await searchBooks(title, libraryName, signal);
return JSON.stringify(books).slice(0, 1200);
} catch (e) {
return `Error: ${e instanceof Error ? e.message : "search failed"}`;
}
}
return "Unknown tool";
}
app.options("/api/agent-stream", (_req: Request, res: Response) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
res.sendStatus(204);
});
app.post("/api/agent-stream", async (req: Request, res: Response) => {
const { query } = req.body as { query: string };
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
const controller = new AbortController();
res.on("close", () => controller.abort());
const send = (event: AgentEvent) => {
res.write(`data: ${JSON.stringify(event)}\n\n`);
};
const heartbeat = setInterval(() => {
if (!res.writableEnded) res.write(': ping\n\n');
}, 1000);
try {
const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
send({ type: "core_agent", data: { intent: "Knowledge", confidence: 0.95, reason: "도서관 도서 검색 쿼리 감지" } });
send({ type: "domain_agent", data: { name: "도서관 검색 Agent (dlserver)" } });
const messages: Anthropic.Messages.MessageParam[] = [
{ role: "user", content: query },
];
let firstIteration = true;
while (true) {
if (controller.signal.aborted) break;
const response = await anthropic.messages.create({
model: "claude-haiku-4-5-20251001",
max_tokens: 1024,
system: `당신은 도서관 도서 검색 에이전트입니다.
사용자가 책 제목과 도서관 이름을 말하면 즉시 search_books 도구를 호출하세요.
- title: 사용자가 말한 책 제목 그대로 (절대 바꾸지 마세요)
- libraryName: 사용자가 말한 도서관 이름 그대로 (예: "판교", "강남")
list_libraries는 사용자가 도서관 이름을 모를 때만 사용하세요.`,
tools: AGENT_TOOLS,
tool_choice: firstIteration ? { type: "any" as const } : { type: "auto" as const },
messages,
});
firstIteration = false;
if (response.stop_reason === "tool_use") {
const toolUseBlocks = response.content.filter(
(b): b is Anthropic.Messages.ToolUseBlock => b.type === "tool_use",
);
const toolResults: Anthropic.Messages.ToolResultBlockParam[] = [];
for (const block of toolUseBlocks) {
if (controller.signal.aborted) break;
send({
type: "tool_call",
data: {
name: block.name,
description: AGENT_TOOLS.find((t) => t.name === block.name)?.description ?? "",
input: block.input as Record<string, unknown>,
},
});
const output = await callAgentTool(
block.name,
block.input as Record<string, unknown>,
controller.signal,
);
if (controller.signal.aborted) break;
send({ type: "tool_result", data: { toolName: block.name, output } });
toolResults.push({ type: "tool_result", tool_use_id: block.id, content: output });
}
messages.push({ role: "assistant", content: response.content });
messages.push({ role: "user", content: toolResults });
} else {
const textBlock = response.content.find(
(b): b is Anthropic.Messages.TextBlock => b.type === "text",
);
send({ type: "response", data: textBlock?.text ?? "검색 결과를 찾을 수 없습니다." });
break;
}
}
} catch (e) {
console.error("[agent-stream] error:", e);
send({ type: "response", data: `오류: ${e instanceof Error ? e.message : "알 수 없는 오류"}` });
} finally {
clearInterval(heartbeat);
}
res.end();
});
// ────────────────────────────────────────────────────────────────────────────
interface HttpError extends Error {
status?: number;
}
app.use((_req: Request, _res: Response, next: NextFunction) => {
const err: HttpError = new Error("Not Found");
err.status = 404;
next(err);
});
app.use((err: HttpError, _req: Request, res: Response, _next: NextFunction) => {
res.status(err.status || 500);
res.json({ message: "Server Error" });
});
export { app };
const isMainModule = import.meta.url === `file://${process.argv[1]}`;
if (isMainModule) {
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`dlserver listening on port ${port}!`);
});
}