Skip to content

Commit

Permalink
Merge branch 'develop' into plugin-opacity
Browse files Browse the repository at this point in the history
  • Loading branch information
RonTuretzky authored Jan 6, 2025
2 parents 20b068c + 12ead17 commit 96402a8
Show file tree
Hide file tree
Showing 7 changed files with 89 additions and 66 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
## 🚩 Overview

<div align="center">
<img src="./docs/static/img/eliza_diagram.jpg" alt="Eliza Diagram" width="100%" />
<img src="./docs/static/img/eliza_diagram.png" alt="Eliza Diagram" width="100%" />
</div>

## ✨ Features
Expand Down
26 changes: 23 additions & 3 deletions agent/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,11 +132,11 @@ export async function loadCharacters(
let characterPaths = charactersArg
?.split(",")
.map((filePath) => filePath.trim());
const loadedCharacters = [];
const loadedCharacters: Character[] = [];

if (characterPaths?.length > 0) {
for (const characterPath of characterPaths) {
let content = null;
let content: string | null = null;
let resolvedPath = "";

// Try different path resolutions in order
Expand Down Expand Up @@ -246,7 +246,7 @@ export async function loadCharacters(
export function getTokenForProvider(
provider: ModelProviderName,
character: Character
): string {
): string | undefined {
switch (provider) {
// no key needed for llama_local or gaianet
case ModelProviderName.LLAMALOCAL:
Expand Down Expand Up @@ -672,13 +672,23 @@ export async function createAgent(
}

function initializeFsCache(baseDir: string, character: Character) {
if (!character?.id) {
throw new Error(
"initializeFsCache requires id to be set in character definition"
);
}
const cacheDir = path.resolve(baseDir, character.id, "cache");

const cache = new CacheManager(new FsCacheAdapter(cacheDir));
return cache;
}

function initializeDbCache(character: Character, db: IDatabaseCacheAdapter) {
if (!character?.id) {
throw new Error(
"initializeFsCache requires id to be set in character definition"
);
}
const cache = new CacheManager(new DbCacheAdapter(db, character.id));
return cache;
}
Expand All @@ -694,6 +704,11 @@ function initializeCache(
if (process.env.REDIS_URL) {
elizaLogger.info("Connecting to Redis...");
const redisClient = new RedisClient(process.env.REDIS_URL);
if (!character?.id) {
throw new Error(
"CacheStore.REDIS requires id to be set in character definition"
);
}
return new CacheManager(
new DbCacheAdapter(redisClient, character.id) // Using DbCacheAdapter since RedisClient also implements IDatabaseCacheAdapter
);
Expand All @@ -713,6 +728,11 @@ function initializeCache(

case CacheStore.FILESYSTEM:
elizaLogger.info("Using File System Cache...");
if (!baseDir) {
throw new Error(
"baseDir must be provided for CacheStore.FILESYSTEM."
);
}
return initializeFsCache(baseDir, character);

default:
Expand Down
Binary file added docs/static/img/eliza_diagram.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,7 @@ ${currentSummary.trim()}
{
user: "{{user2}}",
content: {
text: "no probblem, give me a few minutes to read through everything",
text: "no problem, give me a few minutes to read through everything",
action: "SUMMARIZE",
},
},
Expand Down
98 changes: 48 additions & 50 deletions packages/client-telegram/src/messageManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1051,6 +1051,53 @@ export class MessageManager {
// Decide whether to respond
const shouldRespond = await this._shouldRespond(message, state);

// Send response in chunks
const callback: HandlerCallback = async (content: Content) => {
const sentMessages = await this.sendMessageInChunks(
ctx,
content,
message.message_id
);
if (sentMessages) {
const memories: Memory[] = [];

// Create memories for each sent message
for (let i = 0; i < sentMessages.length; i++) {
const sentMessage = sentMessages[i];
const isLastMessage = i === sentMessages.length - 1;

const memory: Memory = {
id: stringToUuid(
sentMessage.message_id.toString() +
"-" +
this.runtime.agentId
),
agentId,
userId: agentId,
roomId,
content: {
...content,
text: sentMessage.text,
inReplyTo: messageId,
},
createdAt: sentMessage.date * 1000,
embedding: getEmbeddingZeroVector(),
};

// 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);
}

return memories;
}
};

if (shouldRespond) {
// Generate response
const context = composeContext({
Expand All @@ -1071,55 +1118,6 @@ export class MessageManager {

if (!responseContent || !responseContent.text) return;

// Send response in chunks
const callback: HandlerCallback = async (content: Content) => {
const sentMessages = await this.sendMessageInChunks(
ctx,
content,
message.message_id
);
if (sentMessages) {
const memories: Memory[] = [];

// Create memories for each sent message
for (let i = 0; i < sentMessages.length; i++) {
const sentMessage = sentMessages[i];
const isLastMessage = i === sentMessages.length - 1;

const memory: Memory = {
id: stringToUuid(
sentMessage.message_id.toString() +
"-" +
this.runtime.agentId
),
agentId,
userId: agentId,
roomId,
content: {
...content,
text: sentMessage.text,
inReplyTo: messageId,
},
createdAt: sentMessage.date * 1000,
embedding: getEmbeddingZeroVector(),
};

// 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);
}

return memories;
}
};

// Execute callback to send messages and log memories
const responseMessages = await callback(responseContent);

Expand All @@ -1135,7 +1133,7 @@ export class MessageManager {
);
}

await this.runtime.evaluate(memory, state, shouldRespond);
await this.runtime.evaluate(memory, state, shouldRespond, callback);
} catch (error) {
elizaLogger.error("❌ Error handling message:", error);
elizaLogger.error("Error sending message:", error);
Expand Down
25 changes: 15 additions & 10 deletions packages/core/src/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,6 @@ import {
type Evaluator,
type Memory,
IVerifiableInferenceAdapter,
VerifiableInferenceOptions,
VerifiableInferenceProvider,
} from "./types.ts";
import { stringToUuid } from "./uuid.ts";

Expand Down Expand Up @@ -628,7 +626,7 @@ export class AgentRuntime implements IAgentRuntime {
*/
async evaluate(
message: Memory,
state?: State,
state: State,
didRespond?: boolean,
callback?: HandlerCallback
) {
Expand All @@ -650,10 +648,12 @@ export class AgentRuntime implements IAgentRuntime {
);

const resolvedEvaluators = await Promise.all(evaluatorPromises);
const evaluatorsData = resolvedEvaluators.filter(Boolean);
const evaluatorsData = resolvedEvaluators.filter(
(evaluator): evaluator is Evaluator => evaluator !== null
);

// if there are no evaluators this frame, return
if (evaluatorsData.length === 0) {
if (!evaluatorsData || evaluatorsData.length === 0) {
return [];
}

Expand All @@ -680,7 +680,7 @@ export class AgentRuntime implements IAgentRuntime {
) as unknown as string[];

for (const evaluator of this.evaluators) {
if (!evaluators.includes(evaluator.name)) continue;
if (!evaluators?.includes(evaluator.name)) continue;

if (evaluator.handler)
await evaluator.handler(this, message, state, {}, callback);
Expand Down Expand Up @@ -859,7 +859,8 @@ export class AgentRuntime implements IAgentRuntime {
);

if (lastMessageWithAttachment) {
const lastMessageTime = lastMessageWithAttachment.createdAt;
const lastMessageTime =
lastMessageWithAttachment?.createdAt ?? Date.now();
const oneHourBeforeLastMessage =
lastMessageTime - 60 * 60 * 1000; // 1 hour before last message

Expand Down Expand Up @@ -956,7 +957,10 @@ Text: ${attachment.text}
});

// Sort messages by timestamp in descending order
existingMemories.sort((a, b) => b.createdAt - a.createdAt);
existingMemories.sort(
(a, b) =>
(b?.createdAt ?? Date.now()) - (a?.createdAt ?? Date.now())
);

// Take the most recent messages
const recentInteractionsData = existingMemories.slice(0, 20);
Expand Down Expand Up @@ -1269,13 +1273,14 @@ Text: ${attachment.text}
);

if (lastMessageWithAttachment) {
const lastMessageTime = lastMessageWithAttachment.createdAt;
const lastMessageTime =
lastMessageWithAttachment?.createdAt ?? Date.now();
const oneHourBeforeLastMessage =
lastMessageTime - 60 * 60 * 1000; // 1 hour before last message

allAttachments = recentMessagesData
.filter((msg) => {
const msgTime = msg.createdAt;
const msgTime = msg.createdAt ?? Date.now();
return msgTime >= oneHourBeforeLastMessage;
})
.flatMap((msg) => msg.content.attachments || []);
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1167,7 +1167,7 @@ export interface IAgentRuntime {
state?: State,
didRespond?: boolean,
callback?: HandlerCallback
): Promise<string[]>;
): Promise<string[] | null>;

ensureParticipantExists(userId: UUID, roomId: UUID): Promise<void>;

Expand Down

0 comments on commit 96402a8

Please sign in to comment.