Skip to content

Commit

Permalink
Retry if malformed JSON error
Browse files Browse the repository at this point in the history
  • Loading branch information
brkagithub committed Feb 10, 2025
1 parent 085d463 commit 75a1958
Show file tree
Hide file tree
Showing 2 changed files with 136 additions and 27 deletions.
113 changes: 90 additions & 23 deletions packages/plugin-dkg/src/actions/dkgAnalyzeSentiment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -392,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));

// Proceed with posting sentiment analysis tweet
const sentimentData = await getSentimentChart(averageScore, topic);
const file = await fetchFileFromUrl(sentimentData.url);

tweetContent += `Top 5 most influential accounts analyzed for ${topic}:\n`;
tweetContent +=
topAuthors
.slice(0, 5)
.map((a) => `@${a}`)
.join(", ") + "\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 += `Analysis memorized on @origin_trail Decentralized Knowledge Graph `;
tweetContent += `${DKG_EXPLORER_LINKS[runtime.getSetting("DKG_ENVIRONMENT")]}${createAssetResult.UAL} @${twitterUser}\n\n`;
tweetContent += `Top 5 most influential accounts analyzed for ${topic}:\n`;
tweetContent +=
topAuthors
.slice(0, 5)
.map((a) => `@${a}`)
.join(", ") + "\n\n";

tweetContent += `This is not financial advice.`;
tweetContent += `Analysis memorized on @origin_trail Decentralized Knowledge Graph `;
tweetContent += `${DKG_EXPLORER_LINKS[runtime.getSetting("DKG_ENVIRONMENT")]}${createAssetResult.UAL} @${twitterUser}\n\n`;

await postTweet(tweetContent.trim(), scraper, postId, file.data);
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
50 changes: 46 additions & 4 deletions packages/plugin-dkg/src/actions/dkgInsert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,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

0 comments on commit 75a1958

Please sign in to comment.