Michel-25 commited on
Commit
0890b11
·
verified ·
1 Parent(s): a8c5e8d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -70
app.py CHANGED
@@ -1,106 +1,79 @@
1
  import gradio as gr
2
  import requests
3
  import json
4
- import time
5
 
6
- def chat_deepseek(message, history):
7
  """
8
- Função para conversar com DeepSeek-V3
9
  """
10
  try:
11
- # URL da API do Hugging Face para DeepSeek-V3
12
- API_URL = "https://api-inference.huggingface.co/models/deepseek-ai/DeepSeek-V3"
13
 
14
- # Preparar o prompt
15
- conversation = ""
16
- for human, assistant in history:
17
- conversation += f"Human: {human}\nAssistant: {assistant}\n"
18
- conversation += f"Human: {message}\nAssistant:"
19
-
20
- # Configurar a requisição
21
  payload = {
22
- "inputs": conversation,
23
  "parameters": {
24
- "max_new_tokens": 500,
25
- "temperature": 0.7,
26
- "do_sample": True,
27
- "return_full_text": False
28
  }
29
  }
30
 
31
- headers = {
32
- "Content-Type": "application/json"
33
- }
34
-
35
- # Fazer a requisição
36
- response = requests.post(API_URL, headers=headers, json=payload, timeout=60)
37
 
38
  if response.status_code == 200:
39
  result = response.json()
40
  if isinstance(result, list) and len(result) > 0:
41
- generated_text = result[0].get('generated_text', '')
42
- # Limpar a resposta
43
- generated_text = generated_text.strip()
44
- if generated_text:
45
- return generated_text
46
- else:
47
- return "Desculpe, não consegui gerar uma resposta válida."
48
- else:
49
- return "Formato de resposta inesperado da API."
50
 
51
  elif response.status_code == 503:
52
- return "🔄 Modelo está carregando... Tente novamente em alguns segundos."
53
 
54
  else:
55
- return f"Erro na API: {response.status_code} - {response.text}"
56
 
57
- except requests.exceptions.Timeout:
58
- return "⏱️ Timeout - O modelo demorou muito para responder. Tente uma pergunta mais simples."
59
-
60
  except Exception as e:
61
- return f"Erro: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
- # Criar a interface do chat
64
- with gr.Blocks(title="DeepSeek-V3 Chat", theme=gr.themes.Soft()) as demo:
65
- gr.Markdown("# 🤖 Chat com DeepSeek-V3")
66
- gr.Markdown("*Modelo pode demorar para carregar na primeira vez*")
67
 
68
- chatbot = gr.Chatbot(
69
- height=500,
70
- placeholder="As mensagens aparecerão aqui..."
71
- )
72
 
73
  with gr.Row():
74
  msg = gr.Textbox(
75
- placeholder="Digite sua mensagem aqui...",
76
  container=False,
77
- scale=7
78
  )
79
- send_btn = gr.Button("Enviar", scale=1, variant="primary")
80
- clear_btn = gr.Button("Limpar", scale=1)
81
 
82
- # Função para processar mensagem
83
- def respond(message, chat_history):
84
- if not message.strip():
85
- return chat_history, ""
86
-
87
- # Adicionar mensagem do usuário ao histórico
88
- chat_history.append([message, "🤔 Pensando..."])
89
-
90
- # Obter resposta do DeepSeek
91
- bot_message = chat_deepseek(message, chat_history[:-1])
92
-
93
- # Atualizar com a resposta real
94
- chat_history[-1][1] = bot_message
95
-
96
- return chat_history, ""
97
 
98
- # Conectar eventos
99
- send_btn.click(respond, [msg, chatbot], [chatbot, msg])
100
  msg.submit(respond, [msg, chatbot], [chatbot, msg])
101
- clear_btn.click(lambda: ([], ""), outputs=[chatbot, msg])
102
 
103
- # Lançar a aplicação
104
  if __name__ == "__main__":
105
  demo.launch()
106
-
 
1
  import gradio as gr
2
  import requests
3
  import json
 
4
 
5
+ def chat_with_ai(message, history):
6
  """
7
+ Função para conversar com um modelo menor e mais estável
8
  """
9
  try:
10
+ # Usando um modelo menor que funciona melhor
11
+ API_URL = "https://api-inference.huggingface.co/models/microsoft/DialoGPT-medium"
12
 
13
+ # Preparar payload simples
 
 
 
 
 
 
14
  payload = {
15
+ "inputs": message,
16
  "parameters": {
17
+ "max_length": 200,
18
+ "temperature": 0.7
 
 
19
  }
20
  }
21
 
22
+ response = requests.post(API_URL, json=payload, timeout=30)
 
 
 
 
 
23
 
24
  if response.status_code == 200:
25
  result = response.json()
26
  if isinstance(result, list) and len(result) > 0:
27
+ return result[0].get('generated_text', 'Não consegui gerar resposta.')
28
+ return "Formato inesperado de resposta."
 
 
 
 
 
 
 
29
 
30
  elif response.status_code == 503:
31
+ return "🔄 Modelo carregando... aguarde alguns segundos e tente novamente."
32
 
33
  else:
34
+ return f"Erro {response.status_code}: {response.text}"
35
 
 
 
 
36
  except Exception as e:
37
+ return f"Erro: {str(e)}"
38
+
39
+ # Interface mais simples
40
+ def respond(message, chat_history):
41
+ if not message.strip():
42
+ return chat_history, ""
43
+
44
+ # Resposta temporária
45
+ chat_history.append([message, "🤔 Pensando..."])
46
+
47
+ # Obter resposta da IA
48
+ try:
49
+ bot_response = chat_with_ai(message, chat_history)
50
+ chat_history[-1][1] = bot_response
51
+ except:
52
+ chat_history[-1][1] = "Desculpe, ocorreu um erro. Tente novamente."
53
+
54
+ return chat_history, ""
55
 
56
+ # Criar interface
57
+ with gr.Blocks(title="Chat IA", theme=gr.themes.Default()) as demo:
58
+ gr.Markdown("# 🤖 Chat com IA")
59
+ gr.Markdown("*Testando modelos de linguagem*")
60
 
61
+ chatbot = gr.Chatbot(height=400)
 
 
 
62
 
63
  with gr.Row():
64
  msg = gr.Textbox(
65
+ placeholder="Digite sua mensagem...",
66
  container=False,
67
+ scale=4
68
  )
69
+ send = gr.Button("Enviar", scale=1)
 
70
 
71
+ clear = gr.Button("Limpar Chat")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
73
+ # Eventos
74
+ send.click(respond, [msg, chatbot], [chatbot, msg])
75
  msg.submit(respond, [msg, chatbot], [chatbot, msg])
76
+ clear.click(lambda: [], outputs=chatbot)
77
 
 
78
  if __name__ == "__main__":
79
  demo.launch()