Skip to content

Commit

Permalink
Merge pull request #355 from ai16z/starknet-work
Browse files Browse the repository at this point in the history
feat: Complete Starknet DB Trust
  • Loading branch information
ponderingdemocritus authored Nov 18, 2024
2 parents a2e0954 + 782db49 commit 53f5bd3
Show file tree
Hide file tree
Showing 37 changed files with 4,075 additions and 7,518 deletions.
7,245 changes: 0 additions & 7,245 deletions package-lock.json

This file was deleted.

1 change: 1 addition & 0 deletions packages/agent/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"@ai16z/plugin-image-generation": "workspace:*",
"@ai16z/plugin-node": "workspace:*",
"@ai16z/plugin-solana": "workspace:*",
"@ai16z/plugin-starknet": "workspace:*",
"readline": "^1.3.0",
"ws": "^8.18.0",
"yargs": "17.7.2"
Expand Down
26 changes: 1 addition & 25 deletions packages/agent/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,26 +159,6 @@ export function getTokenForProvider(
}
}

export async function createDirectRuntime(
character: Character,
db: IDatabaseAdapter,
token: string
) {
console.log("Creating runtime for character", character.name);
return new AgentRuntime({
databaseAdapter: db,
token,
modelProvider: character.modelProvider,
evaluators: [],
character,
plugins: [],
providers: [],
actions: [],
services: [],
managers: [],
});
}

function initializeDatabase() {
if (process.env.POSTGRES_URL) {
return new PostgresDatabaseAdapter({
Expand Down Expand Up @@ -233,10 +213,6 @@ export async function createAgent(
token: string
) {
console.log("Creating runtime for character", character.name);
console.log(
"character.settings.secrets?.WALLET_PUBLIC_KEY",
character.settings.secrets?.WALLET_PUBLIC_KEY
);
return new AgentRuntime({
databaseAdapter: db,
token,
Expand Down Expand Up @@ -275,7 +251,7 @@ async function startAgent(character: Character, directClient: any) {
`Error starting agent for character ${character.name}:`,
error
);
throw error; // Re-throw after logging
throw error;
}
}

Expand Down
6 changes: 5 additions & 1 deletion packages/client-auto/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ export class AutoClient {
this.runtime = runtime;

const trustScoreDb = new TrustScoreDatabase(runtime.databaseAdapter.db);
this.trustScoreProvider = new TrustScoreManager(runtime, null, trustScoreDb);
this.trustScoreProvider = new TrustScoreManager(
runtime,
null,
trustScoreDb
);
this.walletProvider = new WalletProvider(
new Connection(runtime.getSetting("RPC_URL")),
new PublicKey(runtime.getSetting("WALLET_PUBLIC_KEY"))
Expand Down
9 changes: 7 additions & 2 deletions packages/client-telegram/src/messageManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,7 @@ export class MessageManager {

// Decide whether to respond
const shouldRespond = await this._shouldRespond(message, state);
console.log("Should respond", shouldRespond);

if (shouldRespond) {
// Generate response
const context = composeContext({
Expand Down Expand Up @@ -454,13 +454,18 @@ export class MessageManager {
content: {
...content,
text: sentMessage.text,
action: !isLastMessage ? "CONTINUE" : undefined,
inReplyTo: messageId,
},
createdAt: sentMessage.date * 1000,
embedding: embeddingZeroVector,
};

// Set action to CONTINUE for all messages except the last one
// For the last message, use the original action from the response content
memory.content.action = !isLastMessage
? "CONTINUE"
: content.action;

await this.runtime.messageManager.createMemory(memory);
memories.push(memory);
}
Expand Down
4 changes: 2 additions & 2 deletions packages/client-telegram/src/telegramClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Context, Telegraf } from "telegraf";

import { IAgentRuntime } from "@ai16z/eliza";
import { MessageManager } from "./messageManager.ts";
import { elizaLogger } from "@ai16z/eliza/src/logger.ts";
import { elizaLogger } from "@ai16z/eliza";

export class TelegramClient {
private bot: Telegraf<Context>;
Expand Down Expand Up @@ -43,7 +43,7 @@ export class TelegramClient {

this.bot.on("message", async (ctx) => {
try {
console.log("📥 Received message:", ctx.message);
// console.log("📥 Received message:", ctx.message);
await this.messageManager.handleMessage(ctx);
} catch (error) {
elizaLogger.error("❌ Error handling message:", error);
Expand Down
69 changes: 40 additions & 29 deletions packages/client-twitter/src/base.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { embeddingZeroVector } from "@ai16z/eliza/src/memory.ts";
import {
Content,
IAgentRuntime,
IImageDescriptionService,
embeddingZeroVector,
Memory,
State,
elizaLogger,
stringToUuid,
UUID,
} from "@ai16z/eliza";
import {
Expand All @@ -20,9 +22,6 @@ import { fileURLToPath } from "url";

import { glob } from "glob";

import { elizaLogger } from "@ai16z/eliza/src/logger.ts";
import { stringToUuid } from "@ai16z/eliza/src/uuid.ts";

export function extractAnswer(text: string): string {
const startIndex = text.indexOf("Answer: ") + 8;
const endIndex = text.indexOf("<|endoftext|>", 11);
Expand Down Expand Up @@ -172,14 +171,14 @@ export class ClientBase extends EventEmitter {
this.runtime.character.style.post.join();

try {
console.log("this.tweetCacheFilePath", this.tweetCacheFilePath);
// console.log("this.tweetCacheFilePath", this.tweetCacheFilePath);
if (fs.existsSync(this.tweetCacheFilePath)) {
// make it?
const data = fs.readFileSync(this.tweetCacheFilePath, "utf-8");
this.lastCheckedTweetId = parseInt(data.trim());
} else {
console.warn("Tweet cache file not found.");
console.warn(this.tweetCacheFilePath);
// console.warn("Tweet cache file not found.");
// console.warn(this.tweetCacheFilePath);
}
} catch (error) {
console.error(
Expand Down Expand Up @@ -274,24 +273,23 @@ export class ClientBase extends EventEmitter {
console.log("Twitter user ID:", userId);
this.twitterUserId = userId;

// Initialize Twitter profile
const profile = await this.initializeProfile();
if (profile) {
console.log("Twitter profile initialized:", profile);

// Store profile info for use in responses
this.runtime.character = {
...this.runtime.character,
twitterProfile: {
username: profile.username,
screenName: profile.screenName,
bio: profile.bio,
nicknames: profile.nicknames
}
};
}


// Initialize Twitter profile
const profile = await this.initializeProfile();
if (profile) {
// console.log("Twitter profile initialized:", profile);

// Store profile info for use in responses
this.runtime.character = {
...this.runtime.character,
twitterProfile: {
username: profile.username,
screenName: profile.screenName,
bio: profile.bio,
nicknames: profile.nicknames,
},
};
}

await this.populateTimeline();

this.onReady();
Expand Down Expand Up @@ -635,8 +633,15 @@ export class ClientBase extends EventEmitter {
return {
username,
screenName: profile.name || this.runtime.character.name,
bio: profile.biography || typeof this.runtime.character.bio === 'string' ? this.runtime.character.bio as string : this.runtime.character.bio.length > 0 ? this.runtime.character.bio[0] : "",
nicknames: this.runtime.character.twitterProfile?.nicknames || []
bio:
profile.biography ||
typeof this.runtime.character.bio === "string"
? (this.runtime.character.bio as string)
: this.runtime.character.bio.length > 0
? this.runtime.character.bio[0]
: "",
nicknames:
this.runtime.character.twitterProfile?.nicknames || [],
};
});

Expand All @@ -646,8 +651,14 @@ export class ClientBase extends EventEmitter {
return {
username: this.runtime.character.name,
screenName: username,
bio: typeof this.runtime.character.bio === 'string' ? this.runtime.character.bio as string : this.runtime.character.bio.length > 0 ? this.runtime.character.bio[0] : "",
nicknames: this.runtime.character.twitterProfile?.nicknames || []
bio:
typeof this.runtime.character.bio === "string"
? (this.runtime.character.bio as string)
: this.runtime.character.bio.length > 0
? this.runtime.character.bio[0]
: "",
nicknames:
this.runtime.character.twitterProfile?.nicknames || [],
};
}
}
Expand Down
31 changes: 17 additions & 14 deletions packages/client-twitter/src/interactions.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,8 @@
import { SearchMode, Tweet } from "agent-twitter-client";
import fs from "fs";
import { composeContext } from "@ai16z/eliza/src/context.ts";
import {
generateMessageResponse,
generateShouldRespond,
} from "@ai16z/eliza/src/generation.ts";
import {
messageCompletionFooter,
shouldRespondFooter,
} from "@ai16z/eliza/src/parsing.ts";
import { composeContext } from "@ai16z/eliza";
import { generateMessageResponse, generateShouldRespond } from "@ai16z/eliza";
import { messageCompletionFooter, shouldRespondFooter } from "@ai16z/eliza";
import {
Content,
HandlerCallback,
Expand All @@ -17,7 +11,7 @@ import {
ModelClass,
State,
} from "@ai16z/eliza";
import { stringToUuid } from "@ai16z/eliza/src/uuid.ts";
import { stringToUuid } from "@ai16z/eliza";
import { ClientBase } from "./base.ts";
import { buildConversationThread, sendTweet, wait } from "./utils.ts";

Expand All @@ -44,15 +38,16 @@ Recent interactions between {{agentName}} and other users:
{{recentPosts}}
# Task: Generate a post in the voice, style and perspective of {{agentName}} (@{{twitterUserName}}):
{{currentPost}}
{{actions}}
# Task: Generate a post in the voice, style and perspective of {{agentName}} (@{{twitterUserName}}). Include an action, if appropriate. {{actionNames}}:
{{currentPost}}
` + messageCompletionFooter;

export const twitterShouldRespondTemplate =
`# INSTRUCTIONS: Determine if {{agentName}} (@{{twitterUserName}}) should respond to the message and participate in the conversation. Do not comment. Just respond with "true" or "false".
Response options are RESPOND, IGNORE and STOP.
Response options are RESPOND, IGNORE and STOP .
{{agentName}} should respond to messages that are directed at them, or participate in conversations that are interesting or relevant to their background, IGNORE messages that are irrelevant to them, and should STOP if the conversation is concluded.
Expand Down Expand Up @@ -195,7 +190,7 @@ export class TwitterInteractionClient extends ClientBase {
message: Memory;
}) {
if (tweet.username === this.runtime.getSetting("TWITTER_USERNAME")) {
console.log("skipping tweet from bot itself", tweet.id);
// console.log("skipping tweet from bot itself", tweet.id);
// Skip processing if the tweet is from the bot itself
return;
}
Expand Down Expand Up @@ -333,6 +328,14 @@ export class TwitterInteractionClient extends ClientBase {
)) as State;

for (const responseMessage of responseMessages) {
if (
responseMessage ===
responseMessages[responseMessages.length - 1]
) {
responseMessage.content.action = response.action;
} else {
responseMessage.content.action = "CONTINUE";
}
await this.runtime.messageManager.createMemory(
responseMessage
);
Expand Down
41 changes: 20 additions & 21 deletions packages/client-twitter/src/post.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Tweet } from "agent-twitter-client";
import fs from "fs";
import { composeContext } from "@ai16z/eliza/src/context.ts";
import { generateText } from "@ai16z/eliza/src/generation.ts";
import { embeddingZeroVector } from "@ai16z/eliza/src/memory.ts";
import { composeContext } from "@ai16z/eliza";
import { generateText } from "@ai16z/eliza";
import { embeddingZeroVector } from "@ai16z/eliza";
import { IAgentRuntime, ModelClass } from "@ai16z/eliza";
import { stringToUuid } from "@ai16z/eliza/src/uuid.ts";
import { stringToUuid } from "@ai16z/eliza";
import { ClientBase } from "./base.ts";

const twitterPostTemplate = `{{timeline}}
Expand All @@ -28,32 +28,31 @@ Write a single sentence post that is {{adjective}} about {{topic}} (without ment
Your response should not contain any questions. Brief, concise statements only. No emojis. Use \\n\\n (double spaces) between statements.`;

export class TwitterPostClient extends ClientBase {


onReady(postImmediately: boolean = true) {
onReady(postImmediately: boolean = true) {
const generateNewTweetLoop = () => {
const minMinutes = parseInt(this.runtime.getSetting("POST_INTERVAL_MIN")) || 90;
const maxMinutes = parseInt(this.runtime.getSetting("POST_INTERVAL_MAX")) || 180;
const randomMinutes = Math.floor(Math.random() * (maxMinutes - minMinutes + 1)) + minMinutes;
const minMinutes =
parseInt(this.runtime.getSetting("POST_INTERVAL_MIN")) || 90;
const maxMinutes =
parseInt(this.runtime.getSetting("POST_INTERVAL_MAX")) || 180;
const randomMinutes =
Math.floor(Math.random() * (maxMinutes - minMinutes + 1)) +
minMinutes;
const delay = randomMinutes * 60 * 1000;

setTimeout(
() => {
this.generateNewTweet();
generateNewTweetLoop(); // Set up next iteration
},
delay
);


setTimeout(() => {
this.generateNewTweet();
generateNewTweetLoop(); // Set up next iteration
}, delay);

console.log(`Next tweet scheduled in ${randomMinutes} minutes`);
};

if (postImmediately) {
this.generateNewTweet();
}
generateNewTweetLoop();
}

constructor(runtime: IAgentRuntime) {
// Initialize the client and pass an optional callback to be called when the client is ready
super({
Expand Down
11 changes: 4 additions & 7 deletions packages/client-twitter/src/search.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
import { SearchMode } from "agent-twitter-client";
import fs from "fs";
import { composeContext } from "@ai16z/eliza/src/context.ts";
import {
generateMessageResponse,
generateText,
} from "@ai16z/eliza/src/generation.ts";
import { messageCompletionFooter } from "@ai16z/eliza/src/parsing.ts";
import { composeContext } from "@ai16z/eliza";
import { generateMessageResponse, generateText } from "@ai16z/eliza";
import { messageCompletionFooter } from "@ai16z/eliza";
import {
Content,
HandlerCallback,
Expand All @@ -15,7 +12,7 @@ import {
ServiceType,
State,
} from "@ai16z/eliza";
import { stringToUuid } from "@ai16z/eliza/src/uuid.ts";
import { stringToUuid } from "@ai16z/eliza";
import { ClientBase } from "./base.ts";
import { buildConversationThread, sendTweet, wait } from "./utils.ts";

Expand Down
Loading

0 comments on commit 53f5bd3

Please sign in to comment.