Skip to content

Commit

Permalink
upd: resolved a bunch of type related errors and ensure project compi…
Browse files Browse the repository at this point in the history
…les properly
  • Loading branch information
JoeyKhd committed Jan 6, 2025
1 parent dc11461 commit 0541aa4
Show file tree
Hide file tree
Showing 6 changed files with 44 additions and 49 deletions.
30 changes: 24 additions & 6 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 @@ -602,9 +602,7 @@ export async function createAgent(
advancedTradePlugin,
]
: []),
...(teeMode !== TEEMode.OFF && walletSecretSalt
? [teePlugin]
: []),
...(teeMode !== TEEMode.OFF && walletSecretSalt ? [teePlugin] : []),
getSecret(character, "COINBASE_API_KEY") &&
getSecret(character, "COINBASE_PRIVATE_KEY") &&
getSecret(character, "COINBASE_NOTIFICATION_URI")
Expand Down Expand Up @@ -657,13 +655,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 @@ -679,6 +687,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 @@ -698,6 +711,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
2 changes: 0 additions & 2 deletions packages/core/src/knowledge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ async function get(
return [];
}

// @ts-expect-error todo
const embedding = await embed(runtime, processed);
const fragments = await runtime.knowledgeManager.searchMemoriesByEmbedding(
embedding,
Expand Down Expand Up @@ -86,7 +85,6 @@ async function set(
const fragments = await splitChunks(preprocessed, chunkSize, bleed);

for (const fragment of fragments) {
// @ts-expect-error todo
const embedding = await embed(runtime, fragment);
await runtime.knowledgeManager.createMemory({
// We namespace the knowledge base uuid to avoid id
Expand Down
52 changes: 19 additions & 33 deletions packages/core/src/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,6 @@ import {
type Evaluator,
type Memory,
IVerifiableInferenceAdapter,
VerifiableInferenceOptions,
VerifiableInferenceProvider,
} from "./types.ts";
import { stringToUuid } from "./uuid.ts";

Expand Down Expand Up @@ -277,31 +275,26 @@ export class AgentRuntime implements IAgentRuntime {
this.cacheManager = opts.cacheManager;

this.messageManager = new MemoryManager({
// @ts-expect-error todo
runtime: this,
tableName: "messages",
});

this.descriptionManager = new MemoryManager({
// @ts-expect-error todo
runtime: this,
tableName: "descriptions",
});

this.loreManager = new MemoryManager({
// @ts-expect-error todo
runtime: this,
tableName: "lore",
});

this.documentsManager = new MemoryManager({
// @ts-expect-error todo
runtime: this,
tableName: "documents",
});

this.knowledgeManager = new MemoryManager({
// @ts-expect-error todo
runtime: this,
tableName: "fragments",
});
Expand Down Expand Up @@ -407,7 +400,6 @@ export class AgentRuntime implements IAgentRuntime {
async initialize() {
for (const [serviceType, service] of this.services.entries()) {
try {
// @ts-expect-error todo
await service.initialize(this);
this.services.set(serviceType, service);
elizaLogger.success(
Expand All @@ -425,7 +417,6 @@ export class AgentRuntime implements IAgentRuntime {
for (const plugin of this.plugins) {
if (plugin.services)
await Promise.all(
// @ts-expect-error todo
plugin.services?.map((service) => service.initialize(this))
);
}
Expand Down Expand Up @@ -619,7 +610,7 @@ export class AgentRuntime implements IAgentRuntime {
elizaLogger.info(
`Executing handler for action: ${action.name}`
);
// @ts-expect-error todo

await action.handler(this, message, state, {}, callback);
} catch (error) {
elizaLogger.error(error);
Expand All @@ -635,10 +626,10 @@ export class AgentRuntime implements IAgentRuntime {
* @param callback The handler callback
* @returns The results of the evaluation.
*/
// @ts-expect-error todo

async evaluate(
message: Memory,
state?: State,
state: State,
didRespond?: boolean,
callback?: HandlerCallback
) {
Expand All @@ -651,7 +642,7 @@ export class AgentRuntime implements IAgentRuntime {
if (!didRespond && !evaluator.alwaysRun) {
return null;
}
// @ts-expect-error todo

const result = await evaluator.validate(this, message, state);
if (result) {
return evaluator;
Expand All @@ -661,20 +652,19 @@ 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 [];
}

const context = composeContext({
// @ts-expect-error todo
state: {
...state,
// @ts-expect-error todo
evaluators: formatEvaluators(evaluatorsData),
// @ts-expect-error todo
evaluatorNames: formatEvaluatorNames(evaluatorsData),
},
template:
Expand All @@ -683,7 +673,6 @@ export class AgentRuntime implements IAgentRuntime {
});

const result = await generateText({
// @ts-expect-error todo
runtime: this,
context,
modelClass: ModelClass.SMALL,
Expand All @@ -696,7 +685,6 @@ export class AgentRuntime implements IAgentRuntime {
if (!evaluators?.includes(evaluator.name)) continue;

if (evaluator.handler)
// @ts-expect-error todo
await evaluator.handler(this, message, state, {}, callback);
}

Expand Down Expand Up @@ -823,15 +811,13 @@ export class AgentRuntime implements IAgentRuntime {
Memory[],
Goal[],
] = await Promise.all([
// @ts-expect-error todo
getActorDetails({ runtime: this, roomId }),
this.messageManager.getMemories({
roomId,
count: conversationLength,
unique: false,
}),
getGoals({
// @ts-expect-error todo
runtime: this,
count: 10,
onlyInProgress: false,
Expand Down Expand Up @@ -875,9 +861,9 @@ export class AgentRuntime implements IAgentRuntime {
);

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

allAttachments = recentMessagesData
Expand Down Expand Up @@ -973,8 +959,10 @@ Text: ${attachment.text}
});

// Sort messages by timestamp in descending order
// @ts-expect-error todo
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 @@ -1190,7 +1178,6 @@ Text: ${attachment.text}
} as State;

const actionPromises = this.actions.map(async (action: Action) => {
// @ts-expect-error todo
const result = await action.validate(this, message, initialState);
if (result) {
return action;
Expand All @@ -1200,7 +1187,6 @@ Text: ${attachment.text}

const evaluatorPromises = this.evaluators.map(async (evaluator) => {
const result = await evaluator.validate(
// @ts-expect-error todo
this,
message,
initialState
Expand All @@ -1215,7 +1201,7 @@ Text: ${attachment.text}
await Promise.all([
Promise.all(evaluatorPromises),
Promise.all(actionPromises),
// @ts-expect-error todo

getProviders(this, message, initialState),
]);

Expand Down Expand Up @@ -1290,15 +1276,15 @@ Text: ${attachment.text}
);

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

allAttachments = recentMessagesData
.filter((msg) => {
const msgTime = msg.createdAt;
// @ts-expect-error todo
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 @@ -1169,7 +1169,7 @@ export interface IAgentRuntime {
state?: State,
didRespond?: boolean,
callback?: HandlerCallback
): Promise<string[]>;
): Promise<string[] | null>;

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

Expand Down
3 changes: 0 additions & 3 deletions packages/plugin-bootstrap/src/providers/facts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import type { Memory, Provider, State } from "@elizaos/core";
import { formatFacts } from "../evaluators/fact.ts";

const factsProvider: Provider = {
// @ts-expect-error todo
get: async (runtime: IAgentRuntime, message: Memory, state?: State) => {
const recentMessagesData = state?.recentMessagesData?.slice(-10);

Expand All @@ -19,11 +18,9 @@ const factsProvider: Provider = {
actors: state?.actorsData,
});

// @ts-expect-error todo
const _embedding = await embed(runtime, recentMessages);

const memoryManager = new MemoryManager({
// @ts-expect-error todo
runtime,
tableName: "facts",
});
Expand Down
4 changes: 0 additions & 4 deletions packages/plugin-nft-generation/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ export function createNFTApiRouter(
}
try {
const collectionAddressRes = await createCollection({
// @ts-expect-error todo
runtime,
collectionName: runtime.character.name,
fee,
Expand Down Expand Up @@ -59,7 +58,6 @@ export function createNFTApiRouter(

try {
const nftInfo = await createNFTMetadata({
// @ts-expect-error todo
runtime,
collectionName,
collectionAdminPublicKey,
Expand Down Expand Up @@ -101,7 +99,6 @@ export function createNFTApiRouter(

try {
const nftRes = await createNFT({
// @ts-expect-error todo
runtime,
collectionName,
collectionAddress,
Expand Down Expand Up @@ -144,7 +141,6 @@ export function createNFTApiRouter(
}
try {
const { success } = await verifyNFT({
// @ts-expect-error todo
runtime,
collectionAddress,
NFTAddress,
Expand Down

0 comments on commit 0541aa4

Please sign in to comment.