-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathai_agents_pipeline.py
More file actions
249 lines (204 loc) · 10.7 KB
/
Copy pathai_agents_pipeline.py
File metadata and controls
249 lines (204 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
"""
🏗️ 4 AI Agents Pipeline — Post #16 Implementation
Research → Draft → Fact-check → Edit → Publish
הרצה: python ai_agents_pipeline.py "נושא הפוסט"
"""
import sys
import re
from datetime import datetime
from pathlib import Path
if sys.platform == "win32":
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
OUTPUT_DIR = Path(__file__).parent / "wordpress_content"
OUTPUT_DIR.mkdir(exist_ok=True)
# ═══════════════════════════════════════════════════════════
# AGENT 1: RESEARCH — אוסף מידע ממקורות
# ═══════════════════════════════════════════════════════════
class ResearchAgent:
"""סורק חומר רקע — сейчас keyword-driven, בעתיד API אמיתי"""
KNOWLEDGE_BASE = {
"ai": [
"AI tools in 2026: Claude, GPT-4, Gemini — multi-modal, 2M token context",
"Retail traders using AI for chart scanning, news sentiment, backtesting",
"Multi-agent architectures: Diamond Scanner, Entry Monitor, Daily Review",
"AI negotiation: Claude reads contracts, flags weak clauses automatically",
],
"trading": [
"ICT/SMC: Silver Bullet (10-11AM), Fair Value Gaps, Killzones",
"RSI+MA20+MA50 confluence on 15 assets, 15-min scan cycle",
"FTMO rules: max 4% daily DD, 2 trades/day Circuit Breaker",
"Kelly Criterion: optimal position sizing, Poisson model for value betting",
],
"business": [
"Small teams + AI = 5X-25X productivity multiplier",
"AI agents: Research, Draft, Fact-check, Edit — parallel workflow",
"WordPress automation: wp_auto_poster.py via REST API",
"Monetization: 5 tracks — Prop Firm, Telegram VIP, Etsy, Affiliate, Betting",
],
}
def research(self, topic: str) -> list[str]:
"""מוצא עובדות רלוונטיות לנושא"""
facts = []
topic_lower = topic.lower()
for category, items in self.KNOWLEDGE_BASE.items():
if any(kw in topic_lower for kw in [category] + category.split()):
facts.extend(items)
if not facts:
facts = [
f"{topic} is a growing trend in 2026",
f"AI and automation are reshaping {topic}",
f"Early adopters of {topic} see 5X-25X efficiency gains",
]
return facts[:6] # Max 6 facts
# ═══════════════════════════════════════════════════════════
# AGENT 2: DRAFT — כותב טיוטה ראשונית
# ═══════════════════════════════════════════════════════════
class DraftAgent:
"""כותב פוסט מלא בעברית — Dark Mode, RTL, SEO"""
TEMPLATE = """<!-- ============================================
AUTO-GENERATED by AI Agents Pipeline
Agent 2: Draft → Agent 3: Fact-check → Agent 4: Edit
============================================ -->
<h1 style="color:#e2e8f0;">{title}</h1>
<p style="color:#94a3b8;">פורסם: {date} | קטגוריה: {category}</p>
<hr style="border-color:#334155;">
<p style="color:#cbd5e1;font-size:1.1em;">
{intro}
</p>
{facts_html}
<h2 style="color:#60a5fa;">למה זה משנה ב-2026</h2>
<p style="color:#cbd5e1;">
{why_matters}
</p>
<h2 style="color:#60a5fa;">תכלס — מה עושים מחר בבוקר</h2>
<div style="background:#0f172a;padding:16px;border-radius:8px;border:1px solid #334155;">
<ol style="color:#cbd5e1;">
{action_items}
</ol>
</div>
<hr style="border-color:#334155;">
<p style="color:#64748b;font-size:0.9em;">
נכתב על ידי 4 AI Agents Pipeline (Research → Draft → Fact-check → Edit).
Commoti AI — {date}
</p>"""
def draft(self, title: str, facts: list[str], category: str = "AI & Business") -> str:
"""מייצר פוסט מלא"""
facts_html = "<h2 style='color:#60a5fa;'>עובדות מפתח</h2>\n<ul style='color:#cbd5e1;'>\n"
for f in facts:
facts_html += f" <li>{f}</li>\n"
facts_html += "</ul>"
intro = f"ב-2026, {title.lower()} הוא לא טרנד — זו מציאות. "
intro += "המספרים מדברים: פי 5 לעובד טוב, פי 25 לעובד מצוין. הנה איך זה עובד."
why = "ה-AI משנה את חוקי המשחק. מה שהיה לוקח צוות של 10 אנשים — "
why += "היום AI עושה לבד, ואתה נשאר עם התובנות. זה לא מחליף אותך — זה מכפיל אותך."
actions = (
"<li>תבחר <strong>משימה אחת</strong> שאתה עושה ידנית כל שבוע</li>\n"
" <li>תכתוב <strong>פרומפט</strong> ל-Claude/GPT — תן לו Actor, Input, Mission</li>\n"
" <li>תריץ — <strong>בדוק, תקן, פרסם</strong> (AIM Framework)</li>\n"
" <li>תחזור על זה כל יום — תראה את המכפיל</li>"
)
return self.TEMPLATE.format(
title=title,
date=datetime.now().strftime("%d/%m/%Y"),
category=category,
intro=intro,
facts_html=facts_html,
why_matters=why,
action_items=actions,
)
# ═══════════════════════════════════════════════════════════
# AGENT 3: FACT-CHECK — מוודא שאין טעויות
# ═══════════════════════════════════════════════════════════
class FactCheckAgent:
"""בודק עובדות — מוודא קישורים, תאריכים, דיוק"""
def verify(self, content: str) -> tuple[bool, list[str]]:
"""מחזיר (האם עבר, רשימת אזהרות)"""
warnings = []
# Check for empty sections
if "<h2" not in content:
warnings.append("⚠️ Missing section headers (h2)")
if "2026" not in content:
warnings.append("⚠️ No year reference found")
if len(content) < 500:
warnings.append(f"⚠️ Content too short ({len(content)} chars)")
# Check for broken placeholders
if "{title}" in content or "{date}" in content:
warnings.append("❌ Unfilled template placeholders found")
# Check HTML structure
if content.count("<h1") > 1:
warnings.append("⚠️ Multiple h1 tags (should have 1)")
passed = len([w for w in warnings if w.startswith("❌")]) == 0
return passed, warnings
# ═══════════════════════════════════════════════════════════
# AGENT 4: EDIT — עריכה לשונית, כותרות, מטא
# ═══════════════════════════════════════════════════════════
class EditAgent:
"""עורך — משפר שפה, מוסיף SEO meta, מתקן פיסוק"""
def polish(self, content: str) -> str:
"""משפר טקסט"""
# Fix common Hebrew RTL issues
content = content.replace(" .", ".")
content = content.replace(" ,", ",")
# Ensure single title
content = re.sub(r'(<h1[^>]*>.*?</h1>)\s*<h1', r'\1\n<!-- SECOND h1 REMOVED -->\n<h1', content, flags=re.DOTALL)
return content
def generate_meta(self, title: str) -> dict:
"""מייצר meta description + tags"""
return {
"meta_description": f"{title} — איך AI משנה את חוקי המשחק ב-2026. פי 5 לעובד טוב, פי 25 למצוין.",
"tags": ["AI", "Automation", "Productivity", "2026"],
"categories": ["AI & Business"],
}
# ═══════════════════════════════════════════════════════════
# ORCHESTRATOR — מנהל 4 הסוכנים
# ═══════════════════════════════════════════════════════════
def run_pipeline(topic: str):
"""מריץ 4 AI Agents: Research → Draft → Fact-check → Edit"""
print("=" * 60)
print(f"🏗️ 4 AI Agents Pipeline — Processing: {topic}")
print("=" * 60)
# Agent 1: Research
print("\n🔍 Agent 1: Research — Scanning knowledge base...")
researcher = ResearchAgent()
facts = researcher.research(topic)
for i, fact in enumerate(facts, 1):
print(f" {i}. {fact}")
print(f" ✅ {len(facts)} facts collected")
# Agent 2: Draft
print("\n✍️ Agent 2: Draft — Writing post...")
drafter = DraftAgent()
content = drafter.draft(topic, facts)
print(f" ✅ Draft complete ({len(content)} chars)")
# Agent 3: Fact-check
print("\n🔎 Agent 3: Fact-check — Verifying...")
checker = FactCheckAgent()
passed, warnings = checker.verify(content)
for w in warnings:
print(f" {w}")
status = "✅ PASSED" if passed else "⚠️ NEEDS REVIEW"
print(f" {status}")
# Agent 4: Edit
print("\n📝 Agent 4: Edit — Polishing...")
editor = EditAgent()
content = editor.polish(content)
meta = editor.generate_meta(topic)
print(f" Meta: {meta['meta_description'][:80]}...")
print(f" Tags: {', '.join(meta['tags'])}")
print(" ✅ Polish complete")
# Save
slug = re.sub(r'[^\w\s-]', '', topic.lower())
slug = re.sub(r'[\s_]+', '_', slug)[:50]
filename = OUTPUT_DIR / f"17_ai_pipeline_{slug}.html"
filename.write_text(content, encoding="utf-8")
print(f"\n💾 Saved: {filename}")
# Stats
print(f"\n📊 Pipeline Stats:")
print(f" Research: {len(facts)} facts")
print(f" Draft: {len(content)} chars")
print(f" Fact-check: {'PASSED' if passed else 'WARNINGS'}")
print(f" Edit: {len(meta['tags'])} tags, meta ready")
print(f"\n🎯 Ready for WordPress: {filename.name}")
return filename
if __name__ == "__main__":
topic = " ".join(sys.argv[1:]) if len(sys.argv) > 1 else "AI Productivity 25X Multiplier"
run_pipeline(topic)