Refactor code structure for improved readability and maintainability
Co-authored-by: Copilot <copilot@github.com>
This commit is contained in:
co-authored by
Copilot
parent
983c8fd6aa
commit
4126b41064
@@ -0,0 +1,86 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { provider, apiKey, userMessageContent } = body;
|
||||
|
||||
let assistantReply = "";
|
||||
|
||||
if (provider === "groq") {
|
||||
const res = await fetch(
|
||||
"https://api.groq.com/openai/v1/chat/completions",
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: "llama-3.1-8b-instant",
|
||||
messages: [
|
||||
{
|
||||
role: "system",
|
||||
content:
|
||||
"Sen MindSpace adlı kullanıcının kişisel yapay zeka terapistisin ve sırdaşısın. Şefkatli, yargılamayan ve destekleyici cevaplar ver. Yüzeysel öğütlerden kaçın.",
|
||||
},
|
||||
{ role: "user", content: userMessageContent },
|
||||
],
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
const errorData = await res.json();
|
||||
throw new Error(errorData.error?.message || "Groq API Hatası");
|
||||
}
|
||||
const data = await res.json();
|
||||
assistantReply = data.choices[0].message.content;
|
||||
} else if (provider === "openai") {
|
||||
const res = await fetch("https://api.openai.com/v1/chat/completions", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: "gpt-4o",
|
||||
messages: [
|
||||
{
|
||||
role: "system",
|
||||
content:
|
||||
"Sen MindSpace adlı kullanıcının kişisel yapay zeka terapistisin ve sırdaşısın. Şefkatli ve destekleyici cevap ver.",
|
||||
},
|
||||
{ role: "user", content: userMessageContent },
|
||||
],
|
||||
}),
|
||||
});
|
||||
if (!res.ok) throw new Error("OpenAI API Hatası");
|
||||
const data = await res.json();
|
||||
assistantReply = data.choices[0].message.content;
|
||||
} else {
|
||||
// Varsayılan: Yerel Ollama
|
||||
const res = await fetch("http://127.0.0.1:11434/api/generate", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
model: "llama3", // veya mistral
|
||||
prompt: `Sen MindSpace adlı kullanıcının kişisel yapay zeka terapistisin ve sırdaşısın. Şefkatli ve destekleyici cevap ver.\n\nKullanıcı: ${userMessageContent}\nTerapist:`,
|
||||
stream: false,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.ok) throw new Error("Ollama API yanıt vermedi.");
|
||||
const data = await res.json();
|
||||
assistantReply = data.response;
|
||||
}
|
||||
|
||||
return NextResponse.json({ reply: assistantReply });
|
||||
} catch (error: any) {
|
||||
console.error("API Route Hatası:", error);
|
||||
return NextResponse.json(
|
||||
{ error: error.message || "Bilinmeyen Sunucu Hatası" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useLiveQuery } from "dexie-react-hooks";
|
||||
import { db } from "@/lib/db";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { Send, Bot, User, Trash2 } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
|
||||
export default function ChatPage() {
|
||||
const [input, setInput] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
// Mesajları eski tarihten yeniye göre sıralayarak al (Sohbet akışı)
|
||||
const messages = useLiveQuery(
|
||||
() => db.chat_messages.orderBy("created_at").toArray(),
|
||||
[],
|
||||
);
|
||||
|
||||
// Ollama'ya veya harici API'ye mesaj gönder
|
||||
const handleSend = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!input.trim()) return;
|
||||
|
||||
const userMessageContent = input.trim();
|
||||
setInput("");
|
||||
setIsLoading(true);
|
||||
|
||||
const userMessage = {
|
||||
id: uuidv4(),
|
||||
role: "user" as const,
|
||||
content: userMessageContent,
|
||||
created_at: new Date().toISOString(),
|
||||
};
|
||||
|
||||
try {
|
||||
await db.chat_messages.add(userMessage);
|
||||
|
||||
// LocalStorage'dan veya Environment ayarlarını okuyup backend API'ye gönderiyoruz
|
||||
const provider = localStorage.getItem("mindspace_ai_provider") || "groq";
|
||||
const apiKey =
|
||||
localStorage.getItem("mindspace_api_key") ||
|
||||
process.env.NEXT_PUBLIC_GROQ_API_KEY ||
|
||||
"";
|
||||
|
||||
const res = await fetch("/api/chat", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
provider,
|
||||
apiKey,
|
||||
userMessageContent,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errData = await res.json();
|
||||
throw new Error(errData.error || "Sunucu hatası oluştu.");
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
const assistantMessage = {
|
||||
id: uuidv4(),
|
||||
role: "assistant" as const,
|
||||
content:
|
||||
data.reply ||
|
||||
"Şu an cevap veremiyorum, lütfen ayarlarınızı kontrol edin.",
|
||||
created_at: new Date().toISOString(),
|
||||
};
|
||||
|
||||
await db.chat_messages.add(assistantMessage);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
await db.chat_messages.add({
|
||||
id: uuidv4(),
|
||||
role: "assistant" as const,
|
||||
content:
|
||||
"API Bağlantısı kurulamadı. Lütfen internetini veya Ayarlar sayfasından API anahtarını kontrol et.",
|
||||
created_at: new Date().toISOString(),
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleClearChat = async () => {
|
||||
await db.chat_messages.clear();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-[calc(100vh-4rem)] p-4 max-w-4xl mx-auto w-full">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-foreground">
|
||||
AI Terapist (Sohbet)
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Ollama veya bulut destekli akıllı asistanınızla konuşun.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={handleClearChat}
|
||||
title="Sohbeti Temizle"
|
||||
>
|
||||
<Trash2 className="w-4 h-4 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-4 space-y-4 rounded-xl border border-border bg-card shadow-sm mb-4">
|
||||
{(!messages || messages.length === 0) && (
|
||||
<div className="flex flex-col items-center justify-center h-full text-muted-foreground">
|
||||
<Bot className="w-12 h-12 mb-2 opacity-50" />
|
||||
<p>Sohbet henüz başlamadı. İlk mesajınızı yollayın!</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{messages?.map((m) => (
|
||||
<div
|
||||
key={m.id}
|
||||
className={`flex w-full ${m.role === "user" ? "justify-end" : "justify-start"}`}
|
||||
>
|
||||
<div
|
||||
className={`flex gap-2 max-w-[80%] ${m.role === "user" ? "flex-row-reverse" : "flex-row"}`}
|
||||
>
|
||||
<div
|
||||
className={`w-8 h-8 rounded-full flex items-center justify-center shrink-0 ${m.role === "user" ? "bg-primary text-primary-foreground" : "bg-secondary text-secondary-foreground"}`}
|
||||
>
|
||||
{m.role === "user" ? (
|
||||
<User className="w-4 h-4" />
|
||||
) : (
|
||||
<Bot className="w-4 h-4" />
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
className={`p-3 rounded-xl ${m.role === "user" ? "bg-primary text-primary-foreground rounded-tr-none" : "bg-muted text-foreground rounded-tl-none border border-border"}`}
|
||||
>
|
||||
{m.content}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{isLoading && (
|
||||
<div className="flex w-full justify-start">
|
||||
<div className="flex gap-2 max-w-[80%]">
|
||||
<div className="w-8 h-8 rounded-full bg-secondary text-secondary-foreground flex items-center justify-center shrink-0">
|
||||
<Bot className="w-4 h-4" />
|
||||
</div>
|
||||
<div className="p-3 rounded-xl bg-muted text-foreground rounded-tl-none border border-border flex items-center gap-2">
|
||||
<div className="w-2 h-2 rounded-full bg-primary/50 animate-bounce" />
|
||||
<div className="w-2 h-2 rounded-full bg-primary/50 animate-bounce delay-75" />
|
||||
<div className="w-2 h-2 rounded-full bg-primary/50 animate-bounce delay-150" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSend} className="flex gap-2 items-center">
|
||||
<Input
|
||||
disabled={isLoading}
|
||||
value={input}
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
placeholder="Bugün nasıl hissediyorsun? Ya da eski günlüklere dayanarak bir şeyler sor..."
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button type="submit" size="icon" disabled={isLoading || !input.trim()}>
|
||||
<Send className="w-4 h-4" />
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
} from "@/components/ui/select";
|
||||
import { Bot, Save } from "lucide-react";
|
||||
|
||||
export default function SettingsPage() {
|
||||
const [aiProvider, setAiProvider] = useState("groq"); // Varsayılan olarak Groq yapalım
|
||||
const [apiKey, setApiKey] = useState("");
|
||||
const [saveStatus, setSaveStatus] = useState("");
|
||||
|
||||
// Sayfa yüklendiğinde LocalStorage'dan ayarları çek
|
||||
useEffect(() => {
|
||||
const savedProvider = localStorage.getItem("mindspace_ai_provider");
|
||||
const savedApiKey = localStorage.getItem("mindspace_api_key");
|
||||
if (savedProvider) setAiProvider(savedProvider);
|
||||
if (savedApiKey) setApiKey(savedApiKey);
|
||||
}, []);
|
||||
|
||||
const handleSave = () => {
|
||||
localStorage.setItem("mindspace_ai_provider", aiProvider);
|
||||
localStorage.setItem("mindspace_api_key", apiKey);
|
||||
|
||||
setSaveStatus("Ayarlar başarıyla kaydedildi!");
|
||||
setTimeout(() => setSaveStatus(""), 3000);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6 p-4 max-w-2xl mx-auto w-full">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-foreground">Ayarlar</h1>
|
||||
<p className="text-muted-foreground mt-1">
|
||||
Yapay zeka asistanı ve uygulama yapılandırmanızı yönetin.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-card border border-border rounded-xl p-6 shadow-sm space-y-6 flex flex-col">
|
||||
<div className="flex items-center gap-3 border-b border-border/50 pb-4">
|
||||
<Bot className="w-6 h-6 text-primary" />
|
||||
<h2 className="text-xl font-semibold">Terapist (AI) Ayarları</h2>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>AI Sağlayıcısı</Label>
|
||||
<Select value={aiProvider} onValueChange={setAiProvider}>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue placeholder="Sağlayıcı seçin" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="ollama">
|
||||
Ollama (Yerel & Gizlilik Odaklı)
|
||||
</SelectItem>
|
||||
<SelectItem value="openai">OpenAI (GPT-4o vb.)</SelectItem>
|
||||
<SelectItem value="groq">Groq (Llama-3 Bulut)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Gizliliğiniz için yerel Ollama önerilir. Sunucunuzda çalışmayan
|
||||
durumlarda OpenAI veya Groq gibi bulut çözümlerine geçebilirsiniz.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{aiProvider !== "ollama" && (
|
||||
<div className="space-y-2">
|
||||
<Label>API Anahtarı ({aiProvider.toUpperCase()})</Label>
|
||||
<Input
|
||||
type="password"
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
placeholder="sk-..."
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Anahtarınız sadece tarayıcınızın kendi local hafızasında güvenle
|
||||
saklanır, hiçbir sunucuya kaydedilmez.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-4 mt-4">
|
||||
<Button onClick={handleSave} className="w-max">
|
||||
<Save className="w-4 h-4 mr-2" />
|
||||
Kaydet
|
||||
</Button>
|
||||
{saveStatus && (
|
||||
<span className="text-sm text-green-600 dark:text-green-400">
|
||||
{saveStatus}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user