empathy-framework 4.1.1__py3-none-any.whl → 4.4.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 (45) hide show
  1. {empathy_framework-4.1.1.dist-info → empathy_framework-4.4.0.dist-info}/METADATA +77 -12
  2. {empathy_framework-4.1.1.dist-info → empathy_framework-4.4.0.dist-info}/RECORD +45 -14
  3. empathy_os/cli_unified.py +13 -0
  4. empathy_os/memory/long_term.py +5 -0
  5. empathy_os/memory/unified.py +149 -9
  6. empathy_os/meta_workflows/__init__.py +74 -0
  7. empathy_os/meta_workflows/agent_creator.py +254 -0
  8. empathy_os/meta_workflows/builtin_templates.py +567 -0
  9. empathy_os/meta_workflows/cli_meta_workflows.py +1551 -0
  10. empathy_os/meta_workflows/form_engine.py +304 -0
  11. empathy_os/meta_workflows/intent_detector.py +298 -0
  12. empathy_os/meta_workflows/models.py +567 -0
  13. empathy_os/meta_workflows/pattern_learner.py +754 -0
  14. empathy_os/meta_workflows/session_context.py +398 -0
  15. empathy_os/meta_workflows/template_registry.py +229 -0
  16. empathy_os/meta_workflows/workflow.py +980 -0
  17. empathy_os/orchestration/execution_strategies.py +888 -1
  18. empathy_os/orchestration/pattern_learner.py +699 -0
  19. empathy_os/socratic/__init__.py +273 -0
  20. empathy_os/socratic/ab_testing.py +969 -0
  21. empathy_os/socratic/blueprint.py +532 -0
  22. empathy_os/socratic/cli.py +689 -0
  23. empathy_os/socratic/collaboration.py +1112 -0
  24. empathy_os/socratic/domain_templates.py +916 -0
  25. empathy_os/socratic/embeddings.py +734 -0
  26. empathy_os/socratic/engine.py +729 -0
  27. empathy_os/socratic/explainer.py +663 -0
  28. empathy_os/socratic/feedback.py +767 -0
  29. empathy_os/socratic/forms.py +624 -0
  30. empathy_os/socratic/generator.py +716 -0
  31. empathy_os/socratic/llm_analyzer.py +635 -0
  32. empathy_os/socratic/mcp_server.py +751 -0
  33. empathy_os/socratic/session.py +306 -0
  34. empathy_os/socratic/storage.py +635 -0
  35. empathy_os/socratic/success.py +719 -0
  36. empathy_os/socratic/visual_editor.py +812 -0
  37. empathy_os/socratic/web_ui.py +925 -0
  38. empathy_os/workflows/manage_documentation.py +18 -2
  39. empathy_os/workflows/release_prep_crew.py +16 -1
  40. empathy_os/workflows/test_coverage_boost_crew.py +16 -1
  41. empathy_os/workflows/test_maintenance_crew.py +18 -1
  42. {empathy_framework-4.1.1.dist-info → empathy_framework-4.4.0.dist-info}/WHEEL +0 -0
  43. {empathy_framework-4.1.1.dist-info → empathy_framework-4.4.0.dist-info}/entry_points.txt +0 -0
  44. {empathy_framework-4.1.1.dist-info → empathy_framework-4.4.0.dist-info}/licenses/LICENSE +0 -0
  45. {empathy_framework-4.1.1.dist-info → empathy_framework-4.4.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,663 @@
1
+ """Workflow Explainer
2
+
3
+ Generates human-readable explanations of workflows, agents, and their behavior.
4
+ Supports multiple output formats and detail levels.
5
+
6
+ Features:
7
+ - Natural language workflow narratives
8
+ - Agent capability explanations
9
+ - Success criteria descriptions
10
+ - Technical vs non-technical audiences
11
+ - Multiple output formats (text, markdown, HTML)
12
+
13
+ Copyright 2026 Smart-AI-Memory
14
+ Licensed under Fair Source License 0.9
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import os
20
+ from dataclasses import dataclass
21
+ from enum import Enum
22
+ from typing import Any
23
+
24
+ from .blueprint import AgentRole, AgentSpec, StageSpec, WorkflowBlueprint
25
+ from .success import SuccessCriteria
26
+
27
+ # =============================================================================
28
+ # EXPLANATION LEVELS
29
+ # =============================================================================
30
+
31
+
32
+ class AudienceLevel(Enum):
33
+ """Target audience for explanations."""
34
+
35
+ TECHNICAL = "technical" # Developers, engineers
36
+ BUSINESS = "business" # Managers, stakeholders
37
+ BEGINNER = "beginner" # New users learning the system
38
+
39
+
40
+ class DetailLevel(Enum):
41
+ """Level of detail in explanations."""
42
+
43
+ BRIEF = "brief" # One-liner summary
44
+ STANDARD = "standard" # Normal explanation
45
+ DETAILED = "detailed" # Full technical details
46
+
47
+
48
+ class OutputFormat(Enum):
49
+ """Output format for explanations."""
50
+
51
+ TEXT = "text"
52
+ MARKDOWN = "markdown"
53
+ HTML = "html"
54
+ JSON = "json"
55
+
56
+
57
+ # =============================================================================
58
+ # DATA STRUCTURES
59
+ # =============================================================================
60
+
61
+
62
+ @dataclass
63
+ class Explanation:
64
+ """A generated explanation."""
65
+
66
+ title: str
67
+ summary: str
68
+ sections: list[dict[str, str]]
69
+ audience: AudienceLevel
70
+ detail_level: DetailLevel
71
+
72
+ def to_text(self) -> str:
73
+ """Convert to plain text."""
74
+ lines = [self.title, "=" * len(self.title), "", self.summary, ""]
75
+
76
+ for section in self.sections:
77
+ lines.append(section["heading"])
78
+ lines.append("-" * len(section["heading"]))
79
+ lines.append(section["content"])
80
+ lines.append("")
81
+
82
+ return "\n".join(lines)
83
+
84
+ def to_markdown(self) -> str:
85
+ """Convert to markdown."""
86
+ lines = [f"# {self.title}", "", self.summary, ""]
87
+
88
+ for section in self.sections:
89
+ lines.append(f"## {section['heading']}")
90
+ lines.append("")
91
+ lines.append(section["content"])
92
+ lines.append("")
93
+
94
+ return "\n".join(lines)
95
+
96
+ def to_html(self) -> str:
97
+ """Convert to HTML."""
98
+ html = [
99
+ "<article class='workflow-explanation'>",
100
+ f"<h1>{self.title}</h1>",
101
+ f"<p class='summary'>{self.summary}</p>",
102
+ ]
103
+
104
+ for section in self.sections:
105
+ html.append("<section>")
106
+ html.append(f"<h2>{section['heading']}</h2>")
107
+ html.append(f"<p>{section['content']}</p>")
108
+ html.append("</section>")
109
+
110
+ html.append("</article>")
111
+ return "\n".join(html)
112
+
113
+ def to_dict(self) -> dict[str, Any]:
114
+ """Convert to dictionary."""
115
+ return {
116
+ "title": self.title,
117
+ "summary": self.summary,
118
+ "sections": self.sections,
119
+ "audience": self.audience.value,
120
+ "detail_level": self.detail_level.value,
121
+ }
122
+
123
+
124
+ # =============================================================================
125
+ # ROLE DESCRIPTIONS
126
+ # =============================================================================
127
+
128
+
129
+ ROLE_DESCRIPTIONS = {
130
+ AudienceLevel.TECHNICAL: {
131
+ AgentRole.ANALYZER: "performs static analysis and data extraction",
132
+ AgentRole.REVIEWER: "evaluates code quality and adherence to standards",
133
+ AgentRole.AUDITOR: "conducts security and compliance audits",
134
+ AgentRole.GENERATOR: "generates new code, tests, or documentation",
135
+ AgentRole.FIXER: "automatically remediate identified issues",
136
+ AgentRole.ORCHESTRATOR: "coordinates multi-agent workflows",
137
+ AgentRole.RESEARCHER: "gathers information and context",
138
+ AgentRole.VALIDATOR: "validates outputs against specifications",
139
+ },
140
+ AudienceLevel.BUSINESS: {
141
+ AgentRole.ANALYZER: "examines the codebase to find patterns and issues",
142
+ AgentRole.REVIEWER: "checks code quality and best practices",
143
+ AgentRole.AUDITOR: "verifies security and compliance requirements",
144
+ AgentRole.GENERATOR: "creates new content automatically",
145
+ AgentRole.FIXER: "automatically corrects problems",
146
+ AgentRole.ORCHESTRATOR: "manages the overall process",
147
+ AgentRole.RESEARCHER: "collects relevant information",
148
+ AgentRole.VALIDATOR: "ensures outputs meet requirements",
149
+ },
150
+ AudienceLevel.BEGINNER: {
151
+ AgentRole.ANALYZER: "looks at your code to understand what it does",
152
+ AgentRole.REVIEWER: "checks if your code follows good practices",
153
+ AgentRole.AUDITOR: "makes sure your code is safe and follows the rules",
154
+ AgentRole.GENERATOR: "writes new code or documentation for you",
155
+ AgentRole.FIXER: "fixes problems it finds",
156
+ AgentRole.ORCHESTRATOR: "manages all the other helpers",
157
+ AgentRole.RESEARCHER: "finds information you need",
158
+ AgentRole.VALIDATOR: "double-checks that everything is correct",
159
+ },
160
+ }
161
+
162
+
163
+ # =============================================================================
164
+ # WORKFLOW EXPLAINER
165
+ # =============================================================================
166
+
167
+
168
+ class WorkflowExplainer:
169
+ """Generates human-readable workflow explanations."""
170
+
171
+ def __init__(
172
+ self,
173
+ audience: AudienceLevel = AudienceLevel.TECHNICAL,
174
+ detail_level: DetailLevel = DetailLevel.STANDARD,
175
+ use_llm: bool = False,
176
+ api_key: str | None = None,
177
+ ):
178
+ """Initialize the explainer.
179
+
180
+ Args:
181
+ audience: Target audience level
182
+ detail_level: Level of detail
183
+ use_llm: Whether to use LLM for richer explanations
184
+ api_key: API key for LLM (if use_llm=True)
185
+ """
186
+ self.audience = audience
187
+ self.detail_level = detail_level
188
+ self.use_llm = use_llm
189
+ self.api_key = api_key or os.environ.get("ANTHROPIC_API_KEY")
190
+ self._client = None
191
+
192
+ def explain_workflow(
193
+ self,
194
+ blueprint: WorkflowBlueprint,
195
+ success_criteria: SuccessCriteria | None = None,
196
+ ) -> Explanation:
197
+ """Generate explanation for a workflow.
198
+
199
+ Args:
200
+ blueprint: The workflow blueprint
201
+ success_criteria: Optional success criteria
202
+
203
+ Returns:
204
+ Explanation object
205
+ """
206
+ sections: list[dict[str, str]] = []
207
+
208
+ # Overview section
209
+ sections.append({
210
+ "heading": "Overview",
211
+ "content": self._explain_overview(blueprint),
212
+ })
213
+
214
+ # Agents section
215
+ sections.append({
216
+ "heading": "Agents Involved",
217
+ "content": self._explain_agents(blueprint.agents),
218
+ })
219
+
220
+ # Process section
221
+ sections.append({
222
+ "heading": "How It Works",
223
+ "content": self._explain_process(blueprint.stages, blueprint.agents),
224
+ })
225
+
226
+ # Success criteria section (if provided)
227
+ if success_criteria:
228
+ sections.append({
229
+ "heading": "Success Metrics",
230
+ "content": self._explain_success_criteria(success_criteria),
231
+ })
232
+
233
+ # Summary
234
+ summary = self._generate_summary(blueprint)
235
+
236
+ return Explanation(
237
+ title=f"Workflow: {blueprint.name}",
238
+ summary=summary,
239
+ sections=sections,
240
+ audience=self.audience,
241
+ detail_level=self.detail_level,
242
+ )
243
+
244
+ def explain_agent(self, agent: AgentSpec) -> Explanation:
245
+ """Generate explanation for a single agent.
246
+
247
+ Args:
248
+ agent: The agent specification
249
+
250
+ Returns:
251
+ Explanation object
252
+ """
253
+ sections: list[dict[str, str]] = []
254
+
255
+ # Role section
256
+ role_desc = ROLE_DESCRIPTIONS.get(self.audience, {}).get(
257
+ agent.role, "performs automated tasks"
258
+ )
259
+ sections.append({
260
+ "heading": "Role",
261
+ "content": f"This agent {role_desc}.",
262
+ })
263
+
264
+ # Capabilities section
265
+ sections.append({
266
+ "heading": "Capabilities",
267
+ "content": self._explain_tools(agent.tools),
268
+ })
269
+
270
+ # How it helps section
271
+ sections.append({
272
+ "heading": "How It Helps",
273
+ "content": self._explain_agent_value(agent),
274
+ })
275
+
276
+ summary = f"{agent.name} is a {agent.role.value} agent that {agent.description.lower()}"
277
+
278
+ return Explanation(
279
+ title=f"Agent: {agent.name}",
280
+ summary=summary,
281
+ sections=sections,
282
+ audience=self.audience,
283
+ detail_level=self.detail_level,
284
+ )
285
+
286
+ def _explain_overview(self, blueprint: WorkflowBlueprint) -> str:
287
+ """Generate workflow overview."""
288
+ if self.audience == AudienceLevel.BEGINNER:
289
+ return (
290
+ f"This workflow uses {len(blueprint.agents)} AI helpers to "
291
+ f"complete {len(blueprint.stages)} steps. "
292
+ f"It focuses on: {', '.join(blueprint.domains)}."
293
+ )
294
+ elif self.audience == AudienceLevel.BUSINESS:
295
+ return (
296
+ f"This automated workflow deploys {len(blueprint.agents)} specialized agents "
297
+ f"across {len(blueprint.stages)} execution stages. "
298
+ f"Target domains: {', '.join(blueprint.domains)}."
299
+ )
300
+ else:
301
+ return (
302
+ f"Multi-agent workflow with {len(blueprint.agents)} agents, "
303
+ f"{len(blueprint.stages)} stages. "
304
+ f"Domains: {', '.join(blueprint.domains)}. "
305
+ f"Created: {blueprint.created_at.strftime('%Y-%m-%d') if blueprint.created_at else 'N/A'}."
306
+ )
307
+
308
+ def _explain_agents(self, agents: list[AgentSpec]) -> str:
309
+ """Generate agents explanation."""
310
+ lines = []
311
+
312
+ for agent in agents:
313
+ role_desc = ROLE_DESCRIPTIONS.get(self.audience, {}).get(
314
+ agent.role, "works on the task"
315
+ )
316
+
317
+ if self.detail_level == DetailLevel.BRIEF:
318
+ lines.append(f"• {agent.name}: {role_desc}")
319
+ else:
320
+ tool_count = len(agent.tools)
321
+ tool_str = f" ({tool_count} tools)" if self.detail_level == DetailLevel.DETAILED else ""
322
+ lines.append(f"• **{agent.name}**{tool_str}: {agent.description}")
323
+
324
+ return "\n".join(lines)
325
+
326
+ def _explain_process(
327
+ self,
328
+ stages: list[StageSpec],
329
+ agents: list[AgentSpec],
330
+ ) -> str:
331
+ """Generate process explanation."""
332
+ agent_lookup = {a.agent_id: a for a in agents}
333
+ lines = []
334
+
335
+ for i, stage in enumerate(stages, 1):
336
+ agent_names = [
337
+ agent_lookup[aid].name
338
+ for aid in stage.agent_ids
339
+ if aid in agent_lookup
340
+ ]
341
+
342
+ if self.audience == AudienceLevel.BEGINNER:
343
+ if stage.parallel:
344
+ lines.append(
345
+ f"{i}. **{stage.name}**: {', '.join(agent_names)} work together at the same time"
346
+ )
347
+ else:
348
+ lines.append(
349
+ f"{i}. **{stage.name}**: {', '.join(agent_names)} work one after another"
350
+ )
351
+ else:
352
+ parallel_str = " (parallel)" if stage.parallel else ""
353
+ lines.append(
354
+ f"{i}. **{stage.name}**{parallel_str}: {', '.join(agent_names)}"
355
+ )
356
+
357
+ if self.detail_level == DetailLevel.DETAILED and stage.dependencies:
358
+ lines.append(f" Depends on: {', '.join(stage.dependencies)}")
359
+
360
+ return "\n".join(lines)
361
+
362
+ def _explain_tools(self, tools: list[Any]) -> str:
363
+ """Generate tools explanation."""
364
+ tool_explanations = {
365
+ "read_file": "read and analyze files",
366
+ "write_file": "create or modify files",
367
+ "grep_code": "search through code",
368
+ "analyze_ast": "understand code structure",
369
+ "run_linter": "check code style",
370
+ "run_tests": "execute test suites",
371
+ "security_scan": "detect vulnerabilities",
372
+ }
373
+
374
+ if self.detail_level == DetailLevel.BRIEF:
375
+ return f"This agent has access to {len(tools)} tools."
376
+
377
+ lines = ["This agent can:"]
378
+ for tool in tools:
379
+ tool_id = tool.tool_id if hasattr(tool, 'tool_id') else str(tool)
380
+ explanation = tool_explanations.get(tool_id, f"use {tool_id}")
381
+ lines.append(f"• {explanation}")
382
+
383
+ return "\n".join(lines)
384
+
385
+ def _explain_agent_value(self, agent: AgentSpec) -> str:
386
+ """Generate explanation of agent's value."""
387
+ value_by_role = {
388
+ AgentRole.ANALYZER: "identifying patterns, issues, and opportunities in your codebase",
389
+ AgentRole.REVIEWER: "ensuring code quality and catching problems before they reach production",
390
+ AgentRole.AUDITOR: "keeping your code secure and compliant with regulations",
391
+ AgentRole.GENERATOR: "saving time by automatically creating code, tests, or documentation",
392
+ AgentRole.FIXER: "automatically resolving issues without manual intervention",
393
+ AgentRole.ORCHESTRATOR: "managing complex workflows efficiently",
394
+ AgentRole.RESEARCHER: "providing relevant context and information",
395
+ AgentRole.VALIDATOR: "ensuring outputs meet quality standards",
396
+ }
397
+
398
+ base_value = value_by_role.get(agent.role, "automating important tasks")
399
+
400
+ if self.audience == AudienceLevel.BEGINNER:
401
+ return f"This helper saves you time by {base_value}."
402
+ else:
403
+ return f"This agent adds value by {base_value}."
404
+
405
+ def _explain_success_criteria(self, criteria: SuccessCriteria) -> str:
406
+ """Generate success criteria explanation."""
407
+ lines = ["The workflow is considered successful when:"]
408
+
409
+ for metric in criteria.metrics:
410
+ if self.audience == AudienceLevel.BEGINNER:
411
+ lines.append(f"• {metric.name}: {metric.description}")
412
+ else:
413
+ target = f" (target: {metric.target_value})" if metric.target_value is not None else ""
414
+ lines.append(f"• **{metric.name}**{target}: {metric.description}")
415
+
416
+ return "\n".join(lines)
417
+
418
+ def _generate_summary(self, blueprint: WorkflowBlueprint) -> str:
419
+ """Generate workflow summary."""
420
+ if self.audience == AudienceLevel.BEGINNER:
421
+ return (
422
+ f"This workflow automatically helps you with {', '.join(blueprint.domains)}. "
423
+ f"It uses {len(blueprint.agents)} AI helpers that work together in "
424
+ f"{len(blueprint.stages)} steps to get the job done."
425
+ )
426
+ elif self.audience == AudienceLevel.BUSINESS:
427
+ return (
428
+ f"{blueprint.description} "
429
+ f"The workflow orchestrates {len(blueprint.agents)} specialized agents "
430
+ f"to deliver results efficiently and consistently."
431
+ )
432
+ else:
433
+ return blueprint.description or f"A {len(blueprint.stages)}-stage workflow for {', '.join(blueprint.domains)}."
434
+
435
+ def generate_narrative(self, blueprint: WorkflowBlueprint) -> str:
436
+ """Generate a narrative story-like explanation.
437
+
438
+ Args:
439
+ blueprint: The workflow blueprint
440
+
441
+ Returns:
442
+ Narrative explanation string
443
+ """
444
+ agent_lookup = {a.agent_id: a for a in blueprint.agents}
445
+
446
+ lines = [
447
+ f"## The {blueprint.name} Story",
448
+ "",
449
+ f"*{blueprint.description}*",
450
+ "",
451
+ "---",
452
+ "",
453
+ ]
454
+
455
+ # Introduction
456
+ lines.append(
457
+ f"When you run this workflow, a team of {len(blueprint.agents)} specialized "
458
+ f"AI agents springs into action. Here's what happens:"
459
+ )
460
+ lines.append("")
461
+
462
+ # Walk through stages
463
+ for i, stage in enumerate(blueprint.stages, 1):
464
+ lines.append(f"### Step {i}: {stage.name}")
465
+ lines.append("")
466
+
467
+ agents_in_stage = [
468
+ agent_lookup[aid] for aid in stage.agent_ids if aid in agent_lookup
469
+ ]
470
+
471
+ if stage.parallel and len(agents_in_stage) > 1:
472
+ lines.append("Working in parallel:")
473
+ for agent in agents_in_stage:
474
+ role_desc = ROLE_DESCRIPTIONS.get(self.audience, {}).get(
475
+ agent.role, "works"
476
+ )
477
+ lines.append(f"- **{agent.name}** {role_desc}")
478
+ else:
479
+ for agent in agents_in_stage:
480
+ role_desc = ROLE_DESCRIPTIONS.get(self.audience, {}).get(
481
+ agent.role, "works"
482
+ )
483
+ lines.append(f"**{agent.name}** {role_desc}.")
484
+
485
+ lines.append("")
486
+
487
+ # Conclusion
488
+ lines.append("### The Result")
489
+ lines.append("")
490
+ lines.append(
491
+ "After all stages complete, you receive a comprehensive report with "
492
+ "findings, recommendations, and any automated fixes that were applied."
493
+ )
494
+
495
+ return "\n".join(lines)
496
+
497
+
498
+ # =============================================================================
499
+ # EXPLANATION GENERATOR (LLM-POWERED)
500
+ # =============================================================================
501
+
502
+
503
+ class LLMExplanationGenerator:
504
+ """Uses LLM to generate richer, more natural explanations."""
505
+
506
+ EXPLAIN_PROMPT = """Generate a clear, helpful explanation of this workflow for a {audience} audience.
507
+
508
+ Workflow: {name}
509
+ Description: {description}
510
+ Domains: {domains}
511
+ Agents: {agents}
512
+ Stages: {stages}
513
+
514
+ Write a {detail_level} explanation that:
515
+ 1. Explains what the workflow does in plain language
516
+ 2. Describes each agent's role
517
+ 3. Walks through the process step by step
518
+ 4. Highlights the value and benefits
519
+
520
+ Format as markdown with clear sections."""
521
+
522
+ def __init__(self, api_key: str | None = None):
523
+ """Initialize the generator.
524
+
525
+ Args:
526
+ api_key: Anthropic API key
527
+ """
528
+ self.api_key = api_key or os.environ.get("ANTHROPIC_API_KEY")
529
+ self._client = None
530
+
531
+ def _get_client(self):
532
+ """Lazy-load Anthropic client."""
533
+ if self._client is None and self.api_key:
534
+ try:
535
+ import anthropic
536
+ self._client = anthropic.Anthropic(api_key=self.api_key)
537
+ except ImportError:
538
+ pass
539
+ return self._client
540
+
541
+ def generate(
542
+ self,
543
+ blueprint: WorkflowBlueprint,
544
+ audience: AudienceLevel = AudienceLevel.BUSINESS,
545
+ detail_level: DetailLevel = DetailLevel.STANDARD,
546
+ ) -> str:
547
+ """Generate LLM-powered explanation.
548
+
549
+ Args:
550
+ blueprint: The workflow blueprint
551
+ audience: Target audience
552
+ detail_level: Level of detail
553
+
554
+ Returns:
555
+ Generated explanation markdown
556
+ """
557
+ client = self._get_client()
558
+ if not client:
559
+ # Fallback to rule-based explainer
560
+ explainer = WorkflowExplainer(audience=audience, detail_level=detail_level)
561
+ return explainer.explain_workflow(blueprint).to_markdown()
562
+
563
+ # Format workflow info for prompt
564
+ agents_str = "\n".join(
565
+ f"- {a.name} ({a.role.value}): {a.description}"
566
+ for a in blueprint.agents
567
+ )
568
+
569
+ stages_str = "\n".join(
570
+ f"- {s.name}: {', '.join(s.agent_ids)}"
571
+ + (" (parallel)" if s.parallel else "")
572
+ for s in blueprint.stages
573
+ )
574
+
575
+ prompt = self.EXPLAIN_PROMPT.format(
576
+ audience=audience.value,
577
+ name=blueprint.name,
578
+ description=blueprint.description,
579
+ domains=", ".join(blueprint.domains),
580
+ agents=agents_str,
581
+ stages=stages_str,
582
+ detail_level=detail_level.value,
583
+ )
584
+
585
+ try:
586
+ response = client.messages.create(
587
+ model="claude-3-5-haiku-20241022",
588
+ max_tokens=1500,
589
+ messages=[{"role": "user", "content": prompt}],
590
+ )
591
+ return response.content[0].text if response.content else ""
592
+ except Exception:
593
+ # Fallback
594
+ explainer = WorkflowExplainer(audience=audience, detail_level=detail_level)
595
+ return explainer.explain_workflow(blueprint).to_markdown()
596
+
597
+
598
+ # =============================================================================
599
+ # HIGH-LEVEL API
600
+ # =============================================================================
601
+
602
+
603
+ def explain_workflow(
604
+ blueprint: WorkflowBlueprint,
605
+ audience: AudienceLevel | str = AudienceLevel.BUSINESS,
606
+ detail_level: DetailLevel | str = DetailLevel.STANDARD,
607
+ format: OutputFormat | str = OutputFormat.MARKDOWN,
608
+ use_llm: bool = False,
609
+ ) -> str:
610
+ """Generate explanation for a workflow.
611
+
612
+ Args:
613
+ blueprint: The workflow blueprint
614
+ audience: Target audience (technical, business, beginner)
615
+ detail_level: Level of detail (brief, standard, detailed)
616
+ format: Output format (text, markdown, html, json)
617
+ use_llm: Whether to use LLM for richer explanations
618
+
619
+ Returns:
620
+ Formatted explanation string
621
+ """
622
+ # Convert string args to enums
623
+ if isinstance(audience, str):
624
+ audience = AudienceLevel(audience)
625
+ if isinstance(detail_level, str):
626
+ detail_level = DetailLevel(detail_level)
627
+ if isinstance(format, str):
628
+ format = OutputFormat(format)
629
+
630
+ if use_llm:
631
+ generator = LLMExplanationGenerator()
632
+ markdown = generator.generate(blueprint, audience, detail_level)
633
+
634
+ if format == OutputFormat.MARKDOWN:
635
+ return markdown
636
+ elif format == OutputFormat.TEXT:
637
+ # Simple markdown to text conversion
638
+ import re
639
+ text = re.sub(r'#{1,6}\s+', '', markdown) # Remove headers
640
+ text = re.sub(r'\*\*([^*]+)\*\*', r'\1', text) # Remove bold
641
+ text = re.sub(r'\*([^*]+)\*', r'\1', text) # Remove italic
642
+ return text
643
+ elif format == OutputFormat.HTML:
644
+ # Simple markdown to HTML
645
+ html = f"<div class='explanation'>{markdown}</div>"
646
+ return html
647
+ else:
648
+ return markdown
649
+
650
+ explainer = WorkflowExplainer(audience=audience, detail_level=detail_level)
651
+ explanation = explainer.explain_workflow(blueprint)
652
+
653
+ if format == OutputFormat.TEXT:
654
+ return explanation.to_text()
655
+ elif format == OutputFormat.MARKDOWN:
656
+ return explanation.to_markdown()
657
+ elif format == OutputFormat.HTML:
658
+ return explanation.to_html()
659
+ elif format == OutputFormat.JSON:
660
+ import json
661
+ return json.dumps(explanation.to_dict(), indent=2)
662
+ else:
663
+ return explanation.to_markdown()