"use client"; import { useState, useEffect } from "react"; import { Card } from "@/shared/components"; import { getProviderAlias, isCustomEmbeddingProvider } from "@/shared/constants/providers"; import { getModelsByProviderId, getModelKind } from "@/shared/constants/models"; import { useCopyToClipboard } from "@/shared/hooks/useCopyToClipboard"; import { Row } from "./exampleShared"; const DEFAULT_RESPONSE_EXAMPLE = `{ "object": "list", "data": [{ "object": "embedding", "index": 0, "embedding": [0.002301, -0.019212, 0.004815, -0.031249, ...] }], "model": "...", "usage": { "prompt_tokens": 9, "total_tokens": 9 } }`; export function EmbeddingExampleCard({ providerId, customAlias }) { const isCustom = isCustomEmbeddingProvider(providerId); const providerAlias = isCustom ? (customAlias || providerId) : getProviderAlias(providerId); const embeddingModels = isCustom ? [] : getModelsByProviderId(providerId).filter((m) => getModelKind(m) === "embedding"); const [selectedModel, setSelectedModel] = useState(embeddingModels[0]?.id ?? ""); const [input, setInput] = useState("The quick brown fox jumps over the lazy dog"); const [dimensions, setDimensions] = useState(""); const [apiKey, setApiKey] = useState(""); const [useTunnel, setUseTunnel] = useState(false); const [localEndpoint, setLocalEndpoint] = useState(""); const [tunnelEndpoint, setTunnelEndpoint] = useState(""); const [result, setResult] = useState(null); const [running, setRunning] = useState(false); const [error, setError] = useState(""); const { copied: copiedCurl, copy: copyCurl } = useCopyToClipboard(); const { copied: copiedRes, copy: copyRes } = useCopyToClipboard(); useEffect(() => { setLocalEndpoint(window.location.origin); fetch("/api/keys") .then((r) => r.json()) .then((d) => { setApiKey((d.keys || []).find((k) => k.isActive !== false)?.key || ""); }) .catch(() => {}); fetch("/api/tunnel/status") .then((r) => r.json()) .then((d) => { if (d.publicUrl) setTunnelEndpoint(d.publicUrl); }) .catch(() => {}); }, []); const endpoint = useTunnel ? tunnelEndpoint : localEndpoint; const modelFull = selectedModel ? `${providerAlias}/${selectedModel}` : ""; // Build request body — include dimensions only if user provided a positive number const buildBody = () => { const body = { model: modelFull, input: input.trim() }; const dim = Number(dimensions); if (dimensions && Number.isFinite(dim) && dim > 0) body.dimensions = dim; return body; }; const curlSnippet = `curl -X POST ${endpoint}/v1/embeddings \\ -H "Content-Type: application/json" \\ -H "Authorization: Bearer ${apiKey || "YOUR_KEY"}" \\ -d '${JSON.stringify(buildBody())}'`; const handleRun = async () => { if (!input.trim() || !modelFull) return; setRunning(true); setError(""); setResult(null); const start = Date.now(); try { const headers = { "Content-Type": "application/json" }; if (apiKey) headers["Authorization"] = `Bearer ${apiKey}`; const res = await fetch("/api/v1/embeddings", { method: "POST", headers, body: JSON.stringify(buildBody()), }); const latencyMs = Date.now() - start; const data = await res.json(); if (!res.ok) { setError(data?.error?.message || data?.error || `HTTP ${res.status}`); return; } setResult({ data, latencyMs }); } catch (e) { setError(e.message || "Network error"); } finally { setRunning(false); } }; // Compact embedding array: first 4 values + count const formatResultJson = (data) => { if (!data) return DEFAULT_RESPONSE_EXAMPLE; const clone = JSON.parse(JSON.stringify(data)); (clone.data || []).forEach((item) => { if (Array.isArray(item.embedding) && item.embedding.length > 4) { item.embedding = [...item.embedding.slice(0, 4).map((v) => parseFloat(v.toFixed(6))), `... (${item.embedding.length} dims)`]; } }); return JSON.stringify(clone, null, 2); }; const resultJson = result ? JSON.stringify(result.data, null, 2) : ""; return (

Example

{/* Model — text input for custom node, dropdown otherwise */} {isCustom ? ( setSelectedModel(e.target.value)} placeholder="e.g. voyage-3, embed-english-v3.0, text-embedding-3-small" className="w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary font-mono" /> ) : ( )} {/* Endpoint */}
useTunnel ? setTunnelEndpoint(e.target.value) : setLocalEndpoint(e.target.value)} className="w-full min-w-0 flex-1 px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary font-mono" placeholder="http://localhost:3000" /> {/* Tunnel toggle — only show if tunnel URL is available */} {tunnelEndpoint && ( )}
{/* API Key */} setApiKey(e.target.value)} placeholder="sk-..." className="w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary font-mono" /> {/* Input */}
setInput(e.target.value)} className="w-full px-3 py-1.5 pr-7 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary" /> {input && ( )}
{/* Dimensions (optional) — truncate embedding vector length */} setDimensions(e.target.value)} placeholder="optional, e.g. 512, 1024 (leave empty for default)" className="w-full px-3 py-1.5 text-sm border border-border rounded-lg bg-background focus:outline-none focus:border-primary" /> {/* Curl + Run */}
Request
{curlSnippet}
{/* Error */} {error &&

{error}

} {/* Response — default example or real result */}
Response {result && ⚡ {result.latencyMs}ms} {result && ( )}
            {formatResultJson(result?.data)}
          
); }