ChaoticEconomist commited on
Commit
ee58796
Β·
verified Β·
1 Parent(s): d888320

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +134 -80
app.py CHANGED
@@ -2,120 +2,174 @@ import gradio as gr
2
  import requests
3
  import os
4
 
5
- # =========================
6
- # CONFIG
7
- # =========================
8
 
9
  API_KEY = os.getenv("XAI_API_KEY")
10
-
11
- if not API_KEY:
12
- raise ValueError("❌ XAI_API_KEY not set. Add it in Hugging Face Secrets.")
13
-
14
  API_URL = "https://api.x.ai/v1/chat/completions"
15
 
 
 
16
 
17
- # =========================
18
- # GROK CALL
19
- # =========================
20
-
21
- def call_grok(prompt):
22
- headers = {
23
- "Authorization": f"Bearer {API_KEY}",
24
- "Content-Type": "application/json"
25
- }
26
-
27
- payload = {
28
- "model": "grok-4-1-fast-non-reasoning",
29
- "messages": [
30
- {"role": "system", "content": "You are a helpful AI assistant."},
31
- {"role": "user", "content": prompt}
32
- ],
33
- "temperature": 0.7
34
- }
35
 
 
36
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  response = requests.post(
38
  API_URL,
39
  headers=headers,
40
  json=payload,
41
- timeout=30
42
  )
43
 
44
  data = response.json()
45
 
46
- # πŸ”΄ Handle API errors cleanly
47
  if "choices" not in data:
48
  return f"❌ API Error:\n{data}"
49
 
50
  return data["choices"][0]["message"]["content"]
51
 
52
  except Exception as e:
53
- return f"❌ Request Failed:\n{str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
 
 
 
55
 
56
- # =========================
57
- # BLOCKSMITH LOGIC
58
- # =========================
59
 
60
- def generate_blocks(user_input):
61
- if not user_input.strip():
62
- return "⚠️ Please enter something."
63
 
64
- # Simulate your β€œblock” concept
65
- prompt = f"""
66
- Break this into structured reasoning blocks:
67
 
68
- Input:
69
- {user_input}
70
 
71
- Output format:
72
- 1. Problem
73
- 2. Key Ideas
74
- 3. Solution Steps
75
- 4. Final Answer
76
- """
77
 
78
- result = call_grok(prompt)
79
- return result
80
 
81
 
82
- # =========================
83
- # UI (CLEAN + MODERN)
84
- # =========================
85
 
86
- with gr.Blocks(theme=gr.themes.Soft(), title="Blocksmith AI") as app:
 
87
 
88
- gr.Markdown("""
89
- # 🧠 Blocksmith AI
90
- Turn any idea into structured reasoning blocks.
91
- """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
 
93
  with gr.Row():
94
- with gr.Column(scale=1):
95
- input_box = gr.Textbox(
96
- label="Your Input",
97
- placeholder="Enter a problem, idea, or question...",
98
- lines=5
99
- )
100
-
101
- generate_btn = gr.Button("⚑ Generate Blocks", variant="primary")
102
-
103
- with gr.Column(scale=1):
104
- output_box = gr.Textbox(
105
- label="Structured Output",
106
- lines=15
107
- )
108
-
109
- # πŸ”₯ Button wiring (this is what usually breaks)
110
- generate_btn.click(
111
- fn=generate_blocks,
112
- inputs=input_box,
113
- outputs=output_box
114
  )
115
 
116
- # =========================
117
- # RUN
118
- # =========================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
 
120
- if __name__ == "__main__":
121
- app.launch()
 
2
  import requests
3
  import os
4
 
5
+ # -----------------------------
6
+ # GROK SETUP (xAI)
7
+ # -----------------------------
8
 
9
  API_KEY = os.getenv("XAI_API_KEY")
 
 
 
 
10
  API_URL = "https://api.x.ai/v1/chat/completions"
11
 
12
+ if not API_KEY:
13
+ raise ValueError("❌ XAI_API_KEY not set in Hugging Face Secrets")
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
+ def call_llm(prompt):
17
  try:
18
+ headers = {
19
+ "Authorization": f"Bearer {API_KEY}",
20
+ "Content-Type": "application/json"
21
+ }
22
+
23
+ payload = {
24
+ # βœ… FIXED MODEL
25
+ "model": "grok-4-1-fast-non-reasoning",
26
+
27
+ "messages": [
28
+ {"role": "system", "content": "You are a helpful AI assistant."},
29
+ {"role": "user", "content": prompt}
30
+ ],
31
+ "temperature": 0.7,
32
+ "max_tokens": 300
33
+ }
34
+
35
  response = requests.post(
36
  API_URL,
37
  headers=headers,
38
  json=payload,
39
+ timeout=30 # βœ… prevents hanging
40
  )
41
 
42
  data = response.json()
43
 
44
+ # βœ… CRITICAL FIX (no more 'choices' crash)
45
  if "choices" not in data:
46
  return f"❌ API Error:\n{data}"
47
 
48
  return data["choices"][0]["message"]["content"]
49
 
50
  except Exception as e:
51
+ return f"❌ Request Failed: {str(e)}"
52
+
53
+
54
+ # -----------------------------
55
+ # BLOCK LOGIC
56
+ # -----------------------------
57
+
58
+ def create_blocks(text):
59
+ lines = [line.strip() for line in text.split("\n") if line.strip()]
60
+ if not lines:
61
+ lines = ["EMPTY"]
62
+
63
+ blocks = [f"{i}: {line}" for i, line in enumerate(lines)]
64
+ return blocks, gr.update(choices=blocks, value=blocks[0])
65
+
66
+
67
+ def select_block(blocks, selected):
68
+ if not blocks or not selected:
69
+ return ""
70
+
71
+ idx = int(selected.split(":")[0])
72
+ return blocks[idx].split(": ", 1)[1]
73
+
74
+
75
+ def update_block(blocks, selected, new_text):
76
+ if not blocks or not selected:
77
+ return blocks, gr.update()
78
+
79
+ idx = int(selected.split(":")[0])
80
+ blocks[idx] = f"{idx}: {new_text}"
81
+
82
+ return blocks, gr.update(choices=blocks, value=blocks[idx])
83
+
84
 
85
+ # -----------------------------
86
+ # AI FUNCTIONS
87
+ # -----------------------------
88
 
89
+ def ai_rewrite(blocks, selected):
90
+ if not blocks or not selected:
91
+ return blocks, gr.update()
92
 
93
+ idx = int(selected.split(":")[0])
94
+ original = blocks[idx].split(": ", 1)[1]
 
95
 
96
+ prompt = f"Rewrite this more clearly and professionally:\n\n{original}"
 
 
97
 
98
+ new_text = call_llm(prompt)
 
99
 
100
+ blocks[idx] = f"{idx}: {new_text}"
 
 
 
 
 
101
 
102
+ return blocks, gr.update(choices=blocks, value=blocks[idx])
 
103
 
104
 
105
+ def ai_summarize(blocks, selected):
106
+ if not blocks or not selected:
107
+ return ""
108
 
109
+ idx = int(selected.split(":")[0])
110
+ text = blocks[idx].split(": ", 1)[1]
111
 
112
+ prompt = f"Summarize this in one concise sentence:\n\n{text}"
113
+
114
+ return call_llm(prompt)
115
+
116
+
117
+ # -----------------------------
118
+ # UI
119
+ # -----------------------------
120
+
121
+ with gr.Blocks(title="Blocksmith + Grok") as app:
122
+
123
+ gr.Markdown("# 🧱 Blocksmith (Powered by Grok)")
124
+
125
+ state_blocks = gr.State([])
126
+
127
+ input_text = gr.Textbox(label="Paste Text", lines=8)
128
+ create_btn = gr.Button("Create Blocks")
129
+
130
+ block_selector = gr.Dropdown(choices=[], label="Blocks", interactive=True)
131
+
132
+ block_editor = gr.Textbox(label="Edit Block")
133
 
134
  with gr.Row():
135
+ update_btn = gr.Button("Update")
136
+ rewrite_btn = gr.Button("✨ Rewrite (AI)")
137
+ summarize_btn = gr.Button("🧠 Summarize")
138
+
139
+ summary_output = gr.Textbox(label="Summary")
140
+
141
+ # -----------------------------
142
+ # EVENTS
143
+ # -----------------------------
144
+
145
+ create_btn.click(
146
+ fn=create_blocks,
147
+ inputs=input_text,
148
+ outputs=[state_blocks, block_selector]
 
 
 
 
 
 
149
  )
150
 
151
+ block_selector.change(
152
+ fn=select_block,
153
+ inputs=[state_blocks, block_selector],
154
+ outputs=block_editor
155
+ )
156
+
157
+ update_btn.click(
158
+ fn=update_block,
159
+ inputs=[state_blocks, block_selector, block_editor],
160
+ outputs=[state_blocks, block_selector]
161
+ )
162
+
163
+ rewrite_btn.click(
164
+ fn=ai_rewrite,
165
+ inputs=[state_blocks, block_selector],
166
+ outputs=[state_blocks, block_selector]
167
+ )
168
+
169
+ summarize_btn.click(
170
+ fn=ai_summarize,
171
+ inputs=[state_blocks, block_selector],
172
+ outputs=summary_output
173
+ )
174
 
175
+ app.launch()