forked from ephemeraHQ/xmtp-agent-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
92 lines (78 loc) · 2.47 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import "dotenv/config";
import { getAddressOfMember } from "@helpers";
import type { Conversation, DecodedMessage } from "@xmtp/node-sdk";
import { initializeAgent, processMessage } from "./langchain";
import { initializeStorage } from "./storage";
import { initializeXmtpClient, startMessageListener } from "./xmtp";
/**
* Validates that required environment variables are set
*/
export function validateEnvironment(): {
coinbaseApiKeyName: string;
coinbaseApiKeyPrivateKey: string;
networkId: string;
} {
const requiredVars = [
"CDP_API_KEY_NAME",
"CDP_API_KEY_PRIVATE_KEY",
"WALLET_KEY",
"XMTP_ENV",
"OPENAI_API_KEY",
"ENCRYPTION_KEY",
];
const missing = requiredVars.filter((v) => !process.env[v]);
if (missing.length) {
console.error("Missing env vars:", missing.join(", "));
process.exit(1);
}
// Replace \\n with actual newlines if present in the private key
if (process.env.CDP_API_KEY_PRIVATE_KEY) {
process.env.CDP_API_KEY_PRIVATE_KEY =
process.env.CDP_API_KEY_PRIVATE_KEY.replace(/\\n/g, "\n");
}
return {
coinbaseApiKeyName: process.env.CDP_API_KEY_NAME as string,
coinbaseApiKeyPrivateKey: process.env.CDP_API_KEY_PRIVATE_KEY as string,
networkId: process.env.NETWORK_ID as string,
};
}
/**
* Handle incoming messages
*/
async function handleMessage(
message: DecodedMessage,
conversation: Conversation,
) {
// Use the sender's address as the user ID
const inboxId = message.senderInboxId;
const members = await conversation.members();
const address = getAddressOfMember(members, inboxId);
if (!address) {
console.log("Unable to find address, skipping");
return;
}
// Initialize or get the agent for this user
const { agent, config } = await initializeAgent(inboxId);
// Process the message with the agent
const response = await processMessage(
agent,
config,
message.content as string,
);
// Send the response back to the user
console.log(`Sending response to ${address}...`);
await conversation.send(response);
console.log("Waiting for more messages...");
}
async function main(): Promise<void> {
console.log("Starting agent...");
// Validate environment variables
validateEnvironment();
// Initialize storage (Redis or local)
await initializeStorage();
// Initialize XMTP client
const xmtpClient = await initializeXmtpClient();
// Start listening for messages
await startMessageListener(xmtpClient, handleMessage);
}
main().catch(console.error);