lamgamepro1 commited on
Commit
8fd43d0
·
verified ·
1 Parent(s): 62987a1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -41
app.py CHANGED
@@ -3,82 +3,102 @@ import os
3
  import requests
4
  import json
5
 
6
- # Groq config
7
  groq_key = os.getenv("GROQ_API_KEY")
8
- MODEL = "llama3-8b-8192" # Siêu nhanh
9
 
10
- status_msg = "❌ Chưa set GROQ_API_KEY trong Secrets"
11
  if groq_key:
12
- status_msg = f"✅ NodeAI Ready - Groq {MODEL}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
  def call_groq(messages):
15
- """Gọi Groq API trực tiếp"""
16
  url = "https://api.groq.com/openai/v1/chat/completions"
17
  headers = {
18
  "Authorization": f"Bearer {groq_key}",
19
  "Content-Type": "application/json"
20
  }
21
 
22
- data = {
23
- "model": MODEL,
24
  "messages": messages,
25
- "max_tokens": 1000,
26
- "temperature": 0.7
 
 
27
  }
28
 
29
  try:
30
- response = requests.post(url, headers=headers, json=data, timeout=20)
31
- response.raise_for_status()
32
- return response.json()["choices"][0]["message"]["content"]
33
- except requests.exceptions.HTTPError as e:
 
 
 
 
34
  if response.status_code == 401:
35
- return "❌ GROQ_API_KEY sai"
36
- elif response.status_code == 429:
37
- return "⏳ Groq rate limit - thử lại sau"
38
- else:
39
- return f"❌ HTTP {response.status_code}"
 
 
 
40
  except Exception as e:
41
- return f"❌ Lỗi: {str(e)}"
42
 
43
  def respond(message, history):
44
  if not groq_key:
45
  return "", history + [{"role": "assistant", "content": status_msg}]
46
 
47
- # Build messages
48
- groq_messages = [{"role": "system", "content": "Bạn là NodeAI - trợ lý AI thông minh, trả lời tiếng Việt."}]
49
 
50
  for msg in history:
51
- if isinstance(msg, dict) and "role" in msg:
52
- groq_messages.append(msg)
53
 
54
- groq_messages.append({"role": "user", "content": message})
55
 
56
- bot_reply = call_groq(groq_messages)
57
- return "", history + [{"role": "assistant", "content": bot_reply}]
58
 
59
  with gr.Blocks(title="NodeAI") as demo:
60
- gr.Markdown("# 🚀 NodeAI - Groq AI Chat")
61
- gr.Markdown("**⚡ Siêu nhanh Llama3 - Miễn phí!**")
62
  gr.Markdown(f"**Status:** {status_msg}")
63
 
64
- chatbot = gr.Chatbot(
65
- height=500,
66
- show_label=False,
67
- avatar_images=("👤", "🤖")
68
- )
69
 
70
  with gr.Row():
71
- msg = gr.Textbox(placeholder="Nhập câu hỏi cho NodeAI...", scale=7)
72
- send_btn = gr.Button("📤 Gửi", variant="primary", scale=1)
73
- clear_btn = gr.Button("🗑️ Clear", scale=1)
74
 
 
75
  msg.submit(respond, [msg, chatbot], [msg, chatbot])
76
  send_btn.click(respond, [msg, chatbot], [msg, chatbot])
77
  clear_btn.click(lambda: [], None, chatbot)
78
 
79
  if __name__ == "__main__":
80
- demo.launch(
81
- theme=gr.themes.Soft(primary_hue="blue"),
82
- server_name="0.0.0.0",
83
- server_port=7860
84
- )
 
3
  import requests
4
  import json
5
 
 
6
  groq_key = os.getenv("GROQ_API_KEY")
7
+ MODEL = "llama3-8b-8192"
8
 
9
+ status_msg = "❌ Chưa set GROQ_API_KEY"
10
  if groq_key:
11
+ status_msg = f"✅ Ready - Groq {MODEL} (key: {len(groq_key)} chars)"
12
+
13
+ def test_groq():
14
+ """Test API key"""
15
+ if not groq_key:
16
+ return "❌ NO GROQ_API_KEY"
17
+
18
+ try:
19
+ url = "https://api.groq.com/openai/v1/models"
20
+ headers = {"Authorization": f"Bearer {groq_key}"}
21
+ r = requests.get(url, headers=headers, timeout=10)
22
+ if r.status_code == 200:
23
+ models = r.json().get('data', [])
24
+ model_names = [m['id'] for m in models[:3]]
25
+ return f"✅ OK - Models: {model_names}"
26
+ return f"❌ {r.status_code}: {r.text[:100]}"
27
+ except Exception as e:
28
+ return f"❌ Test error: {str(e)}"
29
 
30
  def call_groq(messages):
31
+ """Groq API với full error debug"""
32
  url = "https://api.groq.com/openai/v1/chat/completions"
33
  headers = {
34
  "Authorization": f"Bearer {groq_key}",
35
  "Content-Type": "application/json"
36
  }
37
 
38
+ payload = {
 
39
  "messages": messages,
40
+ "model": MODEL,
41
+ "stream": False,
42
+ "temperature": 0.7,
43
+ "max_tokens": 1000
44
  }
45
 
46
  try:
47
+ print(f"Sending to Groq: {json.dumps(payload, indent=2)}") # DEBUG
48
+ response = requests.post(url, headers=headers, json=payload, timeout=30)
49
+
50
+ print(f"Response status: {response.status_code}") # DEBUG
51
+ print(f"Response: {response.text[:500]}") # DEBUG
52
+
53
+ if response.status_code == 400:
54
+ return f"❌ 400 Bad Request\n{response.text}"
55
  if response.status_code == 401:
56
+ return "❌ API Key sai"
57
+ if response.status_code == 429:
58
+ return "⏳ Rate limit"
59
+
60
+ response.raise_for_status()
61
+ data = response.json()
62
+ return data["choices"][0]["message"]["content"]
63
+
64
  except Exception as e:
65
+ return f"❌ Error: {str(e)}\nStatus: {getattr(response, 'status_code', 'N/A')}"
66
 
67
  def respond(message, history):
68
  if not groq_key:
69
  return "", history + [{"role": "assistant", "content": status_msg}]
70
 
71
+ # Clean messages format
72
+ messages = [{"role": "system", "content": "Bạn là NodeAI - trợ lý AI tiếng Việt."}]
73
 
74
  for msg in history:
75
+ if isinstance(msg, dict) and "role" in msg and msg.get("content"):
76
+ messages.append({"role": msg["role"], "content": str(msg["content"])})
77
 
78
+ messages.append({"role": "user", "content": str(message)})
79
 
80
+ reply = call_groq(messages)
81
+ return "", history + [{"role": "assistant", "content": reply}]
82
 
83
  with gr.Blocks(title="NodeAI") as demo:
84
+ gr.Markdown("# 🚀 NodeAI - Groq AI")
 
85
  gr.Markdown(f"**Status:** {status_msg}")
86
 
87
+ # Test button
88
+ test_btn = gr.Button("🧪 Test Groq API")
89
+ test_output = gr.Textbox(label="API Test", lines=3)
90
+
91
+ chatbot = gr.Chatbot(height=400, avatar_images=("👤", "🤖"))
92
 
93
  with gr.Row():
94
+ msg = gr.Textbox(placeholder="Hỏi NodeAI...", scale=7)
95
+ send_btn = gr.Button("📤", variant="primary", scale=1)
96
+ clear_btn = gr.Button("🗑️", scale=1)
97
 
98
+ test_btn.click(test_groq, outputs=test_output)
99
  msg.submit(respond, [msg, chatbot], [msg, chatbot])
100
  send_btn.click(respond, [msg, chatbot], [msg, chatbot])
101
  clear_btn.click(lambda: [], None, chatbot)
102
 
103
  if __name__ == "__main__":
104
+ demo.launch(theme=gr.themes.Soft(primary_hue="blue"))