crewforge 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. crewforge/__init__.py +3 -0
  2. crewforge/__main__.py +4 -0
  3. crewforge/cli.py +128 -0
  4. crewforge/cli_support.py +109 -0
  5. crewforge/core/__init__.py +54 -0
  6. crewforge/core/agent.py +118 -0
  7. crewforge/core/client.py +253 -0
  8. crewforge/core/config.py +181 -0
  9. crewforge/core/crew.py +144 -0
  10. crewforge/core/errors.py +106 -0
  11. crewforge/core/parsing.py +110 -0
  12. crewforge/core/providers.py +131 -0
  13. crewforge/core/usage.py +163 -0
  14. crewforge/py.typed +0 -0
  15. crewforge/recipes/__init__.py +1 -0
  16. crewforge/recipes/api/__init__.py +38 -0
  17. crewforge/recipes/api/agents.py +523 -0
  18. crewforge/recipes/api/analytics.py +99 -0
  19. crewforge/recipes/api/appcheck.py +73 -0
  20. crewforge/recipes/api/cli.py +127 -0
  21. crewforge/recipes/api/formatters.py +32 -0
  22. crewforge/recipes/api/generator.py +37 -0
  23. crewforge/recipes/api/pipeline.py +86 -0
  24. crewforge/recipes/api/scaffold.py +68 -0
  25. crewforge/recipes/api/templates/docker-compose.j2 +9 -0
  26. crewforge/recipes/api/templates/dockerfile.j2 +7 -0
  27. crewforge/recipes/api/templates/env.example.j2 +2 -0
  28. crewforge/recipes/api/templates/fastapi_main.j2 +10 -0
  29. crewforge/recipes/api/templates/model.j2 +4 -0
  30. crewforge/recipes/api/templates/requirements.j2 +6 -0
  31. crewforge/recipes/api/templates/route.j2 +4 -0
  32. crewforge/recipes/api/templates/test.j2 +3 -0
  33. crewforge/recipes/api/utils.py +134 -0
  34. crewforge/recipes/content/__init__.py +20 -0
  35. crewforge/recipes/content/agents.py +735 -0
  36. crewforge/recipes/content/cli.py +128 -0
  37. crewforge/recipes/content/export.py +84 -0
  38. crewforge/recipes/content/pipeline.py +222 -0
  39. crewforge/recipes/content/settings.py +63 -0
  40. crewforge/recipes/content/text.py +57 -0
  41. crewforge/recipes/docs/__init__.py +48 -0
  42. crewforge/recipes/docs/agents.py +426 -0
  43. crewforge/recipes/docs/cli.py +156 -0
  44. crewforge/recipes/docs/export.py +118 -0
  45. crewforge/recipes/docs/index.py +117 -0
  46. crewforge/recipes/docs/ingest.py +212 -0
  47. crewforge/recipes/docs/pipeline.py +223 -0
  48. crewforge/recipes/docs/retrieve.py +70 -0
  49. crewforge/recipes/docs/settings.py +54 -0
  50. crewforge/recipes/review/__init__.py +1 -0
  51. crewforge/recipes/review/agents.py +331 -0
  52. crewforge/recipes/review/cli.py +144 -0
  53. crewforge/recipes/review/pipeline.py +125 -0
  54. crewforge/recipes/review/report.py +103 -0
  55. crewforge/recipes/review/sources.py +89 -0
  56. crewforge-0.1.0.dist-info/METADATA +372 -0
  57. crewforge-0.1.0.dist-info/RECORD +61 -0
  58. crewforge-0.1.0.dist-info/WHEEL +5 -0
  59. crewforge-0.1.0.dist-info/entry_points.txt +2 -0
  60. crewforge-0.1.0.dist-info/licenses/LICENSE +21 -0
  61. crewforge-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,735 @@
1
+ """The eight content agents (ported from contentforge).
2
+
3
+ Each agent keeps contentforge's prompts and ``AgentResult`` shape, but runs on
4
+ the crewforge core: :meth:`ContentAgent.execute` raises (naming the agent) on
5
+ empty or unparseable output, and the pipeline runs it through ``Crew.step`` so
6
+ no failure can be swallowed. :meth:`ContentAgent.run` keeps contentforge's
7
+ "never raise, return a failed result" behaviour for library callers.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import logging
13
+ from dataclasses import dataclass, field
14
+ from datetime import datetime, timezone
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from ...core.agent import Agent
19
+ from ...core.client import LLMClient
20
+ from ...core.errors import OutputParseError
21
+ from ...core.parsing import parse_json
22
+ from ...core.usage import UsageTracker
23
+ from .export import export_html, export_json_report, export_markdown
24
+ from .settings import ContentSettings
25
+ from .text import reading_time, slugify, word_count
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+
30
+ @dataclass
31
+ class AgentResult:
32
+ """Standardized result from any content agent."""
33
+
34
+ agent_name: str
35
+ status: str = "success" # success | partial | failed
36
+ content: str = ""
37
+ metadata: dict[str, Any] = field(default_factory=dict)
38
+ tokens_used: int = 0
39
+ latency_ms: float = 0.0
40
+ error: str | None = None
41
+ reasoning: str | None = None
42
+
43
+ @property
44
+ def ok(self) -> bool:
45
+ return self.status == "success"
46
+
47
+
48
+ class ContentAgent(Agent):
49
+ """Base for content agents: applies per-agent overrides from ``content.agents``."""
50
+
51
+ # contentforge's default: writing benefits from more sampling freedom than review.
52
+ temperature = 0.7
53
+
54
+ def __init__(
55
+ self,
56
+ client: LLMClient,
57
+ tracker: UsageTracker | None = None,
58
+ *,
59
+ config: ContentSettings | None = None,
60
+ ) -> None:
61
+ self.config = config or ContentSettings()
62
+ override = self.config.get_agent_config(self.name)
63
+ super().__init__(
64
+ client,
65
+ tracker,
66
+ system_prompt=override.system_prompt_override,
67
+ model=override.model_override,
68
+ temperature=override.temperature_override,
69
+ max_tokens=override.max_tokens_override,
70
+ )
71
+ self._agent_config = override
72
+ self._iteration = 0
73
+
74
+ async def execute(self, **kwargs: Any) -> AgentResult: # pragma: no cover - abstract
75
+ raise NotImplementedError
76
+
77
+ async def run(self, **kwargs: Any) -> AgentResult:
78
+ """Run with error capture (library API); the pipeline uses ``execute``."""
79
+ self._iteration += 1
80
+ try:
81
+ return await self.execute(**kwargs)
82
+ except Exception as exc:
83
+ logger.error("[%s] failed: %s", self.name, exc)
84
+ return AgentResult(agent_name=self.name, status="failed", error=str(exc))
85
+
86
+
87
+ class ResearchAgent(ContentAgent):
88
+ name = "research"
89
+ description = "Gathers background information, key facts, and expert perspectives"
90
+
91
+ system_prompt = """You are the Research Agent in a content creation pipeline.
92
+
93
+ Your role:
94
+ 1. Analyze the given topic and identify 5-8 key subtopics
95
+ 2. Provide factual information, statistics, and expert quotes for each
96
+ 3. Identify trending angles and unique perspectives
97
+ 4. Flag any controversial claims that need verification
98
+ 5. Suggest primary and secondary sources
99
+
100
+ Output format (JSON):
101
+ {
102
+ "topic": "...",
103
+ "key_subtopics": [
104
+ {"title": "...", "key_facts": [...], "statistics": [...], "expert_quotes": [...]}
105
+ ],
106
+ "trending_angles": [...],
107
+ "controversial_claims": [...],
108
+ "suggested_sources": [...],
109
+ "unique_angle": "..."
110
+ }
111
+
112
+ Be thorough but concise.
113
+ You have NO web access: work from general knowledge, never invent sources, URLs or
114
+ exact statistics, and list anything uncertain under "controversial_claims"."""
115
+
116
+ async def execute(self, topic: str = "", **kwargs) -> AgentResult:
117
+ """Research a given topic and return structured findings."""
118
+ prompt = f"""Research the following topic thoroughly:
119
+
120
+ Topic: {topic}
121
+
122
+ Provide:
123
+ 1. 5-8 key subtopics with supporting facts and statistics
124
+ 2. Expert perspectives and notable quotes
125
+ 3. Current trends and unique angles
126
+ 4. Any controversial claims that need fact-checking
127
+ 5. A suggested unique angle for the article
128
+
129
+ Return as structured JSON."""
130
+
131
+ response = await self.ask(prompt)
132
+
133
+ return AgentResult(
134
+ agent_name=self.name,
135
+ content=response.content,
136
+ tokens_used=response.usage.total_tokens,
137
+ latency_ms=response.latency_ms,
138
+ reasoning=response.reasoning or None,
139
+ metadata={
140
+ "topic": topic,
141
+ "has_statistics": "statistics" in response.content.lower(),
142
+ "has_quotes": "quote" in response.content.lower(),
143
+ "output_length": len(response.content),
144
+ },
145
+ )
146
+
147
+
148
+ class OutlineAgent(ContentAgent):
149
+ name = "outline"
150
+ description = "Creates structured outlines with section hierarchy and word allocation"
151
+
152
+ system_prompt = """You are the Outline Agent in a content creation pipeline.
153
+
154
+ Your role:
155
+ 1. Take research data and create a well-structured article outline
156
+ 2. Allocate word count per section proportionally to importance
157
+ 3. Ensure logical flow: hook → context → body → conclusion
158
+ 4. Add SEO keyword placement suggestions per section
159
+ 5. Include transition notes between sections
160
+
161
+ Output format (JSON):
162
+ {
163
+ "title": "...",
164
+ "meta_description": "...",
165
+ "target_word_count": N,
166
+ "sections": [
167
+ {
168
+ "heading": "...",
169
+ "subheadings": [...],
170
+ "word_allocation": N,
171
+ "key_points": [...],
172
+ "seo_keywords": [...],
173
+ "transition_note": "..."
174
+ }
175
+ ],
176
+ "estimated_reading_time": "X min",
177
+ "content_type": "article|guide|listicle|comparison"
178
+ }
179
+
180
+ Aim for 6-10 sections with clear hierarchy."""
181
+
182
+ async def execute(
183
+ self, research_data: str = "", target_words: int = 2000, **kwargs
184
+ ) -> AgentResult:
185
+ """Create an outline from research data."""
186
+ prompt = f"""Based on the following research data, create a detailed article outline.
187
+
188
+ Target word count: {target_words} words
189
+
190
+ Research Data:
191
+ {research_data}
192
+
193
+ Create a structured outline with:
194
+ - Compelling title and meta description
195
+ - 6-10 sections with word allocation
196
+ - Key points per section
197
+ - SEO keyword suggestions
198
+ - Logical flow with transitions
199
+
200
+ Return as structured JSON."""
201
+
202
+ response = await self.ask(prompt)
203
+
204
+ return AgentResult(
205
+ agent_name=self.name,
206
+ content=response.content,
207
+ tokens_used=response.usage.total_tokens,
208
+ latency_ms=response.latency_ms,
209
+ reasoning=response.reasoning or None,
210
+ metadata={
211
+ "target_words": target_words,
212
+ "output_length": len(response.content),
213
+ },
214
+ )
215
+
216
+
217
+ class WriterAgent(ContentAgent):
218
+ name = "writer"
219
+ description = "Generates full content draft from outline and research"
220
+
221
+ system_prompt = """You are the Writer Agent in a content creation pipeline.
222
+
223
+ Your role:
224
+ 1. Write engaging, well-researched content following the provided outline
225
+ 2. Maintain consistent tone and voice throughout
226
+ 3. Include natural keyword integration (not keyword stuffing)
227
+ 4. Use varied sentence structures and paragraph lengths
228
+ 5. Add relevant examples, analogies, and data points
229
+ 6. Write in a style that's informative yet accessible
230
+
231
+ Writing guidelines:
232
+ - Start with a compelling hook
233
+ - Use subheadings (##) for each major section
234
+ - Include bullet points and numbered lists for scannability
235
+ - Add internal transition sentences between sections
236
+ - End with a strong conclusion and call-to-action
237
+ - Write in active voice predominantly
238
+ - Cite statistics with source context (not raw URLs)
239
+
240
+ Output: Full article in Markdown format."""
241
+
242
+ async def execute(
243
+ self,
244
+ outline: str = "",
245
+ research_data: str = "",
246
+ language: str = "en",
247
+ **kwargs,
248
+ ) -> AgentResult:
249
+ """Generate a full content draft."""
250
+ prompt = f"""Write a complete article based on the following outline and research.
251
+
252
+ Language: {language}
253
+
254
+ OUTLINE:
255
+ {outline}
256
+
257
+ RESEARCH DATA:
258
+ {research_data}
259
+
260
+ Write the full article in Markdown. Follow the outline structure precisely.
261
+ Each section should meet its word allocation target.
262
+ Include natural keyword integration as specified in the outline."""
263
+
264
+ response = await self.ask(prompt, max_tokens=8192)
265
+
266
+ word_count = len(response.content.split())
267
+
268
+ return AgentResult(
269
+ agent_name=self.name,
270
+ content=response.content,
271
+ tokens_used=response.usage.total_tokens,
272
+ latency_ms=response.latency_ms,
273
+ reasoning=response.reasoning or None,
274
+ metadata={
275
+ "word_count": word_count,
276
+ "language": language,
277
+ "output_length": len(response.content),
278
+ },
279
+ )
280
+
281
+
282
+ class SEOAgent(ContentAgent):
283
+ name = "seo"
284
+ description = "Analyzes and optimizes content for search engine visibility"
285
+
286
+ system_prompt = """You are the SEO Agent in a content creation pipeline.
287
+
288
+ Your role:
289
+ 1. Analyze content for SEO effectiveness
290
+ 2. Suggest keyword density improvements
291
+ 3. Optimize title and meta description for CTR
292
+ 4. Check heading hierarchy (H1 → H2 → H3)
293
+ 5. Recommend internal/external linking opportunities
294
+ 6. Identify featured snippet opportunities
295
+ 7. Suggest image alt-text recommendations
296
+
297
+ Output format (JSON):
298
+ {
299
+ "seo_score": 0-100,
300
+ "keyword_analysis": {
301
+ "primary_keyword": "...",
302
+ "secondary_keywords": [...],
303
+ "keyword_density": "...%",
304
+ "recommendations": [...]
305
+ },
306
+ "title_optimization": {
307
+ "current": "...",
308
+ "suggested": "...",
309
+ "reason": "..."
310
+ },
311
+ "meta_description": {
312
+ "current": "...",
313
+ "optimized": "...",
314
+ "char_count": N
315
+ },
316
+ "heading_structure": {
317
+ "issues": [...],
318
+ "suggestions": [...]
319
+ },
320
+ "featured_snippet_candidates": [...],
321
+ "internal_link_suggestions": [...],
322
+ "image_alt_suggestions": [...],
323
+ "overall_recommendations": [...]
324
+ }"""
325
+
326
+ async def execute(
327
+ self, content: str = "", target_keywords: list[str] | None = None, **kwargs
328
+ ) -> AgentResult:
329
+ """Analyze content for SEO and provide optimization recommendations."""
330
+ keywords_str = ", ".join(target_keywords) if target_keywords else "auto-detect"
331
+
332
+ prompt = f"""Analyze the following content for SEO effectiveness.
333
+
334
+ Target Keywords: {keywords_str}
335
+
336
+ CONTENT:
337
+ {content}
338
+
339
+ Provide:
340
+ 1. SEO score (0-100)
341
+ 2. Keyword density analysis
342
+ 3. Title and meta description optimization
343
+ 4. Heading structure review
344
+ 5. Featured snippet opportunities
345
+ 6. Internal linking suggestions
346
+ 7. Image alt-text recommendations
347
+
348
+ Return as structured JSON."""
349
+
350
+ response = await self.ask(prompt)
351
+
352
+ return AgentResult(
353
+ agent_name=self.name,
354
+ content=response.content,
355
+ tokens_used=response.usage.total_tokens,
356
+ latency_ms=response.latency_ms,
357
+ reasoning=response.reasoning or None,
358
+ metadata={
359
+ "target_keywords": target_keywords or [],
360
+ "content_length": len(content),
361
+ },
362
+ )
363
+
364
+
365
+ class EditorAgent(ContentAgent):
366
+ name = "editor"
367
+ description = "Refines content for clarity, grammar, tone, and readability"
368
+
369
+ system_prompt = """You are the Editor Agent in a content creation pipeline.
370
+
371
+ Your role:
372
+ 1. Fix grammar, spelling, and punctuation errors
373
+ 2. Improve sentence clarity and readability
374
+ 3. Ensure consistent tone and voice
375
+ 4. Remove redundancy and filler words
376
+ 5. Strengthen weak transitions
377
+ 6. Verify factual claims have proper attribution
378
+ 7. Improve paragraph flow and pacing
379
+ 8. Ensure the content matches the target reading level
380
+
381
+ Editing principles:
382
+ - Preserve the author's voice while improving clarity
383
+ - Short sentences for impact, longer for explanation
384
+ - Every paragraph must earn its place
385
+ - Active voice over passive
386
+ - Specific over vague
387
+ - Show, don't tell
388
+
389
+ Output: Return the FULL edited article in Markdown, plus a change summary."""
390
+
391
+ async def execute(
392
+ self,
393
+ content: str = "",
394
+ seo_recommendations: str = "",
395
+ target_reading_level: str = "general",
396
+ **kwargs,
397
+ ) -> AgentResult:
398
+ """Edit and refine the content draft."""
399
+ seo_block = ""
400
+ if seo_recommendations:
401
+ seo_block = f"SEO RECOMMENDATIONS TO INCORPORATE:\n{seo_recommendations}\n"
402
+
403
+ prompt = f"""Edit the following article for maximum quality.
404
+
405
+ Target reading level: {target_reading_level}
406
+
407
+ {seo_block}
408
+ CONTENT:
409
+ {content}
410
+
411
+ Return:
412
+ 1. The FULL edited article in Markdown (not a diff)
413
+ 2. A brief change summary at the end (as a comment block)"""
414
+
415
+ response = await self.ask(prompt, max_tokens=8192)
416
+
417
+ return AgentResult(
418
+ agent_name=self.name,
419
+ content=response.content,
420
+ tokens_used=response.usage.total_tokens,
421
+ latency_ms=response.latency_ms,
422
+ reasoning=response.reasoning or None,
423
+ metadata={
424
+ "input_length": len(content),
425
+ "output_length": len(response.content),
426
+ "reading_level": target_reading_level,
427
+ },
428
+ )
429
+
430
+
431
+ class QualityAgent(ContentAgent):
432
+ name = "quality"
433
+ description = "Fact-checks content, scores quality, and flags issues"
434
+
435
+ system_prompt = """You are the Quality Agent in a content creation pipeline.
436
+
437
+ Your role:
438
+ 1. Score overall content quality (0-100)
439
+ 2. Check factual accuracy of claims and statistics
440
+ 3. Verify logical consistency throughout the piece
441
+ 4. Detect potential plagiarism patterns
442
+ 5. Check for bias or unbalanced perspectives
443
+ 6. Verify all statistics have proper context
444
+ 7. Ensure the content delivers on the title's promise
445
+ 8. Check readability metrics
446
+
447
+ Quality dimensions (score each 0-100):
448
+ - Accuracy: Factual correctness
449
+ - Completeness: Covers the topic thoroughly
450
+ - Clarity: Easy to understand
451
+ - Engagement: Keeps reader interest
452
+ - Originality: Unique perspective
453
+ - Structure: Logical organization
454
+ - SEO: Search optimization
455
+ - Readability: Appropriate reading level
456
+
457
+ Output format (JSON):
458
+ {
459
+ "overall_score": N,
460
+ "pass_threshold": true|false,
461
+ "dimensions": {
462
+ "accuracy": {"score": N, "notes": "..."},
463
+ "completeness": {"score": N, "notes": "..."},
464
+ "clarity": {"score": N, "notes": "..."},
465
+ "engagement": {"score": N, "notes": "..."},
466
+ "originality": {"score": N, "notes": "..."},
467
+ "structure": {"score": N, "notes": "..."},
468
+ "seo": {"score": N, "notes": "..."},
469
+ "readability": {"score": N, "notes": "..."}
470
+ },
471
+ "factual_issues": [...],
472
+ "logical_inconsistencies": [...],
473
+ "bias_flags": [...],
474
+ "improvement_suggestions": [...],
475
+ "strengths": [...]
476
+ }"""
477
+
478
+ async def execute(
479
+ self,
480
+ content: str = "",
481
+ threshold: float = 0.8,
482
+ title: str = "",
483
+ **kwargs,
484
+ ) -> AgentResult:
485
+ """Score content quality and flag issues."""
486
+ prompt = f"""Evaluate the quality of the following article.
487
+
488
+ Title: {title}
489
+ Quality threshold: {threshold * 100}%
490
+
491
+ CONTENT:
492
+ {content}
493
+
494
+ Score each dimension (0-100) and provide:
495
+ 1. Overall quality score
496
+ 2. Per-dimension scores with notes
497
+ 3. Factual issues found
498
+ 4. Logical inconsistencies
499
+ 5. Bias flags
500
+ 6. Improvement suggestions
501
+ 7. Key strengths
502
+
503
+ Return as structured JSON."""
504
+
505
+ response = await self.ask(prompt)
506
+
507
+ # Fences and surrounding prose are tolerated; a reply without a numeric
508
+ # overall_score is a failure of this agent (contentforge silently used 0,
509
+ # which made the editor loop burn every iteration).
510
+ parsed = parse_json(response.content, agent=self.name)
511
+ raw_score = parsed.get("overall_score")
512
+ if isinstance(raw_score, bool) or not isinstance(raw_score, (int, float, str)):
513
+ raise OutputParseError(self.name, "JSON has no numeric overall_score")
514
+ try:
515
+ overall_score = float(raw_score)
516
+ except ValueError as exc:
517
+ raise OutputParseError(
518
+ self.name, f"overall_score is not a number: {raw_score!r}"
519
+ ) from exc
520
+ if not 0 <= overall_score <= 100:
521
+ raise OutputParseError(self.name, f"overall_score {overall_score} is outside 0-100")
522
+
523
+ return AgentResult(
524
+ agent_name=self.name,
525
+ content=response.content,
526
+ tokens_used=response.usage.total_tokens,
527
+ latency_ms=response.latency_ms,
528
+ reasoning=response.reasoning or None,
529
+ metadata={
530
+ "overall_score": overall_score,
531
+ "threshold": threshold,
532
+ "passes_threshold": overall_score >= threshold * 100,
533
+ "content_length": len(content),
534
+ },
535
+ )
536
+
537
+
538
+ class TranslatorAgent(ContentAgent):
539
+ name = "translator"
540
+ description = "Adapts content to target languages while preserving tone and SEO"
541
+
542
+ system_prompt = """You are the Translator Agent in a content creation pipeline.
543
+
544
+ Your role:
545
+ 1. Translate content to the target language accurately
546
+ 2. Adapt cultural references and idioms for the target audience
547
+ 3. Preserve SEO keywords (transliterate or localize as appropriate)
548
+ 4. Maintain heading structure and Markdown formatting
549
+ 5. Keep proper nouns and brand names unchanged unless localized versions exist
550
+ 6. Adapt statistics and date formats for the target locale
551
+ 7. Preserve the original tone and voice
552
+
553
+ Supported languages:
554
+ - zh (Chinese Simplified) — 优先使用简体中文
555
+ - ms (Malay) — Gunakan bahasa Melayu standard
556
+ - ja (Japanese) — 日本語で自然な表現を使用
557
+ - ko (Korean) — 한국어로 자연스러운 표현 사용
558
+ - id (Indonesian) — Gunakan bahasa Indonesia baku
559
+ - th (Thai) — ใช้ภาษาไทยที่เป็นธรรมชาติ
560
+ - vi (Vietnamese) — Sử dụng tiếng Việt tự nhiên
561
+ - ar (Arabic) — استخدم اللغة العربية الفصحى
562
+
563
+ Output: Full translated article in Markdown, same structure as original."""
564
+
565
+ async def execute(
566
+ self,
567
+ content: str = "",
568
+ target_language: str = "zh",
569
+ source_language: str = "en",
570
+ preserve_keywords: list[str] | None = None,
571
+ **kwargs,
572
+ ) -> AgentResult:
573
+ """Translate content to target language."""
574
+ keywords_note = ""
575
+ if preserve_keywords:
576
+ keywords_note = (
577
+ f"\nPreserve these keywords in original form: {', '.join(preserve_keywords)}"
578
+ )
579
+
580
+ prompt = f"""Translate the following article from {source_language} to {target_language}.
581
+
582
+ Rules:
583
+ - Maintain Markdown formatting exactly
584
+ - Adapt cultural references naturally
585
+ - Keep brand names and proper nouns unchanged{keywords_note}
586
+
587
+ ARTICLE:
588
+ {content}
589
+
590
+ Return the full translated article in Markdown."""
591
+
592
+ response = await self.ask(prompt, max_tokens=8192)
593
+
594
+ return AgentResult(
595
+ agent_name=self.name,
596
+ content=response.content,
597
+ tokens_used=response.usage.total_tokens,
598
+ latency_ms=response.latency_ms,
599
+ metadata={
600
+ "source_language": source_language,
601
+ "target_language": target_language,
602
+ "input_length": len(content),
603
+ "output_length": len(response.content),
604
+ },
605
+ )
606
+
607
+
608
+ class PublisherAgent(ContentAgent):
609
+ name = "publisher"
610
+ description = "Formats content for target platforms and exports files"
611
+
612
+ system_prompt = """You are the Publisher Agent in a content creation pipeline.
613
+
614
+ Your role:
615
+ 1. Format content for the target platform(s)
616
+ 2. Generate platform-specific metadata
617
+ 3. Create social media snippets for distribution
618
+ 4. Generate email newsletter version
619
+ 5. Create plain-text fallback version
620
+ 6. Add proper front matter (YAML/TOML as needed)
621
+
622
+ Platform formats:
623
+ - markdown: Clean Markdown with YAML front matter
624
+ - html: Semantic HTML5 with proper meta tags
625
+ - wordpress: WordPress-compatible with shortcodes
626
+ - medium: Medium-optimized (clean, no front matter)
627
+ - newsletter: Email-friendly HTML with inline styles
628
+ - social: Social media snippets (Twitter, LinkedIn, Facebook)
629
+
630
+ Output format (JSON):
631
+ {
632
+ "formats": {
633
+ "markdown": "...",
634
+ "html_snippet": "...",
635
+ "social_twitter": "...",
636
+ "social_linkedin": "...",
637
+ "newsletter_subject": "...",
638
+ "newsletter_preview": "..."
639
+ },
640
+ "metadata": {
641
+ "title": "...",
642
+ "description": "...",
643
+ "tags": [...],
644
+ "category": "...",
645
+ "reading_time": "...",
646
+ "word_count": N
647
+ }
648
+ }"""
649
+
650
+ async def execute(
651
+ self,
652
+ content: str = "",
653
+ title: str = "",
654
+ publish_targets: list[str] | None = None,
655
+ output_dir: str = "./output",
656
+ **kwargs,
657
+ ) -> AgentResult:
658
+ """Format and export content for target platforms."""
659
+ targets = publish_targets or ["markdown"]
660
+ targets_str = ", ".join(targets)
661
+
662
+ prompt = f"""Format the following article for these platforms: {targets_str}
663
+
664
+ Title: {title}
665
+
666
+ CONTENT:
667
+ {content}
668
+
669
+ Generate:
670
+ 1. Platform-specific formatted versions
671
+ 2. Social media snippets (Twitter: 280 chars, LinkedIn: professional tone)
672
+ 3. Email newsletter subject line and preview text
673
+ 4. Complete metadata (tags, category, reading time, word count)
674
+
675
+ Return as structured JSON."""
676
+
677
+ response = await self.ask(prompt)
678
+ formats = parse_json(response.content, agent=self.name)
679
+
680
+ meta = formats.get("metadata") if isinstance(formats.get("metadata"), dict) else {}
681
+ metadata = {
682
+ "title": title,
683
+ "description": str(meta.get("description", "")),
684
+ "tags": meta.get("tags", []),
685
+ "language": kwargs.get("language", "en"),
686
+ "word_count": word_count(content),
687
+ "reading_time": reading_time(content),
688
+ "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
689
+ }
690
+ output_path = Path(output_dir)
691
+ stem = slugify(title)[:60] or "article"
692
+ files: list[str] = []
693
+ for target in targets:
694
+ if target == "markdown":
695
+ files.append(str(export_markdown(content, metadata, output_path / f"{stem}.md")))
696
+ elif target == "html":
697
+ files.append(str(export_html(content, metadata, output_path / f"{stem}.html")))
698
+ elif target == "json":
699
+ record = {"metadata": metadata, "content": content}
700
+ files.append(str(export_json_report(record, output_path / f"{stem}.json")))
701
+ else:
702
+ raise ValueError(f"unknown publish target {target!r}")
703
+ # Social snippets, newsletter lines and metadata exactly as the model returned them.
704
+ files.append(str(export_json_report(formats, output_path / f"{stem}.publisher.json")))
705
+
706
+ return AgentResult(
707
+ agent_name=self.name,
708
+ content=response.content,
709
+ tokens_used=response.usage.total_tokens,
710
+ latency_ms=response.latency_ms,
711
+ metadata={
712
+ "publish_targets": targets,
713
+ "output_files": files,
714
+ "content_length": len(content),
715
+ },
716
+ )
717
+
718
+
719
+ AGENT_REGISTRY: dict[str, type[ContentAgent]] = {
720
+ "research": ResearchAgent,
721
+ "outline": OutlineAgent,
722
+ "writer": WriterAgent,
723
+ "seo": SEOAgent,
724
+ "editor": EditorAgent,
725
+ "translator": TranslatorAgent,
726
+ "quality": QualityAgent,
727
+ "publisher": PublisherAgent,
728
+ }
729
+
730
+
731
+ def get_agent(name: str, **kwargs: Any) -> ContentAgent:
732
+ cls = AGENT_REGISTRY.get(name)
733
+ if not cls:
734
+ raise ValueError(f"Unknown agent: {name}. Available: {list(AGENT_REGISTRY)}")
735
+ return cls(**kwargs)