Repository navigation
Expand file tree
/
Copy patheditor-agent-tool.ts
More file actions
305 lines (290 loc) · 11.3 KB
/
Copy patheditor-agent-tool.ts
File metadata and controls
305 lines (290 loc) · 11.3 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
import type { ChunkType } from '@mastra/core/stream'
import type { InferUITool } from '@mastra/core/tools'
import { createTool } from '@mastra/core/tools'
import { SpanType, getOrCreateSpan } from '@mastra/core/observability'
import { z } from 'zod'
import { editorAgent } from '../agents/editorAgent'
import { log } from '../config/logger'
import type { RequestContext } from '@mastra/core/request-context'
export interface EditorAgentContext extends RequestContext {
userId?: string
}
const editorToolOutputSchema = z.object({
editedContent: z.string().describe('The edited and improved content'),
contentType: z.string().describe('The identified content type'),
changes: z.array(z.string()).describe('List of key changes made'),
suggestions: z
.array(z.string())
.optional()
.describe('Additional suggestions for improvement'),
})
type EditorAgentOutput = z.infer<typeof editorToolOutputSchema>
export const editorTool = createTool({
id: 'editor-agent',
description:
'Calls the editor agent to edit and improve content across multiple formats including blog posts, technical documentation, business communications, creative writing, and general content.',
inputSchema: z.object({
content: z.string().describe('The content to be edited'),
contentType: z
.enum(['blog', 'technical', 'business', 'creative', 'general'])
.optional()
.describe(
"The type of content being edited (defaults to 'general')"
),
instructions: z
.string()
.optional()
.describe('Specific editing instructions or focus areas'),
tone: z
.enum(['professional', 'casual', 'formal', 'engaging', 'technical'])
.optional()
.describe('Desired tone for the edited content'),
}),
outputSchema: editorToolOutputSchema,
strict: true,
onInputStart: ({ toolCallId }) => {
log.info('editorTool tool input streaming started', {
toolCallId,
hook: 'onInputStart',
})
},
onInputDelta: ({ inputTextDelta, toolCallId }) => {
log.info('editorTool received input chunk', {
toolCallId,
inputTextDelta,
hook: 'onInputDelta',
})
},
onInputAvailable: ({ input, toolCallId }) => {
log.info('editorTool received input', {
toolCallId,
inputData: {
content: input.content,
contentType: input.contentType,
instructions: input.instructions,
tone: input.tone,
},
hook: 'onInputAvailable',
})
},
// Streaming: Pipe a nested agent's textStream into the tool writer so the UI
// receives nested agent chunks while the tool is running. See:
// https://mastra.ai/docs/streaming/tool-streaming#tool-using-an-agent
execute: async (inputData, context) => {
// Emit progress start
await context?.writer?.custom({
type: 'data-tool-progress',
data: {
status: 'in-progress',
message: '📝 Starting editor agent',
stage: 'editor-agent',
},
id: 'editor-agent',
})
const {
content,
contentType = 'general',
instructions,
tone,
} = inputData
const writer = context?.writer
const span = getOrCreateSpan({
type: SpanType.TOOL_CALL,
name: 'editor-agent',
input: inputData,
metadata: {
'tool.id': 'editor-agent',
contentType,
tone: tone ?? 'not-specified',
operation: 'editor-agent-run',
},
})
try {
// Direct agent usage
// Build the prompt with context
let prompt = `Edit the following content`
if (contentType !== 'general') {
prompt += ` (content type: ${contentType})`
}
if (tone) {
prompt += ` with a ${tone} tone`
}
if (
typeof instructions === 'string' &&
instructions.trim().length > 0
) {
prompt += `. Additional instructions: ${instructions}`
}
prompt += `:\n\n${content}`
await writer?.custom({
type: 'data-tool-progress',
data: {
status: 'in-progress',
message: '🤖 Generating edited content',
stage: 'editor-agent',
},
id: 'editor-agent',
})
// Use the agent's streaming API when available, following the Mastra nested-agent example.
// Prefer the agent instance registered on `context.mastra` so usage is correctly
// attributed to the running Mastra runtime; fall back to the imported agent.
let resultText = ''
try {
let streamedText = ''
const agent =
context?.mastra?.getAgent?.('editorAgent') ?? editorAgent
const stream = await agent.stream(prompt, {
structuredOutput: {
schema: editorToolOutputSchema,
},
onChunk: (chunk: ChunkType<EditorAgentOutput>) => {
if (
chunk.type === 'text-delta' &&
typeof chunk.payload?.text === 'string'
) {
streamedText += chunk.payload.text
}
},
})
// Stream the agent's text stream into the tool writer so the UI receives
// nested and merged chunks while the tool is running. This also allows
// Mastra to aggregate usage into the tool run (see docs).
if (stream?.textStream && writer) {
await context?.writer?.custom({
type: 'data-tool-progress',
data: {
status: 'in-progress',
message: '🔁 Streaming text from editor agent',
stage: 'editor-agent',
},
id: 'editor-agent',
})
await stream.textStream.pipeTo(
writer as WritableStream
)
resultText = (await stream.text) ?? streamedText
} else if (stream?.fullStream && writer) {
// Some runtimes expose a fullStream; pipe it so nested events and
// structured payloads are forwarded to the tool writer.
await context?.writer?.custom({
type: 'data-tool-progress',
data: {
status: 'in-progress',
message:
'🔁 Streaming from editor agent (full stream)',
stage: 'editor-agent',
},
id: 'editor-agent',
})
await stream.fullStream.pipeTo(
writer as WritableStream
)
resultText = (await stream.text) ?? streamedText
} else if (stream) {
// No UI writer available, but stream exists
resultText = (await stream.text) ?? streamedText
} else {
// Fallback to synchronous generate using the agent instance
const result = await agent.generate(prompt)
resultText = result.text
}
} catch (err) {
// Streaming/generation error — bubble up after logging
const msg = err instanceof Error ? err.message : String(err)
span?.error({
error: err instanceof Error ? err : new Error(msg),
endSpan: true,
})
throw err
}
// Parse the structured response from the editor agent
let parsedResult: EditorAgentOutput
try {
parsedResult = JSON.parse(resultText) as EditorAgentOutput
} catch {
// Fallback for non-JSON responses
parsedResult = {
editedContent: resultText,
contentType,
changes: ['Content edited and improved'],
suggestions: [],
}
}
span?.update({
output: parsedResult,
metadata: {
'tool.output.success': true,
},
})
span?.end()
await writer?.custom({
type: 'data-tool-progress',
data: {
status: 'done',
message: '✅ Editing complete',
stage: 'editor-agent',
},
id: 'editor-agent',
})
return {
editedContent: parsedResult.editedContent ?? resultText,
contentType: parsedResult.contentType ?? contentType,
changes: parsedResult.changes ?? [
'Content edited and improved',
],
suggestions: parsedResult.suggestions ?? [],
}
} catch (error) {
const errorMsg =
error instanceof Error ? error.message : 'Unknown error'
span?.error({
error: error instanceof Error ? error : new Error(errorMsg),
endSpan: true,
})
throw new Error(`Failed to edit content: ${errorMsg}`, {
cause: error,
})
}
},
toModelOutput: (output: EditorAgentOutput) => ({
type: 'content',
value: [
{
type: 'text' as const,
text: `Content type: ${output.contentType}`,
},
output.changes.length > 0
? {
type: 'text' as const,
text: `Changes:\n- ${output.changes.join('\n- ')}`,
}
: undefined,
output.suggestions?.length
? {
type: 'text' as const,
text: `Suggestions:\n- ${output.suggestions.join('\n- ')}`,
}
: undefined,
{
type: 'text' as const,
text: output.editedContent,
},
].filter(
(part): part is { type: 'text'; text: string } => Boolean(part)
),
}),
onOutput: ({ output, toolCallId, toolName }) => {
log.info('editorTool completed', {
toolCallId,
toolName,
outputData: {
editedContent: output.editedContent,
contentType: output.contentType,
changes: output.changes,
suggestions: output.suggestions,
},
hook: 'onOutput',
})
},
})
export type EditorAgentUITool = InferUITool<typeof editorTool>