-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
130 lines (108 loc) · 4.5 KB
/
Copy pathmain.py
File metadata and controls
130 lines (108 loc) · 4.5 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
from langchain_core.runnables import RunnableConfig
from langgraph.types import Command
from rich.console import Console
from rich.panel import Panel
from rich.progress import Progress, SpinnerColumn, TextColumn
from agentic_workflow.shared.state.main_state import AgentState
from agentic_workflow.graph import graph
from data_layer.database.crud import ReviewDB
from agentic_workflow.shared.utils.logging_utils import setup_logging
from agentic_workflow.shared.utils.callbacks import RichProgressCallbackHandler
from dotenv import load_dotenv
from pathlib import Path
import os
import asyncio
import uuid
import logging
# Setup logging
setup_logging()
logger = logging.getLogger(__name__)
async def run_workflow_async(init_state, graph_instance, config, console: Console):
current_input = init_state
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console,
) as progress:
task_id = progress.add_task("Agent is running...", total=None)
# Setup callback handler
callback_handler = RichProgressCallbackHandler(progress, task_id)
config['callbacks'] = [callback_handler]
while True:
result = await graph_instance.ainvoke(current_input, config)
logger.debug(f"Graph returned. Keys in result: {list(result.keys())}")
if "__interrupt__" in result:
progress.stop()
query = result["__interrupt__"][0].value["query"]
console.print(Panel(query, title="[bold yellow]Human Input Required[/bold yellow]"))
answer = await asyncio.get_event_loop().run_in_executor(None, console.input, "Please provide the answer: ")
current_input = Command(resume={"data": answer})
progress.start()
continue
return result
def main():
load_dotenv(
Path(__file__).resolve().parent / ".env",
override=False,
)
console = Console()
console.print(Panel("Literature Review Agent", style="bold blue", expand=False))
topic = console.input("Enter the research topic: ")
paper_recency = console.input("Enter paper recency (e.g., 'after 2023', 'last 2 years'): ")
# Initialize database and create new review
db = ReviewDB()
review = db.create_review(
topic=topic,
paper_recency=paper_recency,
orchestrator_model=os.getenv("ORCHESTRATOR_MODEL", "openai/gpt-4o"),
text_model=os.getenv("TEXT_MODEL", "openai/gpt-4-turbo"),
embedding_model=os.getenv("EMBEDDING_MODEL", "qwen/qwen3-embedding-8b")
)
console.print(Panel(
f"Review ID: {review.id}\nTopic: {topic}",
title="[bold green]Starting New Literature Review[/bold green]",
expand=False
))
init_state = AgentState(
review_id=review.id,
topic=topic,
paper_recency=paper_recency,
completed=False,
messages=[],
search_queries=[],
plan=None
)
thread_id = str(uuid.uuid4())
graph_config = RunnableConfig(
recursion_limit=200,
configurable={"thread_id": thread_id}
)
final_state_dict = asyncio.run(run_workflow_async(init_state, graph, graph_config, console))
final_state = AgentState(**final_state_dict)
if final_state.plan is None:
console.print(Panel("No plan was generated. The review process failed.", style="bold red"))
latest_msg = final_state.messages[-1] if final_state.messages else "No messages in final state."
logger.error(f"Review failed. Last message: {latest_msg}")
db.update_review_status(review.id, 'failed')
else:
if final_state.completed:
db.update_review_status(review.id, 'completed')
db.update_review_metrics(
review.id,
total_sections=len(final_state.literature_survey),
total_papers_used=len(db.get_papers_for_review(review.id))
)
# Display LaTeX export path if available
if final_state.latex_export_path:
console.print(Panel(
f"LaTeX export: {final_state.latex_export_path}",
title="[bold cyan]📄 LaTeX Export[/bold cyan]",
expand=False
))
console.print(Panel(
f"Review ID: {review.id}",
title="[bold green]✓ Review Completed and Saved[/bold green]",
expand=False
))
if __name__ == "__main__":
main()