Skip to content

Commit 302e356

Browse files
committed
latest WIP - BUG endless loop
1 parent 0a4e2e4 commit 302e356

File tree

4 files changed

+118
-41
lines changed

4 files changed

+118
-41
lines changed

core/src/actions/cashtags.ts

+50-31
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ interface TokenPair {
2727
name: string;
2828
symbol: string;
2929
};
30+
marketCap: number;
3031
priceNative: string;
3132
priceUsd: string;
3233
txns: {
@@ -147,10 +148,10 @@ export const searchCashTags = async (
147148
};
148149

149150
export const cashtags: Action = {
150-
name: "FIND_BEST_MATCH",
151+
name: "FIND_BEST_CASHTAG_MATCH",
151152
similes: ["FIND_TOKEN", "SEARCH_TOKEN", "GET_TOKEN", "FIND_PAIR"],
152153
description:
153-
"Searches for the best matching token pair based on age, liquidity, volume, and transaction count",
154+
"Searches for the best matching token pair (ca) or $cashtag ($SOL) based on age, liquidity, volume, and transaction count",
154155
validate: async (runtime: IAgentRuntime, message: Memory, state: State) => {
155156
return true
156157
},
@@ -163,50 +164,62 @@ export const cashtags: Action = {
163164
) => {
164165
const userId = runtime.agentId;
165166
const { roomId } = message;
166-
const datestr = new Date().toUTCString().replace(/:/g, "-");
167167

168+
168169
// Extract cashtag from message
169170
const cashtag = message.content.text
170171
.match(/\$[A-Za-z]+/)?.[0]
171172
?.replace("$", "");
172173

173-
if (!cashtag) {
174-
callback({
175-
text: "No cashtag found in the message. Please include a cashtag (e.g. $PNUT)",
176-
action: "FIND_BEST_MATCH_RESPONSE",
177-
source: "DexScreener",
178-
});
179-
return;
180-
}
181-
182174
const callbackData: Content = {
183175
text: undefined,
184176
action: "FIND_BEST_MATCH_RESPONSE",
185177
source: "DexScreener",
186178
attachments: [],
187179
};
188180

181+
if (!cashtag) {
182+
// callback({
183+
// text: "No cashtag found in the message. Please include a cashtag (e.g. $PNUT)",
184+
// action: "FIND_BEST_MATCH_RESPONSE",
185+
// source: "DexScreener",
186+
// });
187+
callbackData.text= "No cashtag found in the message. Please include a cashtag (e.g. $PNUT)";
188+
189+
return;
190+
}
191+
192+
console.log(`[${roomId}] Processing FIND_BEST_MATCH request... $`, cashtag);
193+
189194
try {
190195
const { data: bestMatch, error } = await searchCashTags(cashtag);
191196

192197
if (error) {
193198
callbackData.text = error;
194-
callback(callbackData);
199+
// callback(callbackData);
195200
return;
196201
}
202+
console.log(bestMatch);
197203

198204
// Format response
199-
const responseText = `Best match for $${cashtag}:
200-
Token: ${bestMatch.baseToken.name} (${bestMatch.baseToken.symbol})
201-
Age: ${Math.floor((Date.now() - bestMatch.pairCreatedAt) / (1000 * 60 * 60 * 24))} days
202-
Liquidity: $${bestMatch.liquidity.usd.toLocaleString()}
203-
24h Volume: $${bestMatch.volume.h24.toLocaleString()}
204-
24h Transactions: ${(bestMatch.txns.h24.buys + bestMatch.txns.h24.sells).toLocaleString()}
205-
Price: $${bestMatch.priceUsd}
206-
DEX: ${bestMatch.dexId}
207-
Pair Address: ${bestMatch.pairAddress}`;
208-
209-
callbackData.text = responseText;
205+
const responseText = `
206+
Best match for $${cashtag}:
207+
Token: ${bestMatch.baseToken.name} (${bestMatch.baseToken.symbol})
208+
MCAP: $${(bestMatch.marketCap).toFixed(2)}M
209+
Age: ${Math.floor((Date.now() - bestMatch.pairCreatedAt) / (1000 * 60 * 60 * 24))} days
210+
Liquidity: $${bestMatch.liquidity.usd.toLocaleString()}
211+
24h Volume: $${bestMatch.volume.h24.toLocaleString()}
212+
24h Transactions: ${(bestMatch.txns.h24.buys + bestMatch.txns.h24.sells).toLocaleString()}
213+
Price: $${bestMatch.priceUsd}
214+
DEX: ${bestMatch.dexId}
215+
Pair Address: ${bestMatch.pairAddress}
216+
217+
URL: ${bestMatch.url}`;
218+
219+
callbackData.text = `Create a reply with the token information for $${cashtag}.
220+
Message from user - ${message.content.text}
221+
Token information - ${responseText}
222+
`;
210223

211224
// Store the full response as an attachment
212225
const attachmentId =
@@ -219,10 +232,10 @@ Pair Address: ${bestMatch.pairAddress}`;
219232
title: `Best Match for $${cashtag}`,
220233
source: "DexScreener",
221234
description: `Token analysis for ${bestMatch.baseToken.symbol}`,
222-
text: JSON.stringify(bestMatch, null, 2),
223-
});
235+
text: JSON.stringify(bestMatch, null, 2)
236+
})
224237

225-
callback(callbackData);
238+
// callback(callbackData);
226239

227240
// Log to database
228241
runtime.databaseAdapter.log({
@@ -240,15 +253,21 @@ Pair Address: ${bestMatch.pairAddress}`;
240253
roomId,
241254
embedding: embeddingZeroVector,
242255
};
256+
243257

244258
await runtime.messageManager.createMemory(memory);
245-
await runtime.evaluate(message, state);
259+
const response = await runtime.evaluate(message, state);
260+
261+
246262
} catch (error) {
247263
console.error("Error in findBestMatch:", error);
248264
callbackData.text = `Error processing request: ${error.message}`;
249265
callback(callbackData);
250266
}
251267

268+
console.log(callbackData);
269+
typeof callback === "function" && callback(callbackData);
270+
252271
return callbackData;
253272
},
254273
examples: [
@@ -263,7 +282,7 @@ Pair Address: ${bestMatch.pairAddress}`;
263282
user: "{{user2}}",
264283
content: {
265284
text: "Let me search for the best matching pair...",
266-
action: "FIND_BEST_MATCH",
285+
action: "FIND_BEST_CASHTAG_MATCH",
267286
},
268287
},
269288
],
@@ -278,7 +297,7 @@ Pair Address: ${bestMatch.pairAddress}`;
278297
user: "{{user2}}",
279298
content: {
280299
text: "I'll look up the token information...",
281-
action: "FIND_BEST_MATCH",
300+
action: "FIND_BEST_CASHTAG_MATCH",
282301
},
283302
},
284303
],
@@ -293,7 +312,7 @@ Pair Address: ${bestMatch.pairAddress}`;
293312
user: "{{user2}}",
294313
content: {
295314
text: "Searching for the best BTC pair...",
296-
action: "FIND_BEST_MATCH",
315+
action: "FIND_BEST_CASHTAG_MATCH",
297316
},
298317
},
299318
],

core/src/adapters/postgres.ts

+7-6
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ export class PostgresDatabaseAdapter extends DatabaseAdapter {
9393
const client = await this.pool.connect();
9494
try {
9595
const { rows } = await client.query(
96-
`SELECT userState FROM participants WHERE "roomId" = $1 AND userId = $2`,
96+
`SELECT "userState" FROM participants WHERE "roomId" = $1 AND "userId" = $2`,
9797
[roomId, userId]
9898
);
9999
return rows.length > 0 ? rows[0].userState : null;
@@ -372,23 +372,23 @@ export class PostgresDatabaseAdapter extends DatabaseAdapter {
372372
if (params.start) {
373373
paramCount++;
374374
sql += ` AND "createdAt" >= to_timestamp($${paramCount})`;
375-
values.push(params.start / 1000);
375+
values.push(Math.round(params.start / 1000));
376376
}
377377

378378
if (params.end) {
379379
paramCount++;
380380
sql += ` AND "createdAt" <= to_timestamp($${paramCount})`;
381-
values.push(params.end / 1000);
381+
values.push(Math.round(params.end / 1000));
382382
}
383383

384384
if (params.unique) {
385385
sql += ` AND "unique" = true`;
386386
}
387387

388388
if (params.agentId) {
389-
sql += ` AND "agentId" = $3`;
390-
values.push(params.agentId);
391389
paramCount++;
390+
sql += ` AND "agentId" = $${paramCount}`;
391+
values.push(params.agentId);
392392
}
393393

394394
sql += ' ORDER BY "createdAt" DESC';
@@ -661,7 +661,8 @@ export class PostgresDatabaseAdapter extends DatabaseAdapter {
661661
}
662662

663663
if (params.agentId) {
664-
sql += ` AND "agentId" = $3`;
664+
paramCount++;
665+
sql += ` AND "agentId" = $${paramCount}`;
665666
values.push(params.agentId);
666667
}
667668

core/src/clients/direct/index.ts

+53-2
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ Note that {{agentName}} is capable of reading/seeing/hearing various forms of me
4040
4141
{{actions}}
4242
43-
# Instructions: Write the next message for {{agentName}}. Ignore "action".
43+
# Instructions: Write the next message for {{agentName}}.
4444
` + messageCompletionFooter;
4545

4646
export interface SimliClientConfig {
@@ -162,7 +162,12 @@ class DirectClient {
162162
inReplyTo: undefined,
163163
};
164164

165-
const userMessage = { content, userId, roomId, agentId: runtime.agentId };
165+
const userMessage = {
166+
content,
167+
userId,
168+
roomId,
169+
agentId: runtime.agentId,
170+
};
166171

167172
const memory: Memory = {
168173
id: messageId,
@@ -199,6 +204,52 @@ class DirectClient {
199204

200205
await runtime.messageManager.createMemory(responseMessage);
201206

207+
// TODO: Improve action loop
208+
if (response?.action) {
209+
const actions = [];
210+
await runtime.processActions(
211+
memory,
212+
[responseMessage],
213+
state,
214+
// @ts-ignore
215+
async (response) => {
216+
actions.push(response);
217+
}
218+
);
219+
220+
// TODO: duplicate compose to get latest state, refactor to add in runtime.getState
221+
222+
const actionState = (await runtime.composeState(
223+
userMessage,
224+
{
225+
agentName: runtime.character.name,
226+
}
227+
)) as State;
228+
229+
const context = composeContext({
230+
state: actionState,
231+
template: `
232+
About {{agentName}}:
233+
{{bio}}
234+
{{lore}}
235+
236+
237+
Recent Messages
238+
{{recentMessages}}
239+
240+
241+
[SYSTEM] Actions completed, now respond to user given the actions outputs.
242+
# Instructions: Write the next message for {{agentName}}.`,
243+
});
244+
const _response = await generateMessageResponse({
245+
runtime: runtime,
246+
context: context,
247+
modelClass: ModelClass.SMALL,
248+
});
249+
res.json(_response);
250+
return;
251+
}
252+
202253
if (!response) {
203254
res.status(500).send(
204255
"No response from generateMessageResponse"

core/src/clients/twitter/interactions.ts

+8-2
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ Recent interactions between {{agentName}} and other users:
4848
# Task: Generate a post in the voice, style and perspective of {{agentName}} (@{{twitterUserName}}):
4949
{{currentPost}}
5050
51+
{{actions}}
5152
` + messageCompletionFooter;
5253

5354
export const shouldRespondTemplate =
@@ -117,7 +118,8 @@ export class TwitterInteractionClient extends ClientBase {
117118
!this.lastCheckedTweetId ||
118119
parseInt(tweet.id) > this.lastCheckedTweetId
119120
) {
120-
const conversationId = tweet.conversationId + "-" + this.runtime.agentId;
121+
const conversationId =
122+
tweet.conversationId + "-" + this.runtime.agentId;
121123

122124
const roomId = stringToUuid(conversationId);
123125

@@ -254,7 +256,11 @@ export class TwitterInteractionClient extends ClientBase {
254256
text: tweet.text,
255257
url: tweet.permanentUrl,
256258
inReplyTo: tweet.inReplyToStatusId
257-
? stringToUuid(tweet.inReplyToStatusId + "-" + this.runtime.agentId)
259+
? stringToUuid(
260+
tweet.inReplyToStatusId +
261+
"-" +
262+
this.runtime.agentId
263+
)
258264
: undefined,
259265
},
260266
userId: userIdUUID,

0 commit comments

Comments
 (0)