-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
314 lines (263 loc) · 11 KB
/
Copy pathmain.py
File metadata and controls
314 lines (263 loc) · 11 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
"""CLI entrypoint for the Multi-Agent Presentation Generator.
Supports two execution modes:
--mode workflow (default) Fixed pipeline: researcher → writer → validator → publisher
--mode agent Autonomous ReAct agent that decides the flow dynamically
Usage:
python main.py "My topic" # workflow mode
python main.py "My topic" --mode agent # agent mode
python main.py "My topic" --mode agent --dry-run # agent + dry run
"""
import asyncio
import argparse
import sys
from dotenv import load_dotenv
load_dotenv()
from langchain_core.messages import HumanMessage
from rich.console import Console
from rich.panel import Panel
from rich.prompt import Prompt
import agents.publisher as pub
from tools.gamma_mcp import GammaMCPManager
from utils.terminal import RunLogger, log_final_result, log_step, log_thinking, log_tool_call, set_logger
console = Console()
async def run_workflow(topic: str, args, gamma_mgr: GammaMCPManager):
"""Run the fixed workflow pipeline (original mode)."""
from graph import build_graph
pub.gamma_manager = gamma_mgr
app = build_graph()
initial_state = {
"topic": topic,
"expanded_topic": "",
"research_results": [],
"slide_outline": [],
"slide_content": "",
"num_slides": args.slides,
"validation_feedback": "",
"validation_passed": False,
"revision_count": 0,
"max_revisions": args.max_revisions,
"gamma_url": "",
"gamma_generation_id": "",
"messages": [],
"current_agent": "",
"status": "started",
"dry_run": args.dry_run,
}
config = {"configurable": {"thread_id": "webinar-demo"}}
async for event in app.astream(initial_state, config, stream_mode="updates"):
pass
final_snapshot = await app.aget_state(config)
return final_snapshot.values
async def run_agent(topic: str, args, gamma_mgr: GammaMCPManager):
"""Run the autonomous ReAct agent mode with Human-in-the-Loop support.
The agent may call interrupt() via request_human_approval, which pauses
execution. We detect this via state.tasks, prompt the user, and resume
with Command(resume=response).
"""
from langgraph.types import Command
from agent_graph import build_agent_graph, DEFAULT_RECURSION_LIMIT
from tools.agent_tools import configure_publisher, reset_counters
# Configure tools
reset_counters()
configure_publisher(gamma_mgr, args.dry_run)
app = build_agent_graph()
user_message = (
f"Create a presentation on the topic: {topic}\n"
f"Target: {args.slides} slides.\n"
f"Language: Ukrainian with English technical terms."
)
config = {
"configurable": {"thread_id": "webinar-demo-agent"},
"recursion_limit": DEFAULT_RECURSION_LIMIT,
}
log_step("Agent mode — LLM decides the execution flow", "info")
log_step(f"Safeguards: max {DEFAULT_RECURSION_LIMIT} iterations, max 8 searches", "info")
# The input for the first run
agent_input = {"messages": [HumanMessage(content=user_message)]}
while True:
# Stream agent execution
async for event in app.astream(agent_input, config, stream_mode="updates"):
_log_agent_event(event, args)
# Check if agent is interrupted (HITL)
state = await app.aget_state(config)
if state.tasks:
# Agent is paused at interrupt() — prompt the human
task = state.tasks[0]
interrupt_data = task.interrupts[0].value if task.interrupts else {}
question = interrupt_data.get("question", "Approve? (y/n/feedback)")
preview = interrupt_data.get("preview", "")
score = interrupt_data.get("score", "?")
reasoning = interrupt_data.get("reasoning", "")
# Extract slide titles from preview for a readable summary
import re as _re
slide_titles = _re.findall(r"^##\s+(.+)$", preview, _re.MULTILINE)
slides_summary = ""
if slide_titles:
slides_summary = "\n".join(
f" {i}. {t}" for i, t in enumerate(slide_titles, 1)
)
slides_summary = f"\n[bold]Slides:[/bold]\n{slides_summary}\n"
console.print()
console.print(Panel(
f"[bold]Score: {score}/10[/bold]\n"
f"{reasoning[:150] if reasoning else ''}\n"
f"{slides_summary}\n"
f"[dim]Full content is visible in the scrollback above.[/dim]\n\n"
f"[bold]'approve' = publish | 'reject' = stop | text = revision feedback[/bold]",
title="[bold red]HUMAN REVIEW REQUIRED[/bold red]",
border_style="red",
width=min(console.width, 90),
))
human_input = Prompt.ask("[bold]Your decision[/bold]")
# Resume the agent with the human's response
agent_input = Command(resume=human_input)
else:
# Agent finished normally — no interrupt pending
break
final_snapshot = await app.aget_state(config)
return final_snapshot.values
def _log_agent_event(event: dict, args):
"""Process and log a single agent stream event."""
if "agent" not in event:
return
msgs = event["agent"].get("messages", [])
for msg in msgs:
# Show agent's thinking/reasoning text
if hasattr(msg, "content") and msg.content:
if hasattr(msg, "tool_calls") and msg.tool_calls:
log_thinking(msg.content)
elif not hasattr(msg, "tool_calls") or not msg.tool_calls:
log_thinking(msg.content)
# Show tool calls
if hasattr(msg, "tool_calls") and msg.tool_calls:
for tc in msg.tool_calls:
tc_args = tc.get("args", {})
key_arg = ""
if tc["name"] == "search_web":
key_arg = tc_args.get("query", "")[:60]
elif tc["name"] == "classify_topic":
key_arg = tc_args.get("topic", "")[:40]
elif tc["name"] == "generate_variants":
key_arg = f"{tc_args.get('num_slides', 10)} slides"
elif tc["name"] == "evaluate_and_select":
key_arg = "comparing variants"
elif tc["name"] == "request_human_approval":
key_arg = f"score {tc_args.get('score', '?')}/10"
elif tc["name"] == "publish_to_gamma":
key_arg = f"{tc_args.get('num_slides', 10)} slides"
log_tool_call(tc["name"], key_arg)
async def main():
parser = argparse.ArgumentParser(
description="Multi-Agent Presentation Generator"
)
parser.add_argument("topic", nargs="*", help="Presentation topic")
parser.add_argument(
"--mode",
choices=["workflow", "agent"],
default="workflow",
help="Execution mode: 'workflow' (fixed pipeline) or 'agent' (autonomous). Default: workflow",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Skip Gamma publishing, output markdown only",
)
parser.add_argument(
"--slides", type=int, default=10, help="Number of slides (default: 10)"
)
parser.add_argument(
"--max-revisions", type=int, default=2,
help="Max revision cycles in workflow mode (default: 2)",
)
args = parser.parse_args()
mode_label = "Agent (autonomous)" if args.mode == "agent" else "Workflow (fixed pipeline)"
console.print(
Panel(
f"[bold cyan]Multi-Agent Presentation Generator[/bold cyan]\n"
f"[dim]Mode: {mode_label} | Powered by LangGraph + OpenAI + Gamma MCP[/dim]",
expand=False,
)
)
topic = " ".join(args.topic) if args.topic else Prompt.ask(
"[bold]Enter presentation topic[/bold]"
)
if not topic or len(topic.strip()) < 5:
console.print("[red]Topic too short. Please provide more detail.[/red]")
sys.exit(1)
console.print(f"\n[bold green]Starting {args.mode} pipeline for:[/bold green] {topic}\n")
# Initialize logger
logger = RunLogger()
set_logger(logger)
logger.write(f"Mode: {args.mode}")
logger.write(f"Topic: {topic}")
logger.write(f"Slides: {args.slides}, Dry run: {args.dry_run}")
# Initialize Gamma MCP (unless dry run)
gamma_mgr = GammaMCPManager()
if not args.dry_run:
try:
await gamma_mgr.connect()
except Exception as e:
console.print(
f"[yellow]Warning: Could not connect to Gamma MCP: {e}[/yellow]"
)
console.print("[yellow]Will fall back to markdown output.[/yellow]\n")
try:
if args.mode == "agent":
final_state = await run_agent(topic, args, gamma_mgr)
# In agent mode, check the last message for gamma URL
messages = final_state.get("messages", [])
gamma_url = ""
for msg in reversed(messages):
content = msg.content if hasattr(msg, "content") else str(msg)
if "gamma.app" in content:
import re
url_match = re.search(r"https://[^\s\"']+gamma\.app[^\s\"']*", content)
if url_match:
gamma_url = url_match.group(0)
break
if "DRY_RUN" in content:
gamma_url = "DRY_RUN"
break
if "FALLBACK" in content:
gamma_url = "FALLBACK_MARKDOWN"
break
else:
final_state = await run_workflow(topic, args, gamma_mgr)
gamma_url = final_state.get("gamma_url", "")
# Display final result
non_url_values = ("DRY_RUN", "FALLBACK_MARKDOWN", "TIMEOUT", "")
if gamma_url and gamma_url not in non_url_values:
log_final_result(
url=gamma_url,
num_slides=args.slides,
theme="Pearl",
)
elif gamma_url == "DRY_RUN" or args.dry_run:
console.print(
Panel(
"[bold yellow]DRY RUN complete.[/bold yellow] "
"Markdown content printed above.",
expand=False,
)
)
elif gamma_url == "FALLBACK_MARKDOWN":
console.print(
Panel(
"[bold yellow]Gamma unavailable — markdown fallback printed above.[/bold yellow]",
expand=False,
)
)
else:
console.print(
Panel(
"[bold yellow]Pipeline complete.[/bold yellow] "
"Check output above for results.",
expand=False,
)
)
finally:
await gamma_mgr.disconnect()
console.print(f"\n[dim]Run log saved to: {logger.path}[/dim]")
logger.close()
if __name__ == "__main__":
asyncio.run(main())