File size: 2,583 Bytes
57fa15f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Running the seven-agent crew for one chapter.

Ported from cell 15. The notebook writes two JSON files beside the notebook and
returns the result; here the step persists the result and nothing depends on a
working directory surviving between steps.

The crew stays one crew. Each specialist task carries `context=[task_analysis]`
and its prompt says "استخدم تحليل الفصل المرفق في السياق" - split into separate
crews, that context would not be there and the instruction would point at
nothing. So the analysis and the six specialists run together, as designed.
"""

from __future__ import annotations

from typing import Any

from crewai import Crew, Process

from app.agents.appendix.agents import (
    agent_analyzer,
    agent_case_study,
    agent_checklist,
    agent_indicators,
    agent_reflection,
    agent_scenarios,
    agent_tools,
)
from app.agents.appendix.tasks import build_tasks


def _pydantic_to_dict(pyd_obj: Any) -> dict:
    if pyd_obj is None:
        return {}
    if hasattr(pyd_obj, "model_dump"):
        return pyd_obj.model_dump()
    return pyd_obj.dict()


async def generate_chapter_appendix(
    chapter_title: str, chapter_text: str, on_progress=None
) -> dict:
    tasks = build_tasks(chapter_title, chapter_text)
    agents = [agent_analyzer(), agent_tools(), agent_reflection(), agent_scenarios(),
              agent_case_study(), agent_checklist(), agent_indicators()]

    crew = Crew(
        agents=agents,
        tasks=tasks,
        process=Process.sequential,
        verbose=True,
    )

    if on_progress:
        on_progress("تحليل الفصل وتوزيع المهام", 0.1)

    await crew.kickoff_async()

    # tasks[0] = تحليل الفصل (سياق داخلي) / tasks[1:] = الأقسام الستة النهائية
    analysis = _pydantic_to_dict(tasks[0].output.pydantic)

    return {
        "chapter_title": chapter_title,
        # Kept rather than discarded: the notebook writes it to a second file
        # "للمراجعة فقط", and it is the only way to see what the distributor
        # told the six specialists to write about.
        "analysis": analysis,
        "tools": _pydantic_to_dict(tasks[1].output.pydantic),
        "reflection_cards": _pydantic_to_dict(tasks[2].output.pydantic),
        "scenarios": _pydantic_to_dict(tasks[3].output.pydantic),
        "case_study": _pydantic_to_dict(tasks[4].output.pydantic),
        "checklist": _pydantic_to_dict(tasks[5].output.pydantic),
        "indicators": _pydantic_to_dict(tasks[6].output.pydantic),
    }