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

feat: Client Reddit Files #1445

Open
wants to merge 6 commits into
base: develop
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions agent/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"@elizaos/plugin-image-generation": "workspace:*",
"@elizaos/plugin-nft-generation": "workspace:*",
"@elizaos/plugin-node": "workspace:*",
"@elizaos/client-reddit": "workspace:*",
"@elizaos/plugin-solana": "workspace:*",
"@elizaos/plugin-starknet": "workspace:*",
"@elizaos/plugin-ton": "workspace:*",
Expand Down
91 changes: 18 additions & 73 deletions agent/src/index.ts
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

all these regressions needs to be fixed

Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { LensAgentClient } from "@elizaos/client-lens";
import { SlackClientInterface } from "@elizaos/client-slack";
import { TelegramClientInterface } from "@elizaos/client-telegram";
import { TwitterClientInterface } from "@elizaos/client-twitter";
import { RedditClientInterface } from "@elizaos/plugin-reddit";
import {
AgentRuntime,
CacheManager,
Expand Down Expand Up @@ -78,8 +79,7 @@ export const wait = (minTime: number = 1000, maxTime: number = 3000) => {

const logFetch = async (url: string, options: any) => {
elizaLogger.debug(`Fetching ${url}`);
// Disabled to avoid disclosure of sensitive information such as API keys
// elizaLogger.debug(JSON.stringify(options, null, 2));
elizaLogger.debug(JSON.stringify(options, null, 2));
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this shouldn't be enabled

return fetch(url, options);
};

Expand Down Expand Up @@ -237,15 +237,8 @@ export async function loadCharacters(
export function getTokenForProvider(
provider: ModelProviderName,
character: Character
): string {
) {
switch (provider) {
// no key needed for llama_local or gaianet
case ModelProviderName.LLAMALOCAL:
return "";
case ModelProviderName.OLLAMA:
return "";
case ModelProviderName.GAIANET:
return "";
case ModelProviderName.OPENAI:
return (
character.settings?.secrets?.OPENAI_API_KEY ||
Expand All @@ -268,7 +261,6 @@ export function getTokenForProvider(
character.settings?.secrets?.OPENAI_API_KEY ||
settings.OPENAI_API_KEY
);
case ModelProviderName.CLAUDE_VERTEX:
case ModelProviderName.ANTHROPIC:
return (
character.settings?.secrets?.ANTHROPIC_API_KEY ||
Expand Down Expand Up @@ -340,15 +332,6 @@ export function getTokenForProvider(
character.settings?.secrets?.AKASH_CHAT_API_KEY ||
settings.AKASH_CHAT_API_KEY
);
case ModelProviderName.GOOGLE:
return (
character.settings?.secrets?.GOOGLE_GENERATIVE_AI_API_KEY ||
settings.GOOGLE_GENERATIVE_AI_API_KEY
);
default:
const errorMessage = `Failed to get token - unsupported model provider: ${provider}`;
elizaLogger.error(errorMessage);
throw new Error(errorMessage);
}
}

Expand Down Expand Up @@ -429,14 +412,19 @@ export async function initializeClients(
clients.lens = lensClient;
}

if (clientTypes.includes(Clients.REDDIT)) {
const redditClient = await RedditClientInterface.start(runtime);
if (redditClient) {
clients.reddit = redditClient;
}
}

elizaLogger.log("client keys", Object.keys(clients));

// TODO: Add Slack client to the list
// Initialize clients as an object

if (clientTypes.includes("slack")) {
const slackClient = await SlackClientInterface.start(runtime);
if (slackClient) clients.slack = slackClient; // Use object property instead of push
if (slackClient) clients.push(slackClient);
}

function determineClientType(client: Client): string {
Expand All @@ -457,6 +445,7 @@ export async function initializeClients(

if (character.plugins?.length > 0) {
for (const plugin of character.plugins) {
// if plugin has clients, add those..
if (plugin.clients) {
for (const client of plugin.clients) {
const startedClient = await client.start(runtime);
Expand Down Expand Up @@ -615,48 +604,9 @@ function initializeDbCache(character: Character, db: IDatabaseCacheAdapter) {
return cache;
}

function initializeCache(
cacheStore: string,
character: Character,
baseDir?: string,
db?: IDatabaseCacheAdapter
) {
switch (cacheStore) {
case CacheStore.REDIS:
if (process.env.REDIS_URL) {
elizaLogger.info("Connecting to Redis...");
const redisClient = new RedisClient(process.env.REDIS_URL);
return new CacheManager(
new DbCacheAdapter(redisClient, character.id) // Using DbCacheAdapter since RedisClient also implements IDatabaseCacheAdapter
);
} else {
throw new Error("REDIS_URL environment variable is not set.");
}

case CacheStore.DATABASE:
if (db) {
elizaLogger.info("Using Database Cache...");
return initializeDbCache(character, db);
} else {
throw new Error(
"Database adapter is not provided for CacheStore.Database."
);
}

case CacheStore.FILESYSTEM:
elizaLogger.info("Using File System Cache...");
return initializeFsCache(baseDir, character);

default:
throw new Error(
`Invalid cache store: ${cacheStore} or required configuration missing.`
);
}
}

async function startAgent(
character: Character,
directClient: DirectClient
directClient
): Promise<AgentRuntime> {
let db: IDatabaseAdapter & IDatabaseCacheAdapter;
try {
Expand All @@ -675,12 +625,7 @@ async function startAgent(

await db.init();

const cache = initializeCache(
process.env.CACHE_STORE ?? CacheStore.DATABASE,
character,
"",
db
); // "" should be replaced with dir for file system caching. THOUGHTS: might probably make this into an env
const cache = initializeDbCache(character, db);
const runtime: AgentRuntime = await createAgent(
character,
db,
Expand Down Expand Up @@ -761,9 +706,9 @@ const startAgents = async () => {
}

// upload some agent functionality into directClient
directClient.startAgent = async (character: Character) => {
// wrap it so we don't have to inject directClient later
return startAgent(character, directClient);
directClient.startAgent = async character => {
// wrap it so we don't have to inject directClient later
return startAgent(character, directClient)
};

directClient.start(serverPort);
Expand All @@ -773,7 +718,7 @@ const startAgents = async () => {
}

elizaLogger.log(
"Run `pnpm start:client` to start the client and visit the outputted URL (http://localhost:5173) to chat with your agents. When running multiple agents, use client with different port `SERVER_PORT=3001 pnpm start:client`"
"Run `pnpm start:client` to start the client and visit the outputted URL (http://localhost:5173) to chat with your agents. When running multiple Eliza instances, use client with different port `SERVER_PORT=3001 pnpm start:client`"
);
};

Expand Down
6 changes: 6 additions & 0 deletions packages/client-reddit/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
*

!dist/**
!package.json
!readme.md
!tsup.config.ts
3 changes: 3 additions & 0 deletions packages/client-reddit/eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import eslintGlobalConfig from "../../eslint.config.mjs";

export default [...eslintGlobalConfig];
22 changes: 22 additions & 0 deletions packages/client-reddit/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "@ai16z/client-reddit",
"version": "0.1.0",
"main": "dist/index.js",
"type": "module",
"types": "dist/index.d.ts",
"dependencies": {
"@ai16z/eliza": "workspace:*",
"snoowrap": "^1.23.0"
},
"devDependencies": {
"@types/node": "^20.0.0",
"tsup": "8.3.5",
"vitest": "^2.1.4"
},
"scripts": {
"build": "tsup --format esm --dts",
"dev": "tsup --format esm --dts --watch",
"test": "vitest run",
"test:watch": "vitest watch"
}
}
49 changes: 49 additions & 0 deletions packages/client-reddit/src/actions/comment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { Action, IAgentRuntime, Memory } from "@ai16z/eliza";

export const createComment: Action = {
name: "CREATE_REDDIT_COMMENT",
similes: ["COMMENT_ON_REDDIT", "REPLY_ON_REDDIT"],
validate: async (runtime: IAgentRuntime, message: Memory) => {
const hasCredentials = !!runtime.getSetting("REDDIT_CLIENT_ID") &&
!!runtime.getSetting("REDDIT_CLIENT_SECRET") &&
!!runtime.getSetting("REDDIT_REFRESH_TOKEN");
return hasCredentials;
},
handler: async (
runtime: IAgentRuntime,
message: Memory,
state: any,
options: any
) => {
const { reddit } = await runtime.getProvider("redditProvider");

// Extract post ID and comment content from message
const postId = options.postId; // This should be a fullname (t3_postid)
const content = message.content.text;

try {
await reddit.getSubmission(postId).reply(content);
return true;
} catch (error) {
console.error("Failed to create Reddit comment:", error);
return false;
}
},
examples: [
[
{
user: "{{user1}}",
content: {
text: "Comment on this Reddit post: t3_abc123 with: Great post!"
},
},
{
user: "{{agentName}}",
content: {
text: "I'll add that comment to the Reddit post",
action: "CREATE_REDDIT_COMMENT",
},
},
],
],
};
88 changes: 88 additions & 0 deletions packages/client-reddit/src/actions/post.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { Action, IAgentRuntime, Memory } from "@ai16z/eliza";
import { RedditPost } from "../types";

export const createPost: Action = {
name: "CREATE_REDDIT_POST",
similes: ["POST_TO_REDDIT", "SUBMIT_REDDIT_POST"],
validate: async (runtime: IAgentRuntime, message: Memory) => {
const hasCredentials = !!runtime.getSetting("REDDIT_CLIENT_ID") &&
!!runtime.getSetting("REDDIT_CLIENT_SECRET") &&
!!runtime.getSetting("REDDIT_REFRESH_TOKEN");
return hasCredentials;
},
handler: async (
runtime: IAgentRuntime,
message: Memory,
state: any,
options: any
) => {
const { reddit } = await runtime.getProvider("redditProvider");

// Parse the subreddit and content from the message
// Expected format: "Post to r/subreddit: Title | Content"
const messageText = message.content.text;
const match = messageText.match(/Post to r\/(\w+):\s*([^|]+)\|(.*)/i);

if (!match) {
throw new Error("Invalid post format. Use: Post to r/subreddit: Title | Content");
}

const [_, subreddit, title, content] = match;

try {
const post = await reddit.submitSelfpost({
subredditName: subreddit.trim(),
title: title.trim(),
text: content.trim()
});

return {
success: true,
data: {
id: post.id,
url: post.url,
subreddit: post.subreddit.display_name,
title: post.title
}
};
} catch (error) {
console.error("Failed to create Reddit post:", error);
return {
success: false,
error: error.message
};
}
},
examples: [
[
{
user: "{{user1}}",
content: {
text: "Post to r/test: My First Post | This is the content of my post"
},
},
{
user: "{{agentName}}",
content: {
text: "I'll create that post on r/test for you",
action: "CREATE_REDDIT_POST",
},
},
],
[
{
user: "{{user1}}",
content: {
text: "Post to r/AskReddit: What's your favorite book? | I'm curious to know what books everyone loves and why."
},
},
{
user: "{{agentName}}",
content: {
text: "Creating your post on r/AskReddit",
action: "CREATE_REDDIT_POST",
},
},
],
],
};
Loading
Loading