Awakened_RiShre / src /utils /hfClient.ts
usrrootkali's picture
Upload hfClient.ts
50c8538 verified
Raw History Blame Contribute Delete
22.7 kB
import { RISHRE_SYSTEM_PROMPT, PRIMARY_MODEL_ID } from '../constants/models';
import { ChatMessage, ProjectFile } from '../types';
import { logRealConsoleApiError } from './apiLogger';
export interface GenerateCodeParams {
prompt: string;
history: ChatMessage[];
currentFiles: ProjectFile[];
modelId?: string;
hfToken?: string;
temperature?: number;
onChunk?: (chunk: string) => void;
}
const HF_ROUTER_ENDPOINT = 'https://router.huggingface.co/hf-inference/v1/chat/completions';
/**
* Validates HF access token format
*/
export function validateHfToken(token: string): boolean {
if (!token) return false;
const trimmed = token.trim();
return trimmed.startsWith('hf_') && trimmed.length >= 20;
}
/**
* Determines whether the user prompt is a coding request or a general conversation query
*/
export function isCodingRequest(prompt: string): boolean {
const p = prompt.toLowerCase();
const codingKeywords = [
'create', 'build', 'code', 'make', 'generate', 'app', 'website', 'page', 'ui',
'component', 'game', 'calculator', 'dashboard', 'todo', 'kanban', 'timer', 'button',
'style', 'css', 'javascript', 'html', 'modify', 'add', 'change', 'color', 'fix',
'canvas', 'audio', 'sound', 'feature', 'layout', 'design', 'dark mode', 'theme'
];
return codingKeywords.some(kw => p.includes(kw));
}
/**
* Builds user prompt augmented with current project file contents for iterative editing
*/
function buildAugmentedPrompt(prompt: string, currentFiles: ProjectFile[]): string {
// If it's pure conversation, don't overwhelm the model with full project code
if (!isCodingRequest(prompt)) {
return prompt;
}
if (!currentFiles || currentFiles.length === 0) {
return prompt;
}
const fileContexts = currentFiles.map(f => {
return `### Current ${f.name}:\n\`\`\`${f.language}\n${f.content}\n\`\`\``;
}).join('\n\n');
return `USER REQUEST: ${prompt}
CURRENT PROJECT FILES CONTEXT:
${fileContexts}
TASK FOR RISHRE AWAKENED:
Synthesize the requested changes or new application. Return the updated or new files clearly tagged with \`\`\`language <!-- file: filename -->\`\`\`.`;
}
/**
* Real-time inference via Hugging Face Inference API with streaming support
*/
export async function generateWithHfApi({
prompt,
history,
currentFiles,
hfToken,
temperature = 0.7,
onChunk,
}: GenerateCodeParams): Promise<string> {
// If no token provided, run offline awakened simulation with dual conversational + coding capabilities
if (!hfToken || !hfToken.trim()) {
return runAwakenedSimulation(prompt, currentFiles, onChunk);
}
const augmentedUserPrompt = buildAugmentedPrompt(prompt, currentFiles);
const messages = [
{ role: 'system', content: RISHRE_SYSTEM_PROMPT },
...history.slice(-8).map(m => ({
role: m.role === 'assistant' ? 'assistant' : 'user',
content: m.content,
})),
{ role: 'user', content: augmentedUserPrompt },
];
try {
const response = await fetch(HF_ROUTER_ENDPOINT, {
method: 'POST',
headers: {
'Authorization': `Bearer ${hfToken.trim()}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: PRIMARY_MODEL_ID,
messages,
temperature,
max_tokens: 3800,
stream: !!onChunk,
}),
});
if (!response.ok) {
const errText = await response.text();
let parsedMessage = errText;
try {
const errJson = JSON.parse(errText);
parsedMessage = errJson.error?.message || errJson.error || errText;
} catch (e) {}
// Log complete diagnostic error object to the real browser console
logRealConsoleApiError({
topic: 'Hugging Face Inference HTTP Error',
endpoint: HF_ROUTER_ENDPOINT,
model: PRIMARY_MODEL_ID,
status: response.status,
statusText: response.statusText,
message: parsedMessage,
requestPayload: {
model: PRIMARY_MODEL_ID,
messagesCount: messages.length,
temperature,
stream: !!onChunk,
},
rawResponse: errText,
});
if (response.status === 401) {
throw new Error('Hugging Face API Authentication Failed (401): Invalid or unauthorized Access Token. Verify token in Settings.');
}
if (response.status === 429) {
throw new Error('Hugging Face Rate Limit Exceeded (429): Quota reached or too many concurrent inference calls.');
}
if (response.status === 503) {
throw new Error('Hugging Face Model Unavailable (503): Model is currently loading on cloud GPU. Please retry shortly.');
}
throw new Error(`Hugging Face API Error (${response.status} ${response.statusText}): ${parsedMessage}`);
}
if (onChunk && response.body) {
const reader = response.body.getReader();
const decoder = new TextDecoder('utf-8');
let fullContent = '';
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || trimmed === 'data: [DONE]') continue;
if (trimmed.startsWith('data: ')) {
try {
const data = JSON.parse(trimmed.slice(6));
const delta = data.choices?.[0]?.delta?.content || '';
if (delta) {
fullContent += delta;
onChunk(fullContent);
}
} catch (e) {}
}
}
}
if (fullContent.trim()) {
return fullContent;
}
// Stream completed with zero content
const emptyStreamErr = new Error('RiShre API Error: Inference stream completed without emitting any tokens.');
logRealConsoleApiError({
topic: 'Empty Stream / No Reply',
endpoint: HF_ROUTER_ENDPOINT,
model: PRIMARY_MODEL_ID,
message: emptyStreamErr.message,
error: emptyStreamErr,
});
throw emptyStreamErr;
}
const data = await response.json();
const result = data.choices?.[0]?.message?.content || '';
if (!result.trim()) {
const emptyReplyErr = new Error('RiShre API Error: Model returned an empty completion response.');
logRealConsoleApiError({
topic: 'Empty Completion Response',
endpoint: HF_ROUTER_ENDPOINT,
model: PRIMARY_MODEL_ID,
message: emptyReplyErr.message,
rawResponse: data,
error: emptyReplyErr,
});
throw emptyReplyErr;
}
if (onChunk && result) {
onChunk(result);
}
return result;
} catch (error: any) {
// Log complete error details to the real browser console
logRealConsoleApiError({
topic: 'API Call Exception / Network Failure',
endpoint: HF_ROUTER_ENDPOINT,
model: PRIMARY_MODEL_ID,
message: error.message || 'Network request failed or connection refused.',
error: error,
});
// Propagate the error so the caller and console record the failure
throw error;
}
}
/**
* Intelligent client-side RiShre Awakened engine:
* Handles BOTH general conversational AI interaction (like Google AI Studio)
* and deep Vibe Coding app synthesis with rich streaming!
*/
export async function runAwakenedSimulation(
prompt: string,
currentFiles: ProjectFile[],
onChunk?: (chunk: string) => void
): Promise<string> {
const p = prompt.trim().toLowerCase();
let generatedContent = '';
const delay = (ms: number) => new Promise(res => setTimeout(res, ms));
// 1. General Conversational Agent Responses (Google AI Studio style)
if (
p.startsWith('hi') ||
p.startsWith('hello') ||
p.startsWith('hey') ||
p.includes('who are you') ||
p.includes('what are you') ||
p.includes('what can you do')
) {
generatedContent = `Hello! I am **RiShre Awakened** — your omni-capable AI partner and vibe coding architect.
Think of me as your dedicated co-founder, research lead, and senior engineer all in one. Here is how we can collaborate:
### 🧠 General Intelligence & Conversational Power
- **Ideation & Brainstorming**: Pitch me product ideas, startup concepts, or architectural dilemmas.
- **Deep Technical Explanations**: Ask me about distributed systems, machine learning, physics, UI/UX philosophy, or business strategy.
- **Creative & Strategic Writing**: Drafting release notes, manifestos, pitches, or copywriting.
### ⚡ Autonomous Vibe Coding & Web Synthesis
- **Instant App Construction**: Simply describe any web application, dashboard, or game in plain English (e.g., *"Build an ambient audio synth"* or *"Create a luxury crypto portfolio"*).
- **Iterative Refinements**: Ask me to *"add haptic spring animations"*, *"switch to royal purple neon"*, or *"inject Web Audio sound synthesis"*.
- **Live Preview & File Export**: Every generated piece runs immediately in your sandboxed preview panel and can be exported as a standalone static web app or Hugging Face Space.
What is on your mind today? Are we exploring an idea or building something legendary?`;
} else if (
p.includes('joke') ||
p.includes('funny') ||
p.includes('humor')
) {
generatedContent = `Here's one tailored for developers and visionaries:
> Why do programmers prefer dark purple mode?
>
> *Because light attracts bugs — but royal purple gives them imposter syndrome.* 👑
Want to brainstorm something wild or shall we build a project together?`;
} else if (
p.includes('explain') ||
p.includes('what is') ||
p.includes('how does') ||
p.includes('why')
) {
// Conceptual / educational question
generatedContent = `### RiShre Awakened Insights
Regarding **"${prompt}"**:
At a fundamental level, modern digital architecture and creative intelligence converge on a single principle: **seamless abstraction**.
1. **The Conceptual Foundation**:
Every complex system begins as a high-dimensional concept. Whether analyzing algorithmic complexity, state synchronization, or human cognitive ergonomics, the key is reducing friction between thought and realization.
2. **The Modern Paradigm**:
Instead of writing repetitive boilerplate, we now practice **Vibe Coding** — where intent, taste, and aesthetics guide the synthesis of production-ready interfaces.
3. **Strategic Takeaway**:
Great software isn't just about syntax; it is about *how it feels to use*. Fluid state transitions, deliberate typographic scale, and harmonious color theory transform utilitarian tools into memorable experiences.
Would you like to explore this topic further, or shall we translate this concept into an interactive visual prototype right here in RiShre?`;
} else if (
p.includes('game') ||
p.includes('shooter') ||
p.includes('arcade') ||
p.includes('space')
) {
// Coding: Luxury Space Game
generatedContent = `### RiShre Awakened Synthesis: Royal Void Interceptor
I have channeled our royal dark purple aesthetic into an arcade interceptor canvas. It features neon violet particle thrusters, laser cannons, procedural starfields, and real-time shield telemetry.
\`\`\`html <!-- file: index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Royal Void Interceptor</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="style.css">
</head>
<body class="bg-[#07040f] text-purple-200 min-h-screen overflow-hidden flex flex-col items-center justify-center font-mono select-none">
<div class="relative w-full h-screen flex flex-col">
<!-- Top Luxury HUD -->
<div class="absolute top-4 left-6 right-6 flex justify-between items-center z-10 pointer-events-none">
<div class="bg-[#120824]/90 border border-purple-500/40 px-5 py-2.5 rounded-2xl backdrop-blur-xl shadow-[0_0_30px_rgba(168,85,247,0.25)] flex items-center gap-3">
<span class="w-2.5 h-2.5 rounded-full bg-purple-400 shadow-[0_0_10px_#c084fc]"></span>
<span class="text-xs text-purple-300 font-bold tracking-wider">SCORE //</span>
<span id="score-val" class="text-xl font-black text-white font-mono">0</span>
</div>
<div class="bg-[#120824]/90 border border-purple-500/40 px-5 py-2.5 rounded-2xl backdrop-blur-xl shadow-[0_0_30px_rgba(168,85,247,0.25)] flex items-center gap-3">
<span class="text-xs text-purple-300 font-bold tracking-wider">AEGIS SHIELD:</span>
<div class="w-28 h-3 bg-purple-950/80 rounded-full overflow-hidden border border-purple-500/30">
<div id="shield-bar" class="w-full h-full bg-gradient-to-r from-purple-500 to-fuchsia-500 transition-all duration-200 shadow-[0_0_12px_#d946ef]"></div>
</div>
</div>
</div>
<!-- Canvas -->
<canvas id="game-canvas" class="w-full h-full cursor-crosshair"></canvas>
<!-- Overlay Instructions -->
<div id="instructions" class="absolute bottom-6 left-1/2 -translate-x-1/2 bg-[#140a2b]/90 border border-purple-500/30 px-6 py-2.5 rounded-full text-xs text-purple-200 backdrop-blur-xl z-10 pointer-events-none shadow-[0_0_25px_rgba(168,85,247,0.2)]">
⚡ <strong class="text-white">Mouse / Pointer</strong> to Pilot • <strong class="text-fuchsia-300">Click</strong> to Discharge Photons
</div>
</div>
<script src="app.js"></script>
</body>
</html>
\`\`\`
\`\`\`css /* file: style.css */
canvas {
background: radial-gradient(circle at center, #130a26 0%, #07040f 100%);
}
\`\`\`
\`\`\`javascript // file: app.js
const canvas = document.getElementById('game-canvas');
const ctx = canvas.getContext('2d');
const scoreEl = document.getElementById('score-val');
const shieldBar = document.getElementById('shield-bar');
let width = (canvas.width = window.innerWidth);
let height = (canvas.height = window.innerHeight);
window.addEventListener('resize', () => {
width = canvas.width = window.innerWidth;
height = canvas.height = window.innerHeight;
});
let score = 0;
let shield = 100;
let player = { x: width / 2, y: height - 120, vx: 0, targetX: width / 2 };
const lasers = [];
const enemies = [];
const particles = [];
const stars = [];
for (let i = 0; i < 110; i++) {
stars.push({
x: Math.random() * width,
y: Math.random() * height,
speed: Math.random() * 2 + 0.4,
size: Math.random() * 2 + 0.5,
hue: Math.random() * 40 + 260
});
}
window.addEventListener('mousemove', (e) => {
player.targetX = e.clientX;
});
window.addEventListener('click', () => {
lasers.push({ x: player.x - 14, y: player.y - 12, vy: -14 });
lasers.push({ x: player.x + 14, y: player.y - 12, vy: -14 });
for (let i = 0; i < 5; i++) {
particles.push({
x: player.x,
y: player.y + 16,
vx: (Math.random() - 0.5) * 3,
vy: Math.random() * 4 + 2,
life: 1,
color: '#c084fc'
});
}
});
function spawnEnemy() {
if (enemies.length < 9 && Math.random() < 0.045) {
enemies.push({
x: Math.random() * (width - 80) + 40,
y: -30,
vy: Math.random() * 2.2 + 1.2,
radius: 20,
hp: 2,
hue: Math.random() * 40 + 310
});
}
}
function gameLoop() {
ctx.fillStyle = 'rgba(7, 4, 15, 0.35)';
ctx.fillRect(0, 0, width, height);
// Stars
stars.forEach(s => {
s.y += s.speed;
if (s.y > height) s.y = 0;
ctx.fillStyle = \`hsl(\${s.hue}, 90%, 75%)\`;
ctx.fillRect(s.x, s.y, s.size, s.size);
});
// Player ship
player.x += (player.targetX - player.x) * 0.16;
ctx.save();
ctx.translate(player.x, player.y);
ctx.beginPath();
ctx.moveTo(0, -26);
ctx.lineTo(18, 20);
ctx.lineTo(0, 12);
ctx.lineTo(-18, 20);
ctx.closePath();
ctx.fillStyle = '#a855f7';
ctx.shadowColor = '#d946ef';
ctx.shadowBlur = 20;
ctx.fill();
ctx.restore();
// Lasers
for (let i = lasers.length - 1; i >= 0; i--) {
const l = lasers[i];
l.y += l.vy;
ctx.fillStyle = '#f472b6';
ctx.shadowColor = '#ec4899';
ctx.shadowBlur = 10;
ctx.fillRect(l.x - 2, l.y, 4, 16);
if (l.y < -20) lasers.splice(i, 1);
}
// Enemies
spawnEnemy();
for (let i = enemies.length - 1; i >= 0; i--) {
const e = enemies[i];
e.y += e.vy;
ctx.beginPath();
ctx.arc(e.x, e.y, e.radius, 0, Math.PI * 2);
ctx.fillStyle = \`hsl(\${e.hue}, 85%, 60%)\`;
ctx.shadowColor = '#e879f9';
ctx.shadowBlur = 15;
ctx.fill();
for (let j = lasers.length - 1; j >= 0; j--) {
const l = lasers[j];
const dx = l.x - e.x;
const dy = l.y - e.y;
if (Math.sqrt(dx * dx + dy * dy) < e.radius) {
lasers.splice(j, 1);
e.hp--;
if (e.hp <= 0) {
score += 150;
scoreEl.textContent = score;
for (let p = 0; p < 14; p++) {
particles.push({
x: e.x, y: e.y,
vx: (Math.random() - 0.5) * 7,
vy: (Math.random() - 0.5) * 7,
life: 1,
color: '#f472b6'
});
}
enemies.splice(i, 1);
break;
}
}
}
if (e.y > height + 40) enemies.splice(i, 1);
}
// Particles
for (let i = particles.length - 1; i >= 0; i--) {
const p = particles[i];
p.x += p.vx;
p.y += p.vy;
p.life -= 0.03;
ctx.fillStyle = p.color;
ctx.globalAlpha = Math.max(0, p.life);
ctx.fillRect(p.x, p.y, 3, 3);
ctx.globalAlpha = 1;
if (p.life <= 0) particles.splice(i, 1);
}
requestAnimationFrame(gameLoop);
}
gameLoop();
\`\`\`
The Royal Void Interceptor has been synthesized and compiled into your live preview panel!`;
} else {
// Default coding synthesis with million-dollar royal dark purple aesthetic
generatedContent = `### RiShre Awakened Synthesis
I have synthesized your vision into a luxury, million-dollar dark purple web experience matching: "${prompt}".
\`\`\`html <!-- file: index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>RiShre Luxury Experience</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;800&family=JetBrains+Mono:wght@400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
</head>
<body class="bg-[#07040f] text-purple-100 min-h-screen flex flex-col items-center justify-center p-6 selection:bg-purple-500 selection:text-white">
<div class="relative w-full max-w-lg bg-[#110724]/80 border border-purple-500/30 rounded-3xl p-8 backdrop-blur-2xl shadow-[0_0_60px_rgba(168,85,247,0.2)] flex flex-col gap-6">
<!-- Top Branding -->
<div class="flex items-center justify-between border-b border-purple-500/20 pb-4">
<div class="flex items-center gap-3">
<div class="w-3.5 h-3.5 rounded-full bg-gradient-to-r from-purple-400 to-fuchsia-400 shadow-[0_0_15px_#c084fc]"></div>
<span class="font-mono text-sm tracking-widest text-purple-300 font-bold">RISHRE_AWAKENED</span>
</div>
<span class="text-xs font-mono text-purple-400/80 bg-purple-950/60 px-3 py-1 rounded-full border border-purple-500/30">
STATUS // QUANTUM_ONLINE
</span>
</div>
<div>
<h1 class="text-2xl font-black text-white tracking-tight bg-clip-text text-transparent bg-gradient-to-r from-white via-purple-100 to-purple-300">
Autonomous Vibe Architecture
</h1>
<p class="text-xs text-purple-300/80 mt-2 leading-relaxed">
Synthesized in response to: <span class="text-fuchsia-300 font-mono font-medium">"${prompt}"</span>
</p>
</div>
<!-- Luxury Interactive Metric Glass -->
<div class="flex flex-col gap-3 bg-[#0a0417]/80 border border-purple-500/20 p-5 rounded-2xl shadow-inner">
<div class="flex justify-between items-center text-xs font-mono text-purple-300">
<span>QUANTUM HARMONICS</span>
<span id="counter-val" class="text-fuchsia-300 font-bold text-base">99.4%</span>
</div>
<div class="w-full bg-purple-950/80 rounded-full h-3 overflow-hidden border border-purple-500/30 p-0.5">
<div id="meter-fill" class="bg-gradient-to-r from-purple-600 via-fuchsia-500 to-pink-500 h-full w-[88%] rounded-full transition-all duration-300 shadow-[0_0_15px_#d946ef]"></div>
</div>
</div>
<!-- Action Buttons -->
<div class="grid grid-cols-2 gap-3">
<button id="pulse-btn" class="py-3 px-4 rounded-xl bg-gradient-to-r from-purple-600 to-fuchsia-600 hover:from-purple-500 hover:to-fuchsia-500 text-white font-bold font-mono text-xs uppercase tracking-wider transition-all shadow-[0_0_25px_rgba(168,85,247,0.4)] cursor-pointer active:scale-95">
⚡ Ignite Pulse
</button>
<button id="color-btn" class="py-3 px-4 rounded-xl bg-[#180b33] hover:bg-[#23104a] text-purple-200 font-mono text-xs border border-purple-500/30 transition-all cursor-pointer active:scale-95">
💎 Shift Resonance
</button>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
\`\`\`
\`\`\`css /* file: style.css */
body {
font-family: 'Plus Jakarta Sans', system-ui, sans-serif;
background-image: radial-gradient(circle at 50% 50%, rgba(168, 85, 247, 0.08) 0%, transparent 60%);
}
\`\`\`
\`\`\`javascript // file: app.js
let resonance = 88;
const counterVal = document.getElementById('counter-val');
const meterFill = document.getElementById('meter-fill');
const pulseBtn = document.getElementById('pulse-btn');
const colorBtn = document.getElementById('color-btn');
pulseBtn.addEventListener('click', () => {
resonance = (resonance + 12) % 100 || 24;
counterVal.textContent = resonance + '%';
meterFill.style.width = resonance + '%';
});
const gradients = [
'from-purple-600 via-fuchsia-500 to-pink-500',
'from-indigo-600 via-purple-500 to-cyan-400',
'from-fuchsia-600 via-rose-500 to-amber-400'
];
let gradIdx = 0;
colorBtn.addEventListener('click', () => {
gradIdx = (gradIdx + 1) % gradients.length;
meterFill.className = \`bg-gradient-to-r \${gradients[gradIdx]} h-full rounded-full transition-all duration-300\`;
});
\`\`\`
The synthesized application is compiled and running in your live preview!`;
}
// Stream in realistic character chunks
if (onChunk) {
const step = 60;
for (let i = 0; i < generatedContent.length; i += step) {
const slice = generatedContent.slice(0, i + step);
onChunk(slice);
await delay(20);
}
}
return generatedContent;
}