-
Notifications
You must be signed in to change notification settings - Fork 157
Expand file tree
/
Copy pathindex.ts
More file actions
387 lines (351 loc) · 11.8 KB
/
Copy pathindex.ts
File metadata and controls
387 lines (351 loc) · 11.8 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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
import express from 'express';
import { v4 as uuidv4 } from 'uuid'; // For generating unique IDs
import {
A2A_PROTOCOL_VERSION,
AgentCard,
Task,
TaskState,
TaskStatusUpdateEvent,
Message,
AGENT_CARD_PATH,
TaskArtifactUpdateEvent,
Artifact,
Part,
Role,
} from '../../../index.js';
import {
InMemoryTaskStore,
TaskStore,
AgentExecutor,
RequestContext,
ExecutionEventBus,
DefaultRequestHandler,
AgentEvent,
} from '../../../server/index.js';
import { agentCardHandler, jsonRpcHandler, UserBuilder } from '../../../server/express/index.js';
import { MessageData } from 'genkit';
import { ai } from './genkit.js';
import { searchMovies, searchPeople } from './tools.js';
if (!process.env.GEMINI_API_KEY || !process.env.TMDB_API_KEY) {
console.error('GEMINI_API_KEY and TMDB_API_KEY environment variables are required');
process.exit(1);
}
// Simple store for contexts
const contexts: Map<string, Message[]> = new Map();
// Load the Genkit prompt
const movieAgentPrompt = ai.prompt('movie_agent');
/**
* MovieAgentExecutor implements the agent's core logic.
*/
class MovieAgentExecutor implements AgentExecutor {
private cancelledTasks = new Set<string>();
public cancelTask = async (taskId: string, _eventBus: ExecutionEventBus): Promise<void> => {
this.cancelledTasks.add(taskId);
// The execute loop is responsible for publishing the final state
};
async execute(requestContext: RequestContext, eventBus: ExecutionEventBus): Promise<void> {
const userMessage = requestContext.userMessage;
const existingTask = requestContext.task;
// Determine IDs for the task and context
const taskId = requestContext.taskId;
const contextId = requestContext.contextId;
console.log(
`[MovieAgentExecutor] Processing message ${userMessage.messageId} for task ${taskId} (context: ${contextId})`
);
// 1. Every streaming turn must begin with a Task or Message event.
const taskSnapshot: Task = existingTask ?? {
id: taskId,
contextId: contextId,
status: {
state: TaskState.TASK_STATE_SUBMITTED,
timestamp: new Date().toISOString(),
message: undefined,
},
artifacts: [],
history: [userMessage],
metadata: userMessage.metadata,
};
eventBus.publish(AgentEvent.task(taskSnapshot));
// 2. Publish "working" status update
const workingStatusUpdate: TaskStatusUpdateEvent = {
taskId: taskId,
contextId: contextId,
status: {
state: TaskState.TASK_STATE_WORKING,
message: {
role: Role.ROLE_AGENT,
messageId: uuidv4(),
parts: [
{
content: { $case: 'text', value: 'Processing your question, hang tight!' },
metadata: undefined,
filename: '',
mediaType: 'text/plain',
},
],
taskId: taskId,
contextId: contextId,
extensions: [],
metadata: {},
referenceTaskIds: [],
},
timestamp: new Date().toISOString(),
},
metadata: {},
};
eventBus.publish(AgentEvent.statusUpdate(workingStatusUpdate));
// 3. Prepare messages for Genkit prompt
const historyForGenkit = contexts.get(contextId) || [];
if (!historyForGenkit.find((m) => m.messageId === userMessage.messageId)) {
historyForGenkit.push(userMessage);
}
contexts.set(contextId, historyForGenkit);
const messages: MessageData[] = historyForGenkit
.map((m) => {
const textContent = m.parts
.map((p) => (p.content?.$case === 'text' ? p.content.value : ''))
.filter((t) => !!t)
.join('\n');
return {
role: (m.role === Role.ROLE_AGENT ? 'model' : 'user') as 'user' | 'model',
content: textContent ? [{ text: textContent }] : [],
};
})
.filter((m) => m.content.length > 0);
if (messages.length === 0) {
console.warn(
`[MovieAgentExecutor] No valid text messages found in history for task ${taskId}.`
);
const failureUpdate: TaskStatusUpdateEvent = {
taskId: taskId,
contextId: contextId,
status: {
state: TaskState.TASK_STATE_FAILED,
message: {
role: Role.ROLE_AGENT,
messageId: uuidv4(),
parts: [
{
content: { $case: 'text', value: 'No message found to process.' },
metadata: undefined,
filename: '',
mediaType: 'text/plain',
},
],
taskId: taskId,
contextId: contextId,
extensions: [],
metadata: {},
referenceTaskIds: [],
},
timestamp: new Date().toISOString(),
},
metadata: {},
};
eventBus.publish(AgentEvent.statusUpdate(failureUpdate));
return;
}
const goal =
(existingTask?.metadata?.goal as string | undefined) ||
(userMessage.metadata?.goal as string | undefined);
try {
// 4. Run the Genkit prompt
const response = await movieAgentPrompt(
{ goal: goal, now: new Date().toISOString() },
{
messages,
tools: [searchMovies, searchPeople],
}
);
// Check if the request has been cancelled
if (this.cancelledTasks.has(taskId)) {
console.log(`[MovieAgentExecutor] Request cancelled for task: ${taskId}`);
const cancelledUpdate: TaskStatusUpdateEvent = {
taskId: taskId,
contextId: contextId,
status: {
state: TaskState.TASK_STATE_CANCELED,
timestamp: new Date().toISOString(),
message: undefined,
},
metadata: {},
};
eventBus.publish(AgentEvent.statusUpdate(cancelledUpdate));
return;
}
const responseText = response.text;
console.info(`[MovieAgentExecutor] Prompt response: ${responseText}`);
const lines = responseText.trim().split('\n');
const finalStateLine = lines.at(-1)?.trim().toUpperCase();
const agentReplyText = lines
.slice(0, lines.length - 1)
.join('\n')
.trim();
let finalA2AState: TaskState = TaskState.TASK_STATE_UNSPECIFIED;
if (finalStateLine === 'COMPLETED') {
finalA2AState = TaskState.TASK_STATE_COMPLETED;
} else if (finalStateLine === 'AWAITING_USER_INPUT') {
finalA2AState = TaskState.TASK_STATE_INPUT_REQUIRED;
} else {
console.warn(
`[MovieAgentExecutor] Unexpected final state line from prompt: "${finalStateLine}". Defaulting to 'completed'.`
);
finalA2AState = TaskState.TASK_STATE_COMPLETED;
}
// 5. Publish artifact with the result
const parts: Part[] = [
{
content: { $case: 'text', value: agentReplyText || 'Completed.' },
metadata: undefined,
filename: '',
mediaType: 'text/plain',
},
];
const artifactId = uuidv4();
const resultArtifact: Artifact = {
artifactId: artifactId,
name: 'Result',
description: 'The result of the movie agent.',
parts: parts,
metadata: undefined,
extensions: [],
};
const artifactUpdate: TaskArtifactUpdateEvent = {
taskId: taskId,
contextId: contextId,
artifact: resultArtifact,
lastChunk: true,
append: false,
metadata: {},
};
eventBus.publish(AgentEvent.artifactUpdate(artifactUpdate));
// 6. Update local history context (internal only)
const agentMessage: Message = {
role: Role.ROLE_AGENT,
messageId: uuidv4(),
parts: parts,
taskId: taskId,
contextId: contextId,
extensions: [],
metadata: {},
referenceTaskIds: [],
};
historyForGenkit.push(agentMessage);
contexts.set(contextId, historyForGenkit);
// 7. Publish final task status update
const finalUpdate: TaskStatusUpdateEvent = {
taskId: taskId,
contextId: contextId,
status: {
state: finalA2AState,
timestamp: new Date().toISOString(),
message: undefined,
},
metadata: {},
};
eventBus.publish(AgentEvent.statusUpdate(finalUpdate));
console.log(`[MovieAgentExecutor] Task ${taskId} finished with state: ${finalA2AState}`);
} catch (error: any) {
console.error(`[MovieAgentExecutor] Error processing task ${taskId}:`, error);
const errorUpdate: TaskStatusUpdateEvent = {
taskId: taskId,
contextId: contextId,
status: {
state: TaskState.TASK_STATE_FAILED,
message: {
role: Role.ROLE_AGENT,
messageId: uuidv4(),
parts: [
{
content: { $case: 'text', value: `Agent error: ${error.message}` },
metadata: undefined,
filename: '',
mediaType: 'text/plain',
},
],
taskId: taskId,
contextId: contextId,
extensions: [],
metadata: undefined,
referenceTaskIds: [],
},
timestamp: new Date().toISOString(),
},
metadata: undefined,
};
eventBus.publish(AgentEvent.statusUpdate(errorUpdate));
}
}
}
// --- Server Setup ---
const movieAgentCard: AgentCard = {
name: 'Movie Agent',
description: 'An agent that can answer questions about movies and actors using TMDB.',
supportedInterfaces: [
{
url: 'http://localhost:41241/',
protocolBinding: 'JSONRPC',
tenant: '',
protocolVersion: A2A_PROTOCOL_VERSION,
},
],
provider: {
organization: 'A2A Samples',
url: 'https://example.com/a2a-samples',
},
version: '0.0.2',
capabilities: {
streaming: true,
pushNotifications: false,
extensions: [],
extendedAgentCard: false,
},
securitySchemes: {}, // Or define actual security schemes if any
securityRequirements: [],
defaultInputModes: ['text'],
defaultOutputModes: ['text', 'task-status'], // task-status is a common output mode
skills: [
{
id: 'general_movie_chat',
name: 'General Movie Chat',
description: 'Answer general questions or chat about movies, actors, directors.',
tags: ['movies', 'actors', 'directors'],
examples: [
'Tell me about the plot of Inception.',
'Recommend a good sci-fi movie.',
'Who directed The Matrix?',
'What other movies has Scarlett Johansson been in?',
'Find action movies starring Keanu Reeves',
'Which came out first, Jurassic Park or Terminator 2?',
],
inputModes: ['text'], // Explicitly defining for skill
outputModes: ['text', 'task-status'], // Explicitly defining for skill
securityRequirements: [],
},
],
documentationUrl: '',
signatures: [],
};
async function main() {
// 1. Create TaskStore
const taskStore: TaskStore = new InMemoryTaskStore();
// 2. Create AgentExecutor
const agentExecutor: AgentExecutor = new MovieAgentExecutor();
// 3. Create DefaultRequestHandler
const requestHandler = new DefaultRequestHandler(movieAgentCard, taskStore, agentExecutor);
// 4. Create and setup Express.js app
const app = express();
app.use(`/${AGENT_CARD_PATH}`, agentCardHandler({ agentCardProvider: requestHandler }));
app.use(jsonRpcHandler({ requestHandler, userBuilder: UserBuilder.noAuthentication }));
// 5. Start the server
const PORT = process.env.PORT || 41241;
app.listen(PORT, (err) => {
if (err) {
throw err;
}
console.log(`[MovieAgent] Server using new framework started on http://localhost:${PORT}`);
console.log(`[MovieAgent] Agent Card: http://localhost:${PORT}/.well-known/agent-card.json`);
console.log('[MovieAgent] Press Ctrl+C to stop the server');
});
}
main().catch(console.error);