darsoarafa commited on
Commit
88ca803
·
verified ·
1 Parent(s): bf6cff2

Create paper.py

Browse files
Files changed (1) hide show
  1. paper.py +199 -0
paper.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import logging
4
+ from datetime import datetime, timedelta
5
+ from langchain_google_genai import ChatGoogleGenerativeAI
6
+ from langchain.schema import SystemMessage, HumanMessage
7
+
8
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
9
+
10
+ class Agent:
11
+ def __init__(self, role: str, goal: str, backstory: str, personality: str = "", llm=None) -> None:
12
+ """
13
+ Initialize an Agent with role, goal, backstory, personality, and assigned LLM.
14
+ """
15
+ self.role = role
16
+ self.goal = goal
17
+ self.backstory = backstory
18
+ self.personality = personality
19
+ self.tools = [] # Initialize with empty list for future tool integrations
20
+ self.llm = llm
21
+
22
+ class Task:
23
+ def __init__(self, description: str, agent: Agent, expected_output: str, context=None) -> None:
24
+ """
25
+ Initialize a Task with its description, the responsible agent, expected output, and optional context.
26
+ """
27
+ self.description = description
28
+ self.agent = agent
29
+ self.expected_output = expected_output
30
+ self.context = context or []
31
+
32
+ google_api_key = os.getenv("GEMINI_API_KEY") # 실제 Google API 키 사용
33
+ if not google_api_key:
34
+ logging.error("GEMINI_API_KEY is not set in the environment variables.")
35
+ llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", google_api_key=google_api_key)
36
+
37
+ # -------------------------------------------------------------------------------
38
+ # Define Academic Research Agents
39
+ # -------------------------------------------------------------------------------
40
+ literature_research_agent = Agent(
41
+ role="Literature Research Agent",
42
+ goal="Research and provide a comprehensive review of existing literature on the research topic.",
43
+ backstory="An experienced academic researcher specialized in literature reviews and meta-analyses.",
44
+ personality="Analytical, thorough, and detail-oriented.",
45
+ llm=llm,
46
+ )
47
+
48
+ outline_agent = Agent(
49
+ role="Outline Agent",
50
+ goal="Generate a structured and detailed outline for a research paper based on the research topic and literature.",
51
+ backstory="A methodical academic planner who organizes research findings into coherent paper structures.",
52
+ personality="Organized, systematic, and insightful.",
53
+ llm=llm,
54
+ )
55
+
56
+ draft_writing_agent = Agent(
57
+ role="Draft Writing Agent",
58
+ goal="Compose a first draft of the research paper based on the literature review and outline.",
59
+ backstory="A skilled academic writer capable of synthesizing research findings into well-structured drafts.",
60
+ personality="Articulate, precise, and scholarly.",
61
+ llm=llm,
62
+ )
63
+
64
+ citation_agent = Agent(
65
+ role="Citation Agent",
66
+ goal="Generate a list of relevant citations and references in the required format for the research paper.",
67
+ backstory="A detail-oriented bibliographic expert with extensive knowledge of citation standards.",
68
+ personality="Meticulous, accurate, and research-savvy.",
69
+ llm=llm,
70
+ )
71
+
72
+ editing_agent = Agent(
73
+ role="Editing Agent",
74
+ goal="Revise and polish the draft for clarity, coherence, and academic tone.",
75
+ backstory="An expert editor skilled in improving academic manuscripts and ensuring high-quality presentation.",
76
+ personality="Critical, precise, and supportive.",
77
+ llm=llm,
78
+ )
79
+
80
+ chatbot_agent = Agent(
81
+ role="Chatbot Agent",
82
+ goal="Engage in interactive conversation to answer queries related to the academic research process.",
83
+ backstory="A conversational AI assistant with extensive knowledge in academia and research methodologies.",
84
+ personality="Helpful, conversational, and knowledgeable.",
85
+ llm=llm,
86
+ )
87
+
88
+ # -------------------------------------------------------------------------------
89
+ # Define Tasks for Academic Research and Writing
90
+ # -------------------------------------------------------------------------------
91
+ literature_research_task = Task(
92
+ description="""Research academic literature on {topic} considering the keywords {keywords}.
93
+
94
+ Please provide:
95
+ - A summary of the current state of research,
96
+ - Key trends and gaps in the literature,
97
+ - Notable studies and their findings,
98
+ - Relevant theoretical frameworks and methodologies.
99
+ Format the response with bullet points and concise summaries.""",
100
+ agent=literature_research_agent,
101
+ expected_output="""A comprehensive literature review summary covering:
102
+ 1. Summary of current research trends
103
+ 2. Identification of gaps and controversies
104
+ 3. Key studies with brief descriptions
105
+ 4. Theoretical frameworks and methodologies used"""
106
+ )
107
+
108
+ outline_task = Task(
109
+ description="""Based on the research topic {topic} and literature review findings, generate a detailed outline for a research paper.
110
+
111
+ Include sections such as:
112
+ - Abstract
113
+ - Introduction (including research questions and objectives)
114
+ - Literature Review
115
+ - Methodology
116
+ - Results/Findings
117
+ - Discussion
118
+ - Conclusion
119
+ - References
120
+ Format the outline in a structured manner with bullet points and subheadings.""",
121
+ agent=outline_agent,
122
+ expected_output="A structured outline for a research paper including all major sections and key points to cover in each section."
123
+ )
124
+
125
+ draft_writing_task = Task(
126
+ description="""Using the research topic {topic}, the literature review, and the generated outline, compose a first draft of the research paper.
127
+
128
+ The draft should include:
129
+ - A coherent narrative flow,
130
+ - Detailed sections as per the outline,
131
+ - Integration of key findings from the literature review.
132
+ Ensure the tone is academic and the content is well-organized.""",
133
+ agent=draft_writing_agent,
134
+ expected_output="A complete first draft of the research paper covering all sections with sufficient academic detail."
135
+ )
136
+
137
+ citation_task = Task(
138
+ description="""Based on the literature review for {topic}, generate a list of key references and citations in APA format.
139
+
140
+ Include:
141
+ - Author names, publication year, title, and source,
142
+ - At least 10 key references relevant to the research topic.
143
+ Format the output as a numbered list of citations.""",
144
+ agent=citation_agent,
145
+ expected_output="A list of 10+ relevant citations in APA format."
146
+ )
147
+
148
+ editing_task = Task(
149
+ description="""Review and edit the draft for clarity, coherence, and academic tone.
150
+
151
+ Focus on:
152
+ - Improving sentence structure,
153
+ - Ensuring logical flow between sections,
154
+ - Correcting grammar and stylistic issues,
155
+ - Enhancing academic tone.
156
+ Provide the polished version of the paper.""",
157
+ agent=editing_agent,
158
+ expected_output="A refined and polished version of the research paper draft."
159
+ )
160
+
161
+ chatbot_task = Task(
162
+ description="Provide a conversational and detailed response to academic research-related queries.",
163
+ agent=chatbot_agent,
164
+ expected_output="A friendly, informative response addressing the query."
165
+ )
166
+
167
+ def run_task(task: Task, input_text: str) -> str:
168
+ """
169
+ Executes the given task using the associated agent's LLM and returns the response content.
170
+ """
171
+ try:
172
+ if not isinstance(task, Task):
173
+ raise ValueError(f"Expected 'task' to be an instance of Task, got {type(task)}")
174
+ if not hasattr(task, 'agent') or not isinstance(task.agent, Agent):
175
+ raise ValueError("Task must have a valid 'agent' attribute of type Agent.")
176
+ system_input = (
177
+ f"Agent Details:\n"
178
+ f"Role: {task.agent.role}\n"
179
+ f"Goal: {task.agent.goal}\n"
180
+ f"Backstory: {task.agent.backstory}\n"
181
+ f"Personality: {task.agent.personality}\n"
182
+ )
183
+ task_input = (
184
+ f"Task Details:\n"
185
+ f"Task Description: {task.description}\n"
186
+ f"Expected Output: {task.expected_output}\n"
187
+ f"Input for Task:\n{input_text}\n"
188
+ )
189
+ messages = [
190
+ SystemMessage(content=system_input),
191
+ HumanMessage(content=task_input)
192
+ ]
193
+ response = task.agent.llm.invoke(messages)
194
+ if not response or not response.content:
195
+ raise ValueError("Empty response from LLM.")
196
+ return response.content
197
+ except Exception as e:
198
+ logging.error(f"Error in task '{task.agent.role}': {e}")
199
+ return f"Error in {task.agent.role}: {e}"