forked from daydreamsai/daydreams
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample-task.ts
More file actions
435 lines (394 loc) · 12 KB
/
Copy pathexample-task.ts
File metadata and controls
435 lines (394 loc) · 12 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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
/**
* Advanced example demonstrating a hierarchical goal planning system using Dreams
* with Claude 3.7 Sonnet for autonomous agent behavior in a game environment. This is still alpha and not all features are available.
*
* This example shows how to:
* 1. Create a hierarchical goal planning system (long/medium/short-term goals)
* 2. Decompose goals into executable tasks
* 3. Track and update goal progress
* 4. Integrate with external APIs (Tavily, Eternum)
*
* Usage
* 1. First ask the agent to "set up a plan to win at Eternum"
* 2. Then ask the agent to execute the plan.
*/
import {
createDreams,
context,
render,
action,
LogLevel,
output,
createContainer,
fetchGraphQL,
type InferContextMemory,
validateEnv,
Logger,
} from "@daydreamsai/core";
import { cliExtension } from "@daydreamsai/cli";
import { deepResearch } from "../deep-research/research";
import { string, z } from "zod/v4";
import { tavily } from "@tavily/core";
import { ETERNUM_CONTEXT } from "./eternum";
import { anthropic } from "@ai-sdk/anthropic";
validateEnv(
z.object({
ANTHROPIC_API_KEY: z.string().min(1, "ANTHROPIC_API_KEY is required"),
TAVILY_API_KEY: z.string().min(1, "TAVILY_API_KEY is required"),
OPENAI_API_KEY: z.string().min(1, "OPENAI_API_KEY is required"),
})
);
/**
* EXAMPLE USAGE:
*
* 1. Initialize the agent with a high-level objective:
* "Build a thriving settlement in Eternum with sustainable resource production"
*
* 2. The agent will automatically:
* - Break this down into hierarchical goals (long/medium/short-term)
* - Prioritize goals based on dependencies and importance
* - Execute tasks to achieve each goal
* - Update goal status as progress is made
*
* 3. Sample goal hierarchy:
* - Long-term: "Establish a self-sustaining settlement"
* - Medium-term: "Secure reliable food production"
* - Short-term: "Build 3 farms near water source"
* - Tasks: [Scout location, Gather resources, Construct buildings]
*/
// ==========================================
// SCHEMA DEFINITIONS
// ==========================================
/**
* Defines the structure of individual tasks that make up a goal
*/
const taskSchema = z.object({
plan: z.string().optional(),
meta: z.any().optional(),
actions: z.array(
z.object({
type: z.string(),
context: z.string(),
payload: z.any(),
})
),
});
/**
* Defines the structure of a goal with metadata for tracking and execution
*/
export const goalSchema = z
.object({
id: z.string(),
description: z.string().describe("A description of the goal"),
success_criteria: z.array(z.string()).describe("The criteria for success"),
dependencies: z.array(z.string()).describe("The dependencies of the goal"),
priority: z.number().min(1).max(10).describe("The priority of the goal"),
required_resources: z
.array(z.string())
.describe("The resources needed to achieve the goal"),
estimated_difficulty: z
.number()
.min(1)
.max(10)
.describe("The estimated difficulty of the goal"),
tasks: z
.array(taskSchema)
.describe(
"The tasks to achieve the goal. This is where you build potential tasks you need todo, based on your understanding of what you can do. These are actions."
),
})
.describe("A goal to be achieved");
/**
* Defines the hierarchical goal planning structure with three time horizons
*/
export const goalPlanningSchema = z.object({
long_term: z
.array(goalSchema)
.describe("Strategic goals that are the main goals you want to achieve"),
medium_term: z
.array(goalSchema)
.describe(
"Tactical goals that will require many short term goals to achieve"
),
short_term: z
.array(goalSchema)
.describe(
"Immediate actionable goals that will require a few tasks to achieve"
),
});
// ==========================================
// MODEL AND CONTAINER SETUP
// ==========================================
// Create a dependency injection container for services
const container = createContainer();
// Register Tavily search service
container.singleton("tavily", () => {
return tavily({
apiKey: process.env.TAVILY_API_KEY!,
});
});
// ==========================================
// CONTEXT DEFINITION
// ==========================================
/**
* Template for the goal manager context
* This provides structure for the LLM to understand the current state
*/
const template = `
Goal: {{goal}}
Tasks: {{tasks}}
Current Task: {{currentTask}}
<goal_planning_rules>
1. Break down the objective into hierarchical goals
2. Each goal must have clear success criteria
3. Identify dependencies between goals
4. Prioritize goals (1-10) based on urgency and impact
5. short term goals should be given a priority of 10
6. Ensure goals are achievable given the current context
7. Consider past experiences when setting goals
8. Use available game state information to inform strategy
# Each goal must include:
- id: Unique temporary ID used in dependencies
- description: Clear goal statement
- success_criteria: Array of specific conditions for completion
- dependencies: Array of prerequisite goal IDs (empty for initial goals)
- priority: Number 1-10 (10 being highest)
- required_resources: Array of resources needed (based on game state)
- estimated_difficulty: Number 1-10 based on past experiences
</goal_planning_rules>
`;
// Type definition for the goal planning schema
type Goal = z.infer<typeof goalPlanningSchema>;
/**
* Context for managing goals and tasks
* This maintains the state of goals and provides rendering for the LLM
*/
const goalContexts = context({
type: "goal-manager",
schema: z.object({
id: string(),
}),
key({ id }) {
return id;
},
create(state) {
return {
goal: null as null | Goal,
tasks: [],
currentTask: null,
};
},
render({ memory }) {
return render(template, {
goal: memory.goal ?? "NONE",
tasks: memory?.tasks?.join("\n"),
currentTask: memory?.currentTask ?? "NONE",
});
},
});
// Type for the goal context memory
type GoalContextMemory = InferContextMemory<typeof goalContexts>;
// ==========================================
// ACTIONS DEFINITION
// ==========================================
/**
* Create the Dreams agent with all necessary components
*/
createDreams({
logger: new Logger({ level: LogLevel.INFO }),
debugger: async (contextId, keys, data) => {
const [type, id] = keys;
await Bun.write(`./logs/tasks/${contextId}/${id}-${type}.md`, data);
},
model: anthropic("claude-3-7-sonnet-latest"),
extensions: [cliExtension, deepResearch],
context: goalContexts,
container,
actions: [
/**
* Action to decompose a goal into executable tasks
*/
action({
name: "decomposeGoal",
description: "Decompose a goal into executable tasks",
schema: {
goalId: z.string().describe("ID of the goal to decompose"),
goalType: z
.enum(["long_term", "medium_term", "short_term"])
.describe("Type of goal"),
},
handler(data, ctx, agent) {
const agentMemory = ctx.agentMemory as GoalContextMemory;
if (!agentMemory.goal) {
throw new Error("No goals have been set yet");
}
const goalType = data.goalType;
const goalId = data.goalId;
// Find the goal in the specified category
const goal = agentMemory.goal[goalType].find(
(g: any) => g.id === goalId
);
if (!goal) {
throw new Error(
`Goal with ID ${goalId} not found in ${goalType} goals`
);
}
// Return the goal for task decomposition
return {
goal,
message: `Ready to decompose goal: ${goal.description}`,
};
},
}),
/**
* Action to set the complete goal plan
*/
action({
name: "setGoalPlan",
description: "Set the complete goal plan",
schema: z.object({ goal: goalPlanningSchema }),
handler(data, ctx, agent) {
const agentMemory = ctx.agentMemory as GoalContextMemory;
agentMemory.goal = data.goal;
return {
plan: data.goal,
message: "Goal plan has been set successfully",
};
},
}),
/**
* Action to update a goal's state or properties
*/
action({
name: "updateGoal",
description: "Update a goal's state or properties",
schema: z.object({
goalId: z.string().describe("ID of the goal to update"),
goalType: z
.enum(["long_term", "medium_term", "short_term"])
.describe("Type of goal"),
updates: goalSchema.partial().describe("Properties to update"),
}),
handler(data, ctx, agent) {
const agentMemory = ctx.agentMemory as GoalContextMemory;
if (!agentMemory.goal) {
throw new Error("No goals have been set yet");
}
const goalType = data.goalType;
const goalId = data.goalId;
// Find the goal in the specified category
const goalIndex = agentMemory.goal[goalType].findIndex(
(g) => g.id === goalId
);
if (goalIndex === -1) {
throw new Error(
`Goal with ID ${goalId} not found in ${goalType} goals`
);
}
// Update the goal with the provided updates
agentMemory.goal[goalType][goalIndex] = {
...agentMemory.goal[goalType][goalIndex],
...data.updates,
};
return {
updatedGoal: agentMemory.goal[goalType][goalIndex],
message: `Goal ${goalId} has been updated successfully`,
};
},
}),
/**
* Action to query Eternum game context
*/
action({
name: "queryEternum",
description:
"This will tell you everything you need to know about Eternum for how to win the game",
schema: z.object({ query: z.string() }),
handler(call, ctx, agent) {
return {
data: {
result: ETERNUM_CONTEXT,
},
timestamp: Date.now(),
};
},
}),
/**
* Action to query Eternum GraphQL API for game state
*/
action({
name: "Query:Eternum:Graphql",
description: "Search Eternum GraphQL API",
schema: z.object({
query: z.string().describe(`
query GetRealmDetails {
s0EternumResourceModels(where: { entity_id: ENTITY_ID }, limit: 100) {
edges {
node {
resource_type
balance
}
}
}
s0EternumBuildingModels(where: { outer_col: X, outer_row: Y }) {
edges {
node {
category
entity_id
inner_col
inner_row
}
}
}
}`),
}),
async handler(data, ctx, agent) {
const result = await fetchGraphQL(
"https://api.cartridge.gg/x/eternum-sepolia/torii/graphql",
data.query
);
if (result instanceof Error) {
return {
error: result.message,
};
}
return {
data: {
result: result,
},
timestamp: Date.now(),
};
},
}),
],
// ==========================================
// OUTPUTS DEFINITION
// ==========================================
outputs: {
/**
* Output to update the goal state
*/
"goal-manager:state": output({
description:
"Use this when you need to update the goals. Use the goal id to update the goal. You should attempt the goal then call this to update the goal.",
instructions: "Increment the state of the goal manager",
schema: z.object({
type: z
.enum(["SET", "UPDATE"])
.describe("SET to set the goals. UPDATE to update a goal."),
goal: goalSchema,
}),
handler: async (call, ctx, agent) => {
console.log("handler", { call, ctx, agent });
return {
data: {
goal: "",
},
timestamp: Date.now(),
};
},
}),
},
}).start({
id: "game",
});