Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

agents.ts

78 lines2.5 KB

1import { chat, defineAgent } from '@tanstack/ai'
2import { createOpenRouterText } from '@tanstack/ai-openrouter'
3import { researcher, seo, writer } from '@/lib/blog-agents'
4​
5function linkAbort(signal: AbortSignal | undefined) {
6 const abortController = new AbortController()
7 if (signal === undefined) return abortController
8 if (signal.aborted) {
9 abortController.abort()
10 return abortController
11 }
12 signal.addEventListener(
13 'abort',
14 () => {
15 abortController.abort()
16 },
17 { once: true },
18 )
19 return abortController
21​
22export function createBlogAgents(apiKey: string) {
23 const researcherAgent = defineAgent({
24 ...researcher,
25 run: (ctx) =>
26 chat({
27 adapter: createOpenRouterText('openai/gpt-5.5', apiKey),
28 messages: ctx.messages,
29 threadId: ctx.threadId,
30 runId: ctx.runId,
31 parentRunId: ctx.parentRunId,
32 subagentRunId: ctx.subagentRunId,
33 resume: ctx.resume,
34 abortController: linkAbort(ctx.abortSignal),
35 systemPrompts: [
36 'You research for a blog desk. Reply in Markdown with short notes and sources. Use a list. Do not write the full post.',
37 ],
38 }),
39 })
40​
41 const writerAgent = defineAgent({
42 ...writer,
43 run: (ctx) =>
44 chat({
45 adapter: createOpenRouterText('openai/gpt-5.5', apiKey),
46 messages: ctx.messages,
47 threadId: ctx.threadId,
48 runId: ctx.runId,
49 parentRunId: ctx.parentRunId,
50 subagentRunId: ctx.subagentRunId,
51 resume: ctx.resume,
52 abortController: linkAbort(ctx.abortSignal),
53 systemPrompts: [
54 'You write blog posts in Markdown. Start with one # title. Use short ## sections and a closing line. When earlier messages contain research notes or SEO text, write only from those messages. Do not add facts that are not in those messages.',
55 ],
56 }),
57 })
58​
59 const seoAgent = defineAgent({
60 ...seo,
61 run: (ctx) =>
62 chat({
63 adapter: createOpenRouterText('openai/gpt-5.5', apiKey),
64 messages: ctx.messages,
65 threadId: ctx.threadId,
66 runId: ctx.runId,
67 parentRunId: ctx.parentRunId,
68 subagentRunId: ctx.subagentRunId,
69 resume: ctx.resume,
70 abortController: linkAbort(ctx.abortSignal),
71 systemPrompts: [
72 'You prepare SEO for a blog post. Reply in Markdown. Give 5 title options, one meta description under 160 characters, and a short tag list. Do not write the full article.',
73 ],
74 }),
75 })
76​
77 return [researcherAgent, writerAgent, seoAgent] as const