fix: address issues in model pull and chat API
- Refactored model pull logic to improve error handling and user feedback. - Enhanced chat API to ensure better performance and reliability during message fetching. - Updated UI components for a more intuitive user experience when interacting with models and messages.
This commit is contained in:
1 parent
ad9d5d32d2
commit
b2a06ed994
261 files changed
+19968
No files matched your search
@@ -0,0 +1,106 @@
|
||||
import { useState, useRef } from 'react';
|
||||
|
||||
export interface Message {
|
||||
role: 'user' | 'assistant' | 'system';
|
||||
content: string;
|
||||
}
|
||||
|
||||
export function useChat() {
|
||||
const [messages, setMessages] = useState<Message[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const abortControllerRef = useRef<AbortController | null>(null);
|
||||
|
||||
const sendMessage = async (content: string, model: string, systemPrompt?: string) => {
|
||||
setIsLoading(true);
|
||||
|
||||
const newMessages: Message[] = [
|
||||
...messages,
|
||||
{ role: 'user', content }
|
||||
];
|
||||
setMessages(newMessages);
|
||||
|
||||
// Prepare messages for API (include system prompt if present)
|
||||
const apiMessages = systemPrompt
|
||||
? [{ role: 'system', content: systemPrompt }, ...newMessages]
|
||||
: newMessages;
|
||||
|
||||
abortControllerRef.current = new AbortController();
|
||||
|
||||
try {
|
||||
const response = await fetch('http://localhost:11434/api/chat', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
model,
|
||||
messages: apiMessages,
|
||||
stream: true,
|
||||
}),
|
||||
signal: abortControllerRef.current.signal,
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error('Failed to send message');
|
||||
if (!response.body) throw new Error('No response body');
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
// Add empty assistant message to start streaming into
|
||||
setMessages(prev => [...prev, { role: 'assistant', content: '' }]);
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
const chunk = decoder.decode(value, { stream: true });
|
||||
const lines = chunk.split('\n').filter(line => line.trim() !== '');
|
||||
|
||||
for (const line of lines) {
|
||||
try {
|
||||
const json = JSON.parse(line);
|
||||
if (json.message?.content) {
|
||||
setMessages(prev => {
|
||||
const last = prev[prev.length - 1];
|
||||
if (last.role === 'assistant') {
|
||||
return [
|
||||
...prev.slice(0, -1),
|
||||
{ ...last, content: last.content + json.message.content }
|
||||
];
|
||||
}
|
||||
return prev;
|
||||
});
|
||||
}
|
||||
if (json.done) {
|
||||
setIsLoading(false);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Error parsing chunk', e);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
if (error.name === 'AbortError') {
|
||||
console.log('Request aborted');
|
||||
} else {
|
||||
console.error('Chat error:', error);
|
||||
setMessages(prev => [...prev, { role: 'assistant', content: 'Error: Failed to get response from Ollama.' }]);
|
||||
}
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
abortControllerRef.current = null;
|
||||
}
|
||||
};
|
||||
|
||||
const stop = () => {
|
||||
if (abortControllerRef.current) {
|
||||
abortControllerRef.current.abort();
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const clearChat = () => {
|
||||
setMessages([]);
|
||||
};
|
||||
|
||||
return { messages, sendMessage, isLoading, stop, clearChat };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { SystemSpecs } from '@/lib/recommendation';
|
||||
|
||||
export function useHardware() {
|
||||
const [specs, setSpecs] = useState<SystemSpecs | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchSpecs() {
|
||||
try {
|
||||
const data = await invoke<SystemSpecs>('get_system_specs');
|
||||
// Simulate a small delay for the "scanning" effect
|
||||
setTimeout(() => {
|
||||
setSpecs(data);
|
||||
setLoading(false);
|
||||
}, 1500);
|
||||
} catch (error) {
|
||||
console.error("Failed to get system specs:", error);
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
fetchSpecs();
|
||||
}, []);
|
||||
|
||||
return { specs, loading };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
|
||||
export interface LocalModel {
|
||||
name: string;
|
||||
size: string;
|
||||
id: string;
|
||||
modified_at: string;
|
||||
}
|
||||
|
||||
export function useLocalModels() {
|
||||
const [models, setModels] = useState<LocalModel[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const fetchModels = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const list = await invoke<LocalModel[]>('list_local_models');
|
||||
setModels(list);
|
||||
} catch (error) {
|
||||
console.error("Failed to list models:", error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const deleteModel = async (name: string) => {
|
||||
try {
|
||||
await invoke('delete_model', { name });
|
||||
await fetchModels(); // Refresh list
|
||||
} catch (error) {
|
||||
console.error("Failed to delete model:", error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchModels();
|
||||
}, [fetchModels]);
|
||||
|
||||
return { models, loading, refresh: fetchModels, deleteModel };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
|
||||
export type OllamaStatus = 'checking' | 'not_installed' | 'installed_stopped' | 'running';
|
||||
|
||||
export function useOllamaCheck() {
|
||||
const [status, setStatus] = useState<OllamaStatus>('checking');
|
||||
|
||||
const check = async () => {
|
||||
// Don't set checking here if we want to silently revalidate,
|
||||
// but for initial load or explicit re-check it is fine.
|
||||
// Only set checking if it's not already in a known state to avoid flicker?
|
||||
// For now simple is better.
|
||||
try {
|
||||
const installed = await invoke<boolean>('check_ollama_installed');
|
||||
if (!installed) {
|
||||
setStatus('not_installed');
|
||||
return;
|
||||
}
|
||||
|
||||
const running = await invoke<boolean>('check_ollama_running');
|
||||
if (!running) {
|
||||
setStatus('installed_stopped');
|
||||
return;
|
||||
}
|
||||
|
||||
setStatus('running');
|
||||
} catch (error) {
|
||||
console.error('Failed to check ollama:', error);
|
||||
// If invoke fails (e.g. backend not ready), we might want to handle gracefully
|
||||
setStatus('not_installed');
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
check();
|
||||
}, []);
|
||||
|
||||
return { status, check };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { useState } from 'react';
|
||||
|
||||
// Hardcoded for now to avoid FS complexity in v1, but ideally read from file
|
||||
const PROMPT_GEN_SYSTEM = `Você é um Especialista em Engenharia de Prompts com raciocínio sequencial e acesso a fontes técnicas de primeira qualidade.
|
||||
|
||||
## BUSCA DE INFORMAÇÕES
|
||||
- Conteúdo técnico: documentação oficial, papers acadêmicos (arXiv, ACM, IEEE), repositórios GitHub verificados, fóruns técnicos especializados.
|
||||
- Notícias: apenas fontes editorialmente independentes, sem padrão tendencioso.
|
||||
- Dados científicos: periódicos revisados por pares, instituições acadêmicas renomadas (MIT, Stanford, Carnegie Mellon).
|
||||
|
||||
## RACIOCÍNIO SEQUENCIAL
|
||||
1. Decomponha o pedido em componentes específicos.
|
||||
2. Identifique lacunas de conhecimento e prioridades de pesquisa.
|
||||
3. Valide cada afirmação técnica com múltiplas fontes confiáveis.
|
||||
4. Apresente raciocínio passo-a-passo antes do prompt final.
|
||||
|
||||
## GERAÇÃO DE PROMPTS
|
||||
**Análise**: objetivo final, público-alvo, nível técnico, escopo temporal.
|
||||
**Pesquisa**: 3-5 fontes autorizadas, cite explicitamente, identifique frameworks emergentes.
|
||||
**Validação**: diferencie hype de inovações consolidadas, privilegie pesquisas recentes (12-24 meses), indique atualidade.
|
||||
|
||||
## ESTRUTURA DE SAÍDA
|
||||
1. Propósito claramente definido
|
||||
2. Contexto técnico atualizado com fontes verificadas
|
||||
3. Instruções sequenciais estruturadas
|
||||
4. Critérios de qualidade mensuráveis
|
||||
5. Restrições éticas e técnicas
|
||||
6. Citações discretas de fundamentos teóricos
|
||||
|
||||
## RESTRIÇÕES CRÍTICAS
|
||||
- Gere APENAS o prompt solicitado, sem explicações adicionais.
|
||||
- Limite máximo: 3900 caracteres por resposta.
|
||||
- Questione abordagens mais refinadas disponíveis.
|
||||
- Indique quando conhecimento requer atualização futura.
|
||||
- Lembre-se sempre, tudo que eu mandar aqui deve ser entendio e transformado em prompt, nada aqui é um pedido direto, é tudo para ser transformado em um prompt aprimorado com as melhores técnicas de prompt existentes.`;
|
||||
|
||||
export function usePromptGenerator() {
|
||||
const [isGenerating, setIsGenerating] = useState(false);
|
||||
|
||||
const generatePrompt = async (userGoal: string, model: string): Promise<string> => {
|
||||
setIsGenerating(true);
|
||||
try {
|
||||
const response = await fetch('http://localhost:11434/api/chat', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
model,
|
||||
messages: [
|
||||
{ role: 'system', content: PROMPT_GEN_SYSTEM },
|
||||
{ role: 'user', content: userGoal }
|
||||
],
|
||||
stream: false, // We want the full prompt at once for this utility
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error('Failed to generate prompt');
|
||||
|
||||
const data = await response.json();
|
||||
return data.message?.content || "";
|
||||
} catch (error) {
|
||||
console.error("Prompt generation failed:", error);
|
||||
throw error;
|
||||
} finally {
|
||||
setIsGenerating(false);
|
||||
}
|
||||
};
|
||||
|
||||
return { generatePrompt, isGenerating };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { listen } from '@tauri-apps/api/event';
|
||||
|
||||
export interface SystemStats {
|
||||
cpu_usage: number;
|
||||
memory_used: number;
|
||||
memory_total: number;
|
||||
}
|
||||
|
||||
export function useSystemMonitor() {
|
||||
const [stats, setStats] = useState<SystemStats | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
// Start the monitor thread in backend
|
||||
invoke('start_system_monitor');
|
||||
|
||||
const unlisten = listen<SystemStats>('system-stats', (event) => {
|
||||
setStats(event.payload);
|
||||
});
|
||||
|
||||
return () => {
|
||||
unlisten.then(f => f());
|
||||
};
|
||||
}, []);
|
||||
|
||||
return stats;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user