Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sentiment improvements + new dkgjs version #13

Merged
merged 3 commits into from
Feb 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/plugin-dkg/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
],
"dependencies": {
"@elizaos/core": "workspace:*",
"dkg.js": "^8.0.4",
"dkg.js": "^8.0.6",
"tsup": "8.3.5",
"agent-twitter-client": "0.0.18",
"vader-sentiment": "^1.1.3",
Expand Down
125 changes: 101 additions & 24 deletions packages/plugin-dkg/src/actions/dkgAnalyzeSentiment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,7 @@ export const dkgAnalyzeSentiment: Action = {
await scraper.login(username, password, email, twitter2faSecret);
if (!(await scraper.isLoggedIn())) {
let attempts = 0;
const maxAttempts = 5;
const maxAttempts = 10;

while (attempts < maxAttempts) {
attempts++;
Expand All @@ -343,6 +343,16 @@ export const dkgAnalyzeSentiment: Action = {
}
}

if (!topic || topic.toLowerCase() === "none") {
await postTweet(
`Didn't recognize a ticker of a financial asset in your post. Please post again while clearly stating which stock or cryptocurrency you want to analyze.`,
scraper,
postId,
);

return true;
}

const scrapedTweets = scraper.searchTweets(
topic,
100,
Expand Down Expand Up @@ -382,37 +392,104 @@ export const dkgAnalyzeSentiment: Action = {
? "Positive 🟢"
: "Negative 🔴";

const createAssetResult = await DkgClient.asset.create(
{
public: ka,
},
{ epochsNum: 12 },
);
elizaLogger.log("Publishing sentiment analysis to DKG");
elizaLogger.log(`KA: ${JSON.stringify(ka, null, 2)}`);

const sentimentData = await getSentimentChart(averageScore, topic);
try {
let createAssetResult;

const file = await fetchFileFromUrl(sentimentData.url);
try {
createAssetResult = await DkgClient.asset.create(
{ public: ka },
{ epochsNum: 12 },
);
} catch (error) {
elizaLogger.error(
"Error occurred while creating asset:",
error.message,
);

let tweetContent = `${topic} sentiment based on top ${tweets.length} latest posts`;
if (numOfTotalTweets - tweets.length > 0) {
tweetContent += ` and ${numOfTotalTweets - tweets.length} existing analysis Knowledge Assets`;
}
tweetContent += ` from the past 48 hours: ${sentiment}\n\n`;
if (
error.message.includes("Unexpected") ||
error.message.includes("JSON")
) {
elizaLogger.warn(
"Detected JSON formatting issue. Attempting to fix...",
);
try {
const fixedJSON = await generateText({
runtime,
context: `Fix this malformed JSON-LD and return only the corrected JSON-LD:\n${JSON.stringify(ka, null, 2)}

Make sure to only output the JSON-LD object. DO NOT OUTPUT ANYTHING ELSE, DONT ADD ANY COMMENTS, REMARKS AND DO NOT WRAP IT IN A CODE/JSON BLOCK, JUST THE JSON LD CONTENT WRAPPED IN { }.`,
modelClass: ModelClass.LARGE,
});

elizaLogger.log(
`Fixed JSON generated by LLM. Retrying...`,
);

// Retry asset creation with the fixed JSON
createAssetResult = await DkgClient.asset.create(
{ public: JSON.parse(fixedJSON) },
{ epochsNum: 12 },
);
} catch (llmError) {
elizaLogger.error(
"Failed to fix JSON using LLM:",
llmError.message,
);
}
}
}

if (!createAssetResult?.UAL) {
elizaLogger.error("UAL not found after asset creation.");
await postTweet(
`Apologies, something went wrong with the sentiment analysis.`,
scraper,
postId,
);
return true;
}

elizaLogger.log("======================== ASSET CREATED");
elizaLogger.log(JSON.stringify(createAssetResult));

tweetContent += `Top 5 most influential accounts analyzed for ${topic}:\n`;
tweetContent +=
topAuthors
.slice(0, 5)
.map((a) => `@${a}`)
.join(", ") + "\n\n";
// Proceed with posting sentiment analysis tweet
const sentimentData = await getSentimentChart(averageScore, topic);
const file = await fetchFileFromUrl(sentimentData.url);

tweetContent += `Analysis memorized on @origin_trail Decentralized Knowledge Graph `;
tweetContent += `${DKG_EXPLORER_LINKS[runtime.getSetting("DKG_ENVIRONMENT")]}${createAssetResult.UAL} @${twitterUser}\n\n`;
let tweetContent = `${topic} sentiment based on top ${tweets.length} latest posts`;
if (numOfTotalTweets - tweets.length > 0) {
tweetContent += ` and ${numOfTotalTweets - tweets.length} existing analysis Knowledge Assets`;
}
tweetContent += ` from the past 48 hours: ${sentiment}\n\n`;

tweetContent += `This is not financial advice.`;
tweetContent += `Top 5 most influential accounts analyzed for ${topic}:\n`;
tweetContent +=
topAuthors
.slice(0, 5)
.map((a) => `@${a}`)
.join(", ") + "\n\n";

await postTweet(tweetContent.trim(), scraper, postId, file.data);
tweetContent += `Analysis memorized on @origin_trail Decentralized Knowledge Graph `;
tweetContent += `${DKG_EXPLORER_LINKS[runtime.getSetting("DKG_ENVIRONMENT")]}${createAssetResult.UAL} @${twitterUser}\n\n`;

tweetContent += `This is not financial advice.`;

await postTweet(tweetContent.trim(), scraper, postId, file.data);
} catch (error) {
elizaLogger.error(
"Unexpected error in sentiment analysis process:",
error.message,
);
await postTweet(
`Apologies, something went wrong with the sentiment analysis.`,
scraper,
postId,
);
}
return true;
},
examples: [
Expand Down
54 changes: 50 additions & 4 deletions packages/plugin-dkg/src/actions/dkgInsert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,10 @@ export const dkgInsert: Action = {
try {
elizaLogger.log("Publishing message to DKG");

elizaLogger.log(
`KA: ${JSON.stringify(memoryKnowledgeGraph, null, 2)}`,
);

createAssetResult = await DkgClient.asset.create(
{
public: memoryKnowledgeGraph,
Expand All @@ -143,12 +147,54 @@ export const dkgInsert: Action = {
JSON.stringify(error.response.data, null, 2),
);
}

if (
error.message.includes("Unexpected") ||
error.message.includes("JSON")
) {
elizaLogger.warn(
"Detected JSON formatting issue. Attempting to fix...",
);
try {
const fixedJSON = await generateText({
runtime,
context: `Fix this malformed JSON-LD and return only the corrected JSON-LD:\n${JSON.stringify(memoryKnowledgeGraph, null, 2)}

Make sure to only output the JSON-LD object. DO NOT OUTPUT ANYTHING ELSE, DONT ADD ANY COMMENTS, REMARKS AND DO NOT WRAP IT IN A CODE/JSON BLOCK, JUST THE JSON LD CONTENT WRAPPED IN { }.`,
modelClass: ModelClass.LARGE,
});

elizaLogger.log(
`Fixed JSON generated by LLM: ${fixedJSON}. Retrying...`,
);

createAssetResult = await DkgClient.asset.create(
{ public: JSON.parse(fixedJSON) },
{ epochsNum: 12 },
);

elizaLogger.log(
"======================== ASSET CREATED AFTER FIX",
);
elizaLogger.log(JSON.stringify(createAssetResult));
} catch (llmError) {
elizaLogger.error(
"Failed to fix JSON using LLM:",
llmError.message,
);
}
}
}

// Reply
callback({
text: `Created a new memory!\n\nRead my mind on @origin_trail Decentralized Knowledge Graph ${DKG_EXPLORER_LINKS[runtime.getSetting("DKG_ENVIRONMENT")]}${createAssetResult.UAL} @${twitterUser}`,
});
if (createAssetResult.UAL) {
callback({
text: `Created a new memory!\n\nRead my mind on @origin_trail Decentralized Knowledge Graph ${DKG_EXPLORER_LINKS[runtime.getSetting("DKG_ENVIRONMENT")]}${createAssetResult.UAL} @${twitterUser}`,
});
} else {
callback({
text: `Apologies, something went wrong with creating the memory.`,
});
}

return true;
},
Expand Down
Loading