1import Anthropic from "@anthropic-ai/sdk";
2
3const client = new Anthropic();
4
5type Hit = { source: string; title: string; text: string };
6
7export async function answer(question: string, hits: Hit[]) {
8 const res = await client.messages.create({
9 model: "claude-haiku-5-5",
10 max_tokens: 1024,
11 messages: [{
12 role: "user",
13 content: [
14 ...hits.map((hit) => ({
15 type: "search_result" as const,
16 source: hit.source,
17 title: hit.title,
18 content: [{ type: "text" as const, text: hit.text }],
19 citations: { enabled: true },
20 })),
21 { type: "text" as const, text: `Answer using only these search results. If they don't contain the answer, say so.\n\nQuestion: ${question}` },
22 ],
23 }],
24 });
25
26 const sources = new Set<string>();
27 for (const block of res.content) {
28 if (block.type !== "text") continue;
29 process.stdout.write(block.text);
30 for (const cite of block.citations ?? []) {
31 if (cite.type === "search_result_location") sources.add(`${cite.title} (${cite.source})`);
32 }
33 }
34 console.log(`\n\nSources:\n${[...sources].join("\n")}`);
35}