File size: 8,203 Bytes
80cb626
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import json
import logging
from datetime import datetime, timedelta
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain.schema import SystemMessage, HumanMessage

logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")

class Agent:
    def __init__(self, role: str, goal: str, backstory: str, personality: str = "", llm=None) -> None:
        """
        Initialize an Agent with role, goal, backstory, personality, and assigned LLM.
        """
        self.role = role
        self.goal = goal
        self.backstory = backstory
        self.personality = personality
        self.tools = []  # Initialize with empty list for future tool integrations
        self.llm = llm

class Task:
    def __init__(self, description: str, agent: Agent, expected_output: str, context=None) -> None:
        """
        Initialize a Task with its description, the responsible agent, expected output, and optional context.
        """
        self.description = description
        self.agent = agent
        self.expected_output = expected_output
        self.context = context or []

google_api_key = os.getenv("GEMINI_API_KEY")  # 실제 Google API 키 사용
if not google_api_key:
    logging.error("GEMINI_API_KEY is not set in the environment variables.")
llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", google_api_key=google_api_key)

# -------------------------------------------------------------------------------
# Define Academic Research Agents
# -------------------------------------------------------------------------------
literature_research_agent = Agent(
    role="Literature Research Agent",
    goal="Research and provide a comprehensive review of existing literature on the research topic.",
    backstory="An experienced academic researcher specialized in literature reviews and meta-analyses.",
    personality="Analytical, thorough, and detail-oriented.",
    llm=llm,
)

outline_agent = Agent(
    role="Outline Agent",
    goal="Generate a structured and detailed outline for a research paper based on the research topic and literature.",
    backstory="A methodical academic planner who organizes research findings into coherent paper structures.",
    personality="Organized, systematic, and insightful.",
    llm=llm,
)

draft_writing_agent = Agent(
    role="Draft Writing Agent",
    goal="Compose a first draft of the research paper based on the literature review and outline.",
    backstory="A skilled academic writer capable of synthesizing research findings into well-structured drafts.",
    personality="Articulate, precise, and scholarly.",
    llm=llm,
)

citation_agent = Agent(
    role="Citation Agent",
    goal="Generate a list of relevant citations and references in the required format for the research paper.",
    backstory="A detail-oriented bibliographic expert with extensive knowledge of citation standards.",
    personality="Meticulous, accurate, and research-savvy.",
    llm=llm,
)

editing_agent = Agent(
    role="Editing Agent",
    goal="Revise and polish the draft for clarity, coherence, and academic tone.",
    backstory="An expert editor skilled in improving academic manuscripts and ensuring high-quality presentation.",
    personality="Critical, precise, and supportive.",
    llm=llm,
)

chatbot_agent = Agent(
    role="Chatbot Agent",
    goal="Engage in interactive conversation to answer queries related to the academic research process.",
    backstory="A conversational AI assistant with extensive knowledge in academia and research methodologies.",
    personality="Helpful, conversational, and knowledgeable.",
    llm=llm,
)

# -------------------------------------------------------------------------------
# Define Tasks for Academic Research and Writing
# -------------------------------------------------------------------------------
literature_research_task = Task(
    description="""Research academic literature on {topic} considering the keywords {keywords}.
    
Please provide:
- A summary of the current state of research,
- Key trends and gaps in the literature,
- Notable studies and their findings,
- Relevant theoretical frameworks and methodologies.
Format the response with bullet points and concise summaries.""",
    agent=literature_research_agent,
    expected_output="""A comprehensive literature review summary covering:
1. Summary of current research trends
2. Identification of gaps and controversies
3. Key studies with brief descriptions
4. Theoretical frameworks and methodologies used"""
)

outline_task = Task(
    description="""Based on the research topic {topic} and literature review findings, generate a detailed outline for a research paper.
    
Include sections such as:
- Abstract
- Introduction (including research questions and objectives)
- Literature Review
- Methodology
- Results/Findings
- Discussion
- Conclusion
- References
Format the outline in a structured manner with bullet points and subheadings.""",
    agent=outline_agent,
    expected_output="A structured outline for a research paper including all major sections and key points to cover in each section."
)

draft_writing_task = Task(
    description="""Using the research topic {topic}, the literature review, and the generated outline, compose a first draft of the research paper.
    
The draft should include:
- A coherent narrative flow,
- Detailed sections as per the outline,
- Integration of key findings from the literature review.
Ensure the tone is academic and the content is well-organized.""",
    agent=draft_writing_agent,
    expected_output="A complete first draft of the research paper covering all sections with sufficient academic detail."
)

citation_task = Task(
    description="""Based on the literature review for {topic}, generate a list of key references and citations in APA format.
    
Include:
- Author names, publication year, title, and source,
- At least 10 key references relevant to the research topic.
Format the output as a numbered list of citations.""",
    agent=citation_agent,
    expected_output="A list of 10+ relevant citations in APA format."
)

editing_task = Task(
    description="""Review and edit the draft for clarity, coherence, and academic tone.
    
Focus on:
- Improving sentence structure,
- Ensuring logical flow between sections,
- Correcting grammar and stylistic issues,
- Enhancing academic tone.
Provide the polished version of the paper.""",
    agent=editing_agent,
    expected_output="A refined and polished version of the research paper draft."
)

chatbot_task = Task(
    description="Provide a conversational and detailed response to academic research-related queries.",
    agent=chatbot_agent,
    expected_output="A friendly, informative response addressing the query."
)

def run_task(task: Task, input_text: str) -> str:
    """
    Executes the given task using the associated agent's LLM and returns the response content.
    """
    try:
        if not isinstance(task, Task):
            raise ValueError(f"Expected 'task' to be an instance of Task, got {type(task)}")
        if not hasattr(task, 'agent') or not isinstance(task.agent, Agent):
            raise ValueError("Task must have a valid 'agent' attribute of type Agent.")
        system_input = (
            f"Agent Details:\n"
            f"Role: {task.agent.role}\n"
            f"Goal: {task.agent.goal}\n"
            f"Backstory: {task.agent.backstory}\n"
            f"Personality: {task.agent.personality}\n"
        )
        task_input = (
            f"Task Details:\n"
            f"Task Description: {task.description}\n"
            f"Expected Output: {task.expected_output}\n"
            f"Input for Task:\n{input_text}\n"
        )
        messages = [
            SystemMessage(content=system_input),
            HumanMessage(content=task_input)
        ]
        response = task.agent.llm.invoke(messages)
        if not response or not response.content:
            raise ValueError("Empty response from LLM.")
        return response.content
    except Exception as e:
        logging.error(f"Error in task '{task.agent.role}': {e}")
        return f"Error in {task.agent.role}: {e}"