omersaidd commited on
Commit
e68d95e
·
verified ·
1 Parent(s): eaf17bd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -55
app.py CHANGED
@@ -1,76 +1,87 @@
1
  import gradio as gr
2
  import requests
 
3
 
4
- # Dify API yapılandırması
5
- api_key = "app-0UV1vRHHnChGssQ2Kc5UK9gg"
6
  api_url = "https://api.dify.ai/v1/chat-messages"
7
 
8
- # Konuşma ID'sini saklamak için
9
- conversation_id = ""
 
 
 
 
 
 
10
 
11
  def chat_with_dify(message, history):
12
- """Etikos AI olarak sorularınıza cevap vermek için buradayım."""
13
- global conversation_id
 
 
 
 
14
 
15
- # API isteği için payload
16
- payload = {
17
  "inputs": {},
18
  "query": message,
19
- "response_mode": "blocking",
20
- "conversation_id": conversation_id,
21
- "user": "user"
22
- }
23
-
24
- headers = {
25
- "Authorization": f"Bearer {api_key}",
26
- "Content-Type": "application/json"
27
  }
28
 
 
29
  try:
30
- response = requests.post(api_url, headers=headers, json=payload)
 
31
 
32
- if response.status_code == 200:
33
- response_data = response.json()
34
-
35
- # Konuşma ID'sini güncelle
36
- if "conversation_id" in response_data and response_data["conversation_id"]:
37
- conversation_id = response_data["conversation_id"]
38
-
39
- return response_data.get("answer", "Yanıt alınamadı")
40
- else:
41
- return f"Hata: {response.status_code}"
42
-
43
- except Exception as e:
44
- return f"İstek gönderilirken hata: {str(e)}"
45
 
46
- # Gradio arayüzünü oluştur
47
- with gr.Blocks(theme=gr.themes.Default(primary_hue="black")) as demo:
48
- with gr.Row():
49
- with gr.Column(scale=4):
50
- gr.Markdown("# Etikos AI Chatbot")
51
- with gr.Column(scale=1, min_width=100):
52
- gr.Image(value="logo.png", label="", show_label=False, height=50, container=False)
53
 
54
- with gr.Row():
55
- clear = gr.Button("Konuşmayı Temizle")
56
-
57
  chatbot = gr.Chatbot(height=400)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
- with gr.Row():
60
- msg = gr.Textbox(label="Mesajınız", placeholder="Mesajınızı buraya yazın...")
61
- send = gr.Button("Gönder")
 
62
 
63
- def respond(message, chat_history):
64
- bot_message = chat_with_dify(message, chat_history)
65
- chat_history.append((message, bot_message))
66
- return "", chat_history
67
 
68
- # Buton olayları
69
- msg.submit(respond, [msg, chatbot], [msg, chatbot])
70
- send.click(respond, [msg, chatbot], [msg, chatbot])
71
- clear.click(lambda: [], outputs=[chatbot])
72
- clear.click(lambda: "", outputs=[msg])
73
 
74
- # Arayüzü başlat
75
- if __name__ == "__main__":
76
- demo.launch()
 
1
  import gradio as gr
2
  import requests
3
+ import json
4
 
5
+ # Dify API configuration
6
+ api_key = "app-0UV1vRHHnChGssQ2Kc5UK9gg" # Your API key
7
  api_url = "https://api.dify.ai/v1/chat-messages"
8
 
9
+ # Headers for API requests
10
+ headers = {
11
+ "Authorization": f"Bearer {api_key}",
12
+ "Content-Type": "application/json"
13
+ }
14
+
15
+ # Initialize conversation history
16
+ conversation_history = []
17
 
18
  def chat_with_dify(message, history):
19
+ """
20
+ Function to communicate with Dify API and get response
21
+ """
22
+ # Add user message to conversation history
23
+ user_message = {"role": "user", "content": message}
24
+ conversation_history.append(user_message)
25
 
26
+ # Prepare data for API request
27
+ data = {
28
  "inputs": {},
29
  "query": message,
30
+ "response_mode": "streaming",
31
+ "conversation_id": "",
32
+ "user": "gradio-user"
 
 
 
 
 
33
  }
34
 
35
+ # Make API request
36
  try:
37
+ response = requests.post(api_url, headers=headers, json=data)
38
+ response.raise_for_status() # Raise exception for HTTP errors
39
 
40
+ # Parse response
41
+ response_data = response.json()
42
+ ai_message = response_data.get("answer", "Sorry, I couldn't generate a response.")
43
+
44
+ # Add AI response to conversation history
45
+ conversation_history.append({"role": "assistant", "content": ai_message})
46
+
47
+ return ai_message
48
+ except requests.exceptions.RequestException as e:
49
+ error_message = f"Error communicating with Dify API: {str(e)}"
50
+ return error_message
 
 
51
 
52
+ # Create Gradio interface
53
+ with gr.Blocks(css="footer {visibility: hidden}") as demo:
54
+ gr.Markdown("# Dify AI Chatbot")
55
+ gr.Markdown("Ask me anything and I'll respond using Dify AI!")
 
 
 
56
 
 
 
 
57
  chatbot = gr.Chatbot(height=400)
58
+ msg = gr.Textbox(placeholder="Type your message here...", show_label=False)
59
+ clear = gr.Button("Clear Conversation")
60
+
61
+ def user(message, history):
62
+ # Add user message to history and return
63
+ return "", history + [[message, None]]
64
+
65
+ def bot(history):
66
+ # Get the last user message
67
+ user_message = history[-1][0]
68
+ # Get bot response
69
+ bot_response = chat_with_dify(user_message, history)
70
+ # Update the last interaction with the bot response
71
+ history[-1][1] = bot_response
72
+ return history
73
 
74
+ def clear_conversation():
75
+ global conversation_history
76
+ conversation_history = []
77
+ return None
78
 
79
+ # Set up the chat flow
80
+ msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
81
+ bot, chatbot, chatbot
82
+ )
83
 
84
+ clear.click(clear_conversation, None, chatbot)
 
 
 
 
85
 
86
+ # Launch the app
87
+ demo.launch()