import { useState } from 'react'; import { Button } from '@/components/ui/button';…
- User
import { useState } from 'react'; import { Button } from '@/components/ui/button'; import { Textarea } from '@/components/ui/textarea'; import { Card, CardContent } from '@/components/ui/card'; import { Loader2, AlertCircle } from 'lucide-react'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/components/ui/select'; import { Alert, AlertDescription } from '@/components/ui/alert';
const LANGUAGES = [ 'American English', 'Gen Z', 'Millennial', 'Hindi', 'Spanish', 'French', 'Boomer', ] as const;
const MODELS = [ 'llama3.1:latest', 'mistral:latest', 'falcon-40b', ] as const;
export function TranslationForm() { const [input, setInput] = useState(''); const [loading, setLoading] = useState(false); const [error, setError] = useState<string | null>(null); const [fromLang, setFromLang] = useState(LANGUAGES[0]); const [toLang, setToLang] = useState(LANGUAGES[1]); const [selectedModel, setSelectedModel] = useState(MODELS[0]); const [apiResponse, setApiResponse] = useState(null);
const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setLoading(true); setError(null); setApiResponse(null);
try { const response = await fetch('http://localhost:11434/api/generate', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ model: selectedModel, prompt: `Be Precise. You are very smart. Translate the following text or colloquial phrase from ${fromLang} to ${toLang}. Ensure you retain the slang's meaning and tone, providing necessary context. Phrase: "${input}" Output format: 1. Translated Phrase: [Provide translation] 2. Context Explanation: [Describe the meaning and context]`, stream: false, }), }); if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } const data = await response.json(); setApiResponse(data); } catch (error) { setError( error instanceof Error && error.message.includes('Failed to fetch') ? 'Unable to connect to Ollama. Please make sure Ollama is running on your computer.' : 'An error occurred while translating. Please try again.' ); } finally { setLoading(false); }};
const parseResponse = (responseText: string) => { const translationMatch = responseText.match(/**Translated Phrase:**(.*?)(?=\n|)/s); const context = contextMatch ? contextMatch[1].trim() : null;
- Assistant
The provided code is a React component for a translation form. While it appears mostly correct, there are some potential issues and improvements that can be made:
-
Error Handling: The block catches the error, but is not always guaranteed to be an instance of . It's safer to check the error type first and handle it accordingly.
-
- User
Can u fix these issues
- Assistant