forked from elizaOS/eliza
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
249 lines (214 loc) · 6.91 KB
/
server.ts
File metadata and controls
249 lines (214 loc) · 6.91 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
/**
* elizaOS REST API Example - Elysia
*
* A REST API server demonstrating the canonical elizaOS implementation.
* Uses AgentRuntime with runtime.messageService.handleMessage for proper
* message processing through the full elizaOS pipeline.
*/
import {
AgentRuntime,
ChannelType,
type Character,
createCharacter,
createMessageMemory,
type IAgentRuntime,
type Plugin,
stringToUuid,
type UUID,
} from "@elizaos/core";
import { cors } from "@elysiajs/cors";
import { Elysia } from "elysia";
import { v4 as uuidv4 } from "uuid";
// ============================================================================
// Configuration
// ============================================================================
const PORT = Number(process.env.PORT ?? 3000);
// Character configuration
// Pass environment variables via character.secrets so getSetting() can find them
// Without POSTGRES_URL, plugin-sql will use PGLite automatically
const character: Character = createCharacter({
name: "Eliza",
bio: "A helpful AI assistant powered by elizaOS.",
secrets: {
OPENAI_API_KEY: process.env.OPENAI_API_KEY || "",
},
});
// ============================================================================
// Runtime State
// ============================================================================
let runtime: IAgentRuntime | null = null;
let initPromise: Promise<IAgentRuntime | null> | null = null;
let initError: string | null = null;
let useClassicFallback = false;
// Session identifiers
const roomId = stringToUuid("chat-room");
const worldId = stringToUuid("chat-world");
async function getRuntime(): Promise<IAgentRuntime | null> {
if (runtime) return runtime;
if (useClassicFallback) return null;
if (initPromise) return initPromise;
initPromise = (async () => {
try {
console.log("🚀 Initializing elizaOS runtime...");
const { default: sqlPlugin } = await import("@elizaos/plugin-sql");
// Choose plugins based on whether OpenAI key is available
const plugins: Plugin[] = [sqlPlugin as Plugin];
if (process.env.OPENAI_API_KEY) {
const { openaiPlugin } = await import("@elizaos/plugin-openai");
plugins.push(openaiPlugin);
} else {
console.log(
"💡 No OPENAI_API_KEY found, using elizaClassicPlugin for responses",
);
const { elizaClassicPlugin } = await import(
"@elizaos/plugin-eliza-classic"
);
plugins.push(elizaClassicPlugin);
}
const newRuntime = new AgentRuntime({
character,
plugins,
});
await newRuntime.initialize();
console.log("✅ elizaOS runtime initialized");
runtime = newRuntime;
return newRuntime;
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
console.error("❌ Failed to initialize elizaOS runtime:", message);
// Check if it's a recoverable error
if (
message.includes("Extension bundle not found") ||
message.includes("migrations")
) {
console.log("⚠️ Database initialization issue.");
console.log("💡 Falling back to classic ELIZA mode.");
useClassicFallback = true;
initError = "Database not compatible. Using classic mode.";
} else {
initError = message;
useClassicFallback = true;
}
return null;
}
})();
return initPromise;
}
// ============================================================================
// Types
// ============================================================================
interface ChatRequest {
message: string;
userId?: string;
}
// ============================================================================
// Elysia App
// ============================================================================
export const app = new Elysia()
.use(cors())
// GET / - Info endpoint
.get("/", async () => {
const rt = await getRuntime();
return {
name: character.name,
bio: character.bio,
version: "2.0.0",
powered_by: "elizaOS",
framework: "Elysia",
mode: rt ? "elizaos" : "classic",
endpoints: {
"POST /chat": "Send a message and receive a response",
"GET /health": "Health check endpoint",
"GET /": "This info endpoint",
},
};
})
// GET /health - Health check
.get("/health", async () => {
const rt = await getRuntime();
return {
status: rt ? "healthy" : "degraded",
mode: rt ? "elizaos" : "classic",
character: character.name,
error: initError,
timestamp: new Date().toISOString(),
};
})
// POST /chat - Chat with the agent using runtime.messageService.handleMessage
.post("/chat", async ({ body, set }) => {
const { message, userId: clientUserId } = body as ChatRequest;
if (!message || typeof message !== "string") {
set.status = 400;
return { error: "Message is required and must be a string" };
}
const rt = await getRuntime();
if (!rt) {
set.status = 503;
return {
error: "Runtime not initialized",
details: initError,
};
}
const userId = (clientUserId || uuidv4()) as UUID;
// Ensure connection exists
await rt.ensureConnection({
entityId: userId,
roomId,
worldId,
userName: "User",
source: "elysia",
channelId: "chat",
serverId: "server",
type: ChannelType.DM,
} as Parameters<typeof rt.ensureConnection>[0]);
// Create message memory
const messageMemory = createMessageMemory({
id: uuidv4() as UUID,
entityId: userId,
roomId,
content: {
text: message,
source: "elysia_rest_api",
channelType: ChannelType.DM,
},
});
// Process message through the canonical elizaOS pipeline
let responseText = "";
await rt.messageService?.handleMessage(
rt,
messageMemory,
async (content) => {
if (content?.text) {
responseText += content.text;
}
return [];
},
);
return {
response:
responseText || "I processed your message but have no response.",
character: character.name,
userId,
mode: "elizaos",
};
});
// ============================================================================
// Server Startup
// ============================================================================
// Pre-initialize runtime
if (import.meta.main) {
app.listen(PORT);
getRuntime().then((rt) => {
console.log(`\n🌐 elizaOS REST API (Elysia)`);
console.log(` http://localhost:${PORT}\n`);
console.log(`📚 Endpoints:`);
console.log(` GET / - Agent info`);
console.log(` GET /health - Health check`);
console.log(
` POST /chat - Chat with agent (uses runtime.messageService.handleMessage)\n`,
);
if (!rt) {
console.log(`⚠️ Runtime initialization issue: ${initError}\n`);
}
});
}