Etikos_AI / app.py
omersaidd's picture
Update app.py
b931afd verified
import gradio as gr
import requests
import json
# Dify API yapılandırması
api_key = "app-0UV1vRHHnChGssQ2Kc5UK9gg" # API anahtarınız
api_url = "https://api.dify.ai/v1/chat-messages"
# API istekleri için başlıklar
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
# Konuşma geçmişini başlat
conversation_history = []
def chat_with_dify(message, history):
"""
Dify API ile iletişim kurma ve yanıt alma fonksiyonu
"""
# Kullanıcı mesajını konuşma geçmişine ekle
user_message = {"role": "user", "content": message}
conversation_history.append(user_message)
# Geçmiş mesajları API için hazırla
messages = []
for msg in conversation_history:
messages.append({
"role": msg["role"],
"content": msg["content"]
})
# API isteği için veriyi hazırla
data = {
"inputs": {},
"query": message,
"user": "gradio-user",
"conversation_id": None, # Yeni konuşma başlatır
"messages": messages # Tüm geçmiş mesajları gönder
}
# API isteği yap
try:
print(f"API isteği gönderiliyor: {api_url}")
print(f"Headers: {headers}")
print(f"Data: {data}")
response = requests.post(api_url, headers=headers, json=data)
# API yanıtını kontrol et
print(f"API Yanıt Kodu: {response.status_code}")
print(f"API Yanıt İçeriği: {response.text[:500]}...") # İlk 500 karakter
# HTTP hata kodu kontrolü
if response.status_code != 200:
return f"API Hatası: HTTP {response.status_code} - {response.text}"
# Yanıtı parse et
if response.text.strip(): # Yanıt boş değilse
try:
response_data = response.json()
ai_message = response_data.get("answer", "Üzgünüm, bir yanıt oluşturamadım.")
# AI yanıtını konuşma geçmişine ekle
conversation_history.append({"role": "assistant", "content": ai_message})
return ai_message
except json.JSONDecodeError as json_err:
return f"JSON çözümleme hatası: {str(json_err)}\nYanıt: {response.text[:200]}..."
else:
return "API'den boş yanıt alındı"
except requests.exceptions.RequestException as e:
error_message = f"Dify API ile iletişim hatası: {str(e)}"
return error_message
# Gradio arayüzünü oluştur
with gr.Blocks(css="footer {visibility: hidden}") as demo:
# Sadece başlık göster, logo yok
gr.HTML("""
<div style="display: flex; align-items: center;">
<h1 style="margin: 0;">Etikos AI Hukuk Asistanı</h1>
</div>
""")
gr.Markdown("Bilgi almak istediğiniz hukuki alanlar ile ilgili soru sorabilirsiniz.")
chatbot = gr.Chatbot(height=400)
msg = gr.Textbox(placeholder="Mesajınızı buraya yazın...", show_label=False)
# Konuşma geçmişini ve geçmiş sohbetleri görüntülemek için
with gr.Row():
clear = gr.Button("Sohbeti Temizle")
show_memory = gr.Button("Konuşma Geçmişini Göster")
# Geçmiş mesajları göstermek için bir metin kutusu
memory_display = gr.Textbox(label="Konuşma Geçmişi", interactive=False, visible=False, lines=10)
def user(message, history):
# Kullanıcı mesajını geçmişe ekle ve dön
return "", history + [[message, None]]
def bot(history):
# Son kullanıcı mesajını al
user_message = history[-1][0]
# Bot yanıtını al
bot_response = chat_with_dify(user_message, history)
# Son etkileşimi bot yanıtıyla güncelle
history[-1][1] = bot_response
return history
def clear_conversation():
global conversation_history
conversation_history = []
return None, gr.update(visible=False, value="")
def display_memory():
memory_text = ""
for i, msg in enumerate(conversation_history):
role = "Kullanıcı" if msg["role"] == "user" else "AI"
memory_text += f"{role}: {msg['content']}\n\n"
return gr.update(visible=True, value=memory_text)
# Sohbet akışını ayarla
msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
bot, chatbot, chatbot
)
clear.click(clear_conversation, None, [chatbot, memory_display])
show_memory.click(display_memory, None, memory_display)
# Uygulamayı başlat
demo.launch()