feat: implement AI-powered Human-in-the-Loop Norm Builder interface and standard CRUD endpoints
This commit is contained in:
@@ -10,7 +10,7 @@ import { ReportDisplay } from './components/ReportDisplay';
|
|||||||
import { PrintableReport } from './components/PrintableReport';
|
import { PrintableReport } from './components/PrintableReport';
|
||||||
import { DownloadIcon, EyeIcon, CogIcon } from './components/Icons';
|
import { DownloadIcon, EyeIcon, CogIcon } from './components/Icons';
|
||||||
import { ApiKeySetup } from './components/ApiKeySetup';
|
import { ApiKeySetup } from './components/ApiKeySetup';
|
||||||
import { AdminCategories } from './components/AdminCategories';
|
import { AdminPanel } from './components/AdminPanel';
|
||||||
|
|
||||||
const App: React.FC = () => {
|
const App: React.FC = () => {
|
||||||
const [viewMode, setViewMode] = useState<'analysis' | 'admin'>('analysis');
|
const [viewMode, setViewMode] = useState<'analysis' | 'admin'>('analysis');
|
||||||
@@ -219,7 +219,12 @@ const App: React.FC = () => {
|
|||||||
<span className="w-10 h-10 border-4 border-blue-500 border-t-transparent rounded-full animate-spin"></span>
|
<span className="w-10 h-10 border-4 border-blue-500 border-t-transparent rounded-full animate-spin"></span>
|
||||||
</div>
|
</div>
|
||||||
) : viewMode === 'admin' ? (
|
) : viewMode === 'admin' ? (
|
||||||
<AdminCategories />
|
<AdminPanel
|
||||||
|
provider={provider}
|
||||||
|
apiKey={apiKey}
|
||||||
|
model={model}
|
||||||
|
endpoint={endpoint}
|
||||||
|
/>
|
||||||
) : (!hasKey || showSetup) ? (
|
) : (!hasKey || showSetup) ? (
|
||||||
<ApiKeySetup onKeySave={handleKeySave} onCancel={hasKey ? () => setShowSetup(false) : undefined} />
|
<ApiKeySetup onKeySave={handleKeySave} onCancel={hasKey ? () => setShowSetup(false) : undefined} />
|
||||||
) : !reportsData ? (
|
) : !reportsData ? (
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import { AdminCategories } from './AdminCategories';
|
||||||
|
import { AdminStandards } from './AdminStandards';
|
||||||
|
import type { AIProvider } from '../types/providers';
|
||||||
|
|
||||||
|
interface AdminPanelProps {
|
||||||
|
apiKey: string;
|
||||||
|
provider: AIProvider;
|
||||||
|
model: string;
|
||||||
|
endpoint?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const AdminPanel: React.FC<AdminPanelProps> = (props) => {
|
||||||
|
const [activeTab, setActiveTab] = useState<'categories' | 'standards'>('categories');
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="max-w-6xl mx-auto p-4 sm:p-6 lg:p-8 animate-fade-in">
|
||||||
|
<div className="mb-8 border-b border-slate-200 dark:border-slate-700">
|
||||||
|
<div className="flex gap-8">
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('categories')}
|
||||||
|
className={`pb-4 text-sm font-bold transition-all border-b-2 ${
|
||||||
|
activeTab === 'categories'
|
||||||
|
? 'border-indigo-500 text-indigo-600 dark:text-indigo-400'
|
||||||
|
: 'border-transparent text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-300'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
1. Categorias Base
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('standards')}
|
||||||
|
className={`pb-4 text-sm font-bold transition-all border-b-2 flex items-center gap-2 ${
|
||||||
|
activeTab === 'standards'
|
||||||
|
? 'border-indigo-500 text-indigo-600 dark:text-indigo-400'
|
||||||
|
: 'border-transparent text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-300'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
2. Construtor de Normas IA
|
||||||
|
<span className="bg-indigo-100 text-indigo-800 dark:bg-indigo-900 dark:text-indigo-200 text-[10px] px-2 py-0.5 rounded-full">Beta</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{activeTab === 'categories' ? <AdminCategories /> : <AdminStandards {...props} />}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
import React, { useState, useEffect } from 'react';
|
||||||
|
import type { Category } from './AdminCategories';
|
||||||
|
import { buildStandardWithAI } from '../services/aiService';
|
||||||
|
import type { AIProvider } from '../types/providers';
|
||||||
|
|
||||||
|
interface AdminStandardsProps {
|
||||||
|
apiKey: string;
|
||||||
|
provider: AIProvider;
|
||||||
|
model: string;
|
||||||
|
endpoint?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const AdminStandards: React.FC<AdminStandardsProps> = ({ apiKey, provider, model, endpoint }) => {
|
||||||
|
const [categories, setCategories] = useState<Category[]>([]);
|
||||||
|
const [selectedCategory, setSelectedCategory] = useState<string>('');
|
||||||
|
const [standards, setStandards] = useState<any[]>([]);
|
||||||
|
const [isLoadingCats, setIsLoadingCats] = useState(true);
|
||||||
|
|
||||||
|
const [isGenerating, setIsGenerating] = useState(false);
|
||||||
|
const [standardName, setStandardName] = useState('');
|
||||||
|
const [generatedJson, setGeneratedJson] = useState('');
|
||||||
|
const [jsonError, setJsonError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchCategories();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (selectedCategory) {
|
||||||
|
fetchStandards(selectedCategory);
|
||||||
|
} else {
|
||||||
|
setStandards([]);
|
||||||
|
}
|
||||||
|
}, [selectedCategory]);
|
||||||
|
|
||||||
|
const fetchCategories = async () => {
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/categories');
|
||||||
|
const data = await res.json();
|
||||||
|
setCategories(data);
|
||||||
|
if (data.length > 0) setSelectedCategory(data[0].id);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
} finally {
|
||||||
|
setIsLoadingCats(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const fetchStandards = async (catId: string) => {
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/standards?categoryId=${catId}`);
|
||||||
|
const data = await res.json();
|
||||||
|
setStandards(data);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleGenerate = async () => {
|
||||||
|
if (!standardName || !selectedCategory) return;
|
||||||
|
|
||||||
|
const cat = categories.find(c => c.id === selectedCategory);
|
||||||
|
if (!cat) return;
|
||||||
|
|
||||||
|
setIsGenerating(true);
|
||||||
|
setJsonError(null);
|
||||||
|
try {
|
||||||
|
const jsonObj = await buildStandardWithAI(
|
||||||
|
{ provider, apiKey, model, endpoint },
|
||||||
|
standardName,
|
||||||
|
cat.description
|
||||||
|
);
|
||||||
|
setGeneratedJson(JSON.stringify(jsonObj, null, 2));
|
||||||
|
} catch (e: any) {
|
||||||
|
setJsonError(e.message || "Erro ao gerar a norma.");
|
||||||
|
} finally {
|
||||||
|
setIsGenerating(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSave = async () => {
|
||||||
|
if (!generatedJson) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(generatedJson);
|
||||||
|
parsed.categoria_id = selectedCategory;
|
||||||
|
|
||||||
|
await fetch('/api/standards', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(parsed)
|
||||||
|
});
|
||||||
|
|
||||||
|
setGeneratedJson('');
|
||||||
|
setStandardName('');
|
||||||
|
fetchStandards(selectedCategory);
|
||||||
|
} catch (e) {
|
||||||
|
setJsonError("Erro ao salvar: JSON inválido ou falha na rede.");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDelete = async (id: string) => {
|
||||||
|
if (!confirm('Excluir esta norma? O app não poderá mais validar relatórios contra ela.')) return;
|
||||||
|
try {
|
||||||
|
await fetch(`/api/standards?id=${id}`, { method: 'DELETE' });
|
||||||
|
fetchStandards(selectedCategory);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isLoadingCats) return <div className="p-8 text-center">Carregando categorias...</div>;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="animate-fade-in space-y-8">
|
||||||
|
{/* Selector */}
|
||||||
|
<div className="bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 p-5">
|
||||||
|
<label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">Selecione a Categoria de Material</label>
|
||||||
|
<select
|
||||||
|
value={selectedCategory}
|
||||||
|
onChange={e => setSelectedCategory(e.target.value)}
|
||||||
|
className="w-full rounded-lg border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-700 px-4 py-2 text-slate-900 dark:text-white"
|
||||||
|
>
|
||||||
|
{categories.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{selectedCategory && (
|
||||||
|
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
|
||||||
|
|
||||||
|
{/* Builder */}
|
||||||
|
<div className="bg-gradient-to-br from-indigo-50 to-blue-50 dark:from-slate-800 dark:to-slate-900 rounded-xl shadow-sm border border-indigo-100 dark:border-slate-700 p-5">
|
||||||
|
<h3 className="text-lg font-bold text-indigo-900 dark:text-indigo-300 mb-4 flex items-center gap-2">
|
||||||
|
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" /></svg>
|
||||||
|
Construtor Assistido por IA
|
||||||
|
</h3>
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Nome exato da Norma</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={standardName}
|
||||||
|
onChange={e => setStandardName(e.target.value)}
|
||||||
|
placeholder="Ex: ASTM A572 Grau 50"
|
||||||
|
className="w-full rounded-lg border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-700 px-4 py-2 text-slate-900 dark:text-white outline-none focus:ring-2 focus:ring-indigo-500"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
onClick={handleGenerate}
|
||||||
|
disabled={isGenerating || !standardName || !apiKey}
|
||||||
|
className="w-full bg-indigo-600 hover:bg-indigo-700 disabled:opacity-50 text-white font-bold py-2.5 rounded-lg transition-all"
|
||||||
|
>
|
||||||
|
{isGenerating ? 'Analisando e Extraindo Limites...' : 'Gerar Estrutura com IA'}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{!apiKey && (
|
||||||
|
<p className="text-red-500 text-xs">Configure a Chave da API no painel inicial primeiro.</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{jsonError && (
|
||||||
|
<div className="p-3 bg-red-100 text-red-700 rounded-lg text-sm">{jsonError}</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{generatedJson && (
|
||||||
|
<div className="mt-6 animate-fade-in">
|
||||||
|
<label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1 flex justify-between">
|
||||||
|
<span>Valide e corrija os parâmetros abaixo:</span>
|
||||||
|
<span className="text-xs bg-yellow-100 text-yellow-800 px-2 py-0.5 rounded">Human-in-the-Loop</span>
|
||||||
|
</label>
|
||||||
|
<textarea
|
||||||
|
value={generatedJson}
|
||||||
|
onChange={e => setGeneratedJson(e.target.value)}
|
||||||
|
className="w-full h-80 font-mono text-sm rounded-lg border-slate-300 dark:border-slate-600 bg-slate-50 dark:bg-slate-950 p-4 text-slate-800 dark:text-slate-300 outline-none focus:ring-2 focus:ring-indigo-500"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
onClick={handleSave}
|
||||||
|
className="mt-4 w-full bg-emerald-600 hover:bg-emerald-700 text-white font-bold py-3 rounded-lg transition-all flex justify-center items-center gap-2"
|
||||||
|
>
|
||||||
|
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" /></svg>
|
||||||
|
Validar e Salvar Norma na Base
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* List */}
|
||||||
|
<div className="bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 p-5">
|
||||||
|
<h3 className="text-lg font-bold text-slate-800 dark:text-slate-200 mb-4">Normas Ativas</h3>
|
||||||
|
|
||||||
|
<div className="space-y-3">
|
||||||
|
{standards.length === 0 ? (
|
||||||
|
<p className="text-sm text-slate-500">Nenhuma norma cadastrada nesta categoria ainda.</p>
|
||||||
|
) : (
|
||||||
|
standards.map(s => (
|
||||||
|
<div key={s.id} className="p-4 rounded-lg border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800/50 flex justify-between items-start">
|
||||||
|
<div>
|
||||||
|
<h4 className="font-bold text-slate-800 dark:text-white">{s.codigo}</h4>
|
||||||
|
<p className="text-xs text-slate-500 dark:text-slate-400 mt-1">{s.produto_especifico}</p>
|
||||||
|
|
||||||
|
<div className="mt-3 flex flex-wrap gap-2">
|
||||||
|
{Object.keys(s.parametros_controle || {}).map(grupo => (
|
||||||
|
<span key={grupo} className="text-[10px] uppercase font-bold bg-slate-200 dark:bg-slate-700 text-slate-600 dark:text-slate-300 px-2 py-1 rounded">
|
||||||
|
{grupo}: {Object.keys(s.parametros_controle[grupo] || {}).length} specs
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => handleDelete(s.id)}
|
||||||
|
className="text-red-500 hover:text-red-700 p-2"
|
||||||
|
title="Excluir"
|
||||||
|
>
|
||||||
|
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /></svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -137,6 +137,87 @@ const server = http.createServer((req, res) => {
|
|||||||
}
|
}
|
||||||
// --- END CATEGORIES CRUD ---
|
// --- END CATEGORIES CRUD ---
|
||||||
|
|
||||||
|
// --- STANDARDS CRUD ---
|
||||||
|
const STANDARDS_FILE = path.join(CONFIG_DIR, 'standards.json');
|
||||||
|
const readStandards = () => {
|
||||||
|
if (fs.existsSync(STANDARDS_FILE)) {
|
||||||
|
try { return JSON.parse(fs.readFileSync(STANDARDS_FILE, 'utf-8')); } catch (e) {}
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
};
|
||||||
|
|
||||||
|
if (pathname === '/api/standards') {
|
||||||
|
if (req.method === 'GET') {
|
||||||
|
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||||
|
const allStandards = readStandards();
|
||||||
|
const catId = parsedUrl.searchParams.get('categoryId');
|
||||||
|
if (catId) {
|
||||||
|
res.end(JSON.stringify(allStandards.filter(s => s.categoria_id === catId)));
|
||||||
|
} else {
|
||||||
|
res.end(JSON.stringify(allStandards));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (req.method === 'POST' || req.method === 'PUT') {
|
||||||
|
let body = '';
|
||||||
|
req.on('data', chunk => body += chunk.toString());
|
||||||
|
req.on('end', () => {
|
||||||
|
try {
|
||||||
|
const standard = JSON.parse(body);
|
||||||
|
|
||||||
|
// Sanitização numérica para parametros_controle
|
||||||
|
if (standard.parametros_controle) {
|
||||||
|
for (const key of Object.keys(standard.parametros_controle)) {
|
||||||
|
const grupo = standard.parametros_controle[key];
|
||||||
|
if (typeof grupo === 'object' && grupo !== null) {
|
||||||
|
for (const prop of Object.keys(grupo)) {
|
||||||
|
const val = grupo[prop];
|
||||||
|
if (val !== null && val !== undefined && val !== '') {
|
||||||
|
const num = parseFloat(val);
|
||||||
|
if (!isNaN(num)) {
|
||||||
|
grupo[prop] = num;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let standards = readStandards();
|
||||||
|
if (req.method === 'POST') {
|
||||||
|
standard.id = Date.now().toString();
|
||||||
|
standards.push(standard);
|
||||||
|
} else {
|
||||||
|
const index = standards.findIndex(s => s.id === standard.id);
|
||||||
|
if (index !== -1) standards[index] = { ...standards[index], ...standard };
|
||||||
|
}
|
||||||
|
fs.writeFileSync(STANDARDS_FILE, JSON.stringify(standards, null, 2));
|
||||||
|
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||||
|
res.end(JSON.stringify(standard));
|
||||||
|
} catch (err) {
|
||||||
|
res.writeHead(400); res.end(JSON.stringify({ error: 'Invalid payload' }));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (req.method === 'DELETE') {
|
||||||
|
const id = parsedUrl.searchParams.get('id');
|
||||||
|
if (id) {
|
||||||
|
let standards = readStandards();
|
||||||
|
standards = standards.filter(s => s.id !== id);
|
||||||
|
fs.writeFileSync(STANDARDS_FILE, JSON.stringify(standards, null, 2));
|
||||||
|
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||||
|
res.end(JSON.stringify({ success: true }));
|
||||||
|
} else {
|
||||||
|
res.writeHead(400); res.end(JSON.stringify({ error: 'Missing id' }));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// --- END STANDARDS CRUD ---
|
||||||
|
|
||||||
// Serve static files
|
// Serve static files
|
||||||
let filePath = path.join(DIST_DIR, req.url === '/' ? 'index.html' : req.url);
|
let filePath = path.join(DIST_DIR, req.url === '/' ? 'index.html' : req.url);
|
||||||
|
|
||||||
|
|||||||
@@ -598,3 +598,87 @@ export const analyzeWithMinimax = async (file: File, apiKey: string, model: stri
|
|||||||
|
|
||||||
return cleanAndParseJson(content) as ReportData[];
|
return cleanAndParseJson(content) as ReportData[];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const buildStandardWithAI = async (
|
||||||
|
options: { provider: AIProvider; apiKey: string; model: string; endpoint?: string },
|
||||||
|
standardName: string,
|
||||||
|
categoryDescription: string
|
||||||
|
) => {
|
||||||
|
const prompt = `Você é um engenheiro de materiais sênior. O usuário solicitou a criação de uma tabela de limites para a norma técnica: "${standardName}".
|
||||||
|
A categoria deste material é descrita como: "${categoryDescription}".
|
||||||
|
|
||||||
|
Sua tarefa é acessar seu conhecimento sobre esta norma e gerar os limites estritos (mínimos e máximos) exigidos.
|
||||||
|
|
||||||
|
RESPONDA APENAS UM JSON VÁLIDO no seguinte formato EXATO:
|
||||||
|
{
|
||||||
|
"codigo": "Nome oficial da norma (ex: ASTM A36/A36M-19)",
|
||||||
|
"produto_especifico": "Descreva o tipo de produto que essa norma cobre",
|
||||||
|
"parametros_controle": {
|
||||||
|
"mecanicos": {
|
||||||
|
"nome_do_parametro_1": valor_numerico,
|
||||||
|
"nome_do_parametro_2": valor_numerico
|
||||||
|
},
|
||||||
|
"quimicos": {
|
||||||
|
"nome_do_parametro": valor_numerico
|
||||||
|
},
|
||||||
|
"fisicos": {
|
||||||
|
"nome_do_parametro": valor_numerico
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Regras Cruciais:
|
||||||
|
1. USE APENAS NÚMEROS (floats/ints) nos valores. NUNCA use strings como "0.25" ou "250". Use 0.25 e 250.
|
||||||
|
2. Se a norma não especifica um limite máximo ou mínimo para um elemento, coloque null (sem aspas).
|
||||||
|
3. O nome da chave dentro de mecânicos/químicos/físicos deve ser em minúsculo, sem acentos, com underscores, e deve conter a unidade ou a palavra min/max (ex: "limite_escoamento_min_mpa", "carbono_max_percentual", "espessura_min_microns").
|
||||||
|
4. Crie APENAS os grupos (mecanicos, quimicos, fisicos) que fazem sentido para a norma solicitada.
|
||||||
|
5. DEVOLVA APENAS O JSON, sem nenhuma formatação ou texto explicativo ao redor.`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
let resultJson = '';
|
||||||
|
|
||||||
|
if (options.provider === 'gemini') {
|
||||||
|
const ai = new GoogleGenAI({ apiKey: options.apiKey });
|
||||||
|
const response = await ai.models.generateContent({
|
||||||
|
model: options.model || 'gemini-2.5-flash',
|
||||||
|
contents: prompt
|
||||||
|
});
|
||||||
|
resultJson = response.text || '';
|
||||||
|
} else if (options.provider === 'openai') {
|
||||||
|
const response = await fetch('https://api.openai.com/v1/chat/completions', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': `Bearer ${options.apiKey}`
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
model: options.model || 'gpt-4o',
|
||||||
|
messages: [{ role: "user", content: prompt }]
|
||||||
|
})
|
||||||
|
});
|
||||||
|
const data = await response.json();
|
||||||
|
resultJson = data.choices[0].message.content;
|
||||||
|
} else if (options.provider === 'openrouter') {
|
||||||
|
const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': `Bearer ${options.apiKey}`,
|
||||||
|
'HTTP-Referer': 'https://steelcheck.reifonas.cloud'
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
model: options.model || 'google/gemini-2.5-flash',
|
||||||
|
messages: [{ role: "user", content: prompt }]
|
||||||
|
})
|
||||||
|
});
|
||||||
|
const data = await response.json();
|
||||||
|
resultJson = data.choices[0].message.content;
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = cleanAndParseJson(resultJson);
|
||||||
|
return parsed;
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Erro no buildStandardWithAI:", error);
|
||||||
|
throw new Error("Falha ao gerar norma com a IA. Tente novamente.");
|
||||||
|
}
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user