Add pre commit (#26)

This commit is contained in:
Lamont Huffman
2025-11-05 11:44:19 +08:00
committed by GitHub
parent 2164371e64
commit 30d86efbb3
33 changed files with 565 additions and 496 deletions

View File

@@ -95,14 +95,14 @@ class ReflectFailure(BaseModel):
"properties": {
"need_rephrase": {
"type": "boolean",
"description": "Set to 'true' if the failed subtask "
"needs to be rephrased due to a design "
"description": "Set to 'true' if the failed"
" subtask needs to be rephrased due to a design "
"flaw or misunderstanding; otherwise, 'false'.",
},
"rephrased_plan": {
"type": "string",
"description": "The modified working meta_planner_agent "
"with only the inappropriate "
"description": "The modified working "
"meta_planner_agent with only the inappropriate "
"subtask replaced by its improved version. If no "
"rephrasing is needed, provide an empty string.",
},

View File

@@ -1,35 +1,46 @@
# -*- coding: utf-8 -*-
"""Deep Research Agent"""
# pylint: disable=too-many-lines, no-name-in-module
import asyncio
import json
import os
from copy import deepcopy
import json
import asyncio
from typing import Type, Optional, Any, Tuple
from datetime import datetime
from typing import Any, Optional, Tuple, Type
from copy import deepcopy
import shortuuid
from agentscope import logger, setup_logger
from agentscope.agent import ReActAgent
from agentscope.formatter import FormatterBase
from agentscope.mcp import StatefulClientBase
from agentscope.memory import MemoryBase
from agentscope.message import Msg, TextBlock, ToolResultBlock, ToolUseBlock
from agentscope.model import ChatModelBase
from agentscope.tool import ToolResponse, view_text_file, write_text_file
from pydantic import BaseModel
from ..agent_deep_research.utils import (
get_dynamic_tool_call_json,
get_structure_output,
load_prompt_dict,
truncate_search_result,
)
from .built_in_prompt.promptmodule import (
FollowupJudge,
ReflectFailure,
from built_in_prompt.promptmodule import (
SubtasksDecomposition,
WebExtraction,
FollowupJudge,
ReflectFailure,
)
from utils import (
truncate_search_result,
load_prompt_dict,
get_dynamic_tool_call_json,
get_structure_output,
)
from agentscope import logger, setup_logger
from agentscope.mcp import StatefulClientBase
from agentscope.agent import ReActAgent
from agentscope.model import ChatModelBase
from agentscope.formatter import FormatterBase
from agentscope.memory import MemoryBase
from agentscope.tool import (
ToolResponse,
view_text_file,
write_text_file,
)
from agentscope.message import (
Msg,
ToolUseBlock,
TextBlock,
ToolResultBlock,
)
_DEEP_RESEARCH_AGENT_DEFAULT_SYS_PROMPT = "You're a helpful assistant."
@@ -149,7 +160,7 @@ class DeepResearchAgent(ReActAgent):
# register all necessary tools for deep research agent
self.toolkit.register_tool_function(view_text_file)
self.toolkit.register_tool_function(write_text_file)
asyncio.create_task(
asyncio.get_running_loop().create_task(
self.toolkit.register_mcp_client(search_mcp_client),
)
@@ -213,16 +224,12 @@ class DeepResearchAgent(ReActAgent):
reasoning_prompt = self.prompt_dict["reasoning_prompt"].format_map(
{
"objective": self.current_subtask[-1].objective,
"meta_planner_agent": (
cur_plan
if cur_plan
else "There is no working meta_planner_agent now."
),
"knowledge_gap": (
f"## Knowledge Gaps:\n {cur_know_gap}"
if cur_know_gap
else ""
),
"plan": cur_plan
if cur_plan
else "There is no working plan now.",
"knowledge_gap": f"## Knowledge Gaps:\n {cur_know_gap}"
if cur_know_gap
else "",
"depth": len(self.current_subtask),
},
)
@@ -300,7 +307,9 @@ class DeepResearchAgent(ReActAgent):
# Async generator handling
async for chunk in tool_res:
# Turn into a tool result block
tool_res_msg.content[0]["output"] = chunk.content # type: ignore[index]
tool_res_msg.content[0][ # type: ignore[index]
"output"
] = chunk.content
# Skip the printing of the finish function call
if (
@@ -488,13 +497,14 @@ class DeepResearchAgent(ReActAgent):
async def decompose_and_expand_subtask(self) -> ToolResponse:
"""Identify the knowledge gaps of the current subtask and generate a
working meta_planner_agent by subtask decomposition. The working meta_planner_agent includes
working meta_planner_agent by subtask decomposition.
The working meta_planner_agent includes
necessary steps for task completion and expanded steps.
Returns:
ToolResponse:
The knowledge gaps and working meta_planner_agent of the current subtask
in JSON format.
The knowledge gaps and working meta_planner_agent
of the current subtask in JSON format.
"""
if len(self.current_subtask) <= self.max_depth:
decompose_sys_prompt = self.prompt_dict["decompose_sys_prompt"]
@@ -947,7 +957,8 @@ class DeepResearchAgent(ReActAgent):
Returns:
ToolResponse:
The reflection about meta_planner_agent rephrasing and subtask decomposition.
The reflection about meta_planner_agent
rephrasing and subtask decomposition.
"""
reflect_sys_prompt = self.prompt_dict["reflect_sys_prompt"]
conversation_history = ""

View File

@@ -10,7 +10,7 @@ from agentscope.memory import InMemoryMemory
from agentscope.message import Msg
from agentscope.model import DashScopeChatModel
from .deep_research_agent import DeepResearchAgent
from deep_research_agent import DeepResearchAgent
async def main(user_query: str) -> None:

View File

@@ -1,12 +1,12 @@
# -*- coding: utf-8 -*-
"""The utilities for deep research agent"""
import json
import os
import json
import re
from typing import Any, Sequence, Type, Union
from typing import Union, Sequence, Any, Type
from pydantic import BaseModel
from agentscope.tool import Toolkit, ToolResponse
from pydantic import BaseModel
TOOL_RESULTS_MAX_WORDS = 5000
@@ -281,11 +281,14 @@ def load_prompt_dict() -> dict:
prompt_dict["summarize_hint"] = (
"Based on your work history above, examine which step in the "
"following working meta_planner_agent has been completed. Mark the completed "
"following working meta_planner_agent has been "
"completed. Mark the completed "
"step with [DONE] at the end of its line (e.g., k. step k [DONE]) "
"and leave the uncompleted steps unchanged. You MUST return only "
"the updated meta_planner_agent, preserving exactly the same format as the "
"original meta_planner_agent. Do not include any explanations, reasoning, "
"the updated meta_planner_agent, preserving exactly "
"the same format as the "
"original meta_planner_agent. Do not include any "
"explanations, reasoning, "
"or section headers such as '## Working Plan:', just output the"
"updated meta_planner_agent itself."
"\n\n## Working Plan:\n{meta_planner_agent}"
@@ -304,11 +307,13 @@ def load_prompt_dict() -> dict:
"following report that consolidates and summarizes the essential "
"findings:\n {intermediate_report}\n\n"
"Such report has been saved to the {report_path}. "
"I will now **proceed to the next item** in the working meta_planner_agent."
"I will now **proceed to the next item** "
"in the working meta_planner_agent."
)
prompt_dict["save_report_hint"] = (
"The milestone results of the current item in working meta_planner_agent "
"The milestone results of the current "
"item in working meta_planner_agent "
"are summarized into the following report:\n{intermediate_report}"
)

View File

@@ -1,16 +1,16 @@
# -*- coding: utf-8 -*-
import os
import uuid
import random
import string
import time
import uuid
from base64 import b64encode
from hashlib import sha256
from hmac import new as hmac_new
from typing import Any, Dict, List
from typing import List, Dict, Any
import requests
from utils import format_time
from .utils import format_time
class CustomSearchTool:

View File

@@ -3,22 +3,25 @@ import asyncio
import json
import os
import time
from typing import Any, Dict, List, Optional
from agentscope_runtime.engine.agents.langgraph_agent import LangGraphAgent
from agentscope_runtime.engine.helpers.helper import simple_call_agent_direct
from configuration import Configuration
from custom_search_tool import CustomSearchTool
from typing import List, Dict, Any, Optional
from dotenv import load_dotenv
from langchain_core.messages import AIMessage, HumanMessage
from langchain_core.runnables import RunnableConfig
from langgraph.graph import END, START, StateGraph
from langgraph.graph import START, END
from langgraph.graph import StateGraph
from langgraph.types import Send
from agentscope_runtime.engine.agents.langgraph_agent import LangGraphAgent
from agentscope_runtime.engine.helpers.helper import simple_call_agent_direct
from configuration import Configuration
from custom_search_tool import CustomSearchTool
from llm_prompts import (
answer_instructions,
query_writer_instructions,
reflection_instructions,
web_searcher_instructions,
reflection_instructions,
answer_instructions,
)
from llm_utils import call_dashscope, extract_json_from_qwen
from state import (
@@ -27,12 +30,12 @@ from state import (
ReflectionState,
WebSearchState,
)
from utils import (
custom_get_citations,
custom_resolve_urls,
get_current_date,
from .utils import (
get_research_topic,
insert_citation_markers,
custom_resolve_urls,
custom_get_citations,
get_current_date,
)
load_dotenv("../.env")

View File

@@ -1,12 +1,11 @@
# -*- coding: utf-8 -*-
import time
from datetime import datetime
from typing import Any, Dict, List
from langchain_core.messages import AIMessage, AnyMessage, HumanMessage
from datetime import datetime
from langchain_core.messages import AnyMessage, AIMessage, HumanMessage
def get_current_date() -> str:
def get_current_date():
return datetime.now().strftime("%B %d, %Y")
@@ -39,7 +38,7 @@ def get_research_topic(messages: List[AnyMessage]) -> str:
return research_topic
def insert_citation_markers(text: str, citations_list: List[Dict]) -> str:
def insert_citation_markers(text, citations_list):
"""
Inserts citation markers into a text string based on start and end indices.