Repository navigation
Expand file tree
/
Copy pathtest-client.mjs
More file actions
222 lines (196 loc) · 6.34 KB
/
Copy pathtest-client.mjs
File metadata and controls
222 lines (196 loc) · 6.34 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
// Простой тестовый клиент для проверки прокси
import fs from "node:fs";
import path from "node:path";
const API_KEY = process.env.AGENT_ROUTER_TOKEN || "sk-test";
const BOOLEAN_FLAGS = new Set(["pretty", "json"]);
function parseArgs(argv) {
const positional = [];
const flags = {};
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg.startsWith("--")) {
const [key, inline] = arg.slice(2).split("=");
if (inline !== undefined) {
flags[key] = inline === "true" ? true : inline === "false" ? false : inline;
} else if (
BOOLEAN_FLAGS.has(key) ||
argv[i + 1] === undefined ||
String(argv[i + 1]).startsWith("--")
) {
flags[key] = true;
} else {
flags[key] = argv[i + 1];
i++;
}
} else {
positional.push(arg);
}
}
return { positional, flags };
}
function loadConfig() {
const configPath = path.join(process.cwd(), "config.json");
return JSON.parse(fs.readFileSync(configPath, "utf8"));
}
function resolveRoute(config, requested) {
const routes = config.routes || {};
const entries = Object.entries(routes);
if (requested) {
if (routes[requested]) {
return { prefix: requested, targetId: routes[requested] };
}
const match = entries.find(([, targetId]) => targetId === requested);
if (match) {
return { prefix: match[0], targetId: match[1] };
}
return null;
}
if (entries.length === 0) return null;
return { prefix: entries[0][0], targetId: entries[0][1] };
}
function formatCost(usage) {
const cost =
usage?.cost ??
usage?.total_cost ??
usage?.cost_details?.upstream_inference_cost;
if (cost == null || cost === "") return "н/д";
const n = Number(cost);
if (!Number.isFinite(n)) return String(cost);
return `$${n.toFixed(8).replace(/0+$/, "").replace(/\.$/, "")}`;
}
function formatTokens(usage) {
if (!usage) return "н/д";
const prompt = usage.prompt_tokens ?? usage.input_tokens;
const completion = usage.completion_tokens ?? usage.output_tokens;
const total = usage.total_tokens ?? (prompt ?? 0) + (completion ?? 0);
const reasoning =
usage.completion_tokens_details?.reasoning_tokens ??
usage.reasoning_tokens;
const parts = [
`prompt ${prompt ?? "н/д"}`,
`completion ${completion ?? "н/д"}`,
`total ${total ?? "н/д"}`,
];
if (reasoning) parts.push(`reasoning ${reasoning}`);
return parts.join(" · ");
}
function extractReply(data) {
const choice = data?.choices?.[0];
const msg = choice?.message || {};
const content = msg.content || choice?.text || null;
const reasoning = msg.reasoning || null;
return { content, reasoning, finishReason: choice?.finish_reason ?? null };
}
function printPretty({ prompt, data, raw }) {
if (!data) {
console.log("Ответ (не JSON):");
console.log(raw);
return;
}
const { content, reasoning, finishReason } = extractReply(data);
const usage = data.usage || {};
console.log("Промпт");
console.log(prompt);
console.log("");
console.log("Ответ");
console.log(content || "(пусто)");
if (!content && reasoning) {
console.log("");
console.log("Рассуждения");
console.log(reasoning);
}
console.log("");
console.log(`Стоимость: ${formatCost(usage)}`);
console.log(`Токены: ${formatTokens(usage)}`);
if (finishReason) console.log(`Завершение: ${finishReason}`);
if (data.model) console.log(`Модель: ${data.model}`);
if (data.provider) console.log(`Провайдер: ${data.provider}`);
}
const config = loadConfig();
const { positional, flags } = parseArgs(process.argv.slice(2));
const requestedTarget =
flags.target || positional[0] || process.env.PROXY_TARGET;
const MODEL =
flags.model || positional[1] || process.env.OPENAI_MODEL || "gpt-5";
const PROMPT =
flags.prompt || process.env.OPENAI_PROMPT || "Say hello";
const MAX_TOKENS = Number(
flags["max-tokens"] || flags.maxTokens || process.env.OPENAI_MAX_TOKENS || 50
);
if (!Number.isFinite(MAX_TOKENS) || MAX_TOKENS <= 0) {
console.error(`Некорректный max-tokens: ${flags["max-tokens"] || flags.maxTokens}`);
process.exit(1);
}
const PRETTY = flags.json ? false : flags.pretty !== false;
const route = resolveRoute(config, requestedTarget);
if (!route) {
const available = Object.entries(config.routes || {})
.map(([prefix, targetId]) => ` ${targetId} (${prefix})`)
.join("\n");
console.error(
requestedTarget
? `Target "${requestedTarget}" не найден в config.json`
: "В config.json нет routes"
);
if (available) {
console.error("Доступные targets:");
console.error(available);
}
process.exit(1);
}
const port = config.port ?? 8787;
const url = `http://localhost:${port}${route.prefix}/v1/chat/completions`;
console.log("========================================");
console.log("Тест Node.js клиента -> прокси");
console.log("========================================");
console.log(`API_KEY: ${API_KEY.substring(0, 20)}...`);
console.log(`MODEL: ${MODEL}`);
console.log(`TARGET: ${route.targetId}`);
console.log(`ROUTE: ${route.prefix}`);
console.log(`PROMPT: ${PROMPT}`);
console.log(`MAX_TOKENS: ${MAX_TOKENS}`);
console.log("");
const requestBody = {
model: MODEL,
messages: [{ role: "user", content: PROMPT }],
max_tokens: MAX_TOKENS,
};
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${API_KEY}`,
},
body: JSON.stringify(requestBody),
};
console.log(`Отправка запроса к ${url}`);
console.log("");
try {
const response = await fetch(url, options);
console.log(`Статус: ${response.status} ${response.statusText}`);
console.log("");
const data = await response.text();
let parsed = null;
try {
parsed = JSON.parse(data);
} catch {
parsed = null;
}
if (PRETTY) {
printPretty({ prompt: PROMPT, data: parsed, raw: data });
} else {
console.log("Ответ:");
console.log(data);
}
if (response.ok) {
console.log("");
console.log("✅ Успех!");
} else {
console.log("");
console.log("❌ Ошибка!");
}
} catch (err) {
console.error("❌ Ошибка запроса:", err.message);
}
console.log("");
console.log("========================================");