File size: 4,694 Bytes
7eb2d16 e68d95e 7eb2d16 bc40506 df9ed6d 39f5444 7eb2d16 bc40506 e68d95e bc40506 e68d95e 7eb2d16 e68d95e bc40506 e68d95e bc40506 e68d95e 7eb2d16 b931afd bc40506 e68d95e 7eb2d16 b931afd 7eb2d16 bc40506 7eb2d16 bc40506 e68d95e 7eb2d16 bc40506 e68d95e bc40506 e68d95e bc40506 e68d95e bc40506 e68d95e 7eb2d16 bc40506 e68d95e b931afd 7ec8bd9 b931afd 7ec8bd9 85d19fc 7eb2d16 bc40506 b931afd e68d95e bc40506 e68d95e bc40506 e68d95e bc40506 e68d95e bc40506 e68d95e 745d95f e68d95e b931afd 7eb2d16 bc40506 e68d95e 7eb2d16 b931afd 7eb2d16 bc40506 e68d95e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 |
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() |