Spaces:
Runtime error
Runtime error
File size: 12,176 Bytes
cd8bd0a | 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 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 | // src/lib/playground/codeExport.ts
import { z } from "zod";
/**
* Endpoint suportado pelo Playground Studio. Reflete os 13 endpoints da API OmniRoute
* consumíveis pelas tabs Chat/Compare/Build/Search/Scrape via Export Code.
*
* D4-rev2 (2026-05-28): contrato expandido de 10 → 13 incluindo `responses`, `video`,
* `music` para refletir a API real (`/v1/responses`, `/v1/videos/generations`,
* `/v1/music/generations`). A tab API (Monaco editor) mantém seu próprio sistema
* de endpoint values (D14) e não consome este type.
*/
export type PlaygroundEndpoint =
| "chat.completions"
| "responses"
| "completions"
| "embeddings"
| "images"
| "audio.transcriptions"
| "audio.speech"
| "video"
| "music"
| "moderations"
| "rerank"
| "search"
| "web.fetch";
/** Linguagens de export suportadas. */
export type ExportLanguage = "curl" | "python" | "typescript";
/** Mensagem chat single-turn ou multi-turn. */
export interface ChatMessage {
role: "system" | "user" | "assistant" | "tool";
content: string | Array<{ type: string; [k: string]: unknown }>;
name?: string;
tool_call_id?: string;
}
/** Tool definition no formato OpenAI Function Calling. */
export interface ToolDefinition {
type: "function";
function: {
name: string;
description?: string;
parameters: Record<string, unknown>;
};
}
/** Estado completo capturável pelo Playground (subset de campos por endpoint). */
export interface PlaygroundState {
endpoint: PlaygroundEndpoint;
baseUrl: string; // ex.: "http://localhost:20128"
model?: string; // não aplicável a web.fetch
systemPrompt?: string;
messages?: ChatMessage[]; // chat/completions
prompt?: string; // completions/embeddings
query?: string; // search/rerank
url?: string; // web.fetch
params?: Partial<{
temperature: number;
max_tokens: number;
top_p: number;
presence_penalty: number;
frequency_penalty: number;
seed: number;
stop: string | string[];
response_format: { type: "text" | "json_object" | "json_schema"; json_schema?: unknown };
}>;
tools?: ToolDefinition[];
stream?: boolean;
// Search-specific
searchProvider?: string;
searchType?: "web" | "news";
maxResults?: number;
// Scrape-specific
fetchProvider?: "firecrawl" | "jina-reader" | "tavily-search";
fetchFormat?: "markdown" | "html" | "links" | "screenshot";
fetchDepth?: 0 | 1 | 2;
// Rerank-specific
rerankModel?: string;
documents?: string[];
}
export const PlaygroundStateSchema = z.object({
endpoint: z.enum([
"chat.completions",
"responses",
"completions",
"embeddings",
"images",
"audio.transcriptions",
"audio.speech",
"video",
"music",
"moderations",
"rerank",
"search",
"web.fetch",
]),
baseUrl: z.string().min(1),
model: z.string().optional(),
systemPrompt: z.string().optional(),
messages: z.array(z.any()).optional(),
prompt: z.string().optional(),
query: z.string().optional(),
url: z.string().optional(),
params: z.record(z.string(), z.any()).optional(),
tools: z.array(z.any()).optional(),
stream: z.boolean().optional(),
searchProvider: z.string().optional(),
searchType: z.enum(["web", "news"]).optional(),
maxResults: z.number().int().optional(),
fetchProvider: z.enum(["firecrawl", "jina-reader", "tavily-search"]).optional(),
fetchFormat: z.enum(["markdown", "html", "links", "screenshot"]).optional(),
fetchDepth: z.union([z.literal(0), z.literal(1), z.literal(2)]).optional(),
rerankModel: z.string().optional(),
documents: z.array(z.string()).optional(),
});
/** Constante: placeholder de API key — NUNCA embutir key real. */
export const API_KEY_PLACEHOLDER = "$OMNIROUTE_API_KEY";
/**
* Resolve o path HTTP a partir do endpoint (ex.: "chat.completions" → "/v1/chat/completions").
* Exportado para reuso em testes.
*/
export function endpointToPath(endpoint: PlaygroundEndpoint): string {
const map: Record<PlaygroundEndpoint, string> = {
"chat.completions": "/v1/chat/completions",
responses: "/v1/responses",
completions: "/v1/completions",
embeddings: "/v1/embeddings",
images: "/v1/images/generations",
"audio.transcriptions": "/v1/audio/transcriptions",
"audio.speech": "/v1/audio/speech",
video: "/v1/videos/generations",
music: "/v1/music/generations",
moderations: "/v1/moderations",
rerank: "/v1/rerank",
search: "/v1/search",
"web.fetch": "/v1/web/fetch",
};
return map[endpoint];
}
/**
* Build the request body for a given endpoint+state.
* Internal helper — returns plain object suitable for JSON.stringify.
*/
function buildBody(state: PlaygroundState): Record<string, unknown> {
const { endpoint, model, params, tools, stream } = state;
switch (endpoint) {
case "chat.completions": {
let messages: ChatMessage[];
if (state.messages && state.messages.length > 0) {
messages = state.messages;
} else if (state.systemPrompt) {
messages = [
{ role: "system", content: state.systemPrompt },
{ role: "user", content: state.prompt ?? "Hello!" },
];
} else {
messages = [{ role: "user", content: state.prompt ?? "Hello!" }];
}
const body: Record<string, unknown> = {
model: model ?? "gpt-4o-mini",
messages,
stream: stream ?? false,
};
if (params) Object.assign(body, params);
if (tools && tools.length > 0) body.tools = tools;
return body;
}
case "responses": {
const body: Record<string, unknown> = {
model: model ?? "gpt-4o-mini",
input: state.prompt ?? "Hello!",
stream: stream ?? false,
};
if (state.systemPrompt) body.instructions = state.systemPrompt;
if (params) Object.assign(body, params);
if (tools && tools.length > 0) body.tools = tools;
return body;
}
case "completions": {
const body: Record<string, unknown> = {
model: model ?? "gpt-3.5-turbo-instruct",
prompt: state.prompt ?? "Hello,",
stream: stream ?? false,
};
if (params) Object.assign(body, params);
return body;
}
case "embeddings": {
return {
model: model ?? "text-embedding-3-small",
input: state.prompt ?? "Hello world",
};
}
case "images": {
return {
model: model ?? "dall-e-3",
prompt: state.prompt ?? "A beautiful sunset",
n: 1,
size: "1024x1024",
};
}
case "audio.transcriptions": {
// Note: actual usage needs multipart/form-data; shown as JSON for documentation
return {
model: model ?? "whisper-1",
file: "<audio-file-binary>",
language: "en",
};
}
case "audio.speech": {
return {
model: model ?? "tts-1",
input: state.prompt ?? "Hello, world!",
voice: "alloy",
};
}
case "video": {
const body: Record<string, unknown> = {
model: model ?? "sora-1.0",
prompt: state.prompt ?? "A cinematic shot of a city at sunset",
};
if (params) Object.assign(body, params);
return body;
}
case "music": {
const body: Record<string, unknown> = {
model: model ?? "music-1",
prompt: state.prompt ?? "An upbeat lo-fi instrumental",
};
if (params) Object.assign(body, params);
return body;
}
case "moderations": {
return {
model: model ?? "text-moderation-latest",
input: state.prompt ?? "Hello world",
};
}
case "rerank": {
return {
model: state.rerankModel ?? model ?? "rerank-english-v3.0",
query: state.query ?? "search query",
documents: state.documents ?? ["Document 1 text", "Document 2 text"],
top_n: 3,
};
}
case "search": {
const body: Record<string, unknown> = {
query: state.query ?? "search query",
};
if (model) body.model = model;
if (state.searchProvider) body.provider = state.searchProvider;
if (state.searchType) body.search_type = state.searchType;
if (state.maxResults) body.max_results = state.maxResults;
return body;
}
case "web.fetch": {
const body: Record<string, unknown> = {
url: state.url ?? "https://example.com",
};
if (state.fetchProvider) body.provider = state.fetchProvider;
if (state.fetchFormat) body.format = state.fetchFormat;
if (state.fetchDepth != null) body.depth = state.fetchDepth;
return body;
}
}
}
/**
* Escape a string for safe embedding inside single-quoted shell literals.
*/
function escSingleQuote(s: string): string {
return s.replace(/'/g, "'\\''");
}
/**
* Generate curl snippet for a given endpoint.
*/
function buildCurlSnippet(state: PlaygroundState): string {
const path = endpointToPath(state.endpoint);
const url = `${state.baseUrl}${path}`;
const body = buildBody(state);
const bodyJson = JSON.stringify(body, null, 2);
const lines: string[] = [
`# Set your API key: export OMNIROUTE_API_KEY="your-key-here"`,
`curl -s -X POST \\`,
` "${url}" \\`,
` -H "Authorization: Bearer ${API_KEY_PLACEHOLDER}" \\`,
` -H "Content-Type: application/json" \\`,
` -d '${escSingleQuote(JSON.stringify(body))}'`,
];
// Also show pretty body as a comment for readability
const prettyLines = bodyJson.split("\n");
const commentBlock = prettyLines.map((l) => `# ${l}`).join("\n");
return `${lines.join("\n")}\n\n# Request body (pretty-printed for reference):\n${commentBlock}`;
}
/**
* Generate Python (requests) snippet for a given endpoint.
*/
function buildPythonSnippet(state: PlaygroundState): string {
const path = endpointToPath(state.endpoint);
const url = `${state.baseUrl}${path}`;
const body = buildBody(state);
const bodyJson = JSON.stringify(body, null, 2);
const lines: string[] = [
`# Set your API key: export ${API_KEY_PLACEHOLDER}="your-key-here"`,
`import os`,
`import json`,
`import requests`,
``,
`api_key = os.environ["OMNIROUTE_API_KEY"]`,
``,
`url = "${url}"`,
`headers = {`,
` "Authorization": f"Bearer {api_key}",`,
` "Content-Type": "application/json",`,
`}`,
``,
`data = json.loads("""`,
bodyJson,
`""")`,
``,
`response = requests.post(url, headers=headers, json=data)`,
`print(response.json())`,
];
return lines.join("\n");
}
/**
* Generate TypeScript (fetch) snippet for a given endpoint.
*/
function buildTypescriptSnippet(state: PlaygroundState): string {
const path = endpointToPath(state.endpoint);
const url = `${state.baseUrl}${path}`;
const body = buildBody(state);
const bodyJson = JSON.stringify(body, null, 2);
const lines: string[] = [
`// Set your API key: export ${API_KEY_PLACEHOLDER}="your-key-here"`,
`const apiKey = process.env.OMNIROUTE_API_KEY ?? "";`,
``,
`const url = "${url}";`,
`const body = ${bodyJson};`,
``,
`const response = await fetch(url, {`,
` method: "POST",`,
` headers: {`,
` "Authorization": \`Bearer \${apiKey}\`,`,
` "Content-Type": "application/json",`,
` },`,
` body: JSON.stringify(body),`,
`});`,
``,
`const data = await response.json();`,
`console.log(data);`,
];
return lines.join("\n");
}
/**
* Gera código para uma linguagem específica a partir do estado atual.
* Sempre usa `API_KEY_PLACEHOLDER` para a API key (D11).
*/
export function exportCode(state: PlaygroundState, language: ExportLanguage): string {
switch (language) {
case "curl":
return buildCurlSnippet(state);
case "python":
return buildPythonSnippet(state);
case "typescript":
return buildTypescriptSnippet(state);
}
}
/** Gera os 3 snippets de uma vez (atalho para o ExportCodeModal de UI). */
export function exportAllLanguages(state: PlaygroundState): Record<ExportLanguage, string> {
return {
curl: exportCode(state, "curl"),
python: exportCode(state, "python"),
typescript: exportCode(state, "typescript"),
};
}
|