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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
# main.py

import argparse
import asyncio
import os
import warnings
from datetime import datetime
from typing import AsyncGenerator, Generator

from orchestrator.research_orchestrator import ResearchOrchestrator, StreamingManager
from save_to_pdf import save_draft_to_pdf
from streaming_config import (
    get_astream_config,
    get_streaming_config,
    is_astream_enabled,
    print_streaming_help,
)

warnings.filterwarnings("ignore")

# Workaround for Windows platform detection issue
import platform

if platform.system() == "Windows":
    os.environ["OPENAI_SKIP_PLATFORM_HEADERS"] = "1"

def validate_environment():
    """Validate that OPENAI_API_KEY is set in the environment/.env."""
    return bool(os.getenv("OPENAI_API_KEY"))

def sanitize_filename(name: str) -> str:
    """Sanitize string to be a valid filename on all OSes."""
    import re
    name = name.strip().replace('\n', ' ')
    name = re.sub(r'[\\/:*?"<>|]', '', name)  # Remove invalid filename chars
    name = name.replace("'", "")
    name = name[:100]  # Limit length
    return name

def yield_progress_updates(total_steps: int) -> Generator[str, None, None]:
    """
    Yield progress update messages for workflow steps
    
    Args:
        total_steps: Total number of workflow steps
        
    Yields:
        str: Progress update messages
    """
    steps = [
        "Topic Analysis",
        "Research Retrieval", 
        "Outline Building",
        "Human Feedback",
        "Draft Writing",
        "Bibliography Generation"
    ]
    
    for i, step in enumerate(steps[:total_steps]):
        progress = (i / total_steps) * 100
        yield f"πŸ”„ Progress: {progress:.1f}% - {step}"
    
    yield "βœ… Progress: 100% - Workflow Complete"

async def astream_progress_updates(total_steps: int) -> AsyncGenerator[str, None]:
    """
    AStream progress update messages for workflow steps
    
    Args:
        total_steps: Total number of workflow steps
        
    Yields:
        str: Progress update messages asynchronously
    """
    steps = [
        "Topic Analysis",
        "Research Retrieval", 
        "Outline Building",
        "Human Feedback",
        "Draft Writing",
        "Bibliography Generation"
    ]
    
    for i, step in enumerate(steps[:total_steps]):
        progress = (i / total_steps) * 100
        yield f"πŸš€ AStream Progress: {progress:.1f}% - {step}"
        await asyncio.sleep(0.1)  # Small delay for async processing
    
    yield "βœ… AStream Progress: 100% - Workflow Complete"

def yield_workflow_status(status_data: dict) -> Generator[str, None, None]:
    """
    Yield workflow status information
    
    Args:
        status_data: Dictionary containing workflow status
        
    Yields:
        str: Status information strings
    """
    if "topic" in status_data:
        yield f"πŸ“ Topic: {status_data['topic']}"
    
    if "refined_topic" in status_data:
        yield f"🎯 Refined Topic: {status_data['refined_topic']}"
    
    if "current_step" in status_data:
        yield f"πŸ”„ Current Step: {status_data['current_step']}"
    
    if "workflow_status" in status_data:
        yield f"πŸ“Š Workflow Status: {status_data['workflow_status']}"

async def astream_workflow_status(status_data: dict) -> AsyncGenerator[str, None]:
    """
    AStream workflow status information
    
    Args:
        status_data: Dictionary containing workflow status
        
    Yields:
        str: Status information strings asynchronously
    """
    if "topic" in status_data:
        yield f"πŸ“ AStream Topic: {status_data['topic']}"
        await asyncio.sleep(0.01)
    
    if "refined_topic" in status_data:
        yield f"🎯 AStream Refined Topic: {status_data['refined_topic']}"
        await asyncio.sleep(0.01)
    
    if "current_step" in status_data:
        yield f"πŸ”„ AStream Current Step: {status_data['current_step']}"
        await asyncio.sleep(0.01)
    
    if "workflow_status" in status_data:
        yield f"πŸ“Š AStream Workflow Status: {status_data['workflow_status']}"
        await asyncio.sleep(0.01)

def yield_error_details(error_info: dict) -> Generator[str, None, None]:
    """
    Yield detailed error information
    
    Args:
        error_info: Dictionary containing error details
        
    Yields:
        str: Error detail strings
    """
    if "error" in error_info:
        yield f"❌ Error: {error_info['error']}"
    
    if "step" in error_info:
        yield f"πŸ“ Failed Step: {error_info['step']}"
    
    if "timestamp" in error_info:
        yield f"⏰ Error Time: {error_info['timestamp']}"

async def astream_error_details(error_info: dict) -> AsyncGenerator[str, None]:
    """
    AStream detailed error information
    
    Args:
        error_info: Dictionary containing error details
        
    Yields:
        str: Error detail strings asynchronously
    """
    if "error" in error_info:
        yield f"❌ AStream Error: {error_info['error']}"
        await asyncio.sleep(0.01)
    
    if "step" in error_info:
        yield f"πŸ“ AStream Failed Step: {error_info['step']}"
        await asyncio.sleep(0.01)
    
    if "timestamp" in error_info:
        yield f"⏰ AStream Error Time: {error_info['timestamp']}"
        await asyncio.sleep(0.01)

def handle_human_feedback(interrupt_data):
    """Handle human feedback from native LangGraph interrupt"""
    
    # Extract the interrupt information
    interrupt_type = interrupt_data.get("type", "unknown")
    interrupt_payload = interrupt_data.get("payload", {})
    
    print(f"πŸ“‹ Interrupt Type: {interrupt_type}")
    
    # Display the outline
    if "outline" in interrupt_payload:
        print("\nπŸ“‹ GENERATED OUTLINE:")
        print("-" * 40)
        print(interrupt_payload["outline"])
        print("-" * 40)
    
    # Display the message and options
    if "message" in interrupt_payload:
        print(f"\n❓ {interrupt_payload['message']}")
    
    if "options" in interrupt_payload:
        print("\nπŸ“ Available options:")
        for key, description in interrupt_payload["options"].items():
            print(f"   β€’ {key}: {description}")
    
    # Keep asking until we get a valid response
    while True:
        print("\n" + "-" * 40)
        choice = input("Your response (approve/revise/reject): ").strip().lower()
        
        # Handle empty input gracefully
        if not choice.strip():
            print("⚠️  No response provided. Please enter 'approve', 'revise', or 'reject'.")
            print("   You can also use shortcuts: 'a' for approve, 'v' for revise, 'r' for reject")
            print("   Or type 'quit' to abort the workflow.")
            continue
        
        # Handle different response types
        if choice in ["approve", "a"]:
            response = {
                "response": "approve",
                "feedback": ""
            }
            return response
        elif choice in ["reject", "r", "abort"]:
            return {
                "response": "reject",
                "feedback": ""
            }
        elif choice in ["revise", "v"]:
            print("\nπŸ“ Please provide specific feedback for revision:")
            feedback = input("Feedback: ").strip()
            if not feedback:
                print("⚠️  No feedback provided. Please provide specific feedback or choose 'approve' to proceed.")
                continue
            return {
                "response": "revise",
                "feedback": feedback
            }
        elif choice == "quit" or choice == "exit":
            print("❌ Workflow aborted by user.")
            return {
                "response": "reject",
                "feedback": ""
            }
        else:
            print(f"⚠️  Invalid response: '{choice}'. Please enter 'approve', 'revise', or 'reject'.")
            print("   You can also use shortcuts: 'a' for approve, 'v' for revise, 'r' for reject")
            print("   Or type 'quit' to abort the workflow.")

async def process_workflow_with_astream(topic: str, streaming_config: dict) -> AsyncGenerator[str, None]:
    """
    Process the research workflow using AStream for enhanced async processing
    
    Args:
        topic: Research topic
        streaming_config: Streaming configuration
        
    Yields:
        str: Progress and status updates asynchronously
    """
    try:
        # Validate environment
        if not validate_environment():
            yield "❌ Environment validation failed"
            return
        
        yield f"πŸš€ Starting AStream research workflow for topic: {topic}"
        
        # Check if AStream is enabled
        astream_enabled = is_astream_enabled(streaming_config.get("preset"))
        if astream_enabled:
            yield "⚑ AStream processing enabled"
            astream_config = get_astream_config(streaming_config.get("preset"))
            yield f"πŸ“Š AStream config: delay={astream_config['delay']}s, buffer_size={astream_config['buffer_size']}"
        else:
            yield "ℹ️  AStream processing disabled, using standard streaming"
        
        # Create streaming manager for real-time display
        streaming_manager = StreamingManager(
            stream_delay=streaming_config["stream_delay"],
            config=streaming_config
        )
        
        # Create orchestrator with streaming support
        orchestrator = ResearchOrchestrator(stream_callback=streaming_manager.handle_stream_event)
        
        # Start the async workflow
        result = await orchestrator.run(topic)
        
        # Handle interrupt if workflow was interrupted
        while result.get("status") == "interrupted":
            yield "⏸️  AStream workflow paused for human feedback"
            
            # Handle the interrupt
            interrupt_data = result.get("interrupt_data", {})
            current_state = result.get("current_state", {})
            
            # Create interrupt data structure for the handler
            interrupt_payload = {
                "type": "outline_approval",
                "payload": {
                    "outline": current_state.get("outline", ""),
                    "topic": current_state.get("refined_topic", ""),
                    "message": "Please review the generated outline and provide feedback",
                    "options": {
                        "approve": "Approve the outline and proceed to draft writing",
                        "revise": "Request revisions to the outline",
                        "reject": "Reject and abort the workflow"
                    }
                }
            }
            
            human_response = handle_human_feedback(interrupt_payload)
            
            # Resume the workflow
            yield "πŸ”„ Resuming AStream workflow with user feedback..."
            
            # Pass the full response string that includes feedback if needed
            if human_response["response"] == "revise" and human_response["feedback"]:
                human_input = f"revise {human_response['feedback']}"
            else:
                human_input = human_response["response"]
            
            result = await orchestrator.resume(result["thread_id"], human_input)
        
        # Check if workflow completed successfully
        if result.get("status") == "completed":
            # Get the result data from the new orchestrator structure
            result_data = result.get("result", {})
            
            # Check if workflow was aborted (rejected by user)
            if result_data.get("workflow_status") == "aborted":
                yield "❌ AStream workflow was rejected by user. No PDF will be generated."
                return
            
            yield "βœ… AStream workflow completed successfully!"
            
            # Generate PDF with draft and bibliography
            safe_topic = sanitize_filename(result_data.get('refined_topic', topic))
            draft_pdf_filename = f"data/{safe_topic}.pdf"
            draft_text = result_data.get("draft") or ""
            bibliography = result_data.get("bibliography") or ""
            
            if not draft_text.strip():
                yield "⚠️  Warning: Draft is empty. PDF will be blank."
            
            # Ensure data directory exists
            os.makedirs("data", exist_ok=True)
            
            try:
                save_draft_to_pdf(
                    result_data.get('refined_topic', topic), 
                    draft_text, 
                    bibliography, 
                    draft_pdf_filename
                )
                yield f"βœ… AStream research paper saved successfully!"
                yield f"πŸ“„ File: {draft_pdf_filename}"
                yield f"πŸ“ Draft length: {len(draft_text)} characters"
                yield f"πŸ“š Bibliography length: {len(bibliography)} characters"
                yield f"πŸ“š Number of references: {bibliography.count('[')}"
            except Exception as e:
                yield f"❌ Error saving PDF: {e}"
        
        elif result.get("status") == "error":
            yield f"❌ AStream workflow error: {result.get('error', 'Unknown error')}"
        
        else:
            yield f"❌ Unexpected AStream workflow status: {result.get('status', 'unknown')}"
            
    except ValueError as e:
        yield f"❌ AStream configuration error: {e}"
    except Exception as e:
        yield f"❌ Unexpected AStream error: {e}"
        import traceback
        traceback.print_exc()

async def process_workflow_with_yield(topic: str, streaming_config: dict) -> AsyncGenerator[str, None]:
    """
    Process the research workflow using yield generators for progressive updates
    
    Args:
        topic: Research topic
        streaming_config: Streaming configuration
        
    Yields:
        str: Progress and status updates
    """
    try:
        # Validate environment
        if not validate_environment():
            yield "❌ Environment validation failed"
            return
        
        yield f"πŸš€ Starting research workflow for topic: {topic}"
        
        # Create streaming manager for real-time display
        streaming_manager = StreamingManager(
            stream_delay=streaming_config["stream_delay"],
            config=streaming_config
        )
        
        # Create orchestrator with streaming support
        orchestrator = ResearchOrchestrator(stream_callback=streaming_manager.handle_stream_event)
        
        # Start the async workflow
        result = await orchestrator.run(topic)
        
        # Handle interrupt if workflow was interrupted
        while result.get("status") == "interrupted":
            yield "⏸️  Workflow paused for human feedback"
            
            # Handle the interrupt
            interrupt_data = result.get("interrupt_data", {})
            current_state = result.get("current_state", {})
            
            # Create interrupt data structure for the handler
            interrupt_payload = {
                "type": "outline_approval",
                "payload": {
                    "outline": current_state.get("outline", ""),
                    "topic": current_state.get("refined_topic", ""),
                    "message": "Please review the generated outline and provide feedback",
                    "options": {
                        "approve": "Approve the outline and proceed to draft writing",
                        "revise": "Request revisions to the outline",
                        "reject": "Reject and abort the workflow"
                    }
                }
            }
            
            human_response = handle_human_feedback(interrupt_payload)
            
            # Resume the workflow
            yield "πŸ”„ Resuming workflow with user feedback..."
            
            # Pass the full response string that includes feedback if needed
            if human_response["response"] == "revise" and human_response["feedback"]:
                human_input = f"revise {human_response['feedback']}"
            else:
                human_input = human_response["response"]
            
            result = await orchestrator.resume(result["thread_id"], human_input)
        
        # Check if workflow completed successfully
        if result.get("status") == "completed":
            # Get the result data from the new orchestrator structure
            result_data = result.get("result", {})
            
            # Check if workflow was aborted (rejected by user)
            if result_data.get("workflow_status") == "aborted":
                yield "❌ Workflow was rejected by user. No PDF will be generated."
                return
            
            yield "βœ… Workflow completed successfully!"
            
            # Generate PDF with draft and bibliography
            safe_topic = sanitize_filename(result_data.get('refined_topic', topic))
            draft_pdf_filename = f"data/{safe_topic}.pdf"
            draft_text = result_data.get("draft") or ""
            bibliography = result_data.get("bibliography") or ""
            
            if not draft_text.strip():
                yield "⚠️  Warning: Draft is empty. PDF will be blank."
            
            # Ensure data directory exists
            os.makedirs("data", exist_ok=True)
            
            try:
                save_draft_to_pdf(
                    result_data.get('refined_topic', topic), 
                    draft_text, 
                    bibliography, 
                    draft_pdf_filename
                )
                yield f"βœ… Research paper saved successfully!"
                yield f"πŸ“„ File: {draft_pdf_filename}"
                yield f"πŸ“ Draft length: {len(draft_text)} characters"
                yield f"πŸ“š Bibliography length: {len(bibliography)} characters"
                yield f"πŸ“š Number of references: {bibliography.count('[')}"
            except Exception as e:
                yield f"❌ Error saving PDF: {e}"
        
        elif result.get("status") == "error":
            yield f"❌ Workflow error: {result.get('error', 'Unknown error')}"
        
        else:
            yield f"❌ Unexpected workflow status: {result.get('status', 'unknown')}"
            
    except ValueError as e:
        yield f"❌ Configuration error: {e}"
    except Exception as e:
        yield f"❌ Unexpected error: {e}"
        import traceback
        traceback.print_exc()

async def main(streaming_preset=None):
    """Main async function to run the research workflow with AStream support"""
    try:
        # Validate environment
        validate_environment()
        
        topic = input("Enter your research topic: ").strip()
        
        if not topic:
            print("No topic provided.")
            return
        
        # Get streaming configuration
        streaming_config = get_streaming_config(streaming_preset)
        
        # Add preset to config for AStream detection
        streaming_config["preset"] = streaming_preset
        
        print(f"\n🎯 Research Topic: {topic}")
        
        # Check AStream status
        # if is_astream_enabled(streaming_preset):
        #     print("⚑ AStream processing: ENABLED")
        #     astream_config = get_astream_config(streaming_preset)
        #     print(f"πŸ“Š AStream settings: delay={astream_config['delay']}s, realtime={astream_config['realtime']}")
        # else:
        #     print("ℹ️  AStream processing: DISABLED")
        
        print("=" * 60)
        
        # Choose processing method based on AStream availability
        if is_astream_enabled(streaming_preset):
            # Use AStream processing
            async for update in process_workflow_with_astream(topic, streaming_config):
                print(update)
        else:
            # Use standard yield processing
            async for update in process_workflow_with_yield(topic, streaming_config):
                print(update)
            
    except KeyboardInterrupt:
        print("\n❌ Workflow interrupted by user.")
    except Exception as e:
        print(f"❌ Unexpected error: {e}")
        import traceback
        traceback.print_exc()

def run_main():
    """Wrapper function to run the async main function"""
    # Parse command line arguments
    parser = argparse.ArgumentParser(description="AI Research Paper Generator with Yield and AStream Support")
    parser.add_argument(
        "--streaming", 
        choices=["fast", "slow", "none", "yield", "astream", "default"],
        default="default",
        help="Streaming speed preset: fast, slow, none, yield, astream, or default"
    )
    parser.add_argument(
        "--help-streaming",
        action="store_true",
        help="Show detailed streaming configuration help"
    )
    
    args = parser.parse_args()
    
    # Show streaming help if requested
    if args.help_streaming:
        print_streaming_help()
        return
    
    # Convert "default" to None for the function
    preset = None if args.streaming == "default" else args.streaming
    
    # Run the main function with the specified streaming preset
    asyncio.run(main(streaming_preset=preset))

if __name__ == "__main__":
    run_main()