Spaces:
Sleeping
Sleeping
| 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="Assumsions Analysis Agent", | |
| goal="Provide a comprehensive review of existing assumsions on the feasibility study topic.", | |
| backstory="An experienced academic researcher specialized in feasibility study assumsions 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 feasibility study based on the assumsions. The outline that needs to be prepared includes: Market Analysis, Technical Analysis, Financial Analysis, Legal and Regulatory Analysis, Risk Analysis, Environmental and Social Impact Analysis, Conclusions and Recommendations.", | |
| backstory="A methodical academic planner who organizes feasibility study 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 feasibility paper based on the assumsions review and outline. The writings that needs to be prepared includes: Market Analysis, Technical Analysis, Financial Analysis, Legal and Regulatory Analysis, Risk Analysis, Environmental and Social Impact Analysis, Conclusions and Recommendations.", | |
| backstory="A skilled academic writer capable of synthesizing feasibility study 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. The writings that needs to be prepared includes: Market Analysis, Technical Analysis, Financial Analysis, Legal and Regulatory Analysis, Risk Analysis, Environmental and Social Impact Analysis, Conclusions and Recommendations.", | |
| backstory="An expert editor skilled in improving feasibility 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 feasibility study documents", | |
| backstory="A conversational AI assistant with extensive knowledge in academia,feasibility study, and research methodologies.", | |
| personality="Helpful, conversational, and knowledgeable.", | |
| llm=llm, | |
| ) | |
| # ------------------------------------------------------------------------------- | |
| # Define Tasks for Academic Research and Writing | |
| # ------------------------------------------------------------------------------- | |
| literature_research_task = Task( | |
| description="""prepare the creation of a Feasibility Study with the theme on {topic} considering the keywords {keywords}. | |
| Please provide: | |
| - Market Analysis | |
| - Technical Analysis | |
| - Financial Analysis | |
| - Legal and Regulatory Analysis | |
| - Risk Analysis | |
| - Environmental and Social Impact Analysis | |
| - Conclusions and Recommendations | |
| Format the response with bullet points and concise summaries.""", | |
| agent=literature_research_agent, | |
| expected_output="""A comprehensive Feasibility Study covering: | |
| 1. Market Analysis | |
| 2. Technical Analysis | |
| 3. Financial Analysis | |
| 4. Legal and Regulatory Analysis | |
| 5. Risk Analysis | |
| 6. Environmental and Social Impact Analysis | |
| 7. Conclusions and Recommendations""" | |
| ) | |
| outline_task = Task( | |
| description="""Based on the Feasibility Study topic {topic} and assumsions review findings, generate a detailed outline for a Feasibility Study paper. | |
| Include sections such as: | |
| - Market Analysis | |
| - Technical Analysis | |
| - Financial Analysis | |
| - Legal and Regulatory Analysis | |
| - Risk Analysis | |
| - Environmental and Social Impact Analysis | |
| - Conclusions and Recommendations | |
| - References | |
| Format the outline in a structured manner with bullet points and subheadings.""", | |
| agent=outline_agent, | |
| expected_output="A structured outline for a Feasibility Study paper including all major sections and key points to cover in each section." | |
| ) | |
| draft_writing_task = Task( | |
| description="""Using the Feasibility Study topic {topic}, the assumsions review, and the generated outline, compose a first draft of the Feasibility Study paper. | |
| The draft should include: | |
| - Market Analysis | |
| - Technical Analysis | |
| - Financial Analysis | |
| - Legal and Regulatory Analysis | |
| - Risk Analysis | |
| - Environmental and Social Impact Analysis | |
| - Conclusions and Recommendations | |
| - References | |
| Ensure the tone is academic and the content is well-organized.""", | |
| agent=draft_writing_agent, | |
| expected_output="A complete first draft of the Feasibility Study paper covering all sections with sufficient academic detail." | |
| ) | |
| citation_task = Task( | |
| description="""Based on the Feasibility Study 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 Feasibility Study paper draft." | |
| ) | |
| chatbot_task = Task( | |
| description="Provide a conversational and detailed response to Feasibility Study-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}" |