-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathopenai.ts
More file actions
202 lines (185 loc) · 5.31 KB
/
openai.ts
File metadata and controls
202 lines (185 loc) · 5.31 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
import OpenAI from "openai";
export type AiMode = "chat" | "token_info";
export type ThreadContext = {
user_telegram: string;
thread_id: number;
type: "bot" | "app";
telegram_update_id?: number | null;
/** When true, skip claim insert (e.g. same handler retrying token_info -> chat); still use history and persist assistant. */
skipClaim?: boolean;
};
export type AiRequestBase = {
input: string;
userId?: string;
context?: Record<string, unknown>;
/** When set, AI layer persists user/assistant and uses thread history for chat. */
threadContext?: ThreadContext;
/** Optional instructions for the model (e.g. length limit); passed to OpenAI native `instructions` field. */
instructions?: string;
};
export type AiResponseBase = {
ok: boolean;
provider: "openai";
output_text?: string;
error?: string;
mode: AiMode;
/** True when claim insert failed (another instance or duplicate); caller should not send. */
skipped?: boolean;
usage?: {
prompt_tokens?: number;
completion_tokens?: number;
total_tokens?: number;
};
meta?: Record<string, unknown>;
};
const OPENAI = process.env.OPENAI?.trim() || "";
const client = OPENAI ? new OpenAI({ apiKey: OPENAI }) : null;
export async function callOpenAiChat(
mode: AiMode,
params: AiRequestBase,
): Promise<AiResponseBase> {
if (!client) {
return {
ok: false,
provider: "openai",
mode,
error: "OPENAI env is not configured on the server.",
};
}
const trimmed = params.input?.trim();
if (!trimmed) {
return {
ok: false,
provider: "openai",
mode,
error: "input is required.",
};
}
const prefix =
mode === "token_info"
? "You are a blockchain and token analyst. Answer clearly and briefly.\n\n"
: "";
try {
const response = await client.responses.create({
model: "gpt-5.2",
...(params.instructions ? { instructions: params.instructions } : {}),
input: `${prefix}${trimmed}`,
});
return {
ok: true,
provider: "openai",
mode,
output_text: (response as any).output_text ?? undefined,
usage: (response as any).usage ?? undefined,
};
} catch (e: any) {
const message =
e?.message ?? "Failed to call OpenAI. Check OPENAI env and network.";
return {
ok: false,
provider: "openai",
mode,
error: message,
};
}
}
/** Call OpenAI with streaming; onDelta(textSoFar) is called for each chunk. Returns final response. */
export async function callOpenAiChatStream(
mode: AiMode,
params: AiRequestBase,
onDelta: (text: string) => void | Promise<void>,
opts?: { isCancelled?: () => boolean; getAbortSignal?: () => Promise<boolean> },
): Promise<AiResponseBase> {
if (!client) {
return {
ok: false,
provider: "openai",
mode,
error: "OPENAI env is not configured on the server.",
};
}
const trimmed = params.input?.trim();
if (!trimmed) {
return {
ok: false,
provider: "openai",
mode,
error: "input is required.",
};
}
const prefix =
mode === "token_info"
? "You are a blockchain and token analyst. Answer clearly and briefly.\n\n"
: "";
try {
const stream = client.responses.stream({
model: "gpt-5.2",
...(params.instructions ? { instructions: params.instructions } : {}),
input: `${prefix}${trimmed}`,
});
stream.on("response.output_text.delta", async (event: { snapshot?: string }) => {
if (opts?.isCancelled && opts.isCancelled()) {
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(stream as any)?.abort?.();
} catch {
/* ignore */
}
return;
}
if (opts?.getAbortSignal && (await opts.getAbortSignal())) {
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(stream as any)?.abort?.();
} catch {
/* ignore */
}
return;
}
const text = event?.snapshot ?? "";
if (text.length > 0) void Promise.resolve(onDelta(text));
});
const response = await stream.finalResponse();
const r = response as any;
let output_text = r.output_text;
if (output_text == null || String(output_text).trim() === "") {
const parts: string[] = [];
for (const item of r.output ?? []) {
if (item?.type === "message" && Array.isArray(item.content)) {
for (const content of item.content) {
if (content?.type === "output_text" && typeof content.text === "string") {
parts.push(content.text);
}
}
}
}
output_text = parts.join("");
}
if (output_text == null || String(output_text).trim() === "") {
return {
ok: false,
provider: "openai",
mode,
error: "OpenAI returned no text.",
usage: r.usage ?? undefined,
};
}
return {
ok: true,
provider: "openai",
mode,
output_text,
usage: r.usage ?? undefined,
};
} catch (e: any) {
const message =
(e && typeof e === "object" && "message" in e ? (e as Error).message : null) ??
(e != null ? String(e) : "Failed to call OpenAI. Check OPENAI env and network.");
return {
ok: false,
provider: "openai",
mode,
error: message,
};
}
}