Etikos_AI / app.py
omersaidd's picture
Update app.py
39f5444 verified
raw
history blame
3.66 kB
import gradio as gr
import requests
import json
# Dify API yapılandırması
api_key = "API_KEY" # 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)
# API isteği için veriyi hazırla
data = {
"inputs": {},
"query": message,
"user": "gradio-user"
}
# 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:
# Logo ve başlık yan yana olacak şekilde HTML formatında
gr.HTML("""
<div style="display: flex; align-items: center; gap: 20px;">
<h1 style="margin: 0;">Etikos AI Hukuk Asistanı</h1>
<img src="logo.png" height="50" />
</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)
clear = gr.Button("Sohbeti Temizle")
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
# Sohbet akışını ayarla
msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
bot, chatbot, chatbot
)
clear.click(clear_conversation, None, chatbot)
# Uygulamayı başlat
demo.launch()