-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathllm.ts
More file actions
260 lines (222 loc) · 7.33 KB
/
Copy pathllm.ts
File metadata and controls
260 lines (222 loc) · 7.33 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
250
251
252
253
254
255
256
257
258
259
260
/**
* LLM Module - AI Model Integration for Discord MCP
*
* Thin wrapper around @decocms/mcps-shared/mesh-chat that maintains the
* existing public API while delegating all API calls to the shared module.
*/
import type { Env } from "./types/env.ts";
import {
generateResponse as sharedGenerateResponse,
generateResponseWithStreaming as sharedGenerateResponseWithStreaming,
transcribeAudio as sharedTranscribeAudio,
type ChatMessage,
type MeshChatConfig,
type StreamCallback,
type WhisperConfig,
} from "@decocms/mcps-shared/mesh-chat";
const DEFAULT_LANGUAGE_MODEL = "anthropic/claude-sonnet-4-20250514";
// ============================================================================
// Types
// ============================================================================
export interface MessageImage {
type: "image" | "audio";
data: string; // base64
mimeType: string;
name?: string;
}
export interface DiscordChatMessage {
role: "system" | "user" | "assistant";
content: string;
images?: MessageImage[];
}
export interface GenerateResponse {
content: string;
model: string;
tokens?: number;
usedFallback?: boolean;
}
export interface DiscordContext {
guildId: string;
channelId: string;
userId: string;
userName: string;
}
export type { MeshChatConfig as LLMConfig, StreamCallback };
// ============================================================================
// Global State
// ============================================================================
let globalLLMConfig: MeshChatConfig | null = null;
let streamingEnabled = true;
let globalWhisperConfig: WhisperConfig | null = null;
export function configureLLM(config: MeshChatConfig): void {
globalLLMConfig = config;
console.log("[LLM] Configured", {
meshUrl: config.meshUrl,
organizationId: config.organizationId,
modelProviderId: config.modelProviderId,
modelId: config.modelId,
agentId: config.agentId,
hasToken: !!config.token,
hasSystemPrompt: !!config.systemPrompt,
});
}
export function clearLLMConfig(): void {
globalLLMConfig = null;
console.log("[LLM] Config cleared");
}
export function configureStreaming(enabled: boolean): void {
streamingEnabled = enabled;
console.log("[LLM] Streaming:", enabled ? "enabled" : "disabled");
}
export function isStreamingEnabled(): boolean {
return streamingEnabled;
}
export function isLLMConfigured(): boolean {
return globalLLMConfig !== null;
}
export function getLLMConfig(): MeshChatConfig | null {
return globalLLMConfig;
}
// ============================================================================
// Helpers
// ============================================================================
function toSharedMessages(messages: DiscordChatMessage[]): ChatMessage[] {
return messages.map((m) => ({
role: m.role,
content: m.content,
media: m.images?.map((img) => ({
type: img.type,
data: img.data,
mimeType: img.mimeType,
name: img.name,
})),
}));
}
// ============================================================================
// Main Functions
// ============================================================================
/**
* Generate a response using the Mesh API.
* Falls back to stored config or env-derived config if global config is not set.
*/
export async function generateResponse(
env: Env,
messages: DiscordChatMessage[],
_options?: { discordContext?: DiscordContext },
): Promise<GenerateResponse> {
let config = globalLLMConfig;
if (!config) {
// Fallback 1: Try stored config (persistent, doesn't depend on env)
const { getStoredConfig, getCurrentEnv } = await import("./bot-manager.ts");
const storedConfig = getStoredConfig();
if (storedConfig) {
console.log("[LLM] Using stored config fallback", {
isApiKey: storedConfig.isApiKey,
hasToken: !!storedConfig.persistentToken,
});
config = {
meshUrl: storedConfig.meshUrl,
organizationId: storedConfig.organizationId,
token: storedConfig.persistentToken,
modelProviderId: storedConfig.modelProviderId ?? "",
modelId: storedConfig.modelId,
agentId: storedConfig.agentId,
};
} else {
// Fallback 2: Build config from env (may have expired token)
const storedEnv = getCurrentEnv();
const effectiveEnv = env.MESH_REQUEST_CONTEXT?.state?.LANGUAGE_MODEL
?.value
? env
: storedEnv?.MESH_REQUEST_CONTEXT?.state?.LANGUAGE_MODEL?.value
? storedEnv
: env;
const organizationId = effectiveEnv.MESH_REQUEST_CONTEXT?.organizationId;
if (!organizationId) {
throw new Error(
"No organizationId found. Please open Mesh Dashboard and click 'Save' on this MCP to refresh the connection.",
);
}
const meshUrl =
effectiveEnv.MESH_REQUEST_CONTEXT?.meshUrl ?? effectiveEnv.MESH_URL;
const token = effectiveEnv.MESH_REQUEST_CONTEXT?.token;
const state = effectiveEnv.MESH_REQUEST_CONTEXT?.state;
if (!state?.LANGUAGE_MODEL?.value) {
throw new Error(
"LANGUAGE_MODEL not configured.\n\n" +
"🔧 **How to fix:**\n" +
"1. Open **Mesh Dashboard**\n" +
"2. Go to this MCP's configuration\n" +
"3. Configure **LANGUAGE_MODEL**\n" +
"4. Click **Save** to apply",
);
}
const modelId = state.LANGUAGE_MODEL.value?.id ?? DEFAULT_LANGUAGE_MODEL;
const connectionId = state.LANGUAGE_MODEL.value?.connectionId as
| string
| undefined;
const agentId = state?.AGENT?.value;
config = {
meshUrl,
organizationId,
token,
modelProviderId: connectionId,
modelId,
agentId,
};
}
}
if (!config) {
throw new Error("LLM not configured");
}
const text = await sharedGenerateResponse(config, toSharedMessages(messages));
return {
content: text,
model: config.modelId ?? DEFAULT_LANGUAGE_MODEL,
usedFallback: false,
};
}
/**
* Generate a response with real-time streaming callback.
* Uses the global config if no config is explicitly provided.
*/
export async function generateResponseWithStreaming(
messages: DiscordChatMessage[],
onStream: StreamCallback,
config?: MeshChatConfig,
): Promise<string> {
const effectiveConfig = config ?? globalLLMConfig;
if (!effectiveConfig) {
throw new Error("LLM not configured");
}
return sharedGenerateResponseWithStreaming(
effectiveConfig,
toSharedMessages(messages),
onStream,
);
}
// ============================================================================
// Whisper Integration
// ============================================================================
export function configureWhisper(config: WhisperConfig): void {
globalWhisperConfig = config;
console.log("[Whisper] Configured", {
meshUrl: config.meshUrl,
whisperConnectionId: config.whisperConnectionId,
hasToken: !!config.token,
});
}
export function isWhisperConfigured(): boolean {
return globalWhisperConfig !== null;
}
export async function transcribeAudio(
audioUrl: string,
_mimeType: string,
filename: string,
): Promise<string | null> {
if (!globalWhisperConfig) {
console.log("[Whisper] Not configured, skipping transcription");
return null;
}
return sharedTranscribeAudio(globalWhisperConfig, audioUrl, filename);
}