-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtransmitter.ts
More file actions
367 lines (329 loc) · 9.5 KB
/
transmitter.ts
File metadata and controls
367 lines (329 loc) · 9.5 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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import type { AiMode, AiRequestBase, AiResponseBase, ThreadContext } from "./openai.js";
import { callOpenAiChat, callOpenAiChatStream } from "./openai.js";
import {
getTokenBySymbol,
normalizeSymbol,
type TokenSearchResult,
} from "../blockchain/coffee.js";
import {
insertMessage,
getThreadHistory,
type Message,
} from "../database/messages.js";
export type AiRequest = AiRequestBase & {
mode?: AiMode;
};
export type AiResponse = AiResponseBase;
const HISTORY_LIMIT = 50;
function formatHistoryForInput(history: Message[]): string {
if (history.length === 0) return "";
const lines = history.map((m) => {
const role = m.role === "user" ? "user" : m.role === "assistant" ? "assistant" : "system";
const content = (m.content ?? "").trim();
return `${role}: ${content}`;
});
return "Previous conversation:\n" + lines.join("\n") + "\n\n";
}
/** Claim by insert; return skipped response if another instance won. */
async function claimUserMessage(
thread: ThreadContext,
content: string,
): Promise<AiResponse | null> {
const inserted = await insertMessage({
user_telegram: thread.user_telegram,
thread_id: thread.thread_id,
type: thread.type,
role: "user",
content,
telegram_update_id: thread.telegram_update_id ?? undefined,
});
if (inserted === null) {
return {
ok: false,
provider: "openai",
mode: "chat",
skipped: true,
};
}
return null;
}
async function persistAssistantMessage(
thread: ThreadContext,
content: string,
): Promise<void> {
await insertMessage({
user_telegram: thread.user_telegram,
thread_id: thread.thread_id,
type: thread.type,
role: "assistant",
content,
});
}
function extractSymbolCandidate(input: string): string | null {
const raw = input.trim();
if (!raw) return null;
// Simple patterns like "USDT", "$USDT", "USDT on TON".
const parts = raw.split(/\s+/);
const first = parts[0]?.replace(/^\$/g, "") ?? "";
const normalized = normalizeSymbol(first);
return normalized || null;
}
function buildTokenFactsBlock(symbol: string, token: any): string {
const lines: string[] = [];
const sym = token?.symbol ?? symbol;
const name = token?.name ?? null;
const address = token?.id ?? token?.address ?? null;
const type = token?.type ?? "token";
const decimals = token?.decimals ?? token?.metadata?.decimals ?? null;
const verification =
token?.verification ?? token?.metadata?.verification ?? null;
const market = token?.market_stats ?? {};
const holders =
market?.holders_count ?? token?.holders ?? market?.holders ?? null;
const priceUsd = market?.price_usd ?? null;
const mcap = market?.mcap ?? market?.fdmc ?? null;
const volume24h = market?.volume_usd_24h ?? null;
lines.push(`Symbol: ${sym}`);
if (name) {
lines.push(`Name: ${name}`);
}
lines.push(`Type: ${type}`);
lines.push(`Blockchain: TON`);
if (address) {
lines.push(`Address: ${address}`);
}
if (decimals != null) {
lines.push(`Decimals: ${decimals}`);
}
if (verification) {
lines.push(`Verification: ${verification}`);
}
if (holders != null) {
lines.push(`Holders: ${holders}`);
}
if (priceUsd != null) {
lines.push(`Price (USD): ${priceUsd}`);
}
if (mcap != null) {
lines.push(`Market cap (USD): ${mcap}`);
}
if (volume24h != null) {
lines.push(`24h volume (USD): ${volume24h}`);
}
return lines.join("\n");
}
async function handleTokenInfo(
request: AiRequest,
): Promise<AiResponse> {
const trimmed = request.input?.trim() ?? "";
const symbolCandidate = extractSymbolCandidate(trimmed);
if (!symbolCandidate) {
return {
ok: false,
provider: "openai",
mode: "token_info",
error: "Could not detect a token symbol. Try sending something like USDT.",
};
}
const tokenResult: TokenSearchResult = await getTokenBySymbol(
symbolCandidate,
);
if (!tokenResult.ok) {
return {
ok: false,
provider: "openai",
mode: "token_info",
error:
tokenResult.error === "not_found"
? `Token ${symbolCandidate} was not found on TON.`
: "Token service is temporarily unavailable.",
meta: {
symbol: symbolCandidate,
reason: tokenResult.reason,
status_code: tokenResult.status_code,
},
};
}
const token = tokenResult.data;
const facts = buildTokenFactsBlock(symbolCandidate, token);
const promptParts = [
"You are a concise TON token analyst.",
"",
"Facts about the token:",
facts,
"",
"User question or context:",
trimmed,
];
const composedInput = promptParts.join("\n");
const result = await callOpenAiChat("token_info", {
input: composedInput,
userId: request.userId,
context: {
...request.context,
symbol: symbolCandidate,
token,
source: "swap.coffee",
},
instructions: request.instructions,
});
return {
...result,
mode: "token_info",
meta: {
...(result.meta ?? {}),
symbol: symbolCandidate,
token,
},
};
}
export async function transmit(request: AiRequest): Promise<AiResponse> {
const mode: AiMode = request.mode ?? "chat";
const thread = request.threadContext;
if (thread && !thread.skipClaim) {
const skipped = await claimUserMessage(thread, request.input);
if (skipped) return skipped;
}
if (mode === "token_info") {
const result = await handleTokenInfo(request);
if (result.ok && result.output_text && thread) {
await persistAssistantMessage(thread, result.output_text);
}
return result;
}
let input = request.input;
if (thread) {
const history = await getThreadHistory({
user_telegram: thread.user_telegram,
thread_id: thread.thread_id,
type: thread.type,
limit: HISTORY_LIMIT,
});
input = formatHistoryForInput(history) + "Current message:\nuser: " + request.input;
}
const result = await callOpenAiChat(mode, {
input,
userId: request.userId,
context: request.context,
instructions: request.instructions,
});
if (result.ok && result.output_text && thread) {
await persistAssistantMessage(thread, result.output_text);
}
return result;
}
/** Stream AI response; onDelta(accumulatedText) is called for each chunk. Only the final OpenAI call is streamed. */
export async function transmitStream(
request: AiRequest,
onDelta: (text: string) => void | Promise<void>,
opts?: { isCancelled?: () => boolean; getAbortSignal?: () => Promise<boolean> },
): Promise<AiResponse> {
const mode: AiMode = request.mode ?? "chat";
const thread = request.threadContext;
if (thread && !thread.skipClaim) {
const skipped = await claimUserMessage(thread, request.input);
if (skipped) return skipped;
}
if (mode === "token_info") {
const tokenResult = await (async () => {
const trimmed = request.input?.trim() ?? "";
const symbolCandidate = extractSymbolCandidate(trimmed);
if (!symbolCandidate) {
return null;
}
return getTokenBySymbol(symbolCandidate);
})();
if (!tokenResult) {
return {
ok: false,
provider: "openai",
mode: "token_info",
error: "Could not detect a token symbol. Try sending something like USDT.",
};
}
if (!tokenResult.ok) {
const symbolCandidate = extractSymbolCandidate(request.input?.trim() ?? "");
return {
ok: false,
provider: "openai",
mode: "token_info",
error:
tokenResult.error === "not_found"
? `Token ${symbolCandidate ?? ""} was not found on TON.`
: "Token service is temporarily unavailable.",
meta: {
symbol: tokenResult.symbol,
reason: tokenResult.reason,
status_code: tokenResult.status_code,
},
};
}
const token = tokenResult.data;
const symbolCandidate = extractSymbolCandidate(request.input?.trim() ?? "")!;
const facts = buildTokenFactsBlock(symbolCandidate, token);
const trimmed = request.input?.trim() ?? "";
const promptParts = [
"You are a concise TON token analyst.",
"",
"Facts about the token:",
facts,
"",
"User question or context:",
trimmed,
];
const composedInput = promptParts.join("\n");
const result = await callOpenAiChatStream(
"token_info",
{
input: composedInput,
userId: request.userId,
context: {
...request.context,
symbol: symbolCandidate,
token,
source: "swap.coffee",
},
instructions: request.instructions,
},
onDelta,
opts,
);
if (result.ok && result.output_text && thread) {
await persistAssistantMessage(thread, result.output_text);
}
return {
...result,
mode: "token_info",
meta: {
...(result.meta ?? {}),
symbol: symbolCandidate,
token,
},
};
}
let input = request.input;
if (thread) {
const history = await getThreadHistory({
user_telegram: thread.user_telegram,
thread_id: thread.thread_id,
type: thread.type,
limit: HISTORY_LIMIT,
});
input = formatHistoryForInput(history) + "Current message:\nuser: " + request.input;
}
const result = await callOpenAiChatStream(
mode,
{
input,
userId: request.userId,
context: request.context,
instructions: request.instructions,
},
onDelta,
opts,
);
if (result.ok && result.output_text && thread) {
await persistAssistantMessage(thread, result.output_text);
}
return result;
}