VectorV17 commited on
Commit
598b09a
·
verified ·
1 Parent(s): 40a96a4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -54
app.py CHANGED
@@ -6,21 +6,20 @@ from langchain_huggingface import HuggingFaceEmbeddings
6
  from langchain_core.documents import Document
7
 
8
  # ==========================================
9
- # 1. INITIALIZE MODELS & VECTOR BASE
10
  # ==========================================
11
- print("Loading Embedding Engine...")
12
  embedding_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
13
 
14
- print("Initializing Local TinyLlama Core on CPU...")
15
- # Replaced deprecated torch_dtype with dtype per pipeline warning
16
  chat_pipeline = pipeline(
17
  "text-generation",
18
- model="TinyLlama/TinyLlama-1.1B-Chat-v1.0",
19
  device="cpu",
20
  dtype=torch.float32
21
  )
22
 
23
- # Fact-checking context store
24
  mock_news_db = [
25
  "AI and Automation: Global studies confirm that while AI will replace 85 million routine operational jobs by late 2026, it simultaneously offsets this by engineering 97 million technical roles.",
26
  "EV Industrial Lifecycle: Electric Vehicles emit zero greenhouse operational gases, but lithium-ion battery extraction increases heavy localized ecosystem toxicity by 42%.",
@@ -31,30 +30,44 @@ vector_store = FAISS.from_documents(documents, embedding_model)
31
 
32
 
33
  # ==========================================
34
- # 2. OPTIMIZED INFERENCE CONTROLLER
35
  # ==========================================
36
- def execution_engine(workspace_type, user_input, system_injection, max_tokens, temp, top_p):
37
  if not user_input.strip():
38
  return "⚠️ **System Input Error:** Workspace field cannot be processed empty."
39
 
40
- # RAG Hook for Debate Mode
41
- context_data = ""
42
  if workspace_type == "debate":
43
  retriever = vector_store.as_retriever(search_kwargs={"k": 1})
44
  matched_docs = retriever.invoke(user_input)
45
- if matched_docs:
46
- context_data = f"\nUse this background context for verification: {matched_docs[0].page_content}"
47
-
48
- # Build clear structural rules to prevent sentence truncation
49
- tailored_instructions = (
50
- f"{system_injection} {context_data}\n"
51
- "CRITICAL: Keep your response short, concise, and structured. "
52
- "Ensure your final sentence is completely finished. Do not cut off mid-sentence."
53
- )
 
 
 
 
 
 
 
 
 
54
 
55
- # Format explicitly into TinyLlama prompt structures
56
- formatted_prompt = f"<|system|>\n{tailored_instructions}</s>\n<|user|>\n{user_input}</s>\n<|assistant|>\n"
 
 
 
 
 
57
 
 
58
  try:
59
  raw_output = chat_pipeline(
60
  formatted_prompt,
@@ -66,10 +79,10 @@ def execution_engine(workspace_type, user_input, system_injection, max_tokens, t
66
  repetition_penalty=1.2
67
  )
68
 
69
- processed_text = raw_output[0]["generated_text"].split("<|assistant|>\n")[-1].strip()
70
 
71
- # Clean up any potential dangling uncompleted tail sentence due to token limits
72
- if processed_text and processed_text[-1] not in [".", "!", "?", '"']:
73
  last_punctuation = max(processed_text.rfind("."), processed_text.rfind("!"), processed_text.rfind("?"))
74
  if last_punctuation != -1:
75
  processed_text = processed_text[:last_punctuation + 1]
@@ -77,33 +90,32 @@ def execution_engine(workspace_type, user_input, system_injection, max_tokens, t
77
  return processed_text
78
 
79
  except Exception as error:
80
- return f"❌ **Pipeline Fault:** Execution timed out or memory overflow occurred. Details: {str(error)}"
81
 
82
 
83
  # ==========================================
84
- # 3. DASHBOARD WINDOW BUILDER (SCREENSHOT 583)
85
  # ==========================================
86
  with gr.Blocks() as demo:
87
 
88
- # Top Banner Section
89
  with gr.Row():
90
  with gr.Column(scale=3):
91
  gr.Markdown("# 🤖 AI News Debate & Summary Agent Suite")
92
  gr.Markdown(
93
- "**About This Agent:** This framework processes user statements and news artifacts "
94
- "to provide dual NLP functions: an adversarial debate environment using real-time "
95
- "vectorized context verification, and an automated complex-news generalization engine."
96
  )
97
 
98
- # Status Module Panel (Mirroring Right side of Screenshot 583)
99
  with gr.Column(scale=1):
100
- # Fixed: Rendered directly without an invalid context manager block
101
  gr.HighlightedText(value=[("ONLINE", "🟢 NLP Match Engine Status")], show_label=False)
102
  gr.Markdown(
103
- "🪪 **Agent Profile:** Similarity-Augmented Assistant \n"
104
- "📦 **Model Matrix:** TinyLlama-1.1B (Quantized Pipeline) \n"
105
- "🧬 **Vectorization Engine:** Text FAISS Embedder \n"
106
- "💻 **Processing Hardware:** Base CPU Architecture"
107
  )
108
 
109
  gr.HTML("<hr style='border: 0.5px solid #374151; margin: 15px 0;'/>")
@@ -153,19 +165,10 @@ with gr.Blocks() as demo:
153
 
154
  gr.HTML("<div style='margin-bottom: 20px;'></div>")
155
 
156
- # Param Configuration Module
157
- with gr.Accordion("⚙️ Advanced Agent Parameter Configurations", open=False):
158
- sys_prompt_template = gr.TextArea(
159
- label="System Prompt Context Injection",
160
- value=(
161
- "You are a concise engineering assistant. "
162
- "If processing a debate, provide a direct counter-argument under 3 sentences and end with a bolded 'Argument Logic Score: X/10'. "
163
- "If simplifying, explain the point directly in clear bullet points under 50 words total."
164
- ),
165
- lines=3
166
- )
167
- max_tokens_val = gr.Slider(minimum=64, maximum=300, value=160, step=16, label="Max new tokens")
168
- temp_val = gr.Slider(minimum=0.1, maximum=1.0, value=0.3, step=0.05, label="Temperature")
169
  top_p_val = gr.Slider(minimum=0.50, maximum=1.00, value=0.85, step=0.05, label="Top-p")
170
 
171
  # Right Panel Output Monitor
@@ -176,17 +179,17 @@ with gr.Blocks() as demo:
176
  )
177
 
178
  # ==========================================
179
- # 4. EVENT MAP TRANSLATORS
180
  # ==========================================
181
  run_debate_action.click(
182
- fn=lambda user_in, sys_p, tokens, t, p: execution_engine("debate", user_in, sys_p, tokens, t, p),
183
- inputs=[debate_text_input, sys_prompt_template, max_tokens_val, temp_val, top_p_val],
184
  outputs=active_output_panel
185
  )
186
 
187
  run_simplifier_action.click(
188
- fn=lambda user_in, sys_p, tokens, t, p: execution_engine("generalize", user_in, sys_p, tokens, t, p),
189
- inputs=[simplify_text_input, sys_prompt_template, max_tokens_val, temp_val, top_p_val],
190
  outputs=active_output_panel
191
  )
192
 
 
6
  from langchain_core.documents import Document
7
 
8
  # ==========================================
9
+ # 1. INITIALIZE ENGINE & VECTOR DATA
10
  # ==========================================
11
+ print("Loading Lightweight Embedding Engine...")
12
  embedding_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
13
 
14
+ print("Initializing High-Performance Qwen Core on CPU...")
 
15
  chat_pipeline = pipeline(
16
  "text-generation",
17
+ model="Qwen/Qwen2.5-1.5B-Instruct",
18
  device="cpu",
19
  dtype=torch.float32
20
  )
21
 
22
+ # Fact-checking RAG context database
23
  mock_news_db = [
24
  "AI and Automation: Global studies confirm that while AI will replace 85 million routine operational jobs by late 2026, it simultaneously offsets this by engineering 97 million technical roles.",
25
  "EV Industrial Lifecycle: Electric Vehicles emit zero greenhouse operational gases, but lithium-ion battery extraction increases heavy localized ecosystem toxicity by 42%.",
 
30
 
31
 
32
  # ==========================================
33
+ # 2. FEW-SHOT PROMPT COMPILER
34
  # ==========================================
35
+ def execution_engine(workspace_type, user_input, max_tokens, temp, top_p):
36
  if not user_input.strip():
37
  return "⚠️ **System Input Error:** Workspace field cannot be processed empty."
38
 
39
+ # 1. Structural Instructions + Few-Shot Examples (The Quality Anchors)
 
40
  if workspace_type == "debate":
41
  retriever = vector_store.as_retriever(search_kwargs={"k": 1})
42
  matched_docs = retriever.invoke(user_input)
43
+ context = matched_docs[0].page_content if matched_docs else "No specific context available."
44
+
45
+ system_instruction = (
46
+ "You are a sharp, polite adversarial debate assistant. Disagree with the user's stance. "
47
+ "Provide exactly one paragraph of logical counter-argument, then provide a score out of 10.\n\n"
48
+ f"VERIFIED CONTEXT TO USE: {context}\n\n"
49
+ "### GOOD EXAMPLE RESPONSE FORMAT:\n"
50
+ "While your point highlights consumer convenience, verified data shows that global emissions from battery manufacturing offset initial green gains by up to 40%. Therefore, an immediate full transition remains structurally flawed.\n\n"
51
+ "**Argument Logic Score: 6/10**"
52
+ )
53
+ else: # Generalize mode
54
+ system_instruction = (
55
+ "You are an expert news editor. Translate complex, jargon-heavy statements into plain, simple English. "
56
+ "Output your answer as clear, high-level summary bullet points under 50 words total.\n\n"
57
+ "### GOOD EXAMPLE RESPONSE FORMAT:\n"
58
+ "* Global markets fell sharply due to sudden central bank interest rate changes.\n"
59
+ "* Local manufacturing activity slowed down to an all-time low."
60
+ )
61
 
62
+ # 2. Construct Prompt using Official Qwen ChatML Template format
63
+ formatted_prompt = (
64
+ f"<|im_start|>system\n{system_instruction}\n"
65
+ "CRITICAL: Keep your response concise. Do not ramble. Complete your final sentence perfectly.<|im_end|>\n"
66
+ f"<|im_start|>user\n{user_input}<|im_end|>\n"
67
+ "<|im_start|>assistant\n"
68
+ )
69
 
70
+ # 3. CPU Execution Pipeline
71
  try:
72
  raw_output = chat_pipeline(
73
  formatted_prompt,
 
79
  repetition_penalty=1.2
80
  )
81
 
82
+ processed_text = raw_output[0]["generated_text"].split("<|im_start|>assistant\n")[-1].strip()
83
 
84
+ # Programmatic Clean Up: Ensure no trailing cut-off sentences are displayed
85
+ if processed_text and processed_text[-1] not in [".", "!", "?", '"', "*"]:
86
  last_punctuation = max(processed_text.rfind("."), processed_text.rfind("!"), processed_text.rfind("?"))
87
  if last_punctuation != -1:
88
  processed_text = processed_text[:last_punctuation + 1]
 
90
  return processed_text
91
 
92
  except Exception as error:
93
+ return f"❌ **Pipeline Fault:** Execution error on CPU node. Details: {str(error)}"
94
 
95
 
96
  # ==========================================
97
+ # 3. MODULAR UI DASHBOARD (GRADIO 6.0)
98
  # ==========================================
99
  with gr.Blocks() as demo:
100
 
101
+ # Header Module
102
  with gr.Row():
103
  with gr.Column(scale=3):
104
  gr.Markdown("# 🤖 AI News Debate & Summary Agent Suite")
105
  gr.Markdown(
106
+ "**About This Agent:** This framework utilizes localized vector embeddings alongside "
107
+ "few-shot prompting to anchor small model reasoning. It delivers deterministic, "
108
+ "concise outputs optimized for zero-error execution on base CPU clusters."
109
  )
110
 
111
+ # Status Module Panel
112
  with gr.Column(scale=1):
 
113
  gr.HighlightedText(value=[("ONLINE", "🟢 NLP Match Engine Status")], show_label=False)
114
  gr.Markdown(
115
+ "🪪 **Agent Profile:** Few-Shot Context Assistant \n"
116
+ "📦 **Model Matrix:** Qwen2.5-1.5B-Instruct \n"
117
+ "🧬 **Vectorization Engine:** Text FAISS Engine \n"
118
+ "💻 **Processing Hardware:** Base CPU Tier"
119
  )
120
 
121
  gr.HTML("<hr style='border: 0.5px solid #374151; margin: 15px 0;'/>")
 
165
 
166
  gr.HTML("<div style='margin-bottom: 20px;'></div>")
167
 
168
+ # Param Configuration Module (Hidden Tuning to keep CPU fast and reliable)
169
+ with gr.Accordion("⚙️ Runtime Parameter Tuning", open=False):
170
+ max_tokens_val = gr.Slider(minimum=64, maximum=256, value=140, step=16, label="Max tokens")
171
+ temp_val = gr.Slider(minimum=0.1, maximum=1.0, value=0.25, step=0.05, label="Temperature (Low = Deterministic)")
 
 
 
 
 
 
 
 
 
172
  top_p_val = gr.Slider(minimum=0.50, maximum=1.00, value=0.85, step=0.05, label="Top-p")
173
 
174
  # Right Panel Output Monitor
 
179
  )
180
 
181
  # ==========================================
182
+ # 4. EVENT CONTROLLERS
183
  # ==========================================
184
  run_debate_action.click(
185
+ fn=lambda user_in, tokens, t, p: execution_engine("debate", user_in, tokens, t, p),
186
+ inputs=[debate_text_input, max_tokens_val, temp_val, top_p_val],
187
  outputs=active_output_panel
188
  )
189
 
190
  run_simplifier_action.click(
191
+ fn=lambda user_in, tokens, t, p: execution_engine("generalize", user_in, tokens, t, p),
192
+ inputs=[simplify_text_input, max_tokens_val, temp_val, top_p_val],
193
  outputs=active_output_panel
194
  )
195