Skip to content

Commit 9cf81fb

Browse files
committed
chore: modernize code with mordern javascript
1 parent ea9d1c0 commit 9cf81fb

15 files changed

+329
-502
lines changed

packages/core/src/actions.ts

+28-28
Original file line numberDiff line numberDiff line change
@@ -9,70 +9,70 @@ import { Action, ActionExample } from "./types.ts";
99
* @returns A string containing formatted examples of conversations.
1010
*/
1111
export const composeActionExamples = (actionsData: Action[], count: number) => {
12-
const data: ActionExample[][][] = actionsData.map((action: Action) => [
13-
...action.examples,
14-
]);
12+
if (!actionsData.length) return '';
13+
14+
const data: ActionExample[][][] = actionsData.map(({ examples }) => [...examples]);
1515

1616
const actionExamples: ActionExample[][] = [];
1717
let length = data.length;
18+
1819
for (let i = 0; i < count && length; i++) {
1920
const actionId = i % length;
2021
const examples = data[actionId];
21-
if (examples.length) {
22-
const rand = ~~(Math.random() * examples.length);
23-
actionExamples[i] = examples.splice(rand, 1)[0];
22+
23+
if (examples?.length) {
24+
const [example] = examples.splice(Math.floor(Math.random() * examples.length), 1);
25+
actionExamples[i] = example;
2426
} else {
2527
i--;
2628
}
2729

28-
if (examples.length == 0) {
30+
if (!examples.length) {
2931
data.splice(actionId, 1);
3032
length--;
3133
}
3234
}
3335

3436
const formattedExamples = actionExamples.map((example) => {
35-
const exampleNames = Array.from({ length: 5 }, () =>
36-
uniqueNamesGenerator({ dictionaries: [names] })
37+
const exampleNames = Array.from(
38+
{ length: 5 },
39+
() => uniqueNamesGenerator({ dictionaries: [names] })
3740
);
3841

39-
return `\n${example
40-
.map((message) => {
41-
let messageString = `${message.user}: ${message.content.text}${message.content.action ? ` (${message.content.action})` : ""}`;
42-
for (let i = 0; i < exampleNames.length; i++) {
43-
messageString = messageString.replaceAll(
44-
`{{user${i + 1}}}`,
45-
exampleNames[i]
46-
);
47-
}
42+
return example
43+
.map(({ user, content: { text, action } }) => {
44+
const actionText = action ? ` (${action})` : '';
45+
let messageString = `${user}: ${text}${actionText}`;
46+
47+
exampleNames.forEach((name, index) => {
48+
messageString = messageString.replaceAll(`{{user${index + 1}}}`, name);
49+
});
4850
return messageString;
4951
})
50-
.join("\n")}`;
52+
.join('\n');
5153
});
5254

53-
return formattedExamples.join("\n");
55+
return formattedExamples.length ? `\n${formattedExamples.join('\n')}` : '';
5456
};
5557

5658
/**
5759
* Formats the names of the provided actions into a comma-separated string.
5860
* @param actions - An array of `Action` objects from which to extract names.
5961
* @returns A comma-separated string of action names.
6062
*/
61-
export function formatActionNames(actions: Action[]) {
62-
return actions
63+
export const formatActionNames = (actions: Action[]): string =>
64+
actions
6365
.sort(() => 0.5 - Math.random())
64-
.map((action: Action) => `${action.name}`)
66+
.map(({ name }) => name)
6567
.join(", ");
66-
}
6768

6869
/**
6970
* Formats the provided actions into a detailed string listing each action's name and description, separated by commas and newlines.
7071
* @param actions - An array of `Action` objects to format.
7172
* @returns A detailed string of actions, including names and descriptions.
7273
*/
73-
export function formatActions(actions: Action[]) {
74-
return actions
74+
export const formatActions = (actions: Action[]): string =>
75+
actions
7576
.sort(() => 0.5 - Math.random())
76-
.map((action: Action) => `${action.name}: ${action.description}`)
77+
.map(({ name, description }) => `${name}: ${description}`)
7778
.join(",\n");
78-
}

packages/core/src/cache.ts

+20-17
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,12 @@ export interface ICacheAdapter {
1414
}
1515

1616
export class MemoryCacheAdapter implements ICacheAdapter {
17-
data: Map<string, string>;
17+
private data = new Map<string, string>();
1818

19-
constructor(initalData?: Map<string, string>) {
20-
this.data = initalData ?? new Map<string, string>();
19+
constructor(initialData?: Map<string, string>) {
20+
if (initialData) {
21+
this.data = initialData;
22+
}
2123
}
2224

2325
async get(key: string): Promise<string | undefined> {
@@ -48,20 +50,23 @@ export class FsCacheAdapter implements ICacheAdapter {
4850
async set(key: string, value: string): Promise<void> {
4951
try {
5052
const filePath = path.join(this.dataDir, key);
51-
// Ensure the directory exists
53+
// Ensure directory exists
5254
await fs.mkdir(path.dirname(filePath), { recursive: true });
5355
await fs.writeFile(filePath, value, "utf8");
5456
} catch (error) {
55-
console.error(error);
57+
console.error(`Failed to write cache file: ${error}`);
5658
}
5759
}
5860

5961
async delete(key: string): Promise<void> {
6062
try {
6163
const filePath = path.join(this.dataDir, key);
6264
await fs.unlink(filePath);
63-
} catch {
64-
// console.error(error);
65+
} catch (error) {
66+
// Skip if file doesn't exist
67+
if (error.code !== 'ENOENT') {
68+
console.error(`Failed to delete cache file: ${error}`);
69+
}
6570
}
6671
}
6772
}
@@ -96,20 +101,18 @@ export class CacheManager<CacheAdapter extends ICacheAdapter = ICacheAdapter>
96101

97102
async get<T = unknown>(key: string): Promise<T | undefined> {
98103
const data = await this.adapter.get(key);
104+
if (!data) return undefined;
99105

100-
if (data) {
101-
const { value, expires } = JSON.parse(data) as {
102-
value: T;
103-
expires: number;
104-
};
105-
106-
if (!expires || expires > Date.now()) {
107-
return value;
108-
}
106+
const { value, expires } = JSON.parse(data) as {
107+
value: T;
108+
expires: number;
109+
};
109110

110-
this.adapter.delete(key).catch(() => {});
111+
if (!expires || expires > Date.now()) {
112+
return value;
111113
}
112114

115+
await this.adapter.delete(key).catch(() => {});
113116
return undefined;
114117
}
115118

packages/core/src/context.ts

+1-4
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,7 @@ export const composeContext = ({
4141
}
4242

4343
// @ts-expect-error match isn't working as expected
44-
const out = template.replace(/{{\w+}}/g, (match) => {
45-
const key = match.replace(/{{|}}/g, "");
46-
return state[key] ?? "";
47-
});
44+
const out = template.replace(/{{(\w+)}}/g, (_, key) => state[key] ?? "");
4845
return out;
4946
};
5047

packages/core/src/embedding.ts

+10-34
Original file line numberDiff line numberDiff line change
@@ -73,19 +73,12 @@ async function getRemoteEmbedding(
7373
method: "POST",
7474
headers: {
7575
"Content-Type": "application/json",
76-
...(options.apiKey
77-
? {
78-
Authorization: `Bearer ${options.apiKey}`,
79-
}
80-
: {}),
76+
...(options.apiKey && { Authorization: `Bearer${options.apiKey}` }),
8177
},
8278
body: JSON.stringify({
8379
input,
8480
model: options.model,
85-
dimensions:
86-
options.dimensions ||
87-
options.length ||
88-
getEmbeddingConfig().dimensions, // Prefer dimensions, fallback to length
81+
dimensions: options.dimensions ?? options.length ?? getEmbeddingConfig().dimensions,
8982
}),
9083
};
9184

@@ -99,23 +92,16 @@ async function getRemoteEmbedding(
9992
);
10093
}
10194

102-
interface EmbeddingResponse {
103-
data: Array<{ embedding: number[] }>;
104-
}
105-
106-
const data: EmbeddingResponse = await response.json();
107-
return data?.data?.[0].embedding;
95+
const { data: [{ embedding }] = [{ embedding: [] }] }= await response.json();
96+
return embedding;
10897
} catch (e) {
10998
elizaLogger.error("Full error details:", e);
11099
throw e;
111100
}
112101
}
113102

114103
export function getEmbeddingType(runtime: IAgentRuntime): "local" | "remote" {
115-
const isNode =
116-
typeof process !== "undefined" &&
117-
process.versions != null &&
118-
process.versions.node != null;
104+
const isNode = Boolean(process?.versions?.node);
119105

120106
// Use local embedding if:
121107
// - Running in Node.js
@@ -185,7 +171,7 @@ export async function embed(runtime: IAgentRuntime, input: string) {
185171
if (cachedEmbedding) return cachedEmbedding;
186172

187173
const config = getEmbeddingConfig();
188-
const isNode = typeof process !== "undefined" && process.versions?.node;
174+
const isNode = Boolean(process?.versions?.node);
189175

190176
// Determine which embedding path to use
191177
if (config.provider === EmbeddingProvider.OpenAI) {
@@ -248,10 +234,7 @@ export async function embed(runtime: IAgentRuntime, input: string) {
248234
elizaLogger.debug("DEBUG - Inside getLocalEmbedding function");
249235

250236
// Check if we're in Node.js environment
251-
const isNode =
252-
typeof process !== "undefined" &&
253-
process.versions != null &&
254-
process.versions.node != null;
237+
const isNode = Boolean(process?.versions?.node);
255238

256239
if (!isNode) {
257240
elizaLogger.warn(
@@ -387,20 +370,13 @@ export async function embed(runtime: IAgentRuntime, input: string) {
387370
}
388371
}
389372

390-
async function retrieveCachedEmbedding(
391-
runtime: IAgentRuntime,
392-
input: string
393-
) {
373+
async function retrieveCachedEmbedding(runtime: IAgentRuntime, input: string) {
394374
if (!input) {
395375
elizaLogger.log("No input to retrieve cached embedding for");
396376
return null;
397377
}
398378

399-
const similaritySearchResult =
400-
await runtime.messageManager.getCachedEmbeddings(input);
401-
if (similaritySearchResult.length > 0) {
402-
return similaritySearchResult[0].embedding;
403-
}
404-
return null;
379+
const [firstResult] = await runtime.messageManager.getCachedEmbeddings(input);
380+
return firstResult?.embedding ?? null;
405381
}
406382
}

packages/core/src/evaluators.ts

+40-45
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,7 @@ export function formatEvaluatorNames(evaluators: Evaluator[]) {
4040
*/
4141
export function formatEvaluators(evaluators: Evaluator[]) {
4242
return evaluators
43-
.map(
44-
(evaluator: Evaluator) =>
45-
`'${evaluator.name}: ${evaluator.description}'`
46-
)
43+
.map(({ name, description }) => `'${name}: ${description}'`)
4744
.join(",\n");
4845
}
4946

@@ -54,52 +51,50 @@ export function formatEvaluators(evaluators: Evaluator[]) {
5451
*/
5552
export function formatEvaluatorExamples(evaluators: Evaluator[]) {
5653
return evaluators
57-
.map((evaluator) => {
58-
return evaluator.examples
59-
.map((example) => {
60-
const exampleNames = Array.from({ length: 5 }, () =>
61-
uniqueNamesGenerator({ dictionaries: [names] })
62-
);
54+
.flatMap(({ examples }) =>
55+
examples.map((example) => {
56+
const exampleNames = [...Array(5)].map(() =>
57+
uniqueNamesGenerator({ dictionaries: [names] })
58+
);
6359

64-
let formattedContext = example.context;
65-
let formattedOutcome = example.outcome;
60+
const { context, messages, outcome } = example;
61+
let formattedContext = context;
62+
let formattedOutcome = outcome;
6663

67-
exampleNames.forEach((name, index) => {
68-
const placeholder = `{{user${index + 1}}}`;
69-
formattedContext = formattedContext.replaceAll(
70-
placeholder,
71-
name
72-
);
73-
formattedOutcome = formattedOutcome.replaceAll(
74-
placeholder,
75-
name
76-
);
77-
});
64+
exampleNames.forEach((name, index) => {
65+
const placeholder = `{{user${index + 1}}}`;
66+
formattedContext = formattedContext.replaceAll(
67+
placeholder,
68+
name
69+
);
70+
formattedOutcome = formattedOutcome.replaceAll(
71+
placeholder,
72+
name
73+
);
74+
});
7875

79-
const formattedMessages = example.messages
80-
.map((message: ActionExample) => {
81-
let messageString = `${message.user}: ${message.content.text}`;
82-
exampleNames.forEach((name, index) => {
83-
const placeholder = `{{user${index + 1}}}`;
84-
messageString = messageString.replaceAll(
85-
placeholder,
86-
name
87-
);
88-
});
89-
return (
90-
messageString +
91-
(message.content.action
92-
? ` (${message.content.action})`
93-
: "")
76+
const formattedMessages = messages
77+
.map((message: ActionExample) => {
78+
let messageString = `${message.user}: ${message.content.text}`;
79+
exampleNames.forEach((name, index) => {
80+
const placeholder = `{{user${index + 1}}}`;
81+
messageString = messageString.replaceAll(
82+
placeholder,
83+
name
9484
);
95-
})
96-
.join("\n");
85+
});
86+
return (
87+
messageString +
88+
(message.content.action
89+
? ` (${message.content.action})`
90+
: "")
91+
);
92+
})
93+
.join("\n");
9794

98-
return `Context:\n${formattedContext}\n\nMessages:\n${formattedMessages}\n\nOutcome:\n${formattedOutcome}`;
99-
})
100-
.join("\n\n");
101-
})
102-
.join("\n\n");
95+
return `Context:\n${formattedContext}\n\nMessages:\n${formattedMessages}\n\nOutcome:\n${formattedOutcome}`;
96+
})
97+
).join("\n\n");
10398
}
10499

105100
/**

0 commit comments

Comments
 (0)