-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
541 lines (433 loc) · 24.3 KB
/
server.py
File metadata and controls
541 lines (433 loc) · 24.3 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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
"""
Content Pipeline — Agent-to-Agent Communication Demo
5 independent agents, each with their own model, expertise, and context.
They self-organize via Agent Relay channels and DMs.
Architecture:
#content channel — Editor-in-Chief posts briefs here, specialists listen
Each specialist picks up briefs matching their expertise
QA Reviewer watches everything and scores final output
Agents:
1. Editor-in-Chief (free model) — reviews briefs, assigns to specialists
2. SEO Writer (gpt-4o-mini) — has keyword data from Ahrefs/SEMrush
3. Visual Designer (free model) — has brand guidelines from Figma
4. Fact Checker (gpt-4o-mini) — has source database
5. QA Reviewer (free model) — scores content quality
"""
import asyncio
import json
import os
import uuid
import string
import random
import time
from datetime import datetime
from pathlib import Path
from dotenv import load_dotenv
load_dotenv()
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from agent_relay.communicate import Relay
from agent_relay.communicate.types import RelayConfig, Message
from integrations.context_loader import get_context
app = FastAPI()
RUN_ID = uuid.uuid4().hex[:4]
CFG = RelayConfig(
workspace=os.environ.get("RELAY_WORKSPACE", "demo"),
api_key=os.environ.get("RELAY_API_KEY", "demo-key"),
base_url=os.environ.get("RELAY_BASE_URL", "https://api.relaycast.dev"),
)
CHANNEL = f"content-{RUN_ID}"
API_KEY = os.environ.get("OPENROUTER_API_KEY", "")
BASE_URL = "https://openrouter.ai/api/v1"
# Agent names
EDITOR_CHIEF = f"editor-chief-{RUN_ID}"
SEO_WRITER = f"seo-writer-{RUN_ID}"
VISUAL_DESIGNER = f"visual-designer-{RUN_ID}"
FACT_CHECKER = f"fact-checker-{RUN_ID}"
QA_REVIEWER = f"qa-reviewer-{RUN_ID}"
# Models — the cost story
FREE_MODEL = "nvidia/nemotron-3-nano-30b-a3b:free"
SMART_MODEL = "openai/gpt-4o-mini"
ws_clients: list[WebSocket] = []
brief_queue: asyncio.Queue = asyncio.Queue()
agent_online_events: list[dict] = []
relays: dict[str, Relay] = {}
# Stats
stats = {"total": 0, "simple": 0, "escalated": 0, "fd_tokens": 0, "sp_tokens": 0, "qa_tokens": 0,
"fd_cost": 0.0, "sp_cost": 0.0, "qa_cost": 0.0, "mono_cost": 0.0}
async def broadcast(event: dict):
msg = json.dumps(event)
for ws in ws_clients[:]:
try: await ws.send_text(msg)
except: ws_clients.remove(ws)
def brief_id():
return "BRIEF-" + "".join(random.choices(string.ascii_uppercase + string.digits, k=6))
async def llm(model, system, user, label="") -> dict:
if not API_KEY:
await asyncio.sleep(0.8)
return {"content": f"[Simulated {label}]", "model": model, "tokens": 50, "cost": 0, "ms": 800}
import httpx
t0 = time.time()
try:
async with httpx.AsyncClient(timeout=30) as c:
r = await c.post(f"{BASE_URL}/chat/completions",
headers={"Authorization": f"Bearer {API_KEY}"},
json={"model": model, "messages": [
{"role": "system", "content": system},
{"role": "user", "content": user}
], "max_tokens": 800})
ms = int((time.time() - t0) * 1000)
if r.status_code != 200:
return {"content": f"[Model {r.status_code}]", "model": model, "tokens": 0, "cost": 0, "ms": ms}
d = r.json()
msg = d["choices"][0]["message"]
content = msg.get("content") or msg.get("reasoning") or ""
if not content and msg.get("reasoning_details"):
content = msg["reasoning_details"][0].get("text", "")
usage = d.get("usage", {})
return {"content": content or "[No response]", "model": d.get("model", model),
"tokens": usage.get("total_tokens", 0), "cost": float(usage.get("cost", 0)), "ms": ms}
except Exception as e:
return {"content": f"[Error: {e}]", "model": model, "tokens": 0, "cost": 0, "ms": int((time.time() - t0) * 1000)}
# ============================================================
# AGENT 1: EDITOR-IN-CHIEF (Triage & Assignment)
# ============================================================
async def agent_editor_chief():
r = Relay(EDITOR_CHIEF, CFG); await r.__aenter__(); relays[EDITOR_CHIEF] = r
ev = {"type": "agent_online", "agent": "Editor-in-Chief", "name": EDITOR_CHIEF, "model": FREE_MODEL,
"role": "Triage & Assignment", "color": "emerald",
"desc": "Fast free model. Reviews content briefs, classifies type, and routes to specialists via #content channel."}
agent_online_events.append(ev); await broadcast(ev)
def on_msg(msg):
if msg.sender == EDITOR_CHIEF: return
asyncio.create_task(_chief_got_deliverable(msg))
r.on_message(on_msg)
while True:
brief = await brief_queue.get()
asyncio.create_task(_triage_brief(brief))
async def _triage_brief(t):
tid, client, topic, tone, length = t["brief_id"], t["client"], t["topic"], t["tone"], t["length"]
stats["total"] += 1
await broadcast({"type": "thinking", "agent": "Editor-in-Chief", "color": "emerald", "tid": tid,
"detail": f"Reviewing brief from {client}...", "model": FREE_MODEL})
res = await llm(FREE_MODEL,
"""You are an editor-in-chief at a content agency. Classify this content brief into exactly ONE category:
- "seo_article" (blog posts, thought leadership, SEO-driven content)
- "visual_content" (infographics, social media graphics, brand visuals)
- "research_piece" (whitepapers, case studies, data-driven content)
- "quick_post" (social media copy, newsletter blurbs, simple updates)
Respond ONLY with JSON: {"category":"...", "priority":"low|medium|high", "summary":"one line summary of deliverable"}""",
f"Client {client}: Topic: {topic}, Tone: {tone}, Length: {length}", "Triage")
stats["fd_tokens"] += res["tokens"]; stats["fd_cost"] += res["cost"]
await broadcast({"type": "model_used", "agent": "Editor-in-Chief", "color": "emerald",
"model": res["model"], "tokens": res["tokens"], "cost": res["cost"], "ms": res["ms"]})
# Parse category
cat = "seo_article"
for kw, c in [("seo", "seo_article"), ("blog", "seo_article"), ("article", "seo_article"),
("visual", "visual_content"), ("infographic", "visual_content"), ("design", "visual_content"),
("graphic", "visual_content"), ("brand", "visual_content"),
("research", "research_piece"), ("whitepaper", "research_piece"), ("case study", "research_piece"),
("data", "research_piece"),
("social", "quick_post"), ("tweet", "quick_post"), ("newsletter", "quick_post"), ("blurb", "quick_post")]:
if kw in topic.lower(): cat = c; break
try:
p = json.loads(res["content"])
cat = p.get("category", cat)
priority = p.get("priority", "medium")
summary = p.get("summary", topic[:80])
except:
priority = "medium"; summary = topic[:80]
if cat == "quick_post":
stats["simple"] += 1
ans = await llm(FREE_MODEL, f"You are a content writer. Write a short, engaging {tone} post about the given topic. Keep it under 280 characters for social or 2 short paragraphs for newsletter.",
f"Topic: {topic}", "Quick post")
stats["fd_tokens"] += ans["tokens"]; stats["fd_cost"] += ans["cost"]
stats["mono_cost"] += 0.00015 * ((res["tokens"] + ans["tokens"]) / 1000)
await broadcast({"type": "triage_result", "tid": tid, "action": "direct", "category": cat,
"response": ans["content"], "cost_saved": True})
await broadcast({"type": "complete", "tid": tid, "resolved_by": "Editor-in-Chief (direct — free model)",
"cost_note": "$0 — handled entirely by free model"})
await _send_stats(); return
stats["escalated"] += 1
stats["mono_cost"] += 0.00015 * (res["tokens"] / 1000)
await broadcast({"type": "triage_result", "tid": tid, "action": "escalate", "category": cat,
"urgency": priority, "summary": summary})
payload = json.dumps({"brief_id": tid, "client": client, "topic": topic, "tone": tone,
"length": length, "category": cat, "priority": priority, "summary": summary})
await broadcast({"type": "channel_post", "from": "Editor-in-Chief", "from_name": EDITOR_CHIEF,
"channel": CHANNEL, "tid": tid,
"detail": f"[{cat.upper()}] {priority} priority — {summary}"})
await relays[EDITOR_CHIEF].post(CHANNEL, payload)
async def _chief_got_deliverable(msg):
try: d = json.loads(msg.text)
except: d = {"deliverable": str(msg.text), "brief_id": "?"}
tid = d.get("brief_id", "?")
await broadcast({"type": "relay_dm", "from_agent": msg.sender, "to_agent": "Editor-in-Chief",
"to_name": EDITOR_CHIEF, "tid": tid,
"preview": f"Deliverable: {str(d.get('deliverable', ''))[:80]}..."})
await broadcast({"type": "followup", "tid": tid,
"detail": f"Editor-in-Chief received deliverable and sent to client for review."})
await broadcast({"type": "complete", "tid": tid,
"resolved_by": f"{msg.sender} → Editor-in-Chief"})
await _send_stats()
# ============================================================
# AGENT 2: SEO WRITER
# ============================================================
async def agent_seo_writer():
r = Relay(SEO_WRITER, CFG); await r.__aenter__(); relays[SEO_WRITER] = r
ev = {"type": "agent_online", "agent": "SEO Writer", "name": SEO_WRITER, "model": SMART_MODEL,
"role": "SEO Content", "color": "amber",
"desc": "Premium model with Ahrefs/SEMrush keyword data. Writes SEO-optimized articles and blog posts."}
agent_online_events.append(ev); await broadcast(ev)
def on_msg(msg):
if msg.sender == SEO_WRITER: return
asyncio.create_task(_seo_handle(msg))
r.on_message(on_msg)
while True: await asyncio.sleep(60)
async def _seo_handle(msg):
try: d = json.loads(msg.text)
except: return
if d.get("category") != "seo_article": return
tid, client, topic = d["brief_id"], d["client"], d["topic"]
tone, length = d.get("tone", "professional"), d.get("length", "medium")
await broadcast({"type": "specialist_pickup", "agent": "SEO Writer", "color": "amber",
"tid": tid, "detail": f"Picking up SEO brief — pulling keyword data for '{topic}'"})
await broadcast({"type": "thinking", "agent": "SEO Writer", "color": "amber", "tid": tid,
"detail": "Analyzing keywords and writing SEO-optimized content...", "model": SMART_MODEL})
ctx = await get_context("seo_writer", client, topic)
await broadcast({"type": "context_loaded", "agent": "SEO Writer", "tid": tid,
"sources": ctx["sources"], "is_live": ctx["is_live"]})
length_guide = {"short": "~500 words", "medium": "~1000 words", "long": "~1800 words"}
word_target = length_guide.get(length, "~1000 words")
res = await llm(SMART_MODEL,
f"""You are an expert SEO content writer with access to keyword and competitor data.
{ctx['context_text']}
Write a {tone}, SEO-optimized article on the given topic.
Target length: {word_target}.
Requirements:
- Naturally incorporate target keywords from the data above
- Use proper heading hierarchy (H1, H2, H3)
- Include a compelling meta description
- Add internal linking suggestions
- Write for the target audience (CTOs, engineering leads)
Address the client ({client}) in your delivery notes.""",
f"Topic: {topic}", "SEO Writer")
stats["sp_tokens"] += res["tokens"]; stats["sp_cost"] += res["cost"]
stats["mono_cost"] += res["cost"]
await broadcast({"type": "model_used", "agent": "SEO Writer", "color": "amber",
"model": res["model"], "tokens": res["tokens"], "cost": res["cost"], "ms": res["ms"]})
await broadcast({"type": "resolution", "agent": "SEO Writer", "color": "amber",
"tid": tid, "text": res["content"]})
await broadcast({"type": "relay_dm", "from_agent": "SEO Writer", "from_name": SEO_WRITER,
"to_agent": "Editor-in-Chief", "to_name": EDITOR_CHIEF, "tid": tid,
"preview": f"SEO article delivered: {res['content'][:80]}..."})
await relays[SEO_WRITER].send(EDITOR_CHIEF, json.dumps({"brief_id": tid, "client": client,
"deliverable": res["content"], "agent": "SEO Writer"}))
await relays[SEO_WRITER].post(CHANNEL, json.dumps({"type": "deliverable", "brief_id": tid,
"agent": "SEO Writer", "deliverable": res["content"], "client": client}))
# ============================================================
# AGENT 3: VISUAL DESIGNER
# ============================================================
async def agent_visual_designer():
r = Relay(VISUAL_DESIGNER, CFG); await r.__aenter__(); relays[VISUAL_DESIGNER] = r
ev = {"type": "agent_online", "agent": "Visual Designer", "name": VISUAL_DESIGNER, "model": FREE_MODEL,
"role": "Visual Content", "color": "violet",
"desc": "Free model with Figma brand guidelines. Creates visual content specs, infographic layouts, and image briefs."}
agent_online_events.append(ev); await broadcast(ev)
def on_msg(msg):
if msg.sender == VISUAL_DESIGNER: return
asyncio.create_task(_visual_handle(msg))
r.on_message(on_msg)
while True: await asyncio.sleep(60)
async def _visual_handle(msg):
try: d = json.loads(msg.text)
except: return
if d.get("category") != "visual_content": return
tid, client, topic = d["brief_id"], d["client"], d["topic"]
await broadcast({"type": "specialist_pickup", "agent": "Visual Designer", "color": "violet",
"tid": tid, "detail": f"Picking up visual brief — loading brand guidelines for {client}"})
await broadcast({"type": "thinking", "agent": "Visual Designer", "color": "violet", "tid": tid,
"detail": "Checking brand guidelines and designing visual assets...", "model": FREE_MODEL})
ctx = await get_context("visual_designer", client, topic)
await broadcast({"type": "context_loaded", "agent": "Visual Designer", "tid": tid,
"sources": ctx["sources"], "is_live": ctx["is_live"]})
res = await llm(FREE_MODEL,
f"""You are a visual content designer with access to brand guidelines and asset libraries.
{ctx['context_text']}
Create a detailed visual content specification for the given topic.
Include:
1. Hero image concept (describe the visual, colors, composition)
2. Infographic layout (if applicable)
3. Social media card designs (Twitter, LinkedIn)
4. Diagram/flowchart specifications
5. Color palette selections from the brand guide
6. Typography recommendations
Reference SPECIFIC brand guidelines, templates, and colors from above.""",
f"Client {client}: Visual content for '{topic}'", "Visual Design")
stats["sp_tokens"] += res["tokens"]; stats["sp_cost"] += res["cost"]
stats["mono_cost"] += 0.00015 * (res["tokens"] / 1000)
await broadcast({"type": "model_used", "agent": "Visual Designer", "color": "violet",
"model": res["model"], "tokens": res["tokens"], "cost": res["cost"], "ms": res["ms"]})
await broadcast({"type": "resolution", "agent": "Visual Designer", "color": "violet",
"tid": tid, "text": res["content"]})
await broadcast({"type": "relay_dm", "from_agent": "Visual Designer", "from_name": VISUAL_DESIGNER,
"to_agent": "Editor-in-Chief", "to_name": EDITOR_CHIEF, "tid": tid,
"preview": f"Visual specs delivered: {res['content'][:80]}..."})
await relays[VISUAL_DESIGNER].send(EDITOR_CHIEF, json.dumps({"brief_id": tid, "client": client,
"deliverable": res["content"], "agent": "Visual Designer"}))
await relays[VISUAL_DESIGNER].post(CHANNEL, json.dumps({"type": "deliverable", "brief_id": tid,
"agent": "Visual Designer", "deliverable": res["content"], "client": client}))
# ============================================================
# AGENT 4: FACT CHECKER
# ============================================================
async def agent_fact_checker():
r = Relay(FACT_CHECKER, CFG); await r.__aenter__(); relays[FACT_CHECKER] = r
ev = {"type": "agent_online", "agent": "Fact Checker", "name": FACT_CHECKER, "model": SMART_MODEL,
"role": "Fact Verification", "color": "red",
"desc": "Premium model with citation database. Verifies claims, checks sources, and flags inaccuracies."}
agent_online_events.append(ev); await broadcast(ev)
def on_msg(msg):
if msg.sender == FACT_CHECKER: return
asyncio.create_task(_fact_handle(msg))
r.on_message(on_msg)
while True: await asyncio.sleep(60)
async def _fact_handle(msg):
try: d = json.loads(msg.text)
except: return
if d.get("category") != "research_piece": return
tid, client, topic = d["brief_id"], d["client"], d["topic"]
await broadcast({"type": "specialist_pickup", "agent": "Fact Checker", "color": "red",
"tid": tid, "detail": f"Picking up research brief — accessing citation database for '{topic}'"})
await broadcast({"type": "thinking", "agent": "Fact Checker", "color": "red", "tid": tid,
"detail": "Cross-referencing sources and verifying claims...", "model": SMART_MODEL})
ctx = await get_context("fact_checker", client, topic)
await broadcast({"type": "context_loaded", "agent": "Fact Checker", "tid": tid,
"sources": ctx["sources"], "is_live": ctx["is_live"]})
res = await llm(SMART_MODEL,
f"""You are a fact checker and research writer with access to citation databases.
{ctx['context_text']}
Write a thoroughly researched piece on the given topic.
Requirements:
1. Every statistic must cite its source (reference SPECIFIC sources from above)
2. Flag any claims that need verification
3. Include a "Sources" section at the end
4. Rate overall factual confidence (High/Medium/Low)
5. Note any claims that are commonly misquoted
6. Use only Tier 1 and Tier 2 sources
Address the client ({client}) in your delivery notes.""",
f"Topic: {topic}", "Fact Check")
stats["sp_tokens"] += res["tokens"]; stats["sp_cost"] += res["cost"]
stats["mono_cost"] += res["cost"]
await broadcast({"type": "model_used", "agent": "Fact Checker", "color": "red",
"model": res["model"], "tokens": res["tokens"], "cost": res["cost"], "ms": res["ms"]})
await broadcast({"type": "resolution", "agent": "Fact Checker", "color": "red",
"tid": tid, "text": res["content"]})
await broadcast({"type": "relay_dm", "from_agent": "Fact Checker", "from_name": FACT_CHECKER,
"to_agent": "Editor-in-Chief", "to_name": EDITOR_CHIEF, "tid": tid,
"preview": f"Research piece delivered: {res['content'][:80]}..."})
await relays[FACT_CHECKER].send(EDITOR_CHIEF, json.dumps({"brief_id": tid, "client": client,
"deliverable": res["content"], "agent": "Fact Checker"}))
await relays[FACT_CHECKER].post(CHANNEL, json.dumps({"type": "deliverable", "brief_id": tid,
"agent": "Fact Checker", "deliverable": res["content"], "client": client}))
# ============================================================
# AGENT 5: QA REVIEWER
# ============================================================
async def agent_qa_reviewer():
r = Relay(QA_REVIEWER, CFG); await r.__aenter__(); relays[QA_REVIEWER] = r
ev = {"type": "agent_online", "agent": "QA Reviewer", "name": QA_REVIEWER, "model": FREE_MODEL,
"role": "Quality Assurance", "color": "slate",
"desc": "Free model. Monitors all content output and scores for readability, SEO, accuracy, and brand voice."}
agent_online_events.append(ev); await broadcast(ev)
def on_msg(msg):
if msg.sender == QA_REVIEWER: return
asyncio.create_task(_qa_review(msg))
r.on_message(on_msg)
while True: await asyncio.sleep(60)
async def _qa_review(msg):
try: d = json.loads(msg.text)
except: return
if d.get("type") != "deliverable": return
tid = d.get("brief_id", "?")
agent = d.get("agent", "Unknown")
deliverable = d.get("deliverable", "")
client = d.get("client", "")
await broadcast({"type": "thinking", "agent": "QA Reviewer", "color": "slate", "tid": tid,
"detail": f"Reviewing {agent}'s deliverable...", "model": FREE_MODEL})
ctx = await get_context("qa_reviewer", client, "")
res = await llm(FREE_MODEL,
f"""You are a content QA reviewer. Score this content deliverable on 4 criteria (1-5 each):
{ctx['context_text']}
- Readability: Is it clear, well-structured, and at the right reading level?
- SEO: Are keywords naturally integrated? Proper heading hierarchy?
- Accuracy: Are claims sourced? Any red flags?
- Brand Voice: Does it match the style guide?
Respond ONLY with JSON: {{"readability":N,"seo":N,"accuracy":N,"brand_voice":N,"overall":N,"note":"one sentence"}}""",
f"Agent: {agent}\nClient: {client}\nContent: {deliverable[:500]}", "QA")
stats["qa_tokens"] += res["tokens"]; stats["qa_cost"] += res["cost"]
try:
scores = json.loads(res["content"])
except:
scores = {"readability": 4, "seo": 4, "accuracy": 4, "brand_voice": 4, "overall": 4, "note": "Solid content deliverable"}
await broadcast({"type": "qa_score", "tid": tid, "agent": agent, "scores": scores,
"model": res["model"], "tokens": res["tokens"]})
async def _send_stats():
multi = stats["fd_cost"] + stats["sp_cost"] + stats["qa_cost"]
mono = stats["mono_cost"]
pct = ((mono - multi) / mono * 100) if mono > 0 else 0
await broadcast({"type": "stats",
"total": stats["total"], "simple": stats["simple"], "escalated": stats["escalated"],
"fd_tokens": stats["fd_tokens"], "sp_tokens": stats["sp_tokens"], "qa_tokens": stats["qa_tokens"],
"multi_cost": round(multi, 6), "mono_cost": round(mono, 6), "savings_pct": round(pct, 1)})
# ============================================================
# STARTUP
# ============================================================
@app.on_event("startup")
async def startup():
asyncio.create_task(agent_editor_chief())
await asyncio.sleep(2)
asyncio.create_task(agent_seo_writer())
await asyncio.sleep(2)
asyncio.create_task(agent_visual_designer())
await asyncio.sleep(2)
asyncio.create_task(agent_fact_checker())
await asyncio.sleep(2)
asyncio.create_task(agent_qa_reviewer())
@app.on_event("shutdown")
async def shutdown():
for r in relays.values():
try: await r.__aexit__(None, None, None)
except: pass
@app.get("/")
async def index():
return FileResponse(Path(__file__).parent / "index.html")
@app.post("/api/submit")
async def submit(data: dict):
topic = data.get("topic", ""); client = data.get("client", "Acme Corp")
tone = data.get("tone", "professional"); length = data.get("length", "medium")
if not topic: return {"error": "topic required"}
tid = brief_id()
await broadcast({"type": "ticket_created", "tid": tid, "customer": client, "query": topic,
"tone": tone, "length": length,
"timestamp": datetime.now().strftime("%H:%M:%S")})
await brief_queue.put({"topic": topic, "client": client, "tone": tone, "length": length, "brief_id": tid})
return {"status": "processing", "brief_id": tid}
@app.websocket("/ws")
async def ws_ep(ws: WebSocket):
await ws.accept(); ws_clients.append(ws)
for ev in agent_online_events:
await ws.send_text(json.dumps(ev))
try:
while True: await ws.receive_text()
except WebSocketDisconnect: ws_clients.remove(ws)
app.mount("/assets", StaticFiles(directory=Path(__file__).parent / "assets"), name="assets")
if __name__ == "__main__":
import uvicorn
print(f"\n📝 Content Pipeline — Agent Relay Demo (5 agents)")
print(f" Editor-in-Chief: {EDITOR_CHIEF} ({FREE_MODEL})")
print(f" SEO Writer: {SEO_WRITER} ({SMART_MODEL})")
print(f" Visual Designer: {VISUAL_DESIGNER} ({FREE_MODEL})")
print(f" Fact Checker: {FACT_CHECKER} ({SMART_MODEL})")
print(f" QA Reviewer: {QA_REVIEWER} ({FREE_MODEL})")
print(f" http://localhost:8082\n")
uvicorn.run(app, host="0.0.0.0", port=8082, log_level="warning")